@metamask-previews/messenger 0.0.0-preview-c3b78c5 → 0.0.0-preview-332b557

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 CHANGED
@@ -10,11 +10,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
10
10
  ### Added
11
11
 
12
12
  - Migrate `Messenger` class from `@metamask/base-controller` package ([#6127](https://github.com/MetaMask/core/pull/6127))
13
+ - Add `delegate` and `revoke` methods ([#6132](https://github.com/MetaMask/core/pull/6132))
14
+ - These allow delegating or revoking capabilities (actions or events) from one `Messenger` instance to another.
15
+ - This allows passing capabilities through chains of messengers of arbitrary length
16
+ - See this ADR for details: https://github.com/MetaMask/decisions/blob/main/decisions/core/0012-messenger-delegation.md
17
+ - Add `parent` constructor parameter and type parameter to `Messenger` ([#6142](https://github.com/MetaMask/core/pull/6142))
18
+ - All capabilities registered under this messenger's namespace are delegated to the parent automatically. This is similar to how the `RestrictedMessenger` would automatically delegate all capabilities to the messenger it was created from.
13
19
 
14
20
  ### Changed
15
21
 
22
+ - **BREAKING:** Add `Namespace` type parameter and required `namespace` constructor parameter ([#6132](https://github.com/MetaMask/core/pull/6132))
23
+ - All published events and registered actions should fall under the given namespace. Typically the namespace is the controller or service name. This is the equivalent to the `Namespace` parameter from the old `RestrictedMessenger` class.
24
+ - **BREAKING:** The `type` property of `ActionConstraint` and `EventConstraint` is now a `NamespacedName` rather than a string ([#6132](https://github.com/MetaMask/core/pull/6132))
16
25
  - Add default for `ReturnHandler` type parameter of `SelectorEventHandler` and `SelectorFunction` ([#6262](https://github.com/MetaMask/core/pull/6262), [#6264](https://github.com/MetaMask/core/pull/6264))
17
26
 
27
+ ### Removed
28
+
29
+ - **BREAKING:** Remove `RestrictedMessenger` class ([#6132](https://github.com/MetaMask/core/pull/6132))
30
+ - 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`.
31
+ - See this ADR for details: https://github.com/MetaMask/decisions/blob/main/decisions/core/0012-messenger-delegation.md
32
+
18
33
  ### Fixed
19
34
 
20
35
  - Update `unsubscribe` type signature to support selector event handlers ([#6262](https://github.com/MetaMask/core/pull/6262))
@@ -1,27 +1,59 @@
1
1
  "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
2
8
  var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
9
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
12
  };
7
- var _Messenger_actions, _Messenger_events, _Messenger_initialEventPayloadGetters, _Messenger_eventPayloadCache;
13
+ var _Messenger_instances, _Messenger_namespace, _Messenger_parent, _Messenger_actions, _Messenger_events, _Messenger_subscriptionDelegationTargets, _Messenger_actionDelegationTargets, _Messenger_initialEventPayloadGetters, _Messenger_eventPayloadCache, _Messenger_registerActionHandler, _Messenger_unregisterActionHandler, _Messenger_registerInitialEventPayload, _Messenger_publish, _Messenger_subscribe, _Messenger_isInCurrentNamespace;
8
14
  Object.defineProperty(exports, "__esModule", { value: true });
9
15
  exports.Messenger = void 0;
10
- const RestrictedMessenger_1 = require("./RestrictedMessenger.cjs");
11
16
  /**
12
17
  * A message broker for "actions" and "events".
13
18
  *
14
19
  * The messenger allows registering functions as 'actions' that can be called elsewhere,
15
20
  * and it allows publishing and subscribing to events. Both actions and events are identified by
16
- * unique strings.
21
+ * unique strings prefixed by a namespace (which is delimited by a colon, e.g.
22
+ * `Namespace:actionName`).
17
23
  *
18
24
  * @template Action - A type union of all Action types.
19
25
  * @template Event - A type union of all Event types.
26
+ * @template Namespace - The namespace for the messenger.
20
27
  */
21
28
  class Messenger {
22
- constructor() {
29
+ /**
30
+ * Construct a messenger.
31
+ *
32
+ * If a parent messenger is given, all actions and events under this messenger's namespace will
33
+ * be delegated to the parent automatically.
34
+ *
35
+ * @param args - Constructor arguments
36
+ * @param args.namespace - The messenger namespace.
37
+ * @param args.parent - The parent messenger.
38
+ */
39
+ constructor({ namespace, parent, }) {
40
+ _Messenger_instances.add(this);
41
+ _Messenger_namespace.set(this, void 0);
42
+ /**
43
+ * The parent messenger. All actions/events under this namespace are automatically delegated to
44
+ * the parent messenger.
45
+ */
46
+ _Messenger_parent.set(this, void 0);
23
47
  _Messenger_actions.set(this, new Map());
24
48
  _Messenger_events.set(this, new Map());
49
+ /**
50
+ * The set of messengers we've delegated events to and their event handlers, by event type.
51
+ */
52
+ _Messenger_subscriptionDelegationTargets.set(this, new Map());
53
+ /**
54
+ * The set of messengers we've delegated actions to, by action type.
55
+ */
56
+ _Messenger_actionDelegationTargets.set(this, new Map());
25
57
  /**
26
58
  * A map of functions for getting the initial event payload.
27
59
  *
@@ -32,23 +64,33 @@ class Messenger {
32
64
  * A cache of selector return values for their respective handlers.
33
65
  */
34
66
  _Messenger_eventPayloadCache.set(this, new Map());
67
+ __classPrivateFieldSet(this, _Messenger_namespace, namespace, "f");
68
+ __classPrivateFieldSet(this, _Messenger_parent, parent, "f");
35
69
  }
36
70
  /**
37
71
  * Register an action handler.
38
72
  *
39
73
  * This will make the registered function available to call via the `call` method.
40
74
  *
75
+ * The action being registered must be under the same namespace as the messenger.
76
+ *
41
77
  * @param actionType - The action type. This is a unique identifier for this action.
42
78
  * @param handler - The action handler. This function gets called when the `call` method is
43
79
  * invoked with the given action type.
44
80
  * @throws Will throw when a handler has been registered for this action type already.
45
- * @template ActionType - A type union of Action type strings.
81
+ * @template ActionType - A type union of Action type strings under this messenger's namespace.
46
82
  */
47
83
  registerActionHandler(actionType, handler) {
48
- if (__classPrivateFieldGet(this, _Messenger_actions, "f").has(actionType)) {
49
- throw new Error(`A handler for ${actionType} has already been registered`);
84
+ /* istanbul ignore if */ // Branch unreachable with valid types
85
+ if (!__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_isInCurrentNamespace).call(this, actionType)) {
86
+ throw new Error(`Only allowed registering action handlers prefixed by '${__classPrivateFieldGet(this, _Messenger_namespace, "f")}:'`);
87
+ }
88
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_registerActionHandler).call(this, actionType, handler);
89
+ if (__classPrivateFieldGet(this, _Messenger_parent, "f")) {
90
+ // @ts-expect-error The parent type isn't constructed in a way that proves it supports this
91
+ // action, but this is OK because it's validated in the constructor.
92
+ this.delegate({ actions: [actionType], messenger: __classPrivateFieldGet(this, _Messenger_parent, "f") });
50
93
  }
51
- __classPrivateFieldGet(this, _Messenger_actions, "f").set(actionType, handler);
52
94
  }
53
95
  /**
54
96
  * Registers action handlers for a list of methods on a messenger client
@@ -73,11 +115,17 @@ class Messenger {
73
115
  *
74
116
  * This will prevent this action from being called.
75
117
  *
118
+ * The action being unregistered must be under the same namespace as the messenger.
119
+ *
76
120
  * @param actionType - The action type. This is a unique identifier for this action.
77
- * @template ActionType - A type union of Action type strings.
121
+ * @template ActionType - A type union of Action type strings under this messenger's namespace.
78
122
  */
79
123
  unregisterActionHandler(actionType) {
80
- __classPrivateFieldGet(this, _Messenger_actions, "f").delete(actionType);
124
+ /* istanbul ignore if */ // Branch unreachable with valid types
125
+ if (!__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_isInCurrentNamespace).call(this, actionType)) {
126
+ throw new Error(`Only allowed unregistering action handlers prefixed by '${__classPrivateFieldGet(this, _Messenger_namespace, "f")}:'`);
127
+ }
128
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_unregisterActionHandler).call(this, actionType);
81
129
  }
82
130
  /**
83
131
  * Unregister all action handlers.
@@ -85,7 +133,9 @@ class Messenger {
85
133
  * This prevents all actions from being called.
86
134
  */
87
135
  clearActions() {
88
- __classPrivateFieldGet(this, _Messenger_actions, "f").clear();
136
+ for (const actionType of __classPrivateFieldGet(this, _Messenger_actions, "f").keys()) {
137
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_unregisterActionHandler).call(this, actionType);
138
+ }
89
139
  }
90
140
  /**
91
141
  * Call an action.
@@ -114,13 +164,25 @@ class Messenger {
114
164
  * Registering a function for getting the payload allows event selectors to have a point of
115
165
  * comparison the first time state changes.
116
166
  *
167
+ * The event type must be under the same namespace as the messenger.
168
+ *
117
169
  * @param args - The arguments to this function
118
170
  * @param args.eventType - The event type to register a payload for.
119
171
  * @param args.getPayload - A function for retrieving the event payload.
120
- * @template EventType - A type union of Event type strings.
172
+ * @template EventType - A type union of Event type strings under this messenger's namespace.
121
173
  */
122
174
  registerInitialEventPayload({ eventType, getPayload, }) {
123
- __classPrivateFieldGet(this, _Messenger_initialEventPayloadGetters, "f").set(eventType, getPayload);
175
+ /* istanbul ignore if */ // Branch unreachable with valid types
176
+ if (!__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_isInCurrentNamespace).call(this, eventType)) {
177
+ throw new Error(`Only allowed registering initial payloads for events prefixed by '${__classPrivateFieldGet(this, _Messenger_namespace, "f")}:'`);
178
+ }
179
+ if (__classPrivateFieldGet(this, _Messenger_parent, "f") &&
180
+ !__classPrivateFieldGet(this, _Messenger_subscriptionDelegationTargets, "f").get(eventType)?.has(__classPrivateFieldGet(this, _Messenger_parent, "f"))) {
181
+ // @ts-expect-error The parent type isn't constructed in a way that proves it supports this
182
+ // event, but this is OK because it's validated in the constructor.
183
+ this.delegate({ events: [eventType], messenger: __classPrivateFieldGet(this, _Messenger_parent, "f") });
184
+ }
185
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_registerInitialEventPayload).call(this, { eventType, getPayload });
124
186
  }
125
187
  /**
126
188
  * Publish an event.
@@ -130,48 +192,31 @@ class Messenger {
130
192
  * Note that this method should never throw directly. Any errors from
131
193
  * subscribers are captured and re-thrown in a timeout handler.
132
194
  *
195
+ * The event being published must be under the same namespace as the messenger.
196
+ *
133
197
  * @param eventType - The event type. This is a unique identifier for this event.
134
198
  * @param payload - The event payload. The type of the parameters for each event handler must
135
199
  * match the type of this payload.
136
- * @template EventType - A type union of Event type strings.
200
+ * @template EventType - A type union of Event type strings under this messenger's namespace.
137
201
  */
138
202
  publish(eventType, ...payload) {
139
- const subscribers = __classPrivateFieldGet(this, _Messenger_events, "f").get(eventType);
140
- if (subscribers) {
141
- for (const [handler, { selector }] of subscribers.entries()) {
142
- try {
143
- if (selector) {
144
- const previousValue = __classPrivateFieldGet(this, _Messenger_eventPayloadCache, "f").get(handler);
145
- const newValue = selector(...payload);
146
- if (newValue !== previousValue) {
147
- __classPrivateFieldGet(this, _Messenger_eventPayloadCache, "f").set(handler, newValue);
148
- handler(newValue, previousValue);
149
- }
150
- }
151
- else {
152
- handler(...payload);
153
- }
154
- }
155
- catch (error) {
156
- // Throw error after timeout so that it is capured as a console error
157
- // (and by Sentry) without interrupting the event publishing.
158
- setTimeout(() => {
159
- throw error;
160
- });
161
- }
162
- }
203
+ /* istanbul ignore if */ // Branch unreachable with valid types
204
+ if (!__classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_isInCurrentNamespace).call(this, eventType)) {
205
+ throw new Error(`Only allowed publishing events prefixed by '${__classPrivateFieldGet(this, _Messenger_namespace, "f")}:'`);
206
+ }
207
+ if (__classPrivateFieldGet(this, _Messenger_parent, "f") &&
208
+ !__classPrivateFieldGet(this, _Messenger_subscriptionDelegationTargets, "f").get(eventType)?.has(__classPrivateFieldGet(this, _Messenger_parent, "f"))) {
209
+ // @ts-expect-error The parent type isn't constructed in a way that proves it supports this
210
+ // event, but this is OK because it's validated in the constructor.
211
+ this.delegate({ events: [eventType], messenger: __classPrivateFieldGet(this, _Messenger_parent, "f") });
163
212
  }
213
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_publish).call(this, eventType, ...payload);
164
214
  }
165
215
  subscribe(eventType, handler, selector) {
166
- let subscribers = __classPrivateFieldGet(this, _Messenger_events, "f").get(eventType);
167
- if (!subscribers) {
168
- subscribers = new Map();
169
- __classPrivateFieldGet(this, _Messenger_events, "f").set(eventType, subscribers);
170
- }
171
216
  // Widen type of event handler by dropping ReturnType parameter.
172
217
  //
173
218
  // We need to drop it here because it's used as the parameter to the event handler, and
174
- // functions in general are contravarient over the parameter type. This means the type is no
219
+ // functions in general are contravariant over the parameter type. This means the type is no
175
220
  // longer valid once it's added to a broader type union with other handlers (because as far
176
221
  // as TypeScript knows, we might call the handler with output from a different selector).
177
222
  //
@@ -180,7 +225,7 @@ class Messenger {
180
225
  // called, but past that point we need to make sure of that with manual review and tests
181
226
  // instead.
182
227
  const widenedHandler = handler;
183
- subscribers.set(widenedHandler, { selector });
228
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_subscribe).call(this, eventType, widenedHandler, { delegation: false, selector });
184
229
  if (selector) {
185
230
  const getPayload = __classPrivateFieldGet(this, _Messenger_initialEventPayloadGetters, "f").get(eventType);
186
231
  if (getPayload) {
@@ -205,17 +250,20 @@ class Messenger {
205
250
  // Widen type of event handler by dropping ReturnType parameter.
206
251
  //
207
252
  // We need to drop it here because it's used as the parameter to the event handler, and
208
- // functions in general are contravarient over the parameter type. This means the type is no
253
+ // functions in general are contravariant over the parameter type. This means the type is no
209
254
  // longer valid once it's added to a broader type union with other handlers (because as far
210
255
  // as TypeScript knows, we might call the handler with output from a different selector).
211
256
  //
212
257
  // This poses no risk in this case, since we never call the handler past this point.
213
258
  const widenedHandler = handler;
214
- if (!subscribers || !subscribers.has(widenedHandler)) {
259
+ if (!subscribers) {
215
260
  throw new Error(`Subscription not found for event: ${eventType}`);
216
261
  }
217
262
  const metadata = subscribers.get(widenedHandler);
218
- if (metadata?.selector) {
263
+ if (!metadata) {
264
+ throw new Error(`Subscription not found for event: ${eventType}`);
265
+ }
266
+ if (metadata.selector) {
219
267
  __classPrivateFieldGet(this, _Messenger_eventPayloadCache, "f").delete(widenedHandler);
220
268
  }
221
269
  subscribers.delete(widenedHandler);
@@ -223,57 +271,298 @@ class Messenger {
223
271
  /**
224
272
  * Clear subscriptions for a specific event.
225
273
  *
226
- * This will remove all subscribed handlers for this event.
274
+ * This will remove all subscribed handlers for this event registered from this messenger. The
275
+ * event may still have subscribers if it has been delegated to another messenger.
227
276
  *
228
277
  * @param eventType - The event type. This is a unique identifier for this event.
229
278
  * @template EventType - A type union of Event type strings.
230
279
  */
231
280
  clearEventSubscriptions(eventType) {
232
- __classPrivateFieldGet(this, _Messenger_events, "f").delete(eventType);
281
+ const subscriptions = __classPrivateFieldGet(this, _Messenger_events, "f").get(eventType);
282
+ if (!subscriptions) {
283
+ return;
284
+ }
285
+ for (const [handler, metadata] of subscriptions.entries()) {
286
+ if (metadata.delegation) {
287
+ continue;
288
+ }
289
+ subscriptions.delete(handler);
290
+ }
291
+ if (subscriptions.size === 0) {
292
+ __classPrivateFieldGet(this, _Messenger_events, "f").delete(eventType);
293
+ }
233
294
  }
234
295
  /**
235
296
  * Clear all subscriptions.
236
297
  *
237
- * This will remove all subscribed handlers for all events.
298
+ * This will remove all subscribed handlers for all events registered from this messenger. Events
299
+ * may still have subscribers if they are delegated to another messenger.
238
300
  */
239
301
  clearSubscriptions() {
240
- __classPrivateFieldGet(this, _Messenger_events, "f").clear();
302
+ for (const eventType of __classPrivateFieldGet(this, _Messenger_events, "f").keys()) {
303
+ this.clearEventSubscriptions(eventType);
304
+ }
241
305
  }
242
306
  /**
243
- * Get a restricted messenger
244
- *
245
- * Returns a wrapper around the messenger instance that restricts access to actions and events.
246
- * The provided allowlists grant the ability to call the listed actions and subscribe to the
247
- * listed events. The "name" provided grants ownership of any actions and events under that
248
- * namespace. Ownership allows registering actions and publishing events, as well as
249
- * unregistering actions and clearing event subscriptions.
250
- *
251
- * @param options - Messenger options.
252
- * @param options.name - The name of the thing this messenger will be handed to (e.g. the
253
- * controller name). This grants "ownership" of actions and events under this namespace to the
254
- * restricted messenger returned.
255
- * @param options.allowedActions - The list of actions that this restricted messenger should be
256
- * allowed to call.
257
- * @param options.allowedEvents - The list of events that this restricted messenger should be
258
- * allowed to subscribe to.
259
- * @template Namespace - The namespace for this messenger. Typically this is the name of the
260
- * module that this messenger has been created for. The authority to publish events and register
261
- * actions under this namespace is granted to this restricted messenger instance.
262
- * @template AllowedAction - A type union of the 'type' string for any allowed actions.
263
- * This must not include internal actions that are in the messenger's namespace.
264
- * @template AllowedEvent - A type union of the 'type' string for any allowed events.
265
- * This must not include internal events that are in the messenger's namespace.
266
- * @returns The restricted messenger.
307
+ * Delegate actions and/or events to another messenger.
308
+ *
309
+ * The messenger these actions/events are delegated to will be able to call these actions and
310
+ * subscribe to these events.
311
+ *
312
+ * Note that the messenger these actions/events are delegated to must still have these
313
+ * actions/events included in its type definition (as part of the Action and Event type
314
+ * parameters). Actions and events are statically type checked, they cannot be delegated
315
+ * dynamically at runtime.
316
+ *
317
+ * @param args - Arguments.
318
+ * @param args.actions - The action types to delegate.
319
+ * @param args.events - The event types to delegate.
320
+ * @param args.messenger - The messenger to delegate to.
321
+ * @template Delegatee - The messenger the actions/events are delegated to.
322
+ * @template DelegatedActions - An array of delegated action types.
323
+ * @template DelegatedEvents - An array of delegated event types.
267
324
  */
268
- getRestricted({ name, allowedActions, allowedEvents, }) {
269
- return new RestrictedMessenger_1.RestrictedMessenger({
270
- messenger: this,
271
- name,
272
- allowedActions,
273
- allowedEvents,
274
- });
325
+ delegate({ actions, events, messenger, }) {
326
+ for (const actionType of actions || []) {
327
+ const delegatedActionHandler = (...args) => {
328
+ // Cast to get more specific type, for this specific action
329
+ // The types get collapsed by `this.#actions`
330
+ const actionHandler = __classPrivateFieldGet(this, _Messenger_actions, "f").get(actionType);
331
+ if (!actionHandler) {
332
+ throw new Error(`Cannot call '${actionType}', action not registered.`);
333
+ }
334
+ return actionHandler(...args);
335
+ };
336
+ let delegationTargets = __classPrivateFieldGet(this, _Messenger_actionDelegationTargets, "f").get(actionType);
337
+ if (!delegationTargets) {
338
+ delegationTargets = new Set();
339
+ __classPrivateFieldGet(this, _Messenger_actionDelegationTargets, "f").set(actionType, delegationTargets);
340
+ }
341
+ if (delegationTargets.has(messenger)) {
342
+ throw new Error(`The action '${actionType}' has already been delegated to this messenger`);
343
+ }
344
+ delegationTargets.add(messenger);
345
+ messenger._internalRegisterDelegatedActionHandler(actionType, delegatedActionHandler);
346
+ }
347
+ for (const eventType of events || []) {
348
+ const untypedSubscriber = (...payload) => {
349
+ messenger._internalPublishDelegated(eventType, ...payload);
350
+ };
351
+ // Cast to get more specific subscriber type for this specific event.
352
+ // The types get collapsed here to the type union of all delegated
353
+ // events, rather than the single subscriber type corresponding to this
354
+ // event.
355
+ const subscriber = untypedSubscriber;
356
+ let delegatedEventSubscriptions = __classPrivateFieldGet(this, _Messenger_subscriptionDelegationTargets, "f").get(eventType);
357
+ if (!delegatedEventSubscriptions) {
358
+ delegatedEventSubscriptions = new Map();
359
+ __classPrivateFieldGet(this, _Messenger_subscriptionDelegationTargets, "f").set(eventType, delegatedEventSubscriptions);
360
+ }
361
+ if (delegatedEventSubscriptions.has(messenger)) {
362
+ throw new Error(`The event '${eventType}' has already been delegated to this messenger`);
363
+ }
364
+ delegatedEventSubscriptions.set(messenger, subscriber);
365
+ const getPayload = __classPrivateFieldGet(this, _Messenger_initialEventPayloadGetters, "f").get(eventType);
366
+ if (getPayload) {
367
+ messenger._internalRegisterDelegatedInitialEventPayload({
368
+ eventType,
369
+ getPayload,
370
+ });
371
+ }
372
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_subscribe).call(this, eventType, subscriber, { delegation: true });
373
+ }
374
+ }
375
+ /**
376
+ * Revoke delegated actions and/or events from another messenger.
377
+ *
378
+ * The messenger these actions/events are delegated to will no longer be able to call these
379
+ * actions or subscribe to these events.
380
+ *
381
+ * @param args - Arguments.
382
+ * @param args.actions - The action types to revoke.
383
+ * @param args.events - The event types to revoke.
384
+ * @param args.messenger - The messenger these actions/events were delegated to.
385
+ * @template Delegatee - The messenger the actions/events are being revoked from.
386
+ * @template DelegatedActions - An array of delegated action types.
387
+ * @template DelegatedEvents - An array of delegated event types.
388
+ */
389
+ revoke({ actions, events, messenger, }) {
390
+ if (messenger === __classPrivateFieldGet(this, _Messenger_parent, "f")) {
391
+ throw new Error('Cannot revoke from parent');
392
+ }
393
+ for (const actionType of actions || []) {
394
+ const delegationTargets = __classPrivateFieldGet(this, _Messenger_actionDelegationTargets, "f").get(actionType);
395
+ if (!delegationTargets || !delegationTargets.has(messenger)) {
396
+ // Nothing to revoke
397
+ continue;
398
+ }
399
+ messenger._internalUnregisterDelegatedActionHandler(actionType);
400
+ delegationTargets.delete(messenger);
401
+ if (delegationTargets.size === 0) {
402
+ __classPrivateFieldGet(this, _Messenger_actionDelegationTargets, "f").delete(actionType);
403
+ }
404
+ }
405
+ for (const eventType of events || []) {
406
+ const delegationTargets = __classPrivateFieldGet(this, _Messenger_subscriptionDelegationTargets, "f").get(eventType);
407
+ if (!delegationTargets) {
408
+ // Nothing to revoke
409
+ continue;
410
+ }
411
+ const delegatedSubscriber = delegationTargets.get(messenger);
412
+ if (!delegatedSubscriber) {
413
+ // Nothing to revoke
414
+ continue;
415
+ }
416
+ this.unsubscribe(eventType, delegatedSubscriber);
417
+ delegationTargets.delete(messenger);
418
+ if (delegationTargets.size === 0) {
419
+ __classPrivateFieldGet(this, _Messenger_subscriptionDelegationTargets, "f").delete(eventType);
420
+ }
421
+ }
422
+ }
423
+ /**
424
+ * Register an action handler for an action delegated from another messenger.
425
+ *
426
+ * This will make the registered function available to call via the `call` method.
427
+ *
428
+ * Note: This is an internal method. Never access this property from another module. This must be
429
+ * exposed as a public property so that these methods can be called internally on other messenger
430
+ * instances.
431
+ *
432
+ * @deprecated Internal use only. Use the `delegate` method for delegation.
433
+ * @param actionType - The action type. This is a unique identifier for this action.
434
+ * @param handler - The action handler. This function gets called when the `call` method is
435
+ * invoked with the given action type.
436
+ * @throws Will throw when a handler has been registered for this action type already.
437
+ * @template ActionType - A type union of Action type strings.
438
+ */
439
+ _internalRegisterDelegatedActionHandler(actionType,
440
+ // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is
441
+ // contravariant over the handler parameter type. Using `Action` would lead to a type error
442
+ // here because the messenger we've delegated to supports _additional_ actions.
443
+ handler) {
444
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_registerActionHandler).call(this, actionType, handler);
445
+ }
446
+ /**
447
+ * Unregister an action handler for an action delegated from another messenger.
448
+ *
449
+ * This will prevent this action from being called.
450
+ *
451
+ * Note: This is an internal method. Never access this property from another module. This must be
452
+ * exposed as a public property so that these methods can be called internally on other messenger
453
+ * instances.
454
+ *
455
+ * @deprecated Internal use only. Use the `delegate` method for delegation.
456
+ * @param actionType - The action type. This is a unqiue identifier for this action.
457
+ * @template ActionType - A type union of Action type strings.
458
+ */
459
+ _internalUnregisterDelegatedActionHandler(actionType) {
460
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_unregisterActionHandler).call(this, actionType);
461
+ }
462
+ /**
463
+ * Register a function for getting the initial payload for an event that has been delegated from
464
+ * another messenger.
465
+ *
466
+ * This is used for events that represent a state change, where the payload is the state.
467
+ * Registering a function for getting the payload allows event selectors to have a point of
468
+ * comparison the first time state changes.
469
+ *
470
+ * Note: This is an internal method. Never access this property from another module. This must be
471
+ * exposed as a public property so that these methods can be called internally on other messenger
472
+ * instances.
473
+ *
474
+ * @deprecated Internal use only. Use the `delegate` method for delegation.
475
+ * @param args - The arguments to this function
476
+ * @param args.eventType - The event type to register a payload for.
477
+ * @param args.getPayload - A function for retrieving the event payload.
478
+ */
479
+ _internalRegisterDelegatedInitialEventPayload({ eventType, getPayload, }) {
480
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_registerInitialEventPayload).call(this, { eventType, getPayload });
481
+ }
482
+ /**
483
+ * Publish an event that was delegated from another messenger.
484
+ *
485
+ * Publishes the given payload to all subscribers of the given event type.
486
+ *
487
+ * Note that this method should never throw directly. Any errors from
488
+ * subscribers are captured and re-thrown in a timeout handler.
489
+ *
490
+ * Note: This is an internal method. Never access this property from another module. This must be
491
+ * exposed as a public property so that these methods can be called internally on other messenger
492
+ * instances.
493
+ *
494
+ * @deprecated Internal use only. Use the `delegate` method for delegation.
495
+ * @param eventType - The event type. This is a unique identifier for this event.
496
+ * @param payload - The event payload. The type of the parameters for each event handler must
497
+ * match the type of this payload.
498
+ * @template EventType - A type union of Event type strings.
499
+ */
500
+ _internalPublishDelegated(eventType, ...payload) {
501
+ __classPrivateFieldGet(this, _Messenger_instances, "m", _Messenger_publish).call(this, eventType, ...payload);
275
502
  }
276
503
  }
277
504
  exports.Messenger = Messenger;
278
- _Messenger_actions = new WeakMap(), _Messenger_events = new WeakMap(), _Messenger_initialEventPayloadGetters = new WeakMap(), _Messenger_eventPayloadCache = new WeakMap();
505
+ _Messenger_namespace = new WeakMap(), _Messenger_parent = new WeakMap(), _Messenger_actions = new WeakMap(), _Messenger_events = new WeakMap(), _Messenger_subscriptionDelegationTargets = new WeakMap(), _Messenger_actionDelegationTargets = new WeakMap(), _Messenger_initialEventPayloadGetters = new WeakMap(), _Messenger_eventPayloadCache = new WeakMap(), _Messenger_instances = new WeakSet(), _Messenger_registerActionHandler = function _Messenger_registerActionHandler(actionType, handler) {
506
+ if (__classPrivateFieldGet(this, _Messenger_actions, "f").has(actionType)) {
507
+ throw new Error(`A handler for ${actionType} has already been registered`);
508
+ }
509
+ __classPrivateFieldGet(this, _Messenger_actions, "f").set(actionType, handler);
510
+ }, _Messenger_unregisterActionHandler = function _Messenger_unregisterActionHandler(actionType) {
511
+ __classPrivateFieldGet(this, _Messenger_actions, "f").delete(actionType);
512
+ const delegationTargets = __classPrivateFieldGet(this, _Messenger_actionDelegationTargets, "f").get(actionType);
513
+ if (!delegationTargets) {
514
+ return;
515
+ }
516
+ for (const messenger of delegationTargets) {
517
+ messenger._internalUnregisterDelegatedActionHandler(actionType);
518
+ }
519
+ __classPrivateFieldGet(this, _Messenger_actionDelegationTargets, "f").delete(actionType);
520
+ }, _Messenger_registerInitialEventPayload = function _Messenger_registerInitialEventPayload({ eventType, getPayload, }) {
521
+ __classPrivateFieldGet(this, _Messenger_initialEventPayloadGetters, "f").set(eventType, getPayload);
522
+ const delegationTargets = __classPrivateFieldGet(this, _Messenger_subscriptionDelegationTargets, "f").get(eventType);
523
+ if (!delegationTargets) {
524
+ return;
525
+ }
526
+ for (const messenger of delegationTargets.keys()) {
527
+ messenger._internalRegisterDelegatedInitialEventPayload({
528
+ eventType,
529
+ getPayload,
530
+ });
531
+ }
532
+ }, _Messenger_publish = function _Messenger_publish(eventType, ...payload) {
533
+ const subscribers = __classPrivateFieldGet(this, _Messenger_events, "f").get(eventType);
534
+ if (subscribers) {
535
+ for (const [handler, { selector }] of subscribers.entries()) {
536
+ try {
537
+ if (selector) {
538
+ const previousValue = __classPrivateFieldGet(this, _Messenger_eventPayloadCache, "f").get(handler);
539
+ const newValue = selector(...payload);
540
+ if (newValue !== previousValue) {
541
+ __classPrivateFieldGet(this, _Messenger_eventPayloadCache, "f").set(handler, newValue);
542
+ handler(newValue, previousValue);
543
+ }
544
+ }
545
+ else {
546
+ handler(...payload);
547
+ }
548
+ }
549
+ catch (error) {
550
+ // Throw error after timeout so that it is capured as a console error
551
+ // (and by Sentry) without interrupting the event publishing.
552
+ setTimeout(() => {
553
+ throw error;
554
+ });
555
+ }
556
+ }
557
+ }
558
+ }, _Messenger_subscribe = function _Messenger_subscribe(eventType, handler, metadata) {
559
+ let subscribers = __classPrivateFieldGet(this, _Messenger_events, "f").get(eventType);
560
+ if (!subscribers) {
561
+ subscribers = new Map();
562
+ __classPrivateFieldGet(this, _Messenger_events, "f").set(eventType, subscribers);
563
+ }
564
+ subscribers.set(handler, metadata);
565
+ }, _Messenger_isInCurrentNamespace = function _Messenger_isInCurrentNamespace(name) {
566
+ return name.startsWith(`${__classPrivateFieldGet(this, _Messenger_namespace, "f")}:`);
567
+ };
279
568
  //# sourceMappingURL=Messenger.cjs.map