New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@metamask-previews/base-controller

Package Overview
Dependencies
Maintainers
2
Versions
534
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@metamask-previews/base-controller - npm Package Compare versions

Comparing version 3.2.3-preview.e3b05ea to 3.2.3-preview.eb58a59

dist/RestrictedControllerMessenger.d.ts

41

dist/BaseControllerV2.d.ts
import type { Json } from '@metamask/utils';
import type { Draft, Patch } from 'immer';
import type { RestrictedControllerMessenger } from './ControllerMessenger';
import type { ActionConstraint, EventConstraint } from './ControllerMessenger';
import type { RestrictedControllerMessenger } from './RestrictedControllerMessenger';
/**

@@ -50,7 +51,17 @@ * A state change listener.

}
export declare type ControllerGetStateAction<ControllerName extends string, ControllerState extends Record<string, unknown>> = {
type: `${ControllerName}:getState`;
handler: () => ControllerState;
};
export declare type ControllerStateChangeEvent<ControllerName extends string, ControllerState extends Record<string, unknown>> = {
type: `${ControllerName}:stateChange`;
payload: [ControllerState, Patch[]];
};
export declare type ControllerActions<ControllerName extends string, ControllerState extends Record<string, unknown>> = ControllerGetStateAction<ControllerName, ControllerState>;
export declare type ControllerEvents<ControllerName extends string, ControllerState extends Record<string, unknown>> = ControllerStateChangeEvent<ControllerName, ControllerState>;
/**
* Controller class that provides state management, subscriptions, and state metadata
*/
export declare class BaseController<N extends string, S extends Record<string, Json>, messenger extends RestrictedControllerMessenger<N, any, any, string, string>> {
private internalState;
export declare class BaseController<ControllerName extends string, ControllerState extends Record<string, Json>, messenger extends RestrictedControllerMessenger<ControllerName, ActionConstraint | ControllerActions<ControllerName, ControllerState>, EventConstraint | ControllerEvents<ControllerName, ControllerState>, string, string>> {
#private;
protected messagingSystem: messenger;

@@ -62,4 +73,4 @@ /**

*/
readonly name: N;
readonly metadata: StateMetadata<S>;
readonly name: ControllerName;
readonly metadata: StateMetadata<ControllerState>;
/**

@@ -76,3 +87,3 @@ * The existence of the `subscribe` property is how the ComposableController detects whether a

* @param options.messenger - Controller messaging system.
* @param options.metadata - State metadata, describing how to "anonymize" the state, and which
* @param options.metadata - ControllerState metadata, describing how to "anonymize" the state, and which
* parts should be persisted.

@@ -84,5 +95,5 @@ * @param options.name - The name of the controller, used as a namespace for events and actions.

messenger: messenger;
metadata: StateMetadata<S>;
name: N;
state: S;
metadata: StateMetadata<ControllerState>;
name: ControllerName;
state: ControllerState;
});

@@ -94,4 +105,4 @@ /**

*/
get state(): S;
set state(_: S);
get state(): ControllerState;
set state(_: ControllerState);
/**

@@ -108,4 +119,4 @@ * Updates controller state. Accepts a callback that is passed a draft copy

*/
protected update(callback: (state: Draft<S>) => void | S): {
nextState: S;
protected update(callback: (state: Draft<ControllerState>) => void | ControllerState): {
nextState: ControllerState;
patches: Patch[];

@@ -144,3 +155,3 @@ inversePatches: Patch[];

*/
export declare function getAnonymizedState<S extends Record<string, Json>>(state: S, metadata: StateMetadata<S>): Record<string, Json>;
export declare function getAnonymizedState<ControllerState extends Record<string, Json>>(state: ControllerState, metadata: StateMetadata<ControllerState>): Record<string, Json>;
/**

@@ -153,3 +164,3 @@ * Returns the subset of state that should be persisted.

*/
export declare function getPersistentState<S extends Record<string, Json>>(state: S, metadata: StateMetadata<S>): Record<string, Json>;
export declare function getPersistentState<ControllerState extends Record<string, Json>>(state: ControllerState, metadata: StateMetadata<ControllerState>): Record<string, Json>;
//# sourceMappingURL=BaseControllerV2.d.ts.map
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
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");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _BaseController_internalState;
Object.defineProperty(exports, "__esModule", { value: true });

@@ -15,3 +27,3 @@ exports.getPersistentState = exports.getAnonymizedState = exports.BaseController = void 0;

* @param options.messenger - Controller messaging system.
* @param options.metadata - State metadata, describing how to "anonymize" the state, and which
* @param options.metadata - ControllerState metadata, describing how to "anonymize" the state, and which
* parts should be persisted.

@@ -22,5 +34,6 @@ * @param options.name - The name of the controller, used as a namespace for events and actions.

constructor({ messenger, metadata, name, state, }) {
_BaseController_internalState.set(this, void 0);
this.messagingSystem = messenger;
this.name = name;
this.internalState = state;
__classPrivateFieldSet(this, _BaseController_internalState, state, "f");
this.metadata = metadata;

@@ -35,3 +48,3 @@ this.messagingSystem.registerActionHandler(`${name}:getState`, () => this.state);

get state() {
return this.internalState;
return __classPrivateFieldGet(this, _BaseController_internalState, "f");
}

@@ -55,4 +68,4 @@ set state(_) {

// produceWithPatches here.
const [nextState, patches, inversePatches] = immer_1.produceWithPatches(this.internalState, callback);
this.internalState = nextState;
const [nextState, patches, inversePatches] = immer_1.produceWithPatches(__classPrivateFieldGet(this, _BaseController_internalState, "f"), callback);
__classPrivateFieldSet(this, _BaseController_internalState, nextState, "f");
this.messagingSystem.publish(`${this.name}:stateChange`, nextState, patches);

@@ -69,4 +82,4 @@ return { nextState, patches, inversePatches };

applyPatches(patches) {
const nextState = (0, immer_1.applyPatches)(this.internalState, patches);
this.internalState = nextState;
const nextState = (0, immer_1.applyPatches)(__classPrivateFieldGet(this, _BaseController_internalState, "f"), patches);
__classPrivateFieldSet(this, _BaseController_internalState, nextState, "f");
this.messagingSystem.publish(`${this.name}:stateChange`, nextState, patches);

@@ -88,2 +101,3 @@ }

exports.BaseController = BaseController;
_BaseController_internalState = new WeakMap();
/**

@@ -128,3 +142,3 @@ * Returns an anonymized representation of the controller state.

if (!stateMetadata) {
throw new Error(`No metadata found for '${key}'`);
throw new Error(`No metadata found for '${String(key)}'`);
}

@@ -131,0 +145,0 @@ const propertyMetadata = stateMetadata[metadataProperty];

@@ -1,24 +0,25 @@

export declare type ActionHandler<Action, ActionType> = (...args: ExtractActionParameters<Action, ActionType>) => ExtractActionResponse<Action, ActionType>;
export declare type ExtractActionParameters<Action, T> = Action extends {
type: T;
handler: (...args: infer H) => any;
} ? H : never;
export declare type ExtractActionResponse<Action, T> = Action extends {
type: T;
handler: (...args: any) => infer H;
} ? H : never;
export declare type ExtractEventHandler<Event, T> = Event extends {
type: T;
payload: infer P;
} ? P extends unknown[] ? (...payload: P) => void : never : never;
export declare type ExtractEventPayload<Event, T> = Event extends {
type: T;
payload: infer P;
} ? P : never;
import { RestrictedControllerMessenger } from './RestrictedControllerMessenger';
export declare type ActionHandler<Action extends ActionConstraint, ActionType = Action['type']> = (...args: ExtractActionParameters<Action, ActionType>) => ExtractActionResponse<Action, ActionType>;
export declare type ExtractActionParameters<Action extends ActionConstraint, ActionType = Action['type']> = Action extends {
type: ActionType;
handler: (...args: infer HandlerArgs) => unknown;
} ? HandlerArgs : never;
export declare type ExtractActionResponse<Action extends ActionConstraint, ActionType = Action['type']> = Action extends {
type: ActionType;
handler: (...args: infer _) => infer HandlerReturnValue;
} ? HandlerReturnValue : never;
export declare type ExtractEventHandler<Event extends EventConstraint, EventType = Event['type']> = Event extends {
type: EventType;
payload: infer Payload;
} ? Payload extends unknown[] ? (...payload: Payload) => void : never : never;
export declare type ExtractEventPayload<Event extends EventConstraint, EventType = Event['type']> = Event extends {
type: EventType;
payload: infer Payload;
} ? Payload extends unknown[] ? Payload : never : never;
export declare type GenericEventHandler = (...args: unknown[]) => void;
export declare type SelectorFunction<Args extends unknown[], ReturnValue> = (...args: Args) => ReturnValue;
export declare type SelectorFunction<Event extends EventConstraint, ReturnValue> = (...args: ExtractEventPayload<Event>) => ReturnValue;
export declare type SelectorEventHandler<SelectorReturnValue> = (newValue: SelectorReturnValue, previousValue: SelectorReturnValue | undefined) => void;
export declare type ActionConstraint = {
type: string;
handler: (...args: any) => unknown;
handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);
};

@@ -32,170 +33,16 @@ export declare type EventConstraint = {

*
* This type verifies that the string T is prefixed by the string Name followed by a colon.
* This type verifies that the string Name is prefixed by the string Name followed by a colon.
*
* @template Name - The namespace we're checking for.
* @template T - The full string, including the namespace.
* @template Namespace - The namespace we're checking for.
* @template Name - The full string, including the namespace.
*/
export declare type Namespaced<Name extends string, T> = T extends `${Name}:${string}` ? T : never;
declare type NarrowToNamespace<T, Namespace extends string> = T extends {
export declare type Namespaced<Namespace extends string, Name> = Name extends `${Namespace}:${string}` ? Name : never;
export declare type NamespacedName<Namespace extends string = string> = `${Namespace}:${string}`;
declare type NarrowToNamespace<Name, Namespace extends string> = Name extends {
type: `${Namespace}:${string}`;
} ? T : never;
declare type NarrowToAllowed<T, Allowed extends string> = T extends {
} ? Name : never;
declare type NarrowToAllowed<Name, Allowed extends string> = Name extends {
type: Allowed;
} ? T : never;
} ? Name : never;
/**
* A restricted controller messenger.
*
* This acts as a wrapper around the controller messenger instance that restricts access to actions
* and events.
*
* @template N - The namespace for this messenger. Typically this is the name of the controller or
* module that this messenger has been created for. The authority to publish events and register
* actions under this namespace is granted to this restricted messenger instance.
* @template Action - A type union of all Action types.
* @template Event - A type union of all Event types.
* @template AllowedAction - A type union of the 'type' string for any allowed actions.
* @template AllowedEvent - A type union of the 'type' string for any allowed events.
*/
export declare class RestrictedControllerMessenger<N extends string, Action extends ActionConstraint, Event extends EventConstraint, AllowedAction extends string, AllowedEvent extends string> {
private readonly controllerMessenger;
private readonly controllerName;
private readonly allowedActions;
private readonly allowedEvents;
/**
* Constructs a restricted controller messenger
*
* The provided allowlists grant the ability to call the listed actions and subscribe to the
* listed events. The "name" provided grants ownership of any actions and events under that
* namespace. Ownership allows registering actions and publishing events, as well as
* unregistering actions and clearing event subscriptions.
*
* @param options - The controller options.
* @param options.controllerMessenger - The controller messenger instance that is being wrapped.
* @param options.name - The name of the thing this messenger will be handed to (e.g. the
* controller name). This grants "ownership" of actions and events under this namespace to the
* restricted controller messenger returned.
* @param options.allowedActions - The list of actions that this restricted controller messenger
* should be alowed to call.
* @param options.allowedEvents - The list of events that this restricted controller messenger
* should be allowed to subscribe to.
*/
constructor({ controllerMessenger, name, allowedActions, allowedEvents, }: {
controllerMessenger: ControllerMessenger<ActionConstraint, EventConstraint>;
name: N;
allowedActions?: AllowedAction[];
allowedEvents?: AllowedEvent[];
});
/**
* Register an action handler.
*
* This will make the registered function available to call via the `call` method.
*
* The action type this handler is registered under *must* be in the current namespace.
*
* @param action - The action type. This is a unqiue identifier for this action.
* @param handler - The action handler. This function gets called when the `call` method is
* invoked with the given action type.
* @throws Will throw when a handler has been registered for this action type already.
* @template T - A type union of Action type strings that are namespaced by N.
*/
registerActionHandler<T extends Namespaced<N, Action['type']>>(action: T, handler: ActionHandler<Action, T>): void;
/**
* Unregister an action handler.
*
* This will prevent this action from being called.
*
* The action type being unregistered *must* be in the current namespace.
*
* @param action - The action type. This is a unqiue identifier for this action.
* @template T - A type union of Action type strings that are namespaced by N.
*/
unregisterActionHandler<T extends Namespaced<N, Action['type']>>(action: T): void;
/**
* Call an action.
*
* This function will call the action handler corresponding to the given action type, passing
* along any parameters given.
*
* The action type being called must be on the action allowlist.
*
* @param action - The action type. This is a unqiue identifier for this action.
* @param params - The action parameters. These must match the type of the parameters of the
* registered action handler.
* @throws Will throw when no handler has been registered for the given type.
* @template T - A type union of allowed Action type strings.
* @returns The action return value.
*/
call<T extends AllowedAction & string>(action: T, ...params: ExtractActionParameters<Action, T>): ExtractActionResponse<Action, T>;
/**
* Publish an event.
*
* Publishes the given payload to all subscribers of the given event type.
*
* The event type being published *must* be in the current namespace.
*
* @param event - The event type. This is a unique identifier for this event.
* @param payload - The event payload. The type of the parameters for each event handler must
* match the type of this payload.
* @template E - A type union of Event type strings that are namespaced by N.
*/
publish<E extends Namespaced<N, Event['type']>>(event: E, ...payload: ExtractEventPayload<Event, E>): void;
/**
* Subscribe to an event.
*
* Registers the given function as an event handler for the given event type.
*
* The event type being subscribed to must be on the event allowlist.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler. The type of the parameters for this event handler must
* match the type of the payload for this event type.
* @template E - A type union of Event type strings.
*/
subscribe<E extends AllowedEvent & string>(eventType: E, handler: ExtractEventHandler<Event, E>): void;
/**
* Subscribe to an event, with a selector.
*
* Registers the given handler function as an event handler for the given
* event type. When an event is published, its payload is first passed to the
* selector. The event handler is only called if the selector's return value
* differs from its last known return value.
*
* The event type being subscribed to must be on the event allowlist.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler. The type of the parameters for this event
* handler must match the return type of the selector.
* @param selector - The selector function used to select relevant data from
* the event payload. The type of the parameters for this selector must match
* the type of the payload for this event type.
* @template E - A type union of Event type strings.
* @template V - The selector return value.
*/
subscribe<E extends AllowedEvent & string, V>(eventType: E, handler: SelectorEventHandler<V>, selector: SelectorFunction<ExtractEventPayload<Event, E>, V>): void;
/**
* Unsubscribe from an event.
*
* Unregisters the given function as an event handler for the given event.
*
* The event type being unsubscribed to must be on the event allowlist.
*
* @param event - The event type. This is a unique identifier for this event.
* @param handler - The event handler to unregister.
* @throws Will throw when the given event handler is not registered for this event.
* @template T - A type union of allowed Event type strings.
*/
unsubscribe<E extends AllowedEvent & string>(event: E, handler: ExtractEventHandler<Event, E>): void;
/**
* Clear subscriptions for a specific event.
*
* This will remove all subscribed handlers for this event.
*
* The event type being cleared *must* be in the current namespace.
*
* @param event - The event type. This is a unique identifier for this event.
* @template E - A type union of Event type strings that are namespaced by N.
*/
clearEventSubscriptions<E extends Namespaced<N, Event['type']>>(event: E): void;
}
/**
* A messaging system for controllers.

@@ -211,9 +58,4 @@ *

export declare class ControllerMessenger<Action extends ActionConstraint, Event extends EventConstraint> {
private readonly actions;
private readonly events;
#private;
/**
* A cache of selector return values for their respective handlers.
*/
private readonly eventPayloadCache;
/**
* Register an action handler.

@@ -227,5 +69,5 @@ *

* @throws Will throw when a handler has been registered for this action type already.
* @template T - A type union of Action type strings.
* @template ActionType - A type union of Action type strings.
*/
registerActionHandler<T extends Action['type']>(actionType: T, handler: ActionHandler<Action, T>): void;
registerActionHandler<ActionType extends Action['type']>(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void;
/**

@@ -237,5 +79,5 @@ * Unregister an action handler.

* @param actionType - The action type. This is a unqiue identifier for this action.
* @template T - A type union of Action type strings.
* @template ActionType - A type union of Action type strings.
*/
unregisterActionHandler<T extends Action['type']>(actionType: T): void;
unregisterActionHandler<ActionType extends Action['type']>(actionType: ActionType): void;
/**

@@ -257,6 +99,6 @@ * Unregister all action handlers.

* @throws Will throw when no handler has been registered for the given type.
* @template T - A type union of Action type strings.
* @template ActionType - A type union of Action type strings.
* @returns The action return value.
*/
call<T extends Action['type']>(actionType: T, ...params: ExtractActionParameters<Action, T>): ExtractActionResponse<Action, T>;
call<ActionType extends Action['type']>(actionType: ActionType, ...params: ExtractActionParameters<Action, ActionType>): ExtractActionResponse<Action, ActionType>;
/**

@@ -273,5 +115,5 @@ * Publish an event.

* match the type of this payload.
* @template E - A type union of Event type strings.
* @template EventType - A type union of Event type strings.
*/
publish<E extends Event['type']>(eventType: E, ...payload: ExtractEventPayload<Event, E>): void;
publish<EventType extends Event['type']>(eventType: EventType, ...payload: ExtractEventPayload<Event, EventType>): void;
/**

@@ -285,5 +127,5 @@ * Subscribe to an event.

* match the type of the payload for this event type.
* @template E - A type union of Event type strings.
* @template EventType - A type union of Event type strings.
*/
subscribe<E extends Event['type']>(eventType: E, handler: ExtractEventHandler<Event, E>): void;
subscribe<EventType extends Event['type']>(eventType: EventType, handler: ExtractEventHandler<Event, EventType>): void;
/**

@@ -303,6 +145,6 @@ * Subscribe to an event, with a selector.

* the type of the payload for this event type.
* @template E - A type union of Event type strings.
* @template V - The selector return value.
* @template EventType - A type union of Event type strings.
* @template SelectorReturnValue - The selector return value.
*/
subscribe<E extends Event['type'], V>(eventType: E, handler: SelectorEventHandler<V>, selector: SelectorFunction<ExtractEventPayload<Event, E>, V>): void;
subscribe<EventType extends Event['type'], SelectorReturnValue>(eventType: EventType, handler: SelectorEventHandler<SelectorReturnValue>, selector: SelectorFunction<ExtractEventPayload<Event, EventType>, SelectorReturnValue>): void;
/**

@@ -316,5 +158,5 @@ * Unsubscribe from an event.

* @throws Will throw when the given event handler is not registered for this event.
* @template E - A type union of Event type strings.
* @template EventType - A type union of Event type strings.
*/
unsubscribe<E extends Event['type']>(eventType: E, handler: ExtractEventHandler<Event, E>): void;
unsubscribe<EventType extends Event['type']>(eventType: EventType, handler: ExtractEventHandler<Event, EventType>): void;
/**

@@ -326,5 +168,5 @@ * Clear subscriptions for a specific event.

* @param eventType - The event type. This is a unique identifier for this event.
* @template E - A type union of Event type strings.
* @template EventType - A type union of Event type strings.
*/
clearEventSubscriptions<E extends Event['type']>(eventType: E): void;
clearEventSubscriptions<EventType extends Event['type']>(eventType: EventType): void;
/**

@@ -353,3 +195,3 @@ * Clear all subscriptions.

* should be allowed to subscribe to.
* @template N - The namespace for this messenger. Typically this is the name of the controller or
* @template Namespace - The namespace for this messenger. Typically this is the name of the controller or
* module that this messenger has been created for. The authority to publish events and register

@@ -361,9 +203,9 @@ * actions under this namespace is granted to this restricted messenger instance.

*/
getRestricted<N extends string, AllowedAction extends string, AllowedEvent extends string>({ name, allowedActions, allowedEvents, }: {
name: N;
getRestricted<Namespace extends string, AllowedAction extends string, AllowedEvent extends string>({ name, allowedActions, allowedEvents, }: {
name: Namespace;
allowedActions?: Extract<Action['type'], AllowedAction>[];
allowedEvents?: Extract<Event['type'], AllowedEvent>[];
}): RestrictedControllerMessenger<N, NarrowToNamespace<Action, N> | NarrowToAllowed<Action, AllowedAction>, NarrowToNamespace<Event, N> | NarrowToAllowed<Event, AllowedEvent>, AllowedAction, AllowedEvent>;
}): RestrictedControllerMessenger<Namespace, NarrowToNamespace<Action, Namespace> | NarrowToAllowed<Action, AllowedAction>, NarrowToNamespace<Event, Namespace> | NarrowToAllowed<Event, AllowedEvent>, AllowedAction, AllowedEvent>;
}
export {};
//# sourceMappingURL=ControllerMessenger.d.ts.map
"use strict";
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _ControllerMessenger_actions, _ControllerMessenger_events, _ControllerMessenger_eventPayloadCache;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ControllerMessenger = exports.RestrictedControllerMessenger = void 0;
exports.ControllerMessenger = void 0;
const RestrictedControllerMessenger_1 = require("./RestrictedControllerMessenger");
/**
* A restricted controller messenger.
*
* This acts as a wrapper around the controller messenger instance that restricts access to actions
* and events.
*
* @template N - The namespace for this messenger. Typically this is the name of the controller or
* module that this messenger has been created for. The authority to publish events and register
* actions under this namespace is granted to this restricted messenger instance.
* @template Action - A type union of all Action types.
* @template Event - A type union of all Event types.
* @template AllowedAction - A type union of the 'type' string for any allowed actions.
* @template AllowedEvent - A type union of the 'type' string for any allowed events.
*/
class RestrictedControllerMessenger {
/**
* Constructs a restricted controller messenger
*
* The provided allowlists grant the ability to call the listed actions and subscribe to the
* listed events. The "name" provided grants ownership of any actions and events under that
* namespace. Ownership allows registering actions and publishing events, as well as
* unregistering actions and clearing event subscriptions.
*
* @param options - The controller options.
* @param options.controllerMessenger - The controller messenger instance that is being wrapped.
* @param options.name - The name of the thing this messenger will be handed to (e.g. the
* controller name). This grants "ownership" of actions and events under this namespace to the
* restricted controller messenger returned.
* @param options.allowedActions - The list of actions that this restricted controller messenger
* should be alowed to call.
* @param options.allowedEvents - The list of events that this restricted controller messenger
* should be allowed to subscribe to.
*/
constructor({ controllerMessenger, name, allowedActions, allowedEvents, }) {
this.controllerMessenger = controllerMessenger;
this.controllerName = name;
this.allowedActions = allowedActions || null;
this.allowedEvents = allowedEvents || null;
}
/**
* Register an action handler.
*
* This will make the registered function available to call via the `call` method.
*
* The action type this handler is registered under *must* be in the current namespace.
*
* @param action - The action type. This is a unqiue identifier for this action.
* @param handler - The action handler. This function gets called when the `call` method is
* invoked with the given action type.
* @throws Will throw when a handler has been registered for this action type already.
* @template T - A type union of Action type strings that are namespaced by N.
*/
registerActionHandler(action, handler) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!action.startsWith(`${this.controllerName}:`)) {
throw new Error(`Only allowed registering action handlers prefixed by '${this.controllerName}:'`);
}
this.controllerMessenger.registerActionHandler(action, handler);
}
/**
* Unregister an action handler.
*
* This will prevent this action from being called.
*
* The action type being unregistered *must* be in the current namespace.
*
* @param action - The action type. This is a unqiue identifier for this action.
* @template T - A type union of Action type strings that are namespaced by N.
*/
unregisterActionHandler(action) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!action.startsWith(`${this.controllerName}:`)) {
throw new Error(`Only allowed unregistering action handlers prefixed by '${this.controllerName}:'`);
}
this.controllerMessenger.unregisterActionHandler(action);
}
/**
* Call an action.
*
* This function will call the action handler corresponding to the given action type, passing
* along any parameters given.
*
* The action type being called must be on the action allowlist.
*
* @param action - The action type. This is a unqiue identifier for this action.
* @param params - The action parameters. These must match the type of the parameters of the
* registered action handler.
* @throws Will throw when no handler has been registered for the given type.
* @template T - A type union of allowed Action type strings.
* @returns The action return value.
*/
call(action, ...params) {
/* istanbul ignore next */ // Branches unreachable with valid types
if (this.allowedActions === null) {
throw new Error('No actions allowed');
}
else if (!this.allowedActions.includes(action)) {
throw new Error(`Action missing from allow list: ${action}`);
}
return this.controllerMessenger.call(action, ...params);
}
/**
* Publish an event.
*
* Publishes the given payload to all subscribers of the given event type.
*
* The event type being published *must* be in the current namespace.
*
* @param event - The event type. This is a unique identifier for this event.
* @param payload - The event payload. The type of the parameters for each event handler must
* match the type of this payload.
* @template E - A type union of Event type strings that are namespaced by N.
*/
publish(event, ...payload) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!event.startsWith(`${this.controllerName}:`)) {
throw new Error(`Only allowed publishing events prefixed by '${this.controllerName}:'`);
}
this.controllerMessenger.publish(event, ...payload);
}
subscribe(event, handler, selector) {
/* istanbul ignore next */ // Branches unreachable with valid types
if (this.allowedEvents === null) {
throw new Error('No events allowed');
}
else if (!this.allowedEvents.includes(event)) {
throw new Error(`Event missing from allow list: ${event}`);
}
if (selector) {
return this.controllerMessenger.subscribe(event, handler, selector);
}
return this.controllerMessenger.subscribe(event, handler);
}
/**
* Unsubscribe from an event.
*
* Unregisters the given function as an event handler for the given event.
*
* The event type being unsubscribed to must be on the event allowlist.
*
* @param event - The event type. This is a unique identifier for this event.
* @param handler - The event handler to unregister.
* @throws Will throw when the given event handler is not registered for this event.
* @template T - A type union of allowed Event type strings.
*/
unsubscribe(event, handler) {
/* istanbul ignore next */ // Branches unreachable with valid types
if (this.allowedEvents === null) {
throw new Error('No events allowed');
}
else if (!this.allowedEvents.includes(event)) {
throw new Error(`Event missing from allow list: ${event}`);
}
this.controllerMessenger.unsubscribe(event, handler);
}
/**
* Clear subscriptions for a specific event.
*
* This will remove all subscribed handlers for this event.
*
* The event type being cleared *must* be in the current namespace.
*
* @param event - The event type. This is a unique identifier for this event.
* @template E - A type union of Event type strings that are namespaced by N.
*/
clearEventSubscriptions(event) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!event.startsWith(`${this.controllerName}:`)) {
throw new Error(`Only allowed clearing events prefixed by '${this.controllerName}:'`);
}
this.controllerMessenger.clearEventSubscriptions(event);
}
}
exports.RestrictedControllerMessenger = RestrictedControllerMessenger;
/**
* A messaging system for controllers.

@@ -190,8 +23,8 @@ *

constructor() {
this.actions = new Map();
this.events = new Map();
_ControllerMessenger_actions.set(this, new Map());
_ControllerMessenger_events.set(this, new Map());
/**
* A cache of selector return values for their respective handlers.
*/
this.eventPayloadCache = new Map();
_ControllerMessenger_eventPayloadCache.set(this, new Map());
}

