@metamask-previews/messenger 0.0.0-preview-3713f9f

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.
@@ -0,0 +1,196 @@
1
+ import type { ActionConstraint, ActionHandler, Messenger, EventConstraint, ExtractActionParameters, ExtractActionResponse, ExtractEventHandler, ExtractEventPayload, NamespacedName, NotNamespacedBy, SelectorEventHandler, SelectorFunction } from "./Messenger.mjs";
2
+ /**
3
+ * A universal supertype of all `RestrictedMessenger` instances. This type can be assigned to any
4
+ * `RestrictedMessenger` type.
5
+ *
6
+ * @template Namespace - Name of the module this messenger is for. Optionally can be used to
7
+ * narrow this type to a constraint for the messenger of a specific module.
8
+ */
9
+ export type RestrictedMessengerConstraint<Namespace extends string = string> = RestrictedMessenger<Namespace, ActionConstraint, EventConstraint, string, string>;
10
+ /**
11
+ * A restricted messenger.
12
+ *
13
+ * This acts as a wrapper around the messenger instance that restricts access to actions
14
+ * and events.
15
+ *
16
+ * @template Namespace - The namespace for this messenger. Typically this is the name of the controller or
17
+ * module that this messenger has been created for. The authority to publish events and register
18
+ * actions under this namespace is granted to this restricted messenger instance.
19
+ * @template Action - A type union of all Action types.
20
+ * @template Event - A type union of all Event types.
21
+ * @template AllowedAction - A type union of the 'type' string for any allowed actions.
22
+ * This must not include internal actions that are in the messenger's namespace.
23
+ * @template AllowedEvent - A type union of the 'type' string for any allowed events.
24
+ * This must not include internal events that are in the messenger's namespace.
25
+ */
26
+ export declare class RestrictedMessenger<Namespace extends string, Action extends ActionConstraint, Event extends EventConstraint, AllowedAction extends string, AllowedEvent extends string> {
27
+ #private;
28
+ /**
29
+ * Constructs a restricted messenger
30
+ *
31
+ * The provided allowlists grant the ability to call the listed actions and subscribe to the
32
+ * listed events. The "name" provided grants ownership of any actions and events under that
33
+ * namespace. Ownership allows registering actions and publishing events, as well as
34
+ * unregistering actions and clearing event subscriptions.
35
+ *
36
+ * @param options - Options.
37
+ * @param options.messenger - The messenger instance that is being wrapped.
38
+ * @param options.name - The name of the thing this messenger will be handed to (e.g. the
39
+ * controller name). This grants "ownership" of actions and events under this namespace to the
40
+ * restricted messenger returned.
41
+ * @param options.allowedActions - The list of actions that this restricted messenger should be
42
+ * allowed to call.
43
+ * @param options.allowedEvents - The list of events that this restricted messenger should be
44
+ * allowed to subscribe to.
45
+ */
46
+ constructor({ messenger, name, allowedActions, allowedEvents, }: {
47
+ messenger?: Messenger<ActionConstraint, EventConstraint>;
48
+ name: Namespace;
49
+ allowedActions: NotNamespacedBy<Namespace, AllowedAction>[];
50
+ allowedEvents: NotNamespacedBy<Namespace, AllowedEvent>[];
51
+ });
52
+ /**
53
+ * Register an action handler.
54
+ *
55
+ * This will make the registered function available to call via the `call` method.
56
+ *
57
+ * The action type this handler is registered under *must* be in the current namespace.
58
+ *
59
+ * @param action - The action type. This is a unique identifier for this action.
60
+ * @param handler - The action handler. This function gets called when the `call` method is
61
+ * invoked with the given action type.
62
+ * @throws Will throw if an action handler that is not in the current namespace is being registered.
63
+ * @template ActionType - A type union of Action type strings that are namespaced by Namespace.
64
+ */
65
+ registerActionHandler<ActionType extends Action['type'] & NamespacedName<Namespace>>(action: ActionType, handler: ActionHandler<Action, ActionType>): void;
66
+ /**
67
+ * Registers action handlers for a list of methods on a messenger client
68
+ *
69
+ * @param messengerClient - The object that is expected to make use of the messenger.
70
+ * @param methodNames - The names of the methods on the messenger client to register as action
71
+ * handlers
72
+ */
73
+ registerMethodActionHandlers<MessengerClient extends {
74
+ name: string;
75
+ }, MethodNames extends keyof MessengerClient & string>(messengerClient: MessengerClient, methodNames: readonly MethodNames[]): void;
76
+ /**
77
+ * Unregister an action handler.
78
+ *
79
+ * This will prevent this action from being called.
80
+ *
81
+ * The action type being unregistered *must* be in the current namespace.
82
+ *
83
+ * @param action - The action type. This is a unique identifier for this action.
84
+ * @throws Will throw if an action handler that is not in the current namespace is being unregistered.
85
+ * @template ActionType - A type union of Action type strings that are namespaced by Namespace.
86
+ */
87
+ unregisterActionHandler<ActionType extends Action['type'] & NamespacedName<Namespace>>(action: ActionType): void;
88
+ /**
89
+ * Call an action.
90
+ *
91
+ * This function will call the action handler corresponding to the given action type, passing
92
+ * along any parameters given.
93
+ *
94
+ * The action type being called must be on the action allowlist.
95
+ *
96
+ * @param actionType - The action type. This is a unique identifier for this action.
97
+ * @param params - The action parameters. These must match the type of the parameters of the
98
+ * registered action handler.
99
+ * @throws Will throw when no handler has been registered for the given type.
100
+ * @template ActionType - A type union of allowed Action type strings.
101
+ * @returns The action return value.
102
+ */
103
+ call<ActionType extends AllowedAction | (Action['type'] & NamespacedName<Namespace>)>(actionType: ActionType, ...params: ExtractActionParameters<Action, ActionType>): ExtractActionResponse<Action, ActionType>;
104
+ /**
105
+ * Register a function for getting the initial payload for an event.
106
+ *
107
+ * This is used for events that represent a state change, where the payload is the state.
108
+ * Registering a function for getting the payload allows event selectors to have a point of
109
+ * comparison the first time state changes.
110
+ *
111
+ * The event type *must* be in the current namespace
112
+ *
113
+ * @param args - The arguments to this function
114
+ * @param args.eventType - The event type to register a payload for.
115
+ * @param args.getPayload - A function for retrieving the event payload.
116
+ */
117
+ registerInitialEventPayload<EventType extends Event['type'] & NamespacedName<Namespace>>({ eventType, getPayload, }: {
118
+ eventType: EventType;
119
+ getPayload: () => ExtractEventPayload<Event, EventType>;
120
+ }): void;
121
+ /**
122
+ * Publish an event.
123
+ *
124
+ * Publishes the given payload to all subscribers of the given event type.
125
+ *
126
+ * The event type being published *must* be in the current namespace.
127
+ *
128
+ * @param event - The event type. This is a unique identifier for this event.
129
+ * @param payload - The event payload. The type of the parameters for each event handler must
130
+ * match the type of this payload.
131
+ * @throws Will throw if an event that is not in the current namespace is being published.
132
+ * @template EventType - A type union of Event type strings that are namespaced by Namespace.
133
+ */
134
+ publish<EventType extends Event['type'] & NamespacedName<Namespace>>(event: EventType, ...payload: ExtractEventPayload<Event, EventType>): void;
135
+ /**
136
+ * Subscribe to an event.
137
+ *
138
+ * Registers the given function as an event handler for the given event type.
139
+ *
140
+ * The event type being subscribed to must be on the event allowlist.
141
+ *
142
+ * @param eventType - The event type. This is a unique identifier for this event.
143
+ * @param handler - The event handler. The type of the parameters for this event handler must
144
+ * match the type of the payload for this event type.
145
+ * @throws Will throw if the given event is not an allowed event for this messenger.
146
+ * @template EventType - A type union of Event type strings.
147
+ */
148
+ subscribe<EventType extends AllowedEvent | (Event['type'] & NamespacedName<Namespace>)>(eventType: EventType, handler: ExtractEventHandler<Event, EventType>): void;
149
+ /**
150
+ * Subscribe to an event, with a selector.
151
+ *
152
+ * Registers the given handler function as an event handler for the given
153
+ * event type. When an event is published, its payload is first passed to the
154
+ * selector. The event handler is only called if the selector's return value
155
+ * differs from its last known return value.
156
+ *
157
+ * The event type being subscribed to must be on the event allowlist.
158
+ *
159
+ * @param eventType - The event type. This is a unique identifier for this event.
160
+ * @param handler - The event handler. The type of the parameters for this event
161
+ * handler must match the return type of the selector.
162
+ * @param selector - The selector function used to select relevant data from
163
+ * the event payload. The type of the parameters for this selector must match
164
+ * the type of the payload for this event type.
165
+ * @throws Will throw if the given event is not an allowed event for this messenger.
166
+ * @template EventType - A type union of Event type strings.
167
+ * @template SelectorReturnValue - The selector return value.
168
+ */
169
+ subscribe<EventType extends AllowedEvent | (Event['type'] & NamespacedName<Namespace>), SelectorReturnValue>(eventType: EventType, handler: SelectorEventHandler<SelectorReturnValue>, selector: SelectorFunction<Event, EventType, SelectorReturnValue>): void;
170
+ /**
171
+ * Unsubscribe from an event.
172
+ *
173
+ * Unregisters the given function as an event handler for the given event.
174
+ *
175
+ * The event type being unsubscribed to must be on the event allowlist.
176
+ *
177
+ * @param event - The event type. This is a unique identifier for this event.
178
+ * @param handler - The event handler to unregister.
179
+ * @throws Will throw if the given event is not an allowed event for this messenger.
180
+ * @template EventType - A type union of allowed Event type strings.
181
+ */
182
+ unsubscribe<EventType extends AllowedEvent | (Event['type'] & NamespacedName<Namespace>)>(event: EventType, handler: ExtractEventHandler<Event, EventType>): void;
183
+ /**
184
+ * Clear subscriptions for a specific event.
185
+ *
186
+ * This will remove all subscribed handlers for this event.
187
+ *
188
+ * The event type being cleared *must* be in the current namespace.
189
+ *
190
+ * @param event - The event type. This is a unique identifier for this event.
191
+ * @throws Will throw if a subscription for an event that is not in the current namespace is being cleared.
192
+ * @template EventType - A type union of Event type strings that are namespaced by Namespace.
193
+ */
194
+ clearEventSubscriptions<EventType extends Event['type'] & NamespacedName<Namespace>>(event: EventType): void;
195
+ }
196
+ //# sourceMappingURL=RestrictedMessenger.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RestrictedMessenger.d.mts","sourceRoot":"","sources":["../src/RestrictedMessenger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,aAAa,EACb,SAAS,EACT,eAAe,EACf,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,gBAAgB,EACjB,wBAAoB;AAErB;;;;;;GAMG;AACH,MAAM,MAAM,6BAA6B,CAAC,SAAS,SAAS,MAAM,GAAG,MAAM,IACzE,mBAAmB,CACjB,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,MAAM,EACN,MAAM,CACP,CAAC;AAEJ;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,mBAAmB,CAC9B,SAAS,SAAS,MAAM,EACxB,MAAM,SAAS,gBAAgB,EAC/B,KAAK,SAAS,eAAe,EAC7B,aAAa,SAAS,MAAM,EAC5B,YAAY,SAAS,MAAM;;IAU3B;;;;;;;;;;;;;;;;;OAiBG;gBACS,EACV,SAAS,EACT,IAAI,EACJ,cAAc,EACd,aAAa,GACd,EAAE;QACD,SAAS,CAAC,EAAE,SAAS,CAAC,gBAAgB,EAAE,eAAe,CAAC,CAAC;QACzD,IAAI,EAAE,SAAS,CAAC;QAChB,cAAc,EAAE,eAAe,CAAC,SAAS,EAAE,aAAa,CAAC,EAAE,CAAC;QAC5D,aAAa,E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,GAAG,OAAO,EAAE,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC;IAWnD;;;;;;;;;;;;OAYG;IACH,SAAS,CACP,SAAS,SACL,YAAY,GACZ,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,SAAS,CAAC,CAAC,EAC/C,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,GAAG,IAAI;IAE7E;;;;;;;;;;;;;;;;;;;OAmBG;IACH,SAAS,CACP,SAAS,SACL,YAAY,GACZ,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,SAAS,CAAC,CAAC,EAC/C,mBAAmB,EAEnB,SAAS,EAAE,SAAS,EACpB,OAAO,EAAE,oBAAoB,CAAC,mBAAmB,CAAC,EAClD,QAAQ,EAAE,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,mBAAmB,CAAC,GAChE,IAAI;IAsBP;;;;;;;;;;;OAWG;IACH,WAAW,CACT,SAAS,SACL,YAAY,GACZ,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,SAAS,CAAC,CAAC,EAC/C,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC;IAOlE;;;;;;;;;;OAUG;IACH,uBAAuB,CACrB,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,SAAS,CAAC,EAC3D,KAAK,EAAE,SAAS;CA4DnB"}
@@ -0,0 +1,234 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ 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");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ 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");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _RestrictedMessenger_instances, _RestrictedMessenger_messenger, _RestrictedMessenger_namespace, _RestrictedMessenger_allowedActions, _RestrictedMessenger_allowedEvents, _RestrictedMessenger_isAllowedEvent, _RestrictedMessenger_isAllowedAction, _RestrictedMessenger_isInCurrentNamespace;
13
+ /**
14
+ * A restricted messenger.
15
+ *
16
+ * This acts as a wrapper around the messenger instance that restricts access to actions
17
+ * and events.
18
+ *
19
+ * @template Namespace - The namespace for this messenger. Typically this is the name of the controller or
20
+ * module that this messenger has been created for. The authority to publish events and register
21
+ * actions under this namespace is granted to this restricted messenger instance.
22
+ * @template Action - A type union of all Action types.
23
+ * @template Event - A type union of all Event types.
24
+ * @template AllowedAction - A type union of the 'type' string for any allowed actions.
25
+ * This must not include internal actions that are in the messenger's namespace.
26
+ * @template AllowedEvent - A type union of the 'type' string for any allowed events.
27
+ * This must not include internal events that are in the messenger's namespace.
28
+ */
29
+ export class RestrictedMessenger {
30
+ /**
31
+ * Constructs a restricted messenger
32
+ *
33
+ * The provided allowlists grant the ability to call the listed actions and subscribe to the
34
+ * listed events. The "name" provided grants ownership of any actions and events under that
35
+ * namespace. Ownership allows registering actions and publishing events, as well as
36
+ * unregistering actions and clearing event subscriptions.
37
+ *
38
+ * @param options - Options.
39
+ * @param options.messenger - The messenger instance that is being wrapped.
40
+ * @param options.name - The name of the thing this messenger will be handed to (e.g. the
41
+ * controller name). This grants "ownership" of actions and events under this namespace to the
42
+ * restricted messenger returned.
43
+ * @param options.allowedActions - The list of actions that this restricted messenger should be
44
+ * allowed to call.
45
+ * @param options.allowedEvents - The list of events that this restricted messenger should be
46
+ * allowed to subscribe to.
47
+ */
48
+ constructor({ messenger, name, allowedActions, allowedEvents, }) {
49
+ _RestrictedMessenger_instances.add(this);
50
+ _RestrictedMessenger_messenger.set(this, void 0);
51
+ _RestrictedMessenger_namespace.set(this, void 0);
52
+ _RestrictedMessenger_allowedActions.set(this, void 0);
53
+ _RestrictedMessenger_allowedEvents.set(this, void 0);
54
+ if (!messenger) {
55
+ throw new Error('Messenger not provided');
56
+ }
57
+ // The above condition guarantees that one of these options is defined.
58
+ __classPrivateFieldSet(this, _RestrictedMessenger_messenger, messenger, "f");
59
+ __classPrivateFieldSet(this, _RestrictedMessenger_namespace, name, "f");
60
+ __classPrivateFieldSet(this, _RestrictedMessenger_allowedActions, allowedActions, "f");
61
+ __classPrivateFieldSet(this, _RestrictedMessenger_allowedEvents, allowedEvents, "f");
62
+ }
63
+ /**
64
+ * Register an action handler.
65
+ *
66
+ * This will make the registered function available to call via the `call` method.
67
+ *
68
+ * The action type this handler is registered under *must* be in the current namespace.
69
+ *
70
+ * @param action - The action type. This is a unique identifier for this action.
71
+ * @param handler - The action handler. This function gets called when the `call` method is
72
+ * invoked with the given action type.
73
+ * @throws Will throw if an action handler that is not in the current namespace is being registered.
74
+ * @template ActionType - A type union of Action type strings that are namespaced by Namespace.
75
+ */
76
+ registerActionHandler(action, handler) {
77
+ /* istanbul ignore if */ // Branch unreachable with valid types
78
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isInCurrentNamespace).call(this, action)) {
79
+ throw new Error(`Only allowed registering action handlers prefixed by '${__classPrivateFieldGet(this, _RestrictedMessenger_namespace, "f")}:'`);
80
+ }
81
+ __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").registerActionHandler(action, handler);
82
+ }
83
+ /**
84
+ * Registers action handlers for a list of methods on a messenger client
85
+ *
86
+ * @param messengerClient - The object that is expected to make use of the messenger.
87
+ * @param methodNames - The names of the methods on the messenger client to register as action
88
+ * handlers
89
+ */
90
+ registerMethodActionHandlers(messengerClient, methodNames) {
91
+ __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").registerMethodActionHandlers(messengerClient, methodNames);
92
+ }
93
+ /**
94
+ * Unregister an action handler.
95
+ *
96
+ * This will prevent this action from being called.
97
+ *
98
+ * The action type being unregistered *must* be in the current namespace.
99
+ *
100
+ * @param action - The action type. This is a unique identifier for this action.
101
+ * @throws Will throw if an action handler that is not in the current namespace is being unregistered.
102
+ * @template ActionType - A type union of Action type strings that are namespaced by Namespace.
103
+ */
104
+ unregisterActionHandler(action) {
105
+ /* istanbul ignore if */ // Branch unreachable with valid types
106
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isInCurrentNamespace).call(this, action)) {
107
+ throw new Error(`Only allowed unregistering action handlers prefixed by '${__classPrivateFieldGet(this, _RestrictedMessenger_namespace, "f")}:'`);
108
+ }
109
+ __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").unregisterActionHandler(action);
110
+ }
111
+ /**
112
+ * Call an action.
113
+ *
114
+ * This function will call the action handler corresponding to the given action type, passing
115
+ * along any parameters given.
116
+ *
117
+ * The action type being called must be on the action allowlist.
118
+ *
119
+ * @param actionType - The action type. This is a unique identifier for this action.
120
+ * @param params - The action parameters. These must match the type of the parameters of the
121
+ * registered action handler.
122
+ * @throws Will throw when no handler has been registered for the given type.
123
+ * @template ActionType - A type union of allowed Action type strings.
124
+ * @returns The action return value.
125
+ */
126
+ call(actionType, ...params) {
127
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isAllowedAction).call(this, actionType)) {
128
+ throw new Error(`Action missing from allow list: ${actionType}`);
129
+ }
130
+ const response = __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").call(actionType, ...params);
131
+ return response;
132
+ }
133
+ /**
134
+ * Register a function for getting the initial payload for an event.
135
+ *
136
+ * This is used for events that represent a state change, where the payload is the state.
137
+ * Registering a function for getting the payload allows event selectors to have a point of
138
+ * comparison the first time state changes.
139
+ *
140
+ * The event type *must* be in the current namespace
141
+ *
142
+ * @param args - The arguments to this function
143
+ * @param args.eventType - The event type to register a payload for.
144
+ * @param args.getPayload - A function for retrieving the event payload.
145
+ */
146
+ registerInitialEventPayload({ eventType, getPayload, }) {
147
+ /* istanbul ignore if */ // Branch unreachable with valid types
148
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isInCurrentNamespace).call(this, eventType)) {
149
+ throw new Error(`Only allowed publishing events prefixed by '${__classPrivateFieldGet(this, _RestrictedMessenger_namespace, "f")}:'`);
150
+ }
151
+ __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").registerInitialEventPayload({
152
+ eventType,
153
+ getPayload,
154
+ });
155
+ }
156
+ /**
157
+ * Publish an event.
158
+ *
159
+ * Publishes the given payload to all subscribers of the given event type.
160
+ *
161
+ * The event type being published *must* be in the current namespace.
162
+ *
163
+ * @param event - The event type. This is a unique identifier for this event.
164
+ * @param payload - The event payload. The type of the parameters for each event handler must
165
+ * match the type of this payload.
166
+ * @throws Will throw if an event that is not in the current namespace is being published.
167
+ * @template EventType - A type union of Event type strings that are namespaced by Namespace.
168
+ */
169
+ publish(event, ...payload) {
170
+ /* istanbul ignore if */ // Branch unreachable with valid types
171
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isInCurrentNamespace).call(this, event)) {
172
+ throw new Error(`Only allowed publishing events prefixed by '${__classPrivateFieldGet(this, _RestrictedMessenger_namespace, "f")}:'`);
173
+ }
174
+ __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").publish(event, ...payload);
175
+ }
176
+ subscribe(event, handler, selector) {
177
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isAllowedEvent).call(this, event)) {
178
+ throw new Error(`Event missing from allow list: ${event}`);
179
+ }
180
+ if (selector) {
181
+ return __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").subscribe(event, handler, selector);
182
+ }
183
+ return __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").subscribe(event, handler);
184
+ }
185
+ /**
186
+ * Unsubscribe from an event.
187
+ *
188
+ * Unregisters the given function as an event handler for the given event.
189
+ *
190
+ * The event type being unsubscribed to must be on the event allowlist.
191
+ *
192
+ * @param event - The event type. This is a unique identifier for this event.
193
+ * @param handler - The event handler to unregister.
194
+ * @throws Will throw if the given event is not an allowed event for this messenger.
195
+ * @template EventType - A type union of allowed Event type strings.
196
+ */
197
+ unsubscribe(event, handler) {
198
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isAllowedEvent).call(this, event)) {
199
+ throw new Error(`Event missing from allow list: ${event}`);
200
+ }
201
+ __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").unsubscribe(event, handler);
202
+ }
203
+ /**
204
+ * Clear subscriptions for a specific event.
205
+ *
206
+ * This will remove all subscribed handlers for this event.
207
+ *
208
+ * The event type being cleared *must* be in the current namespace.
209
+ *
210
+ * @param event - The event type. This is a unique identifier for this event.
211
+ * @throws Will throw if a subscription for an event that is not in the current namespace is being cleared.
212
+ * @template EventType - A type union of Event type strings that are namespaced by Namespace.
213
+ */
214
+ clearEventSubscriptions(event) {
215
+ if (!__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isInCurrentNamespace).call(this, event)) {
216
+ throw new Error(`Only allowed clearing events prefixed by '${__classPrivateFieldGet(this, _RestrictedMessenger_namespace, "f")}:'`);
217
+ }
218
+ __classPrivateFieldGet(this, _RestrictedMessenger_messenger, "f").clearEventSubscriptions(event);
219
+ }
220
+ }
221
+ _RestrictedMessenger_messenger = new WeakMap(), _RestrictedMessenger_namespace = new WeakMap(), _RestrictedMessenger_allowedActions = new WeakMap(), _RestrictedMessenger_allowedEvents = new WeakMap(), _RestrictedMessenger_instances = new WeakSet(), _RestrictedMessenger_isAllowedEvent = function _RestrictedMessenger_isAllowedEvent(eventType) {
222
+ // Safely upcast to allow runtime check
223
+ const allowedEvents = __classPrivateFieldGet(this, _RestrictedMessenger_allowedEvents, "f");
224
+ return (__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isInCurrentNamespace).call(this, eventType) ||
225
+ (allowedEvents !== null && allowedEvents.includes(eventType)));
226
+ }, _RestrictedMessenger_isAllowedAction = function _RestrictedMessenger_isAllowedAction(actionType) {
227
+ // Safely upcast to allow runtime check
228
+ const allowedActions = __classPrivateFieldGet(this, _RestrictedMessenger_allowedActions, "f");
229
+ return (__classPrivateFieldGet(this, _RestrictedMessenger_instances, "m", _RestrictedMessenger_isInCurrentNamespace).call(this, actionType) ||
230
+ (allowedActions !== null && allowedActions.includes(actionType)));
231
+ }, _RestrictedMessenger_isInCurrentNamespace = function _RestrictedMessenger_isInCurrentNamespace(name) {
232
+ return name.startsWith(`${__classPrivateFieldGet(this, _RestrictedMessenger_namespace, "f")}:`);
233
+ };
234
+ //# sourceMappingURL=RestrictedMessenger.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RestrictedMessenger.mjs","sourceRoot":"","sources":["../src/RestrictedMessenger.ts"],"names":[],"mappings":";;;;;;;;;;;;AA+BA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,mBAAmB;IAe9B;;;;;;;;;;;;;;;;;OAiBG;IACH,YAAY,EACV,SAAS,EACT,IAAI,EACJ,cAAc,EACd,aAAa,GAMd;;QApCQ,iDAAyD;QAEzD,iDAAsB;QAEtB,sDAA6D;QAE7D,qDAA2D;QA+BlE,IAAI,CAAC,SAAS,EAAE;YACd,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC3C;QACD,uEAAuE;QACvE,uBAAA,IAAI,kCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,kCAAc,IAAI,MAAA,CAAC;QACvB,uBAAA,IAAI,uCAAmB,c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B,KAAK,CAAC,EAAE;YAChC,MAAM,IAAI,KAAK,CAAC,kCAAkC,KAAK,EAAE,CAAC,CAAC;SAC5D;QACD,uBAAA,IAAI,sCAAW,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;;;;;;OAUG;IACH,uBAAuB,CAErB,KAAgB;QAChB,IAAI,CAAC,uBAAA,IAAI,iFAAsB,MAA1B,IAAI,EAAuB,KAAK,CAAC,EAAE;YACtC,MAAM,IAAI,KAAK,CACb,6CAA6C,uBAAA,IAAI,sCAAW,IAAI,CACjE,CAAC;SACH;QACD,uBAAA,IAAI,sCAAW,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC;IACjD,CAAC;CAqDF;4UA1CG,SAAwB;IAIxB,uCAAuC;IACvC,MAAM,aAAa,GAAoB,uBAAA,IAAI,0CAAe,CAAC;IAC3D,OAAO,CACL,uBAAA,IAAI,iFAAsB,MAA1B,IAAI,EAAuB,SAAS,CAAC;QACrC,CAAC,aAAa,KAAK,IAAI,IAAI,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAC9D,CAAC;AACJ,CAAC,uFAWC,UAA0B;IAI1B,uCAAuC;IACvC,MAAM,cAAc,GAAoB,uBAAA,IAAI,2CAAgB,CAAC;IAC7D,OAAO,CACL,uBAAA,IAAI,iFAAsB,MAA1B,IAAI,EAAuB,UAAU,CAAC;QACtC,CAAC,cAAc,KAAK,IAAI,IAAI,cAAc,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CACjE,CAAC;AACJ,CAAC,iGAQqB,IAAY;IAChC,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,sCAAW,GAAG,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import type {\n ActionConstraint,\n ActionHandler,\n Messenger,\n EventConstraint,\n ExtractActionParameters,\n ExtractActionResponse,\n ExtractEventHandler,\n ExtractEventPayload,\n NamespacedName,\n NotNamespacedBy,\n SelectorEventHandler,\n SelectorFunction,\n} from './Messenger';\n\n/**\n * A universal supertype of all `RestrictedMessenger` instances. This type can be assigned to any\n * `RestrictedMessenger` type.\n *\n * @template Namespace - Name of the module this messenger is for. Optionally can be used to\n * narrow this type to a constraint for the messenger of a specific module.\n */\nexport type RestrictedMessengerConstraint<Namespace extends string = string> =\n RestrictedMessenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n string,\n string\n >;\n\n/**\n * A restricted messenger.\n *\n * This acts as a wrapper around the messenger instance that restricts access to actions\n * and events.\n *\n * @template Namespace - The namespace for this messenger. Typically this is the name of the controller or\n * module that this messenger has been created for. The authority to publish events and register\n * actions under this namespace is granted to this restricted messenger instance.\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template AllowedAction - A type union of the 'type' string for any allowed actions.\n * This must not include internal actions that are in the messenger's namespace.\n * @template AllowedEvent - A type union of the 'type' string for any allowed events.\n * This must not include internal events that are in the messenger's namespace.\n */\nexport class RestrictedMessenger<\n Namespace extends string,\n Action extends ActionConstraint,\n Event extends EventConstraint,\n AllowedAction extends string,\n AllowedEvent extends string,\n> {\n readonly #messenger: Messenger<ActionConstraint, EventConstraint>;\n\n readonly #namespace: Namespace;\n\n readonly #allowedActions: NotNamespacedBy<Namespace, AllowedAction>[];\n\n readonly #allowedEvents: NotNamespacedBy<Namespace, AllowedEvent>[];\n\n /**\n * Constructs a restricted messenger\n *\n * The provided allowlists grant the ability to call the listed actions and subscribe to the\n * listed events. The \"name\" provided grants ownership of any actions and events under that\n * namespace. Ownership allows registering actions and publishing events, as well as\n * unregistering actions and clearing event subscriptions.\n *\n * @param options - Options.\n * @param options.messenger - The messenger instance that is being wrapped.\n * @param options.name - The name of the thing this messenger will be handed to (e.g. the\n * controller name). This grants \"ownership\" of actions and events under this namespace to the\n * restricted messenger returned.\n * @param options.allowedActions - The list of actions that this restricted messenger should be\n * allowed to call.\n * @param options.allowedEvents - The list of events that this restricted messenger should be\n * allowed to subscribe to.\n */\n constructor({\n messenger,\n name,\n allowedActions,\n allowedEvents,\n }: {\n messenger?: Messenger<ActionConstraint, EventConstraint>;\n name: Namespace;\n allowedActions: NotNamespacedBy<Namespace, AllowedAction>[];\n allowedEvents: NotNamespacedBy<Namespace, AllowedEvent>[];\n }) {\n if (!messenger) {\n throw new Error('Messenger not provided');\n }\n // The above condition guarantees that one of these options is defined.\n this.#messenger = messenger;\n this.#namespace = name;\n this.#allowedActions = allowedActions;\n this.#allowedEvents = allowedEvents;\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 type this handler is registered under *must* be in the current namespace.\n *\n * @param action - 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 if an action handler that is not in the current namespace is being registered.\n * @template ActionType - A type union of Action type strings that are namespaced by Namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(action: ActionType, handler: ActionHandler<Action, ActionType>) {\n /* istanbul ignore if */ // Branch unreachable with valid types\n if (!this.#isInCurrentNamespace(action)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#messenger.registerActionHandler(action, 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 */\n registerMethodActionHandlers<\n MessengerClient extends { name: string },\n MethodNames extends keyof MessengerClient & string,\n >(messengerClient: MessengerClient, methodNames: readonly MethodNames[]) {\n this.#messenger.registerMethodActionHandlers(messengerClient, methodNames);\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action type being unregistered *must* be in the current namespace.\n *\n * @param action - The action type. This is a unique identifier for this action.\n * @throws Will throw if an action handler that is not in the current namespace is being unregistered.\n * @template ActionType - A type union of Action type strings that are namespaced by Namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(action: ActionType) {\n /* istanbul ignore if */ // Branch unreachable with valid types\n if (!this.#isInCurrentNamespace(action)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#messenger.unregisterActionHandler(action);\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 * The action type being called must be on the action allowlist.\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 allowed Action type strings.\n * @returns The action return value.\n */\n call<\n ActionType extends\n | AllowedAction\n | (Action['type'] & NamespacedName<Namespace>),\n >(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n if (!this.#isAllowedAction(actionType)) {\n throw new Error(`Action missing from allow list: ${actionType}`);\n }\n const response = this.#messenger.call<ActionType>(actionType, ...params);\n\n return response;\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 in the current namespace\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 */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }) {\n /* istanbul ignore if */ // Branch unreachable with valid types\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n this.#messenger.registerInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * The event type being published *must* be in the current namespace.\n *\n * @param event - 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 * @throws Will throw if an event that is not in the current namespace is being published.\n * @template EventType - A type union of Event type strings that are namespaced by Namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n event: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ) {\n /* istanbul ignore if */ // Branch unreachable with valid types\n if (!this.#isInCurrentNamespace(event)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n this.#messenger.publish(event, ...payload);\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 * The event type being subscribed to must be on the event allowlist.\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 * @throws Will throw if the given event is not an allowed event for this messenger.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<\n EventType extends\n | AllowedEvent\n | (Event['type'] & NamespacedName<Namespace>),\n >(eventType: EventType, handler: ExtractEventHandler<Event, EventType>): 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 * The event type being subscribed to must be on the event allowlist.\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 * @throws Will throw if the given event is not an allowed event for this messenger.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<\n EventType extends\n | AllowedEvent\n | (Event['type'] & NamespacedName<Namespace>),\n SelectorReturnValue,\n >(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<\n EventType extends\n | AllowedEvent\n | (Event['type'] & NamespacedName<Namespace>),\n SelectorReturnValue,\n >(\n event: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ) {\n if (!this.#isAllowedEvent(event)) {\n throw new Error(`Event missing from allow list: ${event}`);\n }\n\n if (selector) {\n return this.#messenger.subscribe(event, handler, selector);\n }\n return this.#messenger.subscribe(event, handler);\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * The event type being unsubscribed to must be on the event allowlist.\n *\n * @param event - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw if the given event is not an allowed event for this messenger.\n * @template EventType - A type union of allowed Event type strings.\n */\n unsubscribe<\n EventType extends\n | AllowedEvent\n | (Event['type'] & NamespacedName<Namespace>),\n >(event: EventType, handler: ExtractEventHandler<Event, EventType>) {\n if (!this.#isAllowedEvent(event)) {\n throw new Error(`Event missing from allow list: ${event}`);\n }\n this.#messenger.unsubscribe(event, handler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event.\n *\n * The event type being cleared *must* be in the current namespace.\n *\n * @param event - The event type. This is a unique identifier for this event.\n * @throws Will throw if a subscription for an event that is not in the current namespace is being cleared.\n * @template EventType - A type union of Event type strings that are namespaced by Namespace.\n */\n clearEventSubscriptions<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >(event: EventType) {\n if (!this.#isInCurrentNamespace(event)) {\n throw new Error(\n `Only allowed clearing events prefixed by '${this.#namespace}:'`,\n );\n }\n this.#messenger.clearEventSubscriptions(event);\n }\n\n /**\n * Determine whether the given event type is allowed. Event types are\n * allowed if they are in the current namespace or on the list of\n * allowed events.\n *\n * @param eventType - The event type to check.\n * @returns Whether the event type is allowed.\n */\n #isAllowedEvent(\n eventType: Event['type'],\n ): eventType is\n | NamespacedName<Namespace>\n | NotNamespacedBy<Namespace, AllowedEvent> {\n // Safely upcast to allow runtime check\n const allowedEvents: string[] | null = this.#allowedEvents;\n return (\n this.#isInCurrentNamespace(eventType) ||\n (allowedEvents !== null && allowedEvents.includes(eventType))\n );\n }\n\n /**\n * Determine whether the given action type is allowed. Action types\n * are allowed if they are in the current namespace or on the list of\n * allowed actions.\n *\n * @param actionType - The action type to check.\n * @returns Whether the action type is allowed.\n */\n #isAllowedAction(\n actionType: Action['type'],\n ): actionType is\n | NamespacedName<Namespace>\n | NotNamespacedBy<Namespace, AllowedAction> {\n // Safely upcast to allow runtime check\n const allowedActions: string[] | null = this.#allowedActions;\n return (\n this.#isInCurrentNamespace(actionType) ||\n (allowedActions !== null && allowedActions.includes(actionType))\n );\n }\n\n /**\n * Determine whether the given name is within the current namespace.\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 name.startsWith(`${this.#namespace}:`);\n }\n}\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RestrictedMessenger = exports.Messenger = void 0;
4
+ var Messenger_1 = require("./Messenger.cjs");
5
+ Object.defineProperty(exports, "Messenger", { enumerable: true, get: function () { return Messenger_1.Messenger; } });
6
+ var RestrictedMessenger_1 = require("./RestrictedMessenger.cjs");
7
+ Object.defineProperty(exports, "RestrictedMessenger", { enumerable: true, get: function () { return RestrictedMessenger_1.RestrictedMessenger; } });
8
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAcA,6CAAwC;AAA/B,sGAAA,SAAS,OAAA;AAElB,iEAA4D;AAAnD,0HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n ActionHandler,\n ExtractActionParameters,\n ExtractActionResponse,\n ExtractEventHandler,\n ExtractEventPayload,\n GenericEventHandler,\n SelectorFunction,\n ActionConstraint,\n EventConstraint,\n NamespacedBy,\n NotNamespacedBy,\n NamespacedName,\n} from './Messenger';\nexport { Messenger } from './Messenger';\nexport type { RestrictedMessengerConstraint } from './RestrictedMessenger';\nexport { RestrictedMessenger } from './RestrictedMessenger';\n"]}
@@ -0,0 +1,5 @@
1
+ export type { ActionHandler, ExtractActionParameters, ExtractActionResponse, ExtractEventHandler, ExtractEventPayload, GenericEventHandler, SelectorFunction, ActionConstraint, EventConstraint, NamespacedBy, NotNamespacedBy, NamespacedName, } from "./Messenger.cjs";
2
+ export { Messenger } from "./Messenger.cjs";
3
+ export type { RestrictedMessengerConstraint } from "./RestrictedMessenger.cjs";
4
+ export { RestrictedMessenger } from "./RestrictedMessenger.cjs";
5
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,aAAa,EACb,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,YAAY,EACZ,eAAe,EACf,cAAc,GACf,wBAAoB;AACrB,OAAO,EAAE,SAAS,EAAE,wBAAoB;AACxC,YAAY,EAAE,6BAA6B,EAAE,kCAA8B;AAC3E,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
@@ -0,0 +1,5 @@
1
+ export type { ActionHandler, ExtractActionParameters, ExtractActionResponse, ExtractEventHandler, ExtractEventPayload, GenericEventHandler, SelectorFunction, ActionConstraint, EventConstraint, NamespacedBy, NotNamespacedBy, NamespacedName, } from "./Messenger.mjs";
2
+ export { Messenger } from "./Messenger.mjs";
3
+ export type { RestrictedMessengerConstraint } from "./RestrictedMessenger.mjs";
4
+ export { RestrictedMessenger } from "./RestrictedMessenger.mjs";
5
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,aAAa,EACb,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,YAAY,EACZ,eAAe,EACf,cAAc,GACf,wBAAoB;AACrB,OAAO,EAAE,SAAS,EAAE,wBAAoB;AACxC,YAAY,EAAE,6BAA6B,EAAE,kCAA8B;AAC3E,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ export { Messenger } from "./Messenger.mjs";
2
+ export { RestrictedMessenger } from "./RestrictedMessenger.mjs";
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,SAAS,EAAE,wBAAoB;AAExC,OAAO,EAAE,mBAAmB,EAAE,kCAA8B","sourcesContent":["export type {\n ActionHandler,\n ExtractActionParameters,\n ExtractActionResponse,\n ExtractEventHandler,\n ExtractEventPayload,\n GenericEventHandler,\n SelectorFunction,\n ActionConstraint,\n EventConstraint,\n NamespacedBy,\n NotNamespacedBy,\n NamespacedName,\n} from './Messenger';\nexport { Messenger } from './Messenger';\nexport type { RestrictedMessengerConstraint } from './RestrictedMessenger';\nexport { RestrictedMessenger } from './RestrictedMessenger';\n"]}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@metamask-previews/messenger",
3
+ "version": "0.0.0-preview-3713f9f",
4
+ "description": "A type-safe message bus library",
5
+ "keywords": [
6
+ "MetaMask",
7
+ "Ethereum"
8
+ ],
9
+ "homepage": "https://github.com/MetaMask/core/tree/main/packages/messenger#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MetaMask/core/issues"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/MetaMask/core.git"
16
+ },
17
+ "license": "MIT",
18
+ "sideEffects": false,
19
+ "exports": {
20
+ ".": {
21
+ "import": {
22
+ "types": "./dist/index.d.mts",
23
+ "default": "./dist/index.mjs"
24
+ },
25
+ "require": {
26
+ "types": "./dist/index.d.cts",
27
+ "default": "./dist/index.cjs"
28
+ }
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "main": "./dist/index.cjs",
33
+ "types": "./dist/index.d.cts",
34
+ "files": [
35
+ "dist/"
36
+ ],
37
+ "scripts": {
38
+ "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
39
+ "build:docs": "typedoc",
40
+ "changelog:update": "../../scripts/update-changelog.sh @metamask/messenger",
41
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/messenger",
42
+ "publish:preview": "yarn npm publish --tag preview",
43
+ "since-latest-release": "../../scripts/since-latest-release.sh",
44
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
45
+ "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
46
+ "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
47
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
48
+ },
49
+ "devDependencies": {
50
+ "@metamask/auto-changelog": "^3.4.4",
51
+ "@types/jest": "^27.4.1",
52
+ "deepmerge": "^4.2.2",
53
+ "immer": "^9.0.6",
54
+ "jest": "^27.5.1",
55
+ "sinon": "^9.2.4",
56
+ "ts-jest": "^27.1.4",
57
+ "typedoc": "^0.24.8",
58
+ "typedoc-plugin-missing-exports": "^2.0.0",
59
+ "typescript": "~5.2.2"
60
+ },
61
+ "engines": {
62
+ "node": "^18.18 || >=20"
63
+ },
64
+ "publishConfig": {
65
+ "access": "public",
66
+ "registry": "https://registry.npmjs.org/"
67
+ }
68
+ }