@metamask-previews/messenger 1.1.1-preview-45a82ea8e → 1.2.0-preview-d8ff44d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -1
- package/dist/Messenger.cjs +34 -2
- package/dist/Messenger.cjs.map +1 -1
- package/dist/Messenger.d.cts +126 -0
- package/dist/Messenger.d.cts.map +1 -1
- package/dist/Messenger.d.mts +126 -0
- package/dist/Messenger.d.mts.map +1 -1
- package/dist/Messenger.mjs +34 -2
- package/dist/Messenger.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Allow overriding action handler in subclass ([#8617](https://github.com/MetaMask/core/pull/8617))
|
|
15
|
+
- The `Messenger` class now has a protected `getAction` method which returns the action handler for a given action name.
|
|
16
|
+
- Add `subscribeOnce` and `waitUntil` utility methods to `Messenger` ([#8575](https://github.com/MetaMask/core/pull/8575))
|
|
17
|
+
|
|
10
18
|
### Deprecated
|
|
11
19
|
|
|
12
20
|
- Deprecate `generate-action-types` CLI tool and `messenger-generate-action-types` binary ([#8378](https://github.com/MetaMask/core/pull/8378))
|
|
@@ -88,7 +96,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
88
96
|
- Existing `RestrictedMessenger` instances should be replaced with a `Messenger` with the `parent` constructor parameter set to the global messenger. We can now use the same class everywhere, passing capabilities using `delegate`.
|
|
89
97
|
- See this ADR for details: https://github.com/MetaMask/decisions/blob/main/decisions/core/0012-messenger-delegation.md
|
|
90
98
|
|
|
91
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.
|
|
99
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.2.0...HEAD
|
|
100
|
+
[1.2.0]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.1.1...@metamask/messenger@1.2.0
|
|
92
101
|
[1.1.1]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.1.0...@metamask/messenger@1.1.1
|
|
93
102
|
[1.1.0]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.0.0...@metamask/messenger@1.1.0
|
|
94
103
|
[1.0.0]: https://github.com/MetaMask/core/compare/@metamask/messenger@0.3.0...@metamask/messenger@1.0.0
|
package/dist/Messenger.cjs
CHANGED
|
@@ -145,6 +145,20 @@ class Messenger {
|
|
|
145
145
|
__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_unregisterActionHandler).call(this, actionType);
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
+
/**
|
|
149
|
+
* Get the action handler for a given action type.
|
|
150
|
+
*
|
|
151
|
+
* This is a protected method to allow subclasses to override the way action
|
|
152
|
+
* handlers are retrieved, for example to implement custom delegation logic.
|
|
153
|
+
*
|
|
154
|
+
* @param actionType - The action type. This is a unique identifier for this
|
|
155
|
+
* action.
|
|
156
|
+
* @returns The action handler for the given action type, or undefined if no
|
|
157
|
+
* handler has been registered.
|
|
158
|
+
*/
|
|
159
|
+
getAction(actionType) {
|
|
160
|
+
return __classPrivateFieldGet(this, _Messenger_actions, "f").get(actionType);
|
|
161
|
+
}
|
|
148
162
|
/**
|
|
149
163
|
* Call an action.
|
|
150
164
|
*
|
|
@@ -159,7 +173,7 @@ class Messenger {
|
|
|
159
173
|
* @returns The action return value.
|
|
160
174
|
*/
|
|
161
175
|
call(actionType, ...params) {
|
|
162
|
-
const handler =
|
|
176
|
+
const handler = this.getAction(actionType);
|
|
163
177
|
if (!handler) {
|
|
164
178
|
throw new Error(__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_isInCurrentNamespace).call(this, actionType)
|
|
165
179
|
? `A handler for ${actionType} has not been registered`
|
|
@@ -242,6 +256,24 @@ class Messenger {
|
|
|
242
256
|
}
|
|
243
257
|
}
|
|
244
258
|
}
|
|
259
|
+
subscribeOnce(eventType, handler, options) {
|
|
260
|
+
const { selector, condition } = options ?? {};
|
|
261
|
+
// Casting to unknown to handle both the code path where a selector is defined and where it is omitted.
|
|
262
|
+
const internalHandler = (...args) => {
|
|
263
|
+
if (condition &&
|
|
264
|
+
!condition(...args)) {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
this.unsubscribe(eventType, internalHandler);
|
|
268
|
+
handler(...args);
|
|
269
|
+
};
|
|
270
|
+
this.subscribe(eventType, internalHandler, selector);
|
|
271
|
+
}
|
|
272
|
+
waitUntil(eventType, options) {
|
|
273
|
+
return new Promise((resolve) => {
|
|
274
|
+
this.subscribeOnce(eventType, (...args) => resolve(args), options);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
245
277
|
/**
|
|
246
278
|
* Unsubscribe from an event.
|
|
247
279
|
*
|
|
@@ -335,7 +367,7 @@ class Messenger {
|
|
|
335
367
|
const delegatedActionHandler = (...args) => {
|
|
336
368
|
// Cast to get more specific type, for this specific action
|
|
337
369
|
// The types get collapsed by `this.#actions`
|
|
338
|
-
const actionHandler =
|
|
370
|
+
const actionHandler = this.getAction(actionType);
|
|
339
371
|
if (!actionHandler) {
|
|
340
372
|
throw new Error(`A handler for ${actionType} has not been registered`);
|
|
341
373
|
}
|
package/dist/Messenger.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Messenger.cjs","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAgGA;;;;;;GAMG;AACU,QAAA,kBAAkB,GAAG,oBAAoB,CAAC;AAkFvD;;;;;;;;;;;GAWG;AACH,MAAa,SAAS;IAmEpB;;;;;;;;;;OAUG;IACH,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,MAAM,GASP;;QA5EQ,uCAAsB;QAE/B;;;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C,6EAsXqB,IAAY;IAChC,OAAO,CACL,uBAAA,IAAI,4BAAW,KAAK,0BAAkB;QACtC,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.#actions.get(actionType) as ActionHandler<\n Action,\n ActionType\n >;\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.#actions.get(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Messenger.cjs","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAgGA;;;;;;GAMG;AACU,QAAA,kBAAkB,GAAG,oBAAoB,CAAC;AAkFvD;;;;;;;;;;;GAWG;AACH,MAAa,SAAS;IAmEpB;;;;;;;;;;OAUG;IACH,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,MAAM,GASP;;QA5EQ,uCAAsB;QAE/B;;;WAGG;QACM,oCAA6B;QAE7B,6BAAW,IAAI,GAAG,EAAqC,EAAC;QAExD,4BAAU,IAAI,GAAG,EAA8C,EAAC;QAEzE;;WAEG;QACM,mDAAiC,IAAI,GAAG,EAG9C,EAAC;QAEJ;;WAEG;QACM,6CAA2B,IAAI,GAAG,EAGxC,EAAC;QAEJ;;;;WAIG;QACM,gDAA8B,IAAI,GAAG,EAG3C,EAAC;QAEJ;;WAEG;QACM,uCAAqB,IAAI,GAAG,EAGlC,EAAC;QAiCF,uBAAA,IAAI,wBAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,qBAAW,MAAM,MAAA,CAAC;QACtB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,IAAI,uBAAA,IAAI,yBAAQ,EAAE,gBAAgB,CAAC;IAC7E,CAAC;IAED;;;;;;;;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+C;IAE/C,IAAI,WAAW,GAAG,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QACxB,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC,6EAqjBqB,IAAY;IAChC,OAAO,CACL,uBAAA,IAAI,4BAAW,KAAK,0BAAkB;QACtC,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Get the action handler for a given action type.\n *\n * This is a protected method to allow subclasses to override the way action\n * handlers are retrieved, for example to implement custom delegation logic.\n *\n * @param actionType - The action type. This is a unique identifier for this\n * action.\n * @returns The action handler for the given action type, or undefined if no\n * handler has been registered.\n */\n protected getAction(\n actionType: Action['type'],\n ): ActionConstraint['handler'] | undefined {\n return this.#actions.get(actionType);\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.getAction(actionType) as\n | ActionHandler<Action, ActionType>\n | undefined;\n\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Subscribe to an event, with a selector, invoking the handler exactly once.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value. Additionally if the optional condition\n * function is provided, it is checked whether it returns `true`.\n * The handler is invoked at most once, after which the subscription is removed.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload. The type of the parameters for this selector must\n * match the type of the payload for this event type.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (hash) => { ... },\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): void;\n\n /**\n * Subscribe to an event, invoking the handler exactly once.\n *\n * Registers the given function as an event handler for the given event type\n * and automatically unsubscribes after the first invocation.\n *\n * If `options.condition` is provided, the handler is only invoked (and the\n * subscription only removed) when the condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the type of the payload for this event type.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (tx) => { ... },\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): void;\n\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): void {\n const { selector, condition } = options ?? {};\n // Casting to unknown to handle both the code path where a selector is defined and where it is omitted.\n const internalHandler = (...args: unknown[]): void => {\n if (\n condition &&\n !(condition as (...args: unknown[]) => boolean)(...args)\n ) {\n return;\n }\n this.unsubscribe(eventType, internalHandler);\n (handler as (...args: unknown[]) => void)(...args);\n };\n\n this.subscribe(\n eventType,\n internalHandler,\n selector as SelectorFunction<Event, EventType, SelectorReturnValue>,\n );\n }\n\n /**\n * Return a promise that resolves the next time the selector's return value\n * changes and, if provided, the `options.condition` predicate returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @returns A promise that resolves with the selector's return value.\n * @example\n * ```typescript\n * const [hash] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;\n\n /**\n * Return a promise that resolves the next time the given event is published.\n *\n * If `options.condition` is provided, the promise only resolves when the\n * condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @returns A promise that resolves with the event payload.\n * @example\n * ```typescript\n * const [transactionMeta] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n * @example\n * ```typescript\n * await messenger.waitUntil('KeyringController:unlock');\n * ```\n */\n waitUntil<EventType extends Event['type']>(\n eventType: EventType,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): Promise<ExtractEventPayload<Event, EventType>>;\n\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): Promise<SelectorReturnValue | ExtractEventPayload<Event, EventType>[0]> {\n return new Promise((resolve) => {\n this.subscribeOnce(\n eventType,\n (...args) => resolve(args),\n options as {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n );\n });\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.getAction(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]}
|
package/dist/Messenger.d.cts
CHANGED
|
@@ -144,6 +144,18 @@ export declare class Messenger<Namespace extends string, Action extends ActionCo
|
|
|
144
144
|
* This prevents all actions from being called.
|
|
145
145
|
*/
|
|
146
146
|
clearActions(): void;
|
|
147
|
+
/**
|
|
148
|
+
* Get the action handler for a given action type.
|
|
149
|
+
*
|
|
150
|
+
* This is a protected method to allow subclasses to override the way action
|
|
151
|
+
* handlers are retrieved, for example to implement custom delegation logic.
|
|
152
|
+
*
|
|
153
|
+
* @param actionType - The action type. This is a unique identifier for this
|
|
154
|
+
* action.
|
|
155
|
+
* @returns The action handler for the given action type, or undefined if no
|
|
156
|
+
* handler has been registered.
|
|
157
|
+
*/
|
|
158
|
+
protected getAction(actionType: Action['type']): ActionConstraint['handler'] | undefined;
|
|
147
159
|
/**
|
|
148
160
|
* Call an action.
|
|
149
161
|
*
|
|
@@ -221,6 +233,120 @@ export declare class Messenger<Namespace extends string, Action extends ActionCo
|
|
|
221
233
|
* @template SelectorReturnValue - The selector return value.
|
|
222
234
|
*/
|
|
223
235
|
subscribe<EventType extends Event['type'], SelectorReturnValue>(eventType: EventType, handler: SelectorEventHandler<SelectorReturnValue>, selector: SelectorFunction<Event, EventType, SelectorReturnValue>): void;
|
|
236
|
+
/**
|
|
237
|
+
* Subscribe to an event, with a selector, invoking the handler exactly once.
|
|
238
|
+
*
|
|
239
|
+
* Registers the given handler function as an event handler for the given
|
|
240
|
+
* event type. When an event is published, its payload is first passed to the
|
|
241
|
+
* selector. The event handler is only called if the selector's return value
|
|
242
|
+
* differs from its last known return value. Additionally if the optional condition
|
|
243
|
+
* function is provided, it is checked whether it returns `true`.
|
|
244
|
+
* The handler is invoked at most once, after which the subscription is removed.
|
|
245
|
+
*
|
|
246
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
247
|
+
* @param handler - The event handler. The type of the parameters for this event
|
|
248
|
+
* handler must match the return type of the selector.
|
|
249
|
+
* @param options - Options bag.
|
|
250
|
+
* @param options.selector - The selector function used to select relevant data
|
|
251
|
+
* from the event payload. The type of the parameters for this selector must
|
|
252
|
+
* match the type of the payload for this event type.
|
|
253
|
+
* @param options.condition - An optional predicate evaluated against the
|
|
254
|
+
* selector's return value. The handler is only invoked when this returns `true`.
|
|
255
|
+
* @template EventType - A type union of Event type strings.
|
|
256
|
+
* @template SelectorReturnValue - The selector return value.
|
|
257
|
+
* @example
|
|
258
|
+
* ```typescript
|
|
259
|
+
* messenger.subscribeOnce(
|
|
260
|
+
* 'TransactionController:transactionConfirmed',
|
|
261
|
+
* (hash) => { ... },
|
|
262
|
+
* { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },
|
|
263
|
+
* );
|
|
264
|
+
* ```
|
|
265
|
+
*/
|
|
266
|
+
subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(eventType: EventType, handler: SelectorEventHandler<SelectorReturnValue>, options: {
|
|
267
|
+
selector: SelectorFunction<Event, EventType, SelectorReturnValue>;
|
|
268
|
+
condition?: (value: SelectorReturnValue) => boolean;
|
|
269
|
+
}): void;
|
|
270
|
+
/**
|
|
271
|
+
* Subscribe to an event, invoking the handler exactly once.
|
|
272
|
+
*
|
|
273
|
+
* Registers the given function as an event handler for the given event type
|
|
274
|
+
* and automatically unsubscribes after the first invocation.
|
|
275
|
+
*
|
|
276
|
+
* If `options.condition` is provided, the handler is only invoked (and the
|
|
277
|
+
* subscription only removed) when the condition returns `true`.
|
|
278
|
+
*
|
|
279
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
280
|
+
* @param handler - The event handler. The type of the parameters for this event
|
|
281
|
+
* handler must match the type of the payload for this event type.
|
|
282
|
+
* @param options - Options bag.
|
|
283
|
+
* @param options.condition - A predicate evaluated against the event payload.
|
|
284
|
+
* The handler is only invoked when this returns `true`.
|
|
285
|
+
* @template EventType - A type union of Event type strings.
|
|
286
|
+
* @example
|
|
287
|
+
* ```typescript
|
|
288
|
+
* messenger.subscribeOnce(
|
|
289
|
+
* 'TransactionController:transactionConfirmed',
|
|
290
|
+
* (tx) => { ... },
|
|
291
|
+
* { condition: (tx) => tx.hash === 'foo' },
|
|
292
|
+
* );
|
|
293
|
+
* ```
|
|
294
|
+
*/
|
|
295
|
+
subscribeOnce<EventType extends Event['type']>(eventType: EventType, handler: ExtractEventHandler<Event, EventType>, options?: {
|
|
296
|
+
condition?: (...payload: ExtractEventPayload<Event, EventType>) => boolean;
|
|
297
|
+
}): void;
|
|
298
|
+
/**
|
|
299
|
+
* Return a promise that resolves the next time the selector's return value
|
|
300
|
+
* changes and, if provided, the `options.condition` predicate returns `true`.
|
|
301
|
+
*
|
|
302
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
303
|
+
* @param options - Options bag.
|
|
304
|
+
* @param options.selector - The selector function used to select relevant data
|
|
305
|
+
* from the event payload.
|
|
306
|
+
* @param options.condition - An optional predicate evaluated against the
|
|
307
|
+
* selector's return value. The promise only resolves when this returns `true`.
|
|
308
|
+
* @template EventType - A type union of Event type strings.
|
|
309
|
+
* @template SelectorReturnValue - The selector return value.
|
|
310
|
+
* @returns A promise that resolves with the selector's return value.
|
|
311
|
+
* @example
|
|
312
|
+
* ```typescript
|
|
313
|
+
* const [hash] = await messenger.waitUntil(
|
|
314
|
+
* 'TransactionController:transactionConfirmed',
|
|
315
|
+
* { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },
|
|
316
|
+
* );
|
|
317
|
+
* ```
|
|
318
|
+
*/
|
|
319
|
+
waitUntil<EventType extends Event['type'], SelectorReturnValue>(eventType: EventType, options: {
|
|
320
|
+
selector: SelectorFunction<Event, EventType, SelectorReturnValue>;
|
|
321
|
+
condition?: (value: SelectorReturnValue) => boolean;
|
|
322
|
+
}): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;
|
|
323
|
+
/**
|
|
324
|
+
* Return a promise that resolves the next time the given event is published.
|
|
325
|
+
*
|
|
326
|
+
* If `options.condition` is provided, the promise only resolves when the
|
|
327
|
+
* condition returns `true`.
|
|
328
|
+
*
|
|
329
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
330
|
+
* @param options - Options bag.
|
|
331
|
+
* @param options.condition - A predicate evaluated against the event payload.
|
|
332
|
+
* The promise only resolves when this returns `true`.
|
|
333
|
+
* @template EventType - A type union of Event type strings.
|
|
334
|
+
* @returns A promise that resolves with the event payload.
|
|
335
|
+
* @example
|
|
336
|
+
* ```typescript
|
|
337
|
+
* const [transactionMeta] = await messenger.waitUntil(
|
|
338
|
+
* 'TransactionController:transactionConfirmed',
|
|
339
|
+
* { condition: (tx) => tx.hash === 'foo' },
|
|
340
|
+
* );
|
|
341
|
+
* ```
|
|
342
|
+
* @example
|
|
343
|
+
* ```typescript
|
|
344
|
+
* await messenger.waitUntil('KeyringController:unlock');
|
|
345
|
+
* ```
|
|
346
|
+
*/
|
|
347
|
+
waitUntil<EventType extends Event['type']>(eventType: EventType, options?: {
|
|
348
|
+
condition?: (...payload: ExtractEventPayload<Event, EventType>) => boolean;
|
|
349
|
+
}): Promise<ExtractEventPayload<Event, EventType>>;
|
|
224
350
|
/**
|
|
225
351
|
* Unsubscribe from an event.
|
|
226
352
|
*
|
package/dist/Messenger.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Messenger.d.cts","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,CACvB,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,CACF,GAAG,IAAI,EAAE,uBAAuB,CAAC,MAAM,EAAE,UAAU,CAAC,KACjD,qBAAqB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAE/C,MAAM,MAAM,uBAAuB,CACjC,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,MAAM,SAAS;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,WAAW,KAAK,OAAO,CAAC;CAClD,GACG,WAAW,GACX,KAAK,CAAC;AAEV,MAAM,MAAM,qBAAqB,CAC/B,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,MAAM,SAAS;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,MAAM,kBAAkB,CAAC;CACzD,GACG,kBAAkB,GAClB,KAAK,CAAC;AAEV,MAAM,MAAM,mBAAmB,CAC7B,KAAK,SAAS,eAAe,EAC7B,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,IACvB,KAAK,SAAS;IAChB,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,MAAM,OAAO,CAAC;CACxB,GACG,OAAO,SAAS,OAAO,EAAE,GACvB,CAAC,GAAG,OAAO,EAAE,OAAO,KAAK,IAAI,GAC7B,KAAK,GACP,KAAK,CAAC;AAEV,MAAM,MAAM,mBAAmB,CAC7B,KAAK,SAAS,eAAe,EAC7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O,EAAE,aAAa,CAAC,gBAAgB,EAAE,UAAU,CAAC,GACnD,IAAI;IAIP;;;;;;;;;;;;OAYG;IACH,yCAAyC,CAAC,UAAU,SAAS,MAAM,CAAC,MAAM,CAAC,EACzE,UAAU,EAAE,UAAU,GACrB,IAAI;IAIP;;;;;;;;;;;;;;;;OAgBG;IACH,6CAA6C,CAC3C,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EAC/B,EACA,SAAS,EACT,UAAU,GACX,EAAE;QACD,SAAS,EAAE,SAAS,CAAC;QACrB,UAAU,EAAE,MAAM,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;KACzD,GAAG,IAAI;IAIR;;;;;;;;;;;;;;;;;OAiBG;IACH,yBAAyB,CAAC,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EACvD,SAAS,EAAE,SAAS,EACpB,GAAG,OAAO,EAAE,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,GAChD,IAAI;CAkBR"}
|
package/dist/Messenger.d.mts
CHANGED
|
@@ -144,6 +144,18 @@ export declare class Messenger<Namespace extends string, Action extends ActionCo
|
|
|
144
144
|
* This prevents all actions from being called.
|
|
145
145
|
*/
|
|
146
146
|
clearActions(): void;
|
|
147
|
+
/**
|
|
148
|
+
* Get the action handler for a given action type.
|
|
149
|
+
*
|
|
150
|
+
* This is a protected method to allow subclasses to override the way action
|
|
151
|
+
* handlers are retrieved, for example to implement custom delegation logic.
|
|
152
|
+
*
|
|
153
|
+
* @param actionType - The action type. This is a unique identifier for this
|
|
154
|
+
* action.
|
|
155
|
+
* @returns The action handler for the given action type, or undefined if no
|
|
156
|
+
* handler has been registered.
|
|
157
|
+
*/
|
|
158
|
+
protected getAction(actionType: Action['type']): ActionConstraint['handler'] | undefined;
|
|
147
159
|
/**
|
|
148
160
|
* Call an action.
|
|
149
161
|
*
|
|
@@ -221,6 +233,120 @@ export declare class Messenger<Namespace extends string, Action extends ActionCo
|
|
|
221
233
|
* @template SelectorReturnValue - The selector return value.
|
|
222
234
|
*/
|
|
223
235
|
subscribe<EventType extends Event['type'], SelectorReturnValue>(eventType: EventType, handler: SelectorEventHandler<SelectorReturnValue>, selector: SelectorFunction<Event, EventType, SelectorReturnValue>): void;
|
|
236
|
+
/**
|
|
237
|
+
* Subscribe to an event, with a selector, invoking the handler exactly once.
|
|
238
|
+
*
|
|
239
|
+
* Registers the given handler function as an event handler for the given
|
|
240
|
+
* event type. When an event is published, its payload is first passed to the
|
|
241
|
+
* selector. The event handler is only called if the selector's return value
|
|
242
|
+
* differs from its last known return value. Additionally if the optional condition
|
|
243
|
+
* function is provided, it is checked whether it returns `true`.
|
|
244
|
+
* The handler is invoked at most once, after which the subscription is removed.
|
|
245
|
+
*
|
|
246
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
247
|
+
* @param handler - The event handler. The type of the parameters for this event
|
|
248
|
+
* handler must match the return type of the selector.
|
|
249
|
+
* @param options - Options bag.
|
|
250
|
+
* @param options.selector - The selector function used to select relevant data
|
|
251
|
+
* from the event payload. The type of the parameters for this selector must
|
|
252
|
+
* match the type of the payload for this event type.
|
|
253
|
+
* @param options.condition - An optional predicate evaluated against the
|
|
254
|
+
* selector's return value. The handler is only invoked when this returns `true`.
|
|
255
|
+
* @template EventType - A type union of Event type strings.
|
|
256
|
+
* @template SelectorReturnValue - The selector return value.
|
|
257
|
+
* @example
|
|
258
|
+
* ```typescript
|
|
259
|
+
* messenger.subscribeOnce(
|
|
260
|
+
* 'TransactionController:transactionConfirmed',
|
|
261
|
+
* (hash) => { ... },
|
|
262
|
+
* { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },
|
|
263
|
+
* );
|
|
264
|
+
* ```
|
|
265
|
+
*/
|
|
266
|
+
subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(eventType: EventType, handler: SelectorEventHandler<SelectorReturnValue>, options: {
|
|
267
|
+
selector: SelectorFunction<Event, EventType, SelectorReturnValue>;
|
|
268
|
+
condition?: (value: SelectorReturnValue) => boolean;
|
|
269
|
+
}): void;
|
|
270
|
+
/**
|
|
271
|
+
* Subscribe to an event, invoking the handler exactly once.
|
|
272
|
+
*
|
|
273
|
+
* Registers the given function as an event handler for the given event type
|
|
274
|
+
* and automatically unsubscribes after the first invocation.
|
|
275
|
+
*
|
|
276
|
+
* If `options.condition` is provided, the handler is only invoked (and the
|
|
277
|
+
* subscription only removed) when the condition returns `true`.
|
|
278
|
+
*
|
|
279
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
280
|
+
* @param handler - The event handler. The type of the parameters for this event
|
|
281
|
+
* handler must match the type of the payload for this event type.
|
|
282
|
+
* @param options - Options bag.
|
|
283
|
+
* @param options.condition - A predicate evaluated against the event payload.
|
|
284
|
+
* The handler is only invoked when this returns `true`.
|
|
285
|
+
* @template EventType - A type union of Event type strings.
|
|
286
|
+
* @example
|
|
287
|
+
* ```typescript
|
|
288
|
+
* messenger.subscribeOnce(
|
|
289
|
+
* 'TransactionController:transactionConfirmed',
|
|
290
|
+
* (tx) => { ... },
|
|
291
|
+
* { condition: (tx) => tx.hash === 'foo' },
|
|
292
|
+
* );
|
|
293
|
+
* ```
|
|
294
|
+
*/
|
|
295
|
+
subscribeOnce<EventType extends Event['type']>(eventType: EventType, handler: ExtractEventHandler<Event, EventType>, options?: {
|
|
296
|
+
condition?: (...payload: ExtractEventPayload<Event, EventType>) => boolean;
|
|
297
|
+
}): void;
|
|
298
|
+
/**
|
|
299
|
+
* Return a promise that resolves the next time the selector's return value
|
|
300
|
+
* changes and, if provided, the `options.condition` predicate returns `true`.
|
|
301
|
+
*
|
|
302
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
303
|
+
* @param options - Options bag.
|
|
304
|
+
* @param options.selector - The selector function used to select relevant data
|
|
305
|
+
* from the event payload.
|
|
306
|
+
* @param options.condition - An optional predicate evaluated against the
|
|
307
|
+
* selector's return value. The promise only resolves when this returns `true`.
|
|
308
|
+
* @template EventType - A type union of Event type strings.
|
|
309
|
+
* @template SelectorReturnValue - The selector return value.
|
|
310
|
+
* @returns A promise that resolves with the selector's return value.
|
|
311
|
+
* @example
|
|
312
|
+
* ```typescript
|
|
313
|
+
* const [hash] = await messenger.waitUntil(
|
|
314
|
+
* 'TransactionController:transactionConfirmed',
|
|
315
|
+
* { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },
|
|
316
|
+
* );
|
|
317
|
+
* ```
|
|
318
|
+
*/
|
|
319
|
+
waitUntil<EventType extends Event['type'], SelectorReturnValue>(eventType: EventType, options: {
|
|
320
|
+
selector: SelectorFunction<Event, EventType, SelectorReturnValue>;
|
|
321
|
+
condition?: (value: SelectorReturnValue) => boolean;
|
|
322
|
+
}): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;
|
|
323
|
+
/**
|
|
324
|
+
* Return a promise that resolves the next time the given event is published.
|
|
325
|
+
*
|
|
326
|
+
* If `options.condition` is provided, the promise only resolves when the
|
|
327
|
+
* condition returns `true`.
|
|
328
|
+
*
|
|
329
|
+
* @param eventType - The event type. This is a unique identifier for this event.
|
|
330
|
+
* @param options - Options bag.
|
|
331
|
+
* @param options.condition - A predicate evaluated against the event payload.
|
|
332
|
+
* The promise only resolves when this returns `true`.
|
|
333
|
+
* @template EventType - A type union of Event type strings.
|
|
334
|
+
* @returns A promise that resolves with the event payload.
|
|
335
|
+
* @example
|
|
336
|
+
* ```typescript
|
|
337
|
+
* const [transactionMeta] = await messenger.waitUntil(
|
|
338
|
+
* 'TransactionController:transactionConfirmed',
|
|
339
|
+
* { condition: (tx) => tx.hash === 'foo' },
|
|
340
|
+
* );
|
|
341
|
+
* ```
|
|
342
|
+
* @example
|
|
343
|
+
* ```typescript
|
|
344
|
+
* await messenger.waitUntil('KeyringController:unlock');
|
|
345
|
+
* ```
|
|
346
|
+
*/
|
|
347
|
+
waitUntil<EventType extends Event['type']>(eventType: EventType, options?: {
|
|
348
|
+
condition?: (...payload: ExtractEventPayload<Event, EventType>) => boolean;
|
|
349
|
+
}): Promise<ExtractEventPayload<Event, EventType>>;
|
|
224
350
|
/**
|
|
225
351
|
* Unsubscribe from an event.
|
|
226
352
|
*
|
package/dist/Messenger.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Messenger.d.mts","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,CACvB,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,CACF,GAAG,IAAI,EAAE,uBAAuB,CAAC,MAAM,EAAE,UAAU,CAAC,KACjD,qBAAqB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAE/C,MAAM,MAAM,uBAAuB,CACjC,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,MAAM,SAAS;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,WAAW,KAAK,OAAO,CAAC;CAClD,GACG,WAAW,GACX,KAAK,CAAC;AAEV,MAAM,MAAM,qBAAqB,CAC/B,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,MAAM,SAAS;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,MAAM,kBAAkB,CAAC;CACzD,GACG,kBAAkB,GAClB,KAAK,CAAC;AAEV,MAAM,MAAM,mBAAmB,CAC7B,KAAK,SAAS,eAAe,EAC7B,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,IACvB,KAAK,SAAS;IAChB,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,MAAM,OAAO,CAAC;CACxB,GACG,OAAO,SAAS,OAAO,EAAE,GACvB,CAAC,GAAG,OAAO,EAAE,OAAO,KAAK,IAAI,GAC7B,KAAK,GACP,KAAK,CAAC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MAAM,CAAC,MAAM,CAAC,EACvE,UAAU,EAAE,UAAU,EAItB,OAAO,EAAE,aAAa,CAAC,gBAAgB,EAAE,UAAU,CAAC,GACnD,IAAI;IAIP;;;;;;;;;;;;OAYG;IACH,yCAAyC,CAAC,UAAU,SAAS,MAAM,CAAC,MAAM,CAAC,EACzE,UAAU,EAAE,UAAU,GACrB,IAAI;IAIP;;;;;;;;;;;;;;;;OAgBG;IACH,6CAA6C,CAC3C,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EAC/B,EACA,SAAS,EACT,UAAU,GACX,EAAE;QACD,SAAS,EAAE,SAAS,CAAC;QACrB,UAAU,EAAE,MAAM,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;KACzD,GAAG,IAAI;IAIR;;;;;;;;;;;;;;;;;OAiBG;IACH,yBAAyB,CAAC,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EACvD,SAAS,EAAE,SAAS,EACpB,GAAG,OAAO,EAAE,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,GAChD,IAAI;CAkBR"}
|
package/dist/Messenger.mjs
CHANGED
|
@@ -142,6 +142,20 @@ export class Messenger {
|
|
|
142
142
|
__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_unregisterActionHandler).call(this, actionType);
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Get the action handler for a given action type.
|
|
147
|
+
*
|
|
148
|
+
* This is a protected method to allow subclasses to override the way action
|
|
149
|
+
* handlers are retrieved, for example to implement custom delegation logic.
|
|
150
|
+
*
|
|
151
|
+
* @param actionType - The action type. This is a unique identifier for this
|
|
152
|
+
* action.
|
|
153
|
+
* @returns The action handler for the given action type, or undefined if no
|
|
154
|
+
* handler has been registered.
|
|
155
|
+
*/
|
|
156
|
+
getAction(actionType) {
|
|
157
|
+
return __classPrivateFieldGet(this, _Messenger_actions, "f").get(actionType);
|
|
158
|
+
}
|
|
145
159
|
/**
|
|
146
160
|
* Call an action.
|
|
147
161
|
*
|
|
@@ -156,7 +170,7 @@ export class Messenger {
|
|
|
156
170
|
* @returns The action return value.
|
|
157
171
|
*/
|
|
158
172
|
call(actionType, ...params) {
|
|
159
|
-
const handler =
|
|
173
|
+
const handler = this.getAction(actionType);
|
|
160
174
|
if (!handler) {
|
|
161
175
|
throw new Error(__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_isInCurrentNamespace).call(this, actionType)
|
|
162
176
|
? `A handler for ${actionType} has not been registered`
|
|
@@ -239,6 +253,24 @@ export class Messenger {
|
|
|
239
253
|
}
|
|
240
254
|
}
|
|
241
255
|
}
|
|
256
|
+
subscribeOnce(eventType, handler, options) {
|
|
257
|
+
const { selector, condition } = options ?? {};
|
|
258
|
+
// Casting to unknown to handle both the code path where a selector is defined and where it is omitted.
|
|
259
|
+
const internalHandler = (...args) => {
|
|
260
|
+
if (condition &&
|
|
261
|
+
!condition(...args)) {
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
this.unsubscribe(eventType, internalHandler);
|
|
265
|
+
handler(...args);
|
|
266
|
+
};
|
|
267
|
+
this.subscribe(eventType, internalHandler, selector);
|
|
268
|
+
}
|
|
269
|
+
waitUntil(eventType, options) {
|
|
270
|
+
return new Promise((resolve) => {
|
|
271
|
+
this.subscribeOnce(eventType, (...args) => resolve(args), options);
|
|
272
|
+
});
|
|
273
|
+
}
|
|
242
274
|
/**
|
|
243
275
|
* Unsubscribe from an event.
|
|
244
276
|
*
|
|
@@ -332,7 +364,7 @@ export class Messenger {
|
|
|
332
364
|
const delegatedActionHandler = (...args) => {
|
|
333
365
|
// Cast to get more specific type, for this specific action
|
|
334
366
|
// The types get collapsed by `this.#actions`
|
|
335
|
-
const actionHandler =
|
|
367
|
+
const actionHandler = this.getAction(actionType);
|
|
336
368
|
if (!actionHandler) {
|
|
337
369
|
throw new Error(`A handler for ${actionType} has not been registered`);
|
|
338
370
|
}
|
package/dist/Messenger.mjs.map
CHANGED
|
@@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AI,WAAW,GAAG,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QACxB,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC,6EAsXqB,IAAY;IAChC,OAAO,CACL,uBAAA,IAAI,4BAAW,KAAK,kBAAkB;QACtC,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.#actions.get(actionType) as ActionHandler<\n Action,\n ActionType\n >;\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.#actions.get(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Messenger.mjs","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":";;;;;;;;;;;;AAgGA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAkFvD;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,SAAS;IAmEpB;;;;;;;;;;OAUG;IACH,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,MAAM,GASP;;QA5EQ,uCAAsB;QAE/B;;;WAGG;QACM,oCAA6B;QAE7B,6BAAW,IAAI,GAAG,EAAqC,EAAC;QAExD,4BAAU,IAAI,GAAG,EAA8C,EAAC;QAEzE;;WAEG;QACM,mDAAiC,IAAI,GAAG,EAG9C,EAAC;QAEJ;;WAEG;QACM,6CAA2B,IAAI,GAAG,EA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C,gBAAgB,CACnB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAC1D,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACvB,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC,uDAmFC,SAAkC,EAClC,OAEwB,EACxB,QAA+C;IAE/C,IAAI,WAAW,GAAG,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QACxB,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC,6EAqjBqB,IAAY;IAChC,OAAO,CACL,uBAAA,IAAI,4BAAW,KAAK,kBAAkB;QACtC,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Get the action handler for a given action type.\n *\n * This is a protected method to allow subclasses to override the way action\n * handlers are retrieved, for example to implement custom delegation logic.\n *\n * @param actionType - The action type. This is a unique identifier for this\n * action.\n * @returns The action handler for the given action type, or undefined if no\n * handler has been registered.\n */\n protected getAction(\n actionType: Action['type'],\n ): ActionConstraint['handler'] | undefined {\n return this.#actions.get(actionType);\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.getAction(actionType) as\n | ActionHandler<Action, ActionType>\n | undefined;\n\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Subscribe to an event, with a selector, invoking the handler exactly once.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value. Additionally if the optional condition\n * function is provided, it is checked whether it returns `true`.\n * The handler is invoked at most once, after which the subscription is removed.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload. The type of the parameters for this selector must\n * match the type of the payload for this event type.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (hash) => { ... },\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): void;\n\n /**\n * Subscribe to an event, invoking the handler exactly once.\n *\n * Registers the given function as an event handler for the given event type\n * and automatically unsubscribes after the first invocation.\n *\n * If `options.condition` is provided, the handler is only invoked (and the\n * subscription only removed) when the condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the type of the payload for this event type.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (tx) => { ... },\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): void;\n\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): void {\n const { selector, condition } = options ?? {};\n // Casting to unknown to handle both the code path where a selector is defined and where it is omitted.\n const internalHandler = (...args: unknown[]): void => {\n if (\n condition &&\n !(condition as (...args: unknown[]) => boolean)(...args)\n ) {\n return;\n }\n this.unsubscribe(eventType, internalHandler);\n (handler as (...args: unknown[]) => void)(...args);\n };\n\n this.subscribe(\n eventType,\n internalHandler,\n selector as SelectorFunction<Event, EventType, SelectorReturnValue>,\n );\n }\n\n /**\n * Return a promise that resolves the next time the selector's return value\n * changes and, if provided, the `options.condition` predicate returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @returns A promise that resolves with the selector's return value.\n * @example\n * ```typescript\n * const [hash] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;\n\n /**\n * Return a promise that resolves the next time the given event is published.\n *\n * If `options.condition` is provided, the promise only resolves when the\n * condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @returns A promise that resolves with the event payload.\n * @example\n * ```typescript\n * const [transactionMeta] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n * @example\n * ```typescript\n * await messenger.waitUntil('KeyringController:unlock');\n * ```\n */\n waitUntil<EventType extends Event['type']>(\n eventType: EventType,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): Promise<ExtractEventPayload<Event, EventType>>;\n\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): Promise<SelectorReturnValue | ExtractEventPayload<Event, EventType>[0]> {\n return new Promise((resolve) => {\n this.subscribeOnce(\n eventType,\n (...args) => resolve(args),\n options as {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n );\n });\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.getAction(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]}
|