@@ -207,9 +40,9 @@ /**

* @throws Will throw when a handler has been registered for this action type already.
* @template T - A type union of Action type strings.
* @template ActionType - A type union of Action type strings.
*/
registerActionHandler(actionType, handler) {
if (this.actions.has(actionType)) {
if (__classPrivateFieldGet(this, _ControllerMessenger_actions, "f").has(actionType)) {
throw new Error(`A handler for ${actionType} has already been registered`);
}
this.actions.set(actionType, handler);
__classPrivateFieldGet(this, _ControllerMessenger_actions, "f").set(actionType, handler);
}

@@ -222,6 +55,6 @@ /**

* @param actionType - The action type. This is a unqiue identifier for this action.
* @template T - A type union of Action type strings.
* @template ActionType - A type union of Action type strings.
*/
unregisterActionHandler(actionType) {
this.actions.delete(actionType);
__classPrivateFieldGet(this, _ControllerMessenger_actions, "f").delete(actionType);
}

@@ -234,3 +67,3 @@ /**

clearActions() {
this.actions.clear();
__classPrivateFieldGet(this, _ControllerMessenger_actions, "f").clear();
}

@@ -247,7 +80,7 @@ /**

* @throws Will throw when no handler has been registered for the given type.
* @template T - A type union of Action type strings.
* @template ActionType - A type union of Action type strings.
* @returns The action return value.
*/
call(actionType, ...params) {
const handler = this.actions.get(actionType);
const handler = __classPrivateFieldGet(this, _ControllerMessenger_actions, "f").get(actionType);
if (!handler) {

@@ -269,6 +102,6 @@ throw new Error(`A handler for ${actionType} has not been registered`);

* match the type of this payload.
* @template E - A type union of Event type strings.
* @template EventType - A type union of Event type strings.
*/
publish(eventType, ...payload) {
const subscribers = this.events.get(eventType);
const subscribers = __classPrivateFieldGet(this, _ControllerMessenger_events, "f").get(eventType);
if (subscribers) {

@@ -278,6 +111,6 @@ for (const [handler, selector] of subscribers.entries()) {

if (selector) {
const previousValue = this.eventPayloadCache.get(handler);
const previousValue = __classPrivateFieldGet(this, _ControllerMessenger_eventPayloadCache, "f").get(handler);
const newValue = selector(...payload);
if (newValue !== previousValue) {
this.eventPayloadCache.set(handler, newValue);
__classPrivateFieldGet(this, _ControllerMessenger_eventPayloadCache, "f").set(handler, newValue);
handler(newValue, previousValue);

@@ -301,6 +134,6 @@ }

subscribe(eventType, handler, selector) {
let subscribers = this.events.get(eventType);
let subscribers = __classPrivateFieldGet(this, _ControllerMessenger_events, "f").get(eventType);
if (!subscribers) {
subscribers = new Map();
this.events.set(eventType, subscribers);
__classPrivateFieldGet(this, _ControllerMessenger_events, "f").set(eventType, subscribers);
}

@@ -317,6 +150,6 @@ subscribers.set(handler, selector);

* @throws Will throw when the given event handler is not registered for this event.
* @template E - A type union of Event type strings.
* @template EventType - A type union of Event type strings.
*/
unsubscribe(eventType, handler) {
const subscribers = this.events.get(eventType);
const subscribers = __classPrivateFieldGet(this, _ControllerMessenger_events, "f").get(eventType);
if (!subscribers || !subscribers.has(handler)) {

@@ -327,3 +160,3 @@ throw new Error(`Subscription not found for event: ${eventType}`);

if (selector) {
this.eventPayloadCache.delete(handler);
__classPrivateFieldGet(this, _ControllerMessenger_eventPayloadCache, "f").delete(handler);
}

@@ -338,6 +171,6 @@ subscribers.delete(handler);

* @param eventType - The event type. This is a unique identifier for this event.
* @template E - A type union of Event type strings.
* @template EventType - A type union of Event type strings.
*/
clearEventSubscriptions(eventType) {
this.events.delete(eventType);
__classPrivateFieldGet(this, _ControllerMessenger_events, "f").delete(eventType);
}

@@ -350,3 +183,3 @@ /**

clearSubscriptions() {
this.events.clear();
__classPrivateFieldGet(this, _ControllerMessenger_events, "f").clear();
}

@@ -370,3 +203,3 @@ /**

* should be allowed to subscribe to.
* @template N - The namespace for this messenger. Typically this is the name of the controller or
* @template Namespace - The namespace for this messenger. Typically this is the name of the controller or
* module that this messenger has been created for. The authority to publish events and register

@@ -379,3 +212,3 @@ * actions under this namespace is granted to this restricted messenger instance.

getRestricted({ name, allowedActions, allowedEvents, }) {
return new RestrictedControllerMessenger({
return new RestrictedControllerMessenger_1.RestrictedControllerMessenger({
controllerMessenger: this,

@@ -389,2 +222,3 @@ name,

exports.ControllerMessenger = ControllerMessenger;
_ControllerMessenger_actions = new WeakMap(), _ControllerMessenger_events = new WeakMap(), _ControllerMessenger_eventPayloadCache = new WeakMap();
//# sourceMappingURL=ControllerMessenger.js.map
export type { BaseConfig, BaseState, Listener } from './BaseController';
export { BaseController } from './BaseController';
export type { Listener as ListenerV2, StateDeriver, StateMetadata, StatePropertyMetadata, } from './BaseControllerV2';
export { BaseController as BaseControllerV2, getAnonymizedState, getPersistentState, } from './BaseControllerV2';
export { BaseController as BaseControllerV2, getAnonymizedState, getPersistentState, type ControllerGetStateAction, type ControllerStateChangeEvent, } from './BaseControllerV2';
export * from './ControllerMessenger';
export * from './RestrictedControllerMessenger';
//# sourceMappingURL=index.d.ts.map

@@ -25,2 +25,3 @@ "use strict";

__exportStar(require("./ControllerMessenger"), exports);
__exportStar(require("./RestrictedControllerMessenger"), exports);
//# sourceMappingURL=index.js.map
{
"name": "@metamask-previews/base-controller",
"version": "3.2.3-preview.e3b05ea",
"version": "3.2.3-preview.eb58a59",
"description": "Provides scaffolding for controllers as well a communication system for all controllers",

@@ -27,12 +27,13 @@ "keywords": [

"publish:preview": "yarn npm publish --tag preview",
"test": "jest",
"test": "jest --reporters=jest-silent-reporter",
"test:clean": "jest --clearCache",
"test:verbose": "jest --verbose",
"test:watch": "jest --watch"
},
"dependencies": {
"@metamask/utils": "^8.1.0",
"@metamask/utils": "^8.2.0",
"immer": "^9.0.6"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.0",
"@metamask/auto-changelog": "^3.4.3",
"@types/jest": "^27.4.1",

@@ -39,0 +40,0 @@ "@types/sinon": "^9.0.10",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc