@metamask/messenger
Advanced tools
+22
-1
@@ -10,2 +10,22 @@ # Changelog | ||
| ## [2.0.0] | ||
| ### Added | ||
| - Add `Messenger.getRegisteredActionTypes` method, which returns the action types the messenger can call directly ([#9271](https://github.com/MetaMask/core/pull/9271)) | ||
| - Add a `buildChild` utility method to `Messenger` ([#9338](https://github.com/MetaMask/core/pull/9338)) | ||
| ### Changed | ||
| - Bump `@metamask/utils` from `^11.9.0` to `^11.11.0` ([#9074](https://github.com/MetaMask/core/pull/9074)) | ||
| ### Removed | ||
| - **BREAKING:** Remove deprecated `generate-action-types` CLI tool ([#9367](https://github.com/MetaMask/core/pull/9367)) | ||
| - The CLI has been extracted to `@metamask/messenger-cli`. Use `messenger-action-types` from that package instead. | ||
| ### Fixed | ||
| - Fix `Messenger.delegate` and `Messenger.revoke` to reduce the chance of TS2590 errors when delegatee has large number of actions/events or a large number of actions/events are being delegated ([#8748](https://github.com/MetaMask/core/pull/8748)) | ||
| ## [1.2.0] | ||
@@ -100,3 +120,4 @@ | ||
| [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.2.0...HEAD | ||
| [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/messenger@2.0.0...HEAD | ||
| [2.0.0]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.2.0...@metamask/messenger@2.0.0 | ||
| [1.2.0]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.1.1...@metamask/messenger@1.2.0 | ||
@@ -103,0 +124,0 @@ [1.1.1]: https://github.com/MetaMask/core/compare/@metamask/messenger@1.1.0...@metamask/messenger@1.1.1 |
+38
-0
@@ -149,2 +149,16 @@ "use strict"; | ||
| /** | ||
| * Get the types of all actions that this messenger can call directly. | ||
| * | ||
| * This includes actions registered on this messenger as well as actions that | ||
| * have been delegated to it from another messenger. | ||
| * | ||
| * Note that this reflects the registrations on this specific messenger | ||
| * instance. | ||
| * | ||
| * @returns An array of every action type this messenger can call directly. | ||
| */ | ||
| getRegisteredActionTypes() { | ||
| return [...__classPrivateFieldGet(this, _Messenger_actions, "f").keys()]; | ||
| } | ||
| /** | ||
| * Get the action handler for a given action type. | ||
@@ -164,2 +178,26 @@ * | ||
| /** | ||
| * Create a new messenger as a child of this messenger (the "parent"). | ||
| * All actions/events are delegated from the child to the parent, and the specified actions/events are delegated from the parent to the child. | ||
| * | ||
| * @param args - Arguments. | ||
| * @param args.namespace - The child messenger namespace. | ||
| * @param args.actions - A list of action types to delegate to the child messenger. | ||
| * @param args.events - A list of event types to delegate to the child messenger. | ||
| * @returns The child messenger. | ||
| */ | ||
| buildChild({ namespace, actions, events, }) { | ||
| const childMessenger = new Messenger({ | ||
| namespace, | ||
| // @ts-expect-error TypeScript cannot correctly infer this, but should be safe | ||
| // given `ChildAction extends Action` and `ChildEvent extends Event`. | ||
| parent: this, | ||
| }); | ||
| this.delegate({ | ||
| messenger: childMessenger, | ||
| actions, | ||
| events, | ||
| }); | ||
| return childMessenger; | ||
| } | ||
| /** | ||
| * Call an action. | ||
@@ -166,0 +204,0 @@ * |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Messenger.cjs","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAgGA;;;;;;GAMG;AACU,QAAA,kBAAkB,GAAG,oBAAoB,CAAC;AAkFvD;;;;;;;;;;;GAWG;AACH,MAAa,SAAS;IAmEpB;;;;;;;;;;OAUG;IACH,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,MAAM,GASP;;QA5EQ,uCAAsB;QAE/B;;;WAGG;QACM,oCAA6B;QAE7B,6BAAW,IAAI,GAAG,EAAqC,EAAC;QAExD,4BAAU,IAAI,GAAG,EAA8C,EAAC;QAEzE;;WAEG;QACM,mDAAiC,IAAI,GAAG,EAG9C,EAAC;QAEJ;;WAEG;QACM,6CAA2B,IAAI,GAAG,EAGxC,EAAC;QAEJ;;;;WAIG;QACM,gDAA8B,IAAI,GAAG,EAG3C,EAAC;QAEJ;;WAEG;QACM,uC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,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAC1D,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACvB,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC,uDAmFC,SAAkC,EAClC,OAEwB,EACxB,QAA+C;IAE/C,IAAI,WAAW,GAAG,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QACxB,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC,6EAqjBqB,IAAY;IAChC,OAAO,CACL,uBAAA,IAAI,4BAAW,KAAK,0BAAkB;QACtC,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Get the action handler for a given action type.\n *\n * This is a protected method to allow subclasses to override the way action\n * handlers are retrieved, for example to implement custom delegation logic.\n *\n * @param actionType - The action type. This is a unique identifier for this\n * action.\n * @returns The action handler for the given action type, or undefined if no\n * handler has been registered.\n */\n protected getAction(\n actionType: Action['type'],\n ): ActionConstraint['handler'] | undefined {\n return this.#actions.get(actionType);\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.getAction(actionType) as\n | ActionHandler<Action, ActionType>\n | undefined;\n\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Subscribe to an event, with a selector, invoking the handler exactly once.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value. Additionally if the optional condition\n * function is provided, it is checked whether it returns `true`.\n * The handler is invoked at most once, after which the subscription is removed.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload. The type of the parameters for this selector must\n * match the type of the payload for this event type.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (hash) => { ... },\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): void;\n\n /**\n * Subscribe to an event, invoking the handler exactly once.\n *\n * Registers the given function as an event handler for the given event type\n * and automatically unsubscribes after the first invocation.\n *\n * If `options.condition` is provided, the handler is only invoked (and the\n * subscription only removed) when the condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the type of the payload for this event type.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (tx) => { ... },\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): void;\n\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): void {\n const { selector, condition } = options ?? {};\n // Casting to unknown to handle both the code path where a selector is defined and where it is omitted.\n const internalHandler = (...args: unknown[]): void => {\n if (\n condition &&\n !(condition as (...args: unknown[]) => boolean)(...args)\n ) {\n return;\n }\n this.unsubscribe(eventType, internalHandler);\n (handler as (...args: unknown[]) => void)(...args);\n };\n\n this.subscribe(\n eventType,\n internalHandler,\n selector as SelectorFunction<Event, EventType, SelectorReturnValue>,\n );\n }\n\n /**\n * Return a promise that resolves the next time the selector's return value\n * changes and, if provided, the `options.condition` predicate returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @returns A promise that resolves with the selector's return value.\n * @example\n * ```typescript\n * const [hash] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;\n\n /**\n * Return a promise that resolves the next time the given event is published.\n *\n * If `options.condition` is provided, the promise only resolves when the\n * condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @returns A promise that resolves with the event payload.\n * @example\n * ```typescript\n * const [transactionMeta] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n * @example\n * ```typescript\n * await messenger.waitUntil('KeyringController:unlock');\n * ```\n */\n waitUntil<EventType extends Event['type']>(\n eventType: EventType,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): Promise<ExtractEventPayload<Event, EventType>>;\n\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): Promise<SelectorReturnValue | ExtractEventPayload<Event, EventType>[0]> {\n return new Promise((resolve) => {\n this.subscribeOnce(\n eventType,\n (...args) => resolve(args),\n options as {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n );\n });\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.getAction(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]} | ||
| {"version":3,"file":"Messenger.cjs","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAgGA;;;;;;GAMG;AACU,QAAA,kBAAkB,GAAG,oBAAoB,CAAC;AAkFvD;;;;;;;;;;;GAWG;AACH,MAAa,SAAS;IAmEpB;;;;;;;;;;OAUG;IACH,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,MAAM,GASP;;QA5EQ,uCAAsB;QAE/B;;;WAGG;QACM,oCAA6B;QAE7B,6BAAW,IAAI,GAAG,EAAqC,EAAC;QAExD,4BAAU,IAAI,GAAG,EAA8C,EAAC;QAEzE;;WAEG;QACM,mDAAiC,IAAI,GAAG,EAG9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,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Get the types of all actions that this messenger can call directly.\n *\n * This includes actions registered on this messenger as well as actions that\n * have been delegated to it from another messenger.\n *\n * Note that this reflects the registrations on this specific messenger\n * instance.\n *\n * @returns An array of every action type this messenger can call directly.\n */\n getRegisteredActionTypes(): string[] {\n return [...this.#actions.keys()];\n }\n\n /**\n * Get the action handler for a given action type.\n *\n * This is a protected method to allow subclasses to override the way action\n * handlers are retrieved, for example to implement custom delegation logic.\n *\n * @param actionType - The action type. This is a unique identifier for this\n * action.\n * @returns The action handler for the given action type, or undefined if no\n * handler has been registered.\n */\n protected getAction(\n actionType: Action['type'],\n ): ActionConstraint['handler'] | undefined {\n return this.#actions.get(actionType);\n }\n\n /**\n * Create a new messenger as a child of this messenger (the \"parent\").\n * All actions/events are delegated from the child to the parent, and the specified actions/events are delegated from the parent to the child.\n *\n * @param args - Arguments.\n * @param args.namespace - The child messenger namespace.\n * @param args.actions - A list of action types to delegate to the child messenger.\n * @param args.events - A list of event types to delegate to the child messenger.\n * @returns The child messenger.\n */\n buildChild<\n ChildNamespace extends string,\n ChildAction extends Action,\n ChildEvent extends Event,\n >({\n namespace,\n actions,\n events,\n }: {\n namespace: ChildNamespace;\n actions?: ChildAction['type'][];\n events?: ChildEvent['type'][];\n }): Messenger<ChildNamespace, ChildAction, ChildEvent> {\n const childMessenger = new Messenger<\n ChildNamespace,\n ChildAction,\n ChildEvent,\n typeof this\n >({\n namespace,\n // @ts-expect-error TypeScript cannot correctly infer this, but should be safe\n // given `ChildAction extends Action` and `ChildEvent extends Event`.\n parent: this,\n });\n\n this.delegate({\n messenger: childMessenger,\n actions,\n events,\n });\n\n return childMessenger;\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.getAction(actionType) as\n | ActionHandler<Action, ActionType>\n | undefined;\n\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Subscribe to an event, with a selector, invoking the handler exactly once.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value. Additionally if the optional condition\n * function is provided, it is checked whether it returns `true`.\n * The handler is invoked at most once, after which the subscription is removed.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload. The type of the parameters for this selector must\n * match the type of the payload for this event type.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (hash) => { ... },\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): void;\n\n /**\n * Subscribe to an event, invoking the handler exactly once.\n *\n * Registers the given function as an event handler for the given event type\n * and automatically unsubscribes after the first invocation.\n *\n * If `options.condition` is provided, the handler is only invoked (and the\n * subscription only removed) when the condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the type of the payload for this event type.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (tx) => { ... },\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): void;\n\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): void {\n const { selector, condition } = options ?? {};\n // Casting to unknown to handle both the code path where a selector is defined and where it is omitted.\n const internalHandler = (...args: unknown[]): void => {\n if (\n condition &&\n !(condition as (...args: unknown[]) => boolean)(...args)\n ) {\n return;\n }\n this.unsubscribe(eventType, internalHandler);\n (handler as (...args: unknown[]) => void)(...args);\n };\n\n this.subscribe(\n eventType,\n internalHandler,\n selector as SelectorFunction<Event, EventType, SelectorReturnValue>,\n );\n }\n\n /**\n * Return a promise that resolves the next time the selector's return value\n * changes and, if provided, the `options.condition` predicate returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @returns A promise that resolves with the selector's return value.\n * @example\n * ```typescript\n * const [hash] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;\n\n /**\n * Return a promise that resolves the next time the given event is published.\n *\n * If `options.condition` is provided, the promise only resolves when the\n * condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @returns A promise that resolves with the event payload.\n * @example\n * ```typescript\n * const [transactionMeta] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n * @example\n * ```typescript\n * await messenger.waitUntil('KeyringController:unlock');\n * ```\n */\n waitUntil<EventType extends Event['type']>(\n eventType: EventType,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): Promise<ExtractEventPayload<Event, EventType>>;\n\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): Promise<SelectorReturnValue | ExtractEventPayload<Event, EventType>[0]> {\n return new Promise((resolve) => {\n this.subscribeOnce(\n eventType,\n (...args) => resolve(args),\n options as {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n );\n });\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee>['type'] &\n Action['type'])[],\n DelegatedEvents extends (MessengerEvents<Delegatee>['type'] &\n Event['type'])[],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.getAction(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee>['type'] &\n Action['type'])[],\n DelegatedEvents extends (MessengerEvents<Delegatee>['type'] &\n Event['type'])[],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]} |
+29
-2
@@ -148,2 +148,14 @@ export type ActionHandler<Action extends ActionConstraint, ActionType = Action['type']> = (...args: ExtractActionParameters<Action, ActionType>) => ExtractActionResponse<Action, ActionType>; | ||
| /** | ||
| * Get the types of all actions that this messenger can call directly. | ||
| * | ||
| * This includes actions registered on this messenger as well as actions that | ||
| * have been delegated to it from another messenger. | ||
| * | ||
| * Note that this reflects the registrations on this specific messenger | ||
| * instance. | ||
| * | ||
| * @returns An array of every action type this messenger can call directly. | ||
| */ | ||
| getRegisteredActionTypes(): string[]; | ||
| /** | ||
| * Get the action handler for a given action type. | ||
@@ -161,2 +173,17 @@ * | ||
| /** | ||
| * Create a new messenger as a child of this messenger (the "parent"). | ||
| * All actions/events are delegated from the child to the parent, and the specified actions/events are delegated from the parent to the child. | ||
| * | ||
| * @param args - Arguments. | ||
| * @param args.namespace - The child messenger namespace. | ||
| * @param args.actions - A list of action types to delegate to the child messenger. | ||
| * @param args.events - A list of event types to delegate to the child messenger. | ||
| * @returns The child messenger. | ||
| */ | ||
| buildChild<ChildNamespace extends string, ChildAction extends Action, ChildEvent extends Event>({ namespace, actions, events, }: { | ||
| namespace: ChildNamespace; | ||
| actions?: ChildAction['type'][]; | ||
| events?: ChildEvent['type'][]; | ||
| }): Messenger<ChildNamespace, ChildAction, ChildEvent>; | ||
| /** | ||
| * Call an action. | ||
@@ -400,3 +427,3 @@ * | ||
| */ | ||
| delegate<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][], DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][]>({ actions, events, messenger, }: { | ||
| delegate<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee>['type'] & Action['type'])[], DelegatedEvents extends (MessengerEvents<Delegatee>['type'] & Event['type'])[]>({ actions, events, messenger, }: { | ||
| actions?: DelegatedActions; | ||
@@ -420,3 +447,3 @@ events?: DelegatedEvents; | ||
| */ | ||
| revoke<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][], DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][]>({ actions, events, messenger, }: { | ||
| revoke<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee>['type'] & Action['type'])[], DelegatedEvents extends (MessengerEvents<Delegatee>['type'] & Event['type'])[]>({ actions, events, messenger, }: { | ||
| actions?: DelegatedActions; | ||
@@ -423,0 +450,0 @@ events?: DelegatedEvents; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Messenger.d.cts","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,CACvB,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,CACF,GAAG,IAAI,EAAE,uBAAuB,CAAC,MAAM,EAAE,UAAU,CAAC,KACjD,qBAAqB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAE/C,MAAM,MAAM,uBAAuB,CACjC,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,MAAM,SAAS;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,WAAW,KAAK,OAAO,CAAC;CAClD,GACG,WAAW,GACX,KAAK,CAAC;AAEV,MAAM,MAAM,qBAAqB,CAC/B,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IACzB,MAAM,SAAS;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,MAAM,kBAAkB,CAAC;CACzD,GACG,kBAAkB,GAClB,KAAK,CAAC;AAEV,MAAM,MAAM,mBAAmB,CAC7B,KAAK,SAAS,eAAe,EAC7B,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,IACvB,KAAK,SAAS;IAChB,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,MAAM,OAAO,CAAC;CACxB,GACG,OAAO,SAAS,OAAO,EAAE,GACvB,CAAC,GAAG,OAAO,EAAE,OAAO,KAAK,IAAI,GAC7B,KAAK,GACP,KAAK,CAAC;AAEV,MAAM,MAAM,mBAAmB,C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CAAuC,CAAC,UAAU,SAAS,MAAM,CAAC,MAAM,CAAC,EACvE,UAAU,EAAE,UAAU,EAItB,OAAO,EAAE,aAAa,CAAC,gBAAgB,EAAE,UAAU,CAAC,GACnD,IAAI;IAIP;;;;;;;;;;;;OAYG;IACH,yCAAyC,CAAC,UAAU,SAAS,MAAM,CAAC,MAAM,CAAC,EACzE,UAAU,EAAE,UAAU,GACrB,IAAI;IAIP;;;;;;;;;;;;;;;;OAgBG;IACH,6CAA6C,CAC3C,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EAC/B,EACA,SAAS,EACT,UAAU,GACX,EAAE;QACD,SAAS,EAAE,SAAS,CAAC;QACrB,UAAU,EAAE,MAAM,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;KACzD,GAAG,IAAI;IAIR;;;;;;;;;;;;;;;;;OAiBG;IACH,yBAAyB,CAAC,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EACvD,SAAS,EAAE,SAAS,EACpB,GAAG,OAAO,EAAE,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,GAChD,IAAI;CAkBR"} |
+29
-2
@@ -148,2 +148,14 @@ export type ActionHandler<Action extends ActionConstraint, ActionType = Action['type']> = (...args: ExtractActionParameters<Action, ActionType>) => ExtractActionResponse<Action, ActionType>; | ||
| /** | ||
| * Get the types of all actions that this messenger can call directly. | ||
| * | ||
| * This includes actions registered on this messenger as well as actions that | ||
| * have been delegated to it from another messenger. | ||
| * | ||
| * Note that this reflects the registrations on this specific messenger | ||
| * instance. | ||
| * | ||
| * @returns An array of every action type this messenger can call directly. | ||
| */ | ||
| getRegisteredActionTypes(): string[]; | ||
| /** | ||
| * Get the action handler for a given action type. | ||
@@ -161,2 +173,17 @@ * | ||
| /** | ||
| * Create a new messenger as a child of this messenger (the "parent"). | ||
| * All actions/events are delegated from the child to the parent, and the specified actions/events are delegated from the parent to the child. | ||
| * | ||
| * @param args - Arguments. | ||
| * @param args.namespace - The child messenger namespace. | ||
| * @param args.actions - A list of action types to delegate to the child messenger. | ||
| * @param args.events - A list of event types to delegate to the child messenger. | ||
| * @returns The child messenger. | ||
| */ | ||
| buildChild<ChildNamespace extends string, ChildAction extends Action, ChildEvent extends Event>({ namespace, actions, events, }: { | ||
| namespace: ChildNamespace; | ||
| actions?: ChildAction['type'][]; | ||
| events?: ChildEvent['type'][]; | ||
| }): Messenger<ChildNamespace, ChildAction, ChildEvent>; | ||
| /** | ||
| * Call an action. | ||
@@ -400,3 +427,3 @@ * | ||
| */ | ||
| delegate<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][], DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][]>({ actions, events, messenger, }: { | ||
| delegate<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee>['type'] & Action['type'])[], DelegatedEvents extends (MessengerEvents<Delegatee>['type'] & Event['type'])[]>({ actions, events, messenger, }: { | ||
| actions?: DelegatedActions; | ||
@@ -420,3 +447,3 @@ events?: DelegatedEvents; | ||
| */ | ||
| revoke<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][], DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][]>({ actions, events, messenger, }: { | ||
| revoke<Delegatee extends Messenger<string, ActionConstraint, EventConstraint>, DelegatedActions extends (MessengerActions<Delegatee>['type'] & Action['type'])[], DelegatedEvents extends (MessengerEvents<Delegatee>['type'] & Event['type'])[]>({ actions, events, messenger, }: { | ||
| actions?: DelegatedActions; | ||
@@ -423,0 +450,0 @@ events?: DelegatedEvents; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Messenger.d.mts","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,CACvB,MAAM,SAAS,gBAAgB,EAC/B,UAAU,GAAG,MAAM,CAAC,MAA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;;;;;;;;;;OAgBG;IACH,6CAA6C,CAC3C,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EAC/B,EACA,SAAS,EACT,UAAU,GACX,EAAE;QACD,SAAS,EAAE,SAAS,CAAC;QACrB,UAAU,EAAE,MAAM,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;KACzD,GAAG,IAAI;IAIR;;;;;;;;;;;;;;;;;OAiBG;IACH,yBAAyB,CAAC,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,EACvD,SAAS,EAAE,SAAS,EACpB,GAAG,OAAO,EAAE,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC,GAChD,IAAI;CAkBR"} |
+38
-0
@@ -146,2 +146,16 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { | ||
| /** | ||
| * Get the types of all actions that this messenger can call directly. | ||
| * | ||
| * This includes actions registered on this messenger as well as actions that | ||
| * have been delegated to it from another messenger. | ||
| * | ||
| * Note that this reflects the registrations on this specific messenger | ||
| * instance. | ||
| * | ||
| * @returns An array of every action type this messenger can call directly. | ||
| */ | ||
| getRegisteredActionTypes() { | ||
| return [...__classPrivateFieldGet(this, _Messenger_actions, "f").keys()]; | ||
| } | ||
| /** | ||
| * Get the action handler for a given action type. | ||
@@ -161,2 +175,26 @@ * | ||
| /** | ||
| * Create a new messenger as a child of this messenger (the "parent"). | ||
| * All actions/events are delegated from the child to the parent, and the specified actions/events are delegated from the parent to the child. | ||
| * | ||
| * @param args - Arguments. | ||
| * @param args.namespace - The child messenger namespace. | ||
| * @param args.actions - A list of action types to delegate to the child messenger. | ||
| * @param args.events - A list of event types to delegate to the child messenger. | ||
| * @returns The child messenger. | ||
| */ | ||
| buildChild({ namespace, actions, events, }) { | ||
| const childMessenger = new Messenger({ | ||
| namespace, | ||
| // @ts-expect-error TypeScript cannot correctly infer this, but should be safe | ||
| // given `ChildAction extends Action` and `ChildEvent extends Event`. | ||
| parent: this, | ||
| }); | ||
| this.delegate({ | ||
| messenger: childMessenger, | ||
| actions, | ||
| events, | ||
| }); | ||
| return childMessenger; | ||
| } | ||
| /** | ||
| * Call an action. | ||
@@ -163,0 +201,0 @@ * |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"Messenger.mjs","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":";;;;;;;;;;;;AAgGA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAkFvD;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,SAAS;IAmEpB;;;;;;;;;;OAUG;IACH,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,MAAM,GASP;;QA5EQ,uCAAsB;QAE/B;;;WAGG;QACM,oCAA6B;QAE7B,6BAAW,IAAI,GAAG,EAAqC,EAAC;QAExD,4BAAU,IAAI,GAAG,EAA8C,EAAC;QAEzE;;WAEG;QACM,mDAAiC,IAAI,GAAG,EAG9C,EAAC;QAEJ;;WAEG;QACM,6CAA2B,IAAI,GAAG,EAGxC,EAAC;QAEJ;;;;WAIG;QACM,gDAA8B,IAAI,GAAG,EAG3C,EAAC;QAEJ;;WAEG;QACM,uCAAqB,IAAI,GAAG,EAGlC,EAAC;QAiCF,uBAAA,IAAI,wBAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,qBAAW,MAAM,MAAA,CAAC;QACtB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,IAAI,uBAAA,IAAI,yBAAQ,EAAE,gBAAgB,CAAC;IAC7E,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,qBAAqB,CAEnB,UAAsB,EAAE,OAA0C;QAClE,IAAI,CAAC,uBAAA,IAAI,6DAAsB,MAA1B,IAAI,EAAuB,UAAU,CAAC,EAAE,CAAC;YAC5C,MAAM,IAAI,KAAK,CACb,yDACE,uBAAA,IAAI,4BACN,IAAI,CACL,CAAC;QACJ,CAAC;QACD,uBAAA,IAAI,8DAAuB,MAA3B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,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC,6EAqjBqB,IAAY;IAChC,OAAO,CACL,uBAAA,IAAI,4BAAW,KAAK,kBAAkB;QACtC,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Get the action handler for a given action type.\n *\n * This is a protected method to allow subclasses to override the way action\n * handlers are retrieved, for example to implement custom delegation logic.\n *\n * @param actionType - The action type. This is a unique identifier for this\n * action.\n * @returns The action handler for the given action type, or undefined if no\n * handler has been registered.\n */\n protected getAction(\n actionType: Action['type'],\n ): ActionConstraint['handler'] | undefined {\n return this.#actions.get(actionType);\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.getAction(actionType) as\n | ActionHandler<Action, ActionType>\n | undefined;\n\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Subscribe to an event, with a selector, invoking the handler exactly once.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value. Additionally if the optional condition\n * function is provided, it is checked whether it returns `true`.\n * The handler is invoked at most once, after which the subscription is removed.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload. The type of the parameters for this selector must\n * match the type of the payload for this event type.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (hash) => { ... },\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): void;\n\n /**\n * Subscribe to an event, invoking the handler exactly once.\n *\n * Registers the given function as an event handler for the given event type\n * and automatically unsubscribes after the first invocation.\n *\n * If `options.condition` is provided, the handler is only invoked (and the\n * subscription only removed) when the condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the type of the payload for this event type.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (tx) => { ... },\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): void;\n\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): void {\n const { selector, condition } = options ?? {};\n // Casting to unknown to handle both the code path where a selector is defined and where it is omitted.\n const internalHandler = (...args: unknown[]): void => {\n if (\n condition &&\n !(condition as (...args: unknown[]) => boolean)(...args)\n ) {\n return;\n }\n this.unsubscribe(eventType, internalHandler);\n (handler as (...args: unknown[]) => void)(...args);\n };\n\n this.subscribe(\n eventType,\n internalHandler,\n selector as SelectorFunction<Event, EventType, SelectorReturnValue>,\n );\n }\n\n /**\n * Return a promise that resolves the next time the selector's return value\n * changes and, if provided, the `options.condition` predicate returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @returns A promise that resolves with the selector's return value.\n * @example\n * ```typescript\n * const [hash] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;\n\n /**\n * Return a promise that resolves the next time the given event is published.\n *\n * If `options.condition` is provided, the promise only resolves when the\n * condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @returns A promise that resolves with the event payload.\n * @example\n * ```typescript\n * const [transactionMeta] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n * @example\n * ```typescript\n * await messenger.waitUntil('KeyringController:unlock');\n * ```\n */\n waitUntil<EventType extends Event['type']>(\n eventType: EventType,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): Promise<ExtractEventPayload<Event, EventType>>;\n\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): Promise<SelectorReturnValue | ExtractEventPayload<Event, EventType>[0]> {\n return new Promise((resolve) => {\n this.subscribeOnce(\n eventType,\n (...args) => resolve(args),\n options as {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n );\n });\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.getAction(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee> & Action)['type'][],\n DelegatedEvents extends (MessengerEvents<Delegatee> & Event)['type'][],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]} | ||
| {"version":3,"file":"Messenger.mjs","sourceRoot":"","sources":["../src/Messenger.ts"],"names":[],"mappings":";;;;;;;;;;;;AAgGA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAkFvD;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,SAAS;IAmEpB;;;;;;;;;;OAUG;IACH,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,MAAM,GASP;;QA5EQ,uCAAsB;QAE/B;;;WAGG;QACM,oCAA6B;QAE7B,6BAAW,IAAI,GAAG,EAAqC,EAAC;QAExD,4BAAU,IAAI,GAAG,EAA8C,EAAC;QAEzE;;WAEG;QACM,mDAAiC,IAAI,GAAG,EAG9C,EAAC;QAEJ;;WAEG;QACM,6CAA2B,IAAI,GAAG,EAGxC,EAAC;QAEJ;;;;WAIG;QACM,gDAA8B,IAAI,GAAG,EAG3C,EAAC;QAEJ;;WAEG;QACM,uCAAqB,IAAI,GAAG,EAGlC,EAAC;QAiCF,uBAAA,IAAI,wBAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,qBAAW,MAAM,MAAA,CAAC;QACtB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,IAAI,uBAAA,IAAI,yBAAQ,EAAE,gBAAgB,CAAC;IAC7E,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,qBAAqB,CAEnB,UAAsB,EAAE,OAA0C;QAClE,IAAI,CAAC,uBAAA,IAAI,6DAAsB,MAA1B,IAAI,EAAuB,UAAU,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I,CAAC,gBAAgB,CACnB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAC1D,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACvB,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC,uDAmFC,SAAkC,EAClC,OAEwB,EACxB,QAA+C;IAE/C,IAAI,WAAW,GAAG,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QACxB,uBAAA,IAAI,yBAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC,6EAyjBqB,IAAY;IAChC,OAAO,CACL,uBAAA,IAAI,4BAAW,KAAK,kBAAkB;QACtC,IAAI,CAAC,UAAU,CAAC,GAAG,uBAAA,IAAI,4BAAW,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export type ActionHandler<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = (\n ...args: ExtractActionParameters<Action, ActionType>\n) => ExtractActionResponse<Action, ActionType>;\n\nexport type ExtractActionParameters<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer HandlerArgs) => unknown;\n}\n ? HandlerArgs\n : never;\n\nexport type ExtractActionResponse<\n Action extends ActionConstraint,\n ActionType = Action['type'],\n> = Action extends {\n type: ActionType;\n handler: (...args: infer _) => infer HandlerReturnValue;\n}\n ? HandlerReturnValue\n : never;\n\nexport type ExtractEventHandler<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? (...payload: Payload) => void\n : never\n : never;\n\nexport type ExtractEventPayload<\n Event extends EventConstraint,\n EventType = Event['type'],\n> = Event extends {\n type: EventType;\n payload: infer Payload;\n}\n ? Payload extends unknown[]\n ? Payload\n : never\n : never;\n\nexport type GenericEventHandler = (...args: unknown[]) => void;\n\nexport type SelectorFunction<\n Event extends EventConstraint,\n EventType extends Event['type'],\n ReturnValue = unknown,\n> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;\nexport type SelectorEventHandler<SelectorReturnValue = unknown> = (\n newValue: SelectorReturnValue,\n previousValue: SelectorReturnValue | undefined,\n) => void;\n\nexport type ActionConstraint = {\n type: NamespacedName;\n handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);\n};\nexport type EventConstraint = {\n type: NamespacedName;\n payload: unknown[];\n};\n\n/**\n * Extract action types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerActions<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, infer Action, EventConstraint>\n ? Action\n : never;\n\n/**\n * Extract event types from a Messenger type.\n *\n * @template Subject - The messenger type to extract from.\n */\nexport type MessengerEvents<\n Subject extends Messenger<string, ActionConstraint, EventConstraint>,\n> =\n Subject extends Messenger<string, ActionConstraint, infer Event>\n ? Event\n : never;\n\n/**\n * Messenger namespace checks can be disabled by using this as the `namespace` constructor\n * parameter, and using `MockAnyNamespace` as the Namespace type parameter.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';\n\n/**\n * A type representing any namespace.\n *\n * This is useful for mocking a variety of different actions/events in unit tests. Please do not\n * use this in production code.\n */\nexport type MockAnyNamespace = string;\n\n/**\n * Metadata for a single event subscription.\n *\n * @template Event - The event this subscription is for.\n */\ntype SubscriptionMetadata<Event extends EventConstraint> = {\n /**\n * Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored\n * when clearing subscriptions.\n */\n delegation: boolean;\n /**\n * The optional selector function for this subscription.\n */\n selector?: SelectorFunction<Event, Event['type']>;\n};\n\n/**\n * A map of event handlers for a specific event.\n *\n * The key is the handler function, and the value contains additional subscription metadata.\n *\n * @template Event - The event these handlers are for.\n */\ntype EventSubscriptionMap<Event extends EventConstraint> = Map<\n GenericEventHandler | SelectorEventHandler,\n SubscriptionMetadata<Event>\n>;\n\n/**\n * A namespaced string\n *\n * This type verifies that the string Name is prefixed by the string Name followed by a colon.\n *\n * @template Namespace - The namespace we're checking for.\n * @template Name - The full string, including the namespace.\n */\nexport type NamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? Name : never;\n\nexport type NotNamespacedBy<\n Namespace extends string,\n Name extends string,\n> = Name extends `${Namespace}:${string}` ? never : Name;\n\nexport type NamespacedName<Namespace extends string = string> =\n `${Namespace}:${string}`;\n\n/**\n * A messenger that actions and/or events can be delegated to.\n *\n * This is a minimal type interface to avoid complex incompatibilities resulting from generics over\n * invariant types.\n */\ntype DelegatedMessenger = Pick<\n // The type is broadened to all actions/events because some messenger methods are contravariant\n // over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this\n // type is narrowed to just the delegated actions/events, the types for event payload and action\n // parameters would not be wide enough.\n Messenger<string, ActionConstraint, EventConstraint>,\n | '_internalPublishDelegated'\n | '_internalRegisterDelegatedActionHandler'\n | '_internalRegisterDelegatedInitialEventPayload'\n | '_internalUnregisterDelegatedActionHandler'\n | 'captureException'\n>;\n\ntype StripNamespace<Namespaced extends NamespacedName> =\n Namespaced extends `${string}:${infer Name}` ? Name : never;\n\n/**\n * A message broker for \"actions\" and \"events\".\n *\n * The messenger allows registering functions as 'actions' that can be called elsewhere,\n * and it allows publishing and subscribing to events. Both actions and events are identified by\n * unique strings prefixed by a namespace (which is delimited by a colon, e.g.\n * `Namespace:actionName`).\n *\n * @template Action - A type union of all Action types.\n * @template Event - A type union of all Event types.\n * @template Namespace - The namespace for the messenger.\n */\nexport class Messenger<\n Namespace extends string,\n Action extends ActionConstraint = never,\n Event extends EventConstraint = never,\n Parent extends Messenger<\n string,\n ActionConstraint,\n EventConstraint,\n // Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type\n // constraint anyway, it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n > = never,\n> {\n readonly #namespace: Namespace;\n\n /**\n * The parent messenger. All actions/events under this namespace are automatically delegated to\n * the parent messenger.\n */\n readonly #parent?: DelegatedMessenger;\n\n readonly #actions = new Map<Action['type'], Action['handler']>();\n\n readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();\n\n /**\n * The set of messengers we've delegated events to and their event handlers, by event type.\n */\n readonly #subscriptionDelegationTargets = new Map<\n Event['type'],\n Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>\n >();\n\n /**\n * The set of messengers we've delegated actions to, by action type.\n */\n readonly #actionDelegationTargets = new Map<\n Action['type'],\n Set<DelegatedMessenger>\n >();\n\n /**\n * A map of functions for getting the initial event payload.\n *\n * Used only for events that represent state changes.\n */\n readonly #initialEventPayloadGetters = new Map<\n Event['type'],\n () => ExtractEventPayload<Event, Event['type']>\n >();\n\n /**\n * A cache of selector return values for their respective handlers.\n */\n readonly #eventPayloadCache = new Map<\n GenericEventHandler,\n unknown | undefined\n >();\n\n /**\n * Reports an error to an error monitoring service.\n *\n * @param error - The error to report.\n */\n readonly captureException?: (error: Error) => void;\n\n /**\n * Construct a messenger.\n *\n * If a parent messenger is given, all actions and events under this messenger's namespace will\n * be delegated to the parent automatically.\n *\n * @param args - Constructor arguments\n * @param args.captureException - Reports an error to an error monitoring service.\n * @param args.namespace - The messenger namespace.\n * @param args.parent - The parent messenger.\n */\n constructor({\n captureException,\n namespace,\n parent,\n }: {\n captureException?: (error: Error) => void;\n namespace: Namespace;\n parent?: Action['type'] extends MessengerActions<Parent>['type']\n ? Event['type'] extends MessengerEvents<Parent>['type']\n ? Parent\n : never\n : never;\n }) {\n this.#namespace = namespace;\n this.#parent = parent;\n this.captureException = captureException ?? this.#parent?.captureException;\n }\n\n /**\n * Register an action handler.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * The action being registered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n registerActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed registering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#registerActionHandler(actionType, handler);\n if (this.#parent) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // action, but this is OK because it's validated in the constructor.\n this.delegate({ actions: [actionType], messenger: this.#parent });\n }\n }\n\n #registerActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n if (this.#actions.has(actionType)) {\n throw new Error(\n `A handler for ${actionType} has already been registered`,\n );\n }\n this.#actions.set(actionType, handler);\n }\n\n /**\n * Registers action handlers for a list of methods on a messenger client\n *\n * @param messengerClient - The object that is expected to make use of the messenger.\n * @param methodNames - The names of the methods on the messenger client to register as action\n * handlers.\n * @template MessengerClient - The type expected to make use of the messenger.\n * @template MethodNames - The type union of method names to register as action handlers.\n */\n registerMethodActionHandlers<\n MessengerClient extends { name: Namespace },\n MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,\n >(\n messengerClient: MessengerClient,\n methodNames: readonly MethodNames[],\n ): void {\n for (const methodName of methodNames) {\n const method = messengerClient[methodName];\n if (typeof method === 'function') {\n const actionType = `${messengerClient.name}:${methodName}` as const;\n this.registerActionHandler(actionType, method.bind(messengerClient));\n }\n }\n }\n\n /**\n * Unregister an action handler.\n *\n * This will prevent this action from being called.\n *\n * The action being unregistered must be under the same namespace as the messenger.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @template ActionType - A type union of Action type strings under this messenger's namespace.\n */\n unregisterActionHandler<\n ActionType extends Action['type'] & NamespacedName<Namespace>,\n >(actionType: ActionType): void {\n if (!this.#isInCurrentNamespace(actionType)) {\n throw new Error(\n `Only allowed unregistering action handlers prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n this.#unregisterActionHandler(actionType);\n }\n\n #unregisterActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#actions.delete(actionType);\n }\n\n /**\n * Unregister all action handlers.\n *\n * This prevents all actions from being called.\n */\n clearActions(): void {\n for (const actionType of this.#actions.keys()) {\n this.#unregisterActionHandler(actionType);\n }\n }\n\n /**\n * Get the types of all actions that this messenger can call directly.\n *\n * This includes actions registered on this messenger as well as actions that\n * have been delegated to it from another messenger.\n *\n * Note that this reflects the registrations on this specific messenger\n * instance.\n *\n * @returns An array of every action type this messenger can call directly.\n */\n getRegisteredActionTypes(): string[] {\n return [...this.#actions.keys()];\n }\n\n /**\n * Get the action handler for a given action type.\n *\n * This is a protected method to allow subclasses to override the way action\n * handlers are retrieved, for example to implement custom delegation logic.\n *\n * @param actionType - The action type. This is a unique identifier for this\n * action.\n * @returns The action handler for the given action type, or undefined if no\n * handler has been registered.\n */\n protected getAction(\n actionType: Action['type'],\n ): ActionConstraint['handler'] | undefined {\n return this.#actions.get(actionType);\n }\n\n /**\n * Create a new messenger as a child of this messenger (the \"parent\").\n * All actions/events are delegated from the child to the parent, and the specified actions/events are delegated from the parent to the child.\n *\n * @param args - Arguments.\n * @param args.namespace - The child messenger namespace.\n * @param args.actions - A list of action types to delegate to the child messenger.\n * @param args.events - A list of event types to delegate to the child messenger.\n * @returns The child messenger.\n */\n buildChild<\n ChildNamespace extends string,\n ChildAction extends Action,\n ChildEvent extends Event,\n >({\n namespace,\n actions,\n events,\n }: {\n namespace: ChildNamespace;\n actions?: ChildAction['type'][];\n events?: ChildEvent['type'][];\n }): Messenger<ChildNamespace, ChildAction, ChildEvent> {\n const childMessenger = new Messenger<\n ChildNamespace,\n ChildAction,\n ChildEvent,\n typeof this\n >({\n namespace,\n // @ts-expect-error TypeScript cannot correctly infer this, but should be safe\n // given `ChildAction extends Action` and `ChildEvent extends Event`.\n parent: this,\n });\n\n this.delegate({\n messenger: childMessenger,\n actions,\n events,\n });\n\n return childMessenger;\n }\n\n /**\n * Call an action.\n *\n * This function will call the action handler corresponding to the given action type, passing\n * along any parameters given.\n *\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param params - The action parameters. These must match the type of the parameters of the\n * registered action handler.\n * @throws Will throw when no handler has been registered for the given type.\n * @template ActionType - A type union of Action type strings.\n * @returns The action return value.\n */\n call<ActionType extends Action['type']>(\n actionType: ActionType,\n ...params: ExtractActionParameters<Action, ActionType>\n ): ExtractActionResponse<Action, ActionType> {\n const handler = this.getAction(actionType) as\n | ActionHandler<Action, ActionType>\n | undefined;\n\n if (!handler) {\n throw new Error(\n this.#isInCurrentNamespace(actionType)\n ? `A handler for ${actionType} has not been registered`\n : `A handler for ${actionType} has not been delegated to ${this.#namespace}`,\n );\n }\n\n return handler(...params);\n }\n\n /**\n * Register a function for getting the initial payload for an event.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * The event type must be under the same namespace as the messenger.\n *\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n registerInitialEventPayload<\n EventType extends Event['type'] & NamespacedName<Namespace>,\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed registering initial payloads for events prefixed by '${\n this.#namespace\n }:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n #registerInitialEventPayload<EventType extends Event['type']>({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#initialEventPayloadGetters.set(eventType, getPayload);\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n return;\n }\n for (const messenger of delegationTargets.keys()) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n }\n\n /**\n * Publish an event.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * The event being published must be under the same namespace as the messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings under this messenger's namespace.\n */\n publish<EventType extends Event['type'] & NamespacedName<Namespace>>(\n eventType: EventType & NamespacedName<Namespace>,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n if (!this.#isInCurrentNamespace(eventType)) {\n throw new Error(\n `Only allowed publishing events prefixed by '${this.#namespace}:'`,\n );\n }\n if (\n this.#parent &&\n !this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)\n ) {\n // @ts-expect-error The parent type isn't constructed in a way that proves it supports this\n // event, but this is OK because it's validated in the constructor.\n this.delegate({ events: [eventType], messenger: this.#parent });\n }\n this.#publish(eventType, ...payload);\n }\n\n #publish<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n const subscribers = this.#events.get(eventType);\n\n if (subscribers) {\n for (const [handler, { selector }] of subscribers.entries()) {\n try {\n if (selector) {\n const previousValue = this.#eventPayloadCache.get(handler);\n const newValue = selector(...payload);\n\n if (newValue !== previousValue) {\n this.#eventPayloadCache.set(handler, newValue);\n handler(newValue, previousValue);\n }\n } else {\n (handler as GenericEventHandler)(...payload);\n }\n } catch (error) {\n // Capture error without interrupting the event publishing.\n if (this.captureException) {\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n );\n } else {\n console.error(error);\n }\n }\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * Registers the given function as an event handler for the given event type.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n */\n subscribe<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n ): void;\n\n /**\n * Subscribe to an event, with a selector.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param selector - The selector function used to select relevant data from\n * the event payload. The type of the parameters for this selector must match\n * the type of the payload for this event type.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void;\n\n subscribe<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,\n ): void {\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This cast means the type system is not guaranteeing the handler is called with the matching\n // input selector return value. The parameter types do ensure they match when `subscribe` is\n // called, but past that point we need to make sure of that with manual review and tests\n // instead.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n this.#subscribe(eventType, widenedHandler, { delegation: false, selector });\n\n if (selector) {\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n const initialValue = selector(...getPayload());\n this.#eventPayloadCache.set(widenedHandler, initialValue);\n }\n }\n }\n\n /**\n * Subscribe to an event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event handler must\n * match the type of the payload for this event type.\n * @param metadata - Event metadata.\n * @template SubscribedEvent - The event being subscribed to.\n * @template SelectorReturnValue - The selector return value.\n */\n #subscribe<SubscribedEvent extends EventConstraint>(\n eventType: SubscribedEvent['type'],\n handler:\n | ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>\n | SelectorEventHandler,\n metadata: SubscriptionMetadata<SubscribedEvent>,\n ): void {\n let subscribers = this.#events.get(eventType);\n if (!subscribers) {\n subscribers = new Map();\n this.#events.set(eventType, subscribers);\n }\n subscribers.set(handler, metadata);\n }\n\n /**\n * Subscribe to an event, with a selector, invoking the handler exactly once.\n *\n * Registers the given handler function as an event handler for the given\n * event type. When an event is published, its payload is first passed to the\n * selector. The event handler is only called if the selector's return value\n * differs from its last known return value. Additionally if the optional condition\n * function is provided, it is checked whether it returns `true`.\n * The handler is invoked at most once, after which the subscription is removed.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the return type of the selector.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload. The type of the parameters for this selector must\n * match the type of the payload for this event type.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (hash) => { ... },\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler: SelectorEventHandler<SelectorReturnValue>,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): void;\n\n /**\n * Subscribe to an event, invoking the handler exactly once.\n *\n * Registers the given function as an event handler for the given event type\n * and automatically unsubscribes after the first invocation.\n *\n * If `options.condition` is provided, the handler is only invoked (and the\n * subscription only removed) when the condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler. The type of the parameters for this event\n * handler must match the type of the payload for this event type.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The handler is only invoked when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @example\n * ```typescript\n * messenger.subscribeOnce(\n * 'TransactionController:transactionConfirmed',\n * (tx) => { ... },\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n */\n subscribeOnce<EventType extends Event['type']>(\n eventType: EventType,\n handler: ExtractEventHandler<Event, EventType>,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): void;\n\n subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): void {\n const { selector, condition } = options ?? {};\n // Casting to unknown to handle both the code path where a selector is defined and where it is omitted.\n const internalHandler = (...args: unknown[]): void => {\n if (\n condition &&\n !(condition as (...args: unknown[]) => boolean)(...args)\n ) {\n return;\n }\n this.unsubscribe(eventType, internalHandler);\n (handler as (...args: unknown[]) => void)(...args);\n };\n\n this.subscribe(\n eventType,\n internalHandler,\n selector as SelectorFunction<Event, EventType, SelectorReturnValue>,\n );\n }\n\n /**\n * Return a promise that resolves the next time the selector's return value\n * changes and, if provided, the `options.condition` predicate returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.selector - The selector function used to select relevant data\n * from the event payload.\n * @param options.condition - An optional predicate evaluated against the\n * selector's return value. The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n * @returns A promise that resolves with the selector's return value.\n * @example\n * ```typescript\n * const [hash] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },\n * );\n * ```\n */\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options: {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n ): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;\n\n /**\n * Return a promise that resolves the next time the given event is published.\n *\n * If `options.condition` is provided, the promise only resolves when the\n * condition returns `true`.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param options - Options bag.\n * @param options.condition - A predicate evaluated against the event payload.\n * The promise only resolves when this returns `true`.\n * @template EventType - A type union of Event type strings.\n * @returns A promise that resolves with the event payload.\n * @example\n * ```typescript\n * const [transactionMeta] = await messenger.waitUntil(\n * 'TransactionController:transactionConfirmed',\n * { condition: (tx) => tx.hash === 'foo' },\n * );\n * ```\n * @example\n * ```typescript\n * await messenger.waitUntil('KeyringController:unlock');\n * ```\n */\n waitUntil<EventType extends Event['type']>(\n eventType: EventType,\n options?: {\n condition?: (\n ...payload: ExtractEventPayload<Event, EventType>\n ) => boolean;\n },\n ): Promise<ExtractEventPayload<Event, EventType>>;\n\n waitUntil<EventType extends Event['type'], SelectorReturnValue>(\n eventType: EventType,\n options?: {\n selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?:\n | ((...payload: ExtractEventPayload<Event, EventType>) => boolean)\n | ((value: SelectorReturnValue) => boolean);\n },\n ): Promise<SelectorReturnValue | ExtractEventPayload<Event, EventType>[0]> {\n return new Promise((resolve) => {\n this.subscribeOnce(\n eventType,\n (...args) => resolve(args),\n options as {\n selector: SelectorFunction<Event, EventType, SelectorReturnValue>;\n condition?: (value: SelectorReturnValue) => boolean;\n },\n );\n });\n }\n\n /**\n * Unsubscribe from an event.\n *\n * Unregisters the given function as an event handler for the given event.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param handler - The event handler to unregister.\n * @throws Will throw when the given event handler is not registered for this event.\n * @template EventType - A type union of Event type strings.\n * @template SelectorReturnValue - The selector return value.\n */\n unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(\n eventType: EventType,\n handler:\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler<SelectorReturnValue>,\n ): void {\n const subscribers = this.#events.get(eventType);\n\n // Widen type of event handler by dropping ReturnType parameter.\n //\n // We need to drop it here because it's used as the parameter to the event handler, and\n // functions in general are contravariant over the parameter type. This means the type is no\n // longer valid once it's added to a broader type union with other handlers (because as far\n // as TypeScript knows, we might call the handler with output from a different selector).\n //\n // This poses no risk in this case, since we never call the handler past this point.\n const widenedHandler = handler as\n | ExtractEventHandler<Event, EventType>\n | SelectorEventHandler;\n if (!subscribers) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n const metadata = subscribers.get(widenedHandler);\n if (!metadata) {\n throw new Error(`Subscription not found for event: ${eventType}`);\n }\n if (metadata.selector) {\n this.#eventPayloadCache.delete(widenedHandler);\n }\n\n subscribers.delete(widenedHandler);\n }\n\n /**\n * Clear subscriptions for a specific event.\n *\n * This will remove all subscribed handlers for this event registered from this messenger. The\n * event may still have subscribers if it has been delegated to another messenger.\n *\n * @param eventType - The event type. This is a unique identifier for this event.\n * @template EventType - A type union of Event type strings.\n */\n clearEventSubscriptions<EventType extends Event['type']>(\n eventType: EventType,\n ): void {\n const subscriptions = this.#events.get(eventType);\n if (!subscriptions) {\n return;\n }\n\n for (const [handler, metadata] of subscriptions.entries()) {\n if (metadata.delegation) {\n continue;\n }\n subscriptions.delete(handler);\n }\n\n if (subscriptions.size === 0) {\n this.#events.delete(eventType);\n }\n }\n\n /**\n * Clear all subscriptions.\n *\n * This will remove all subscribed handlers for all events registered from this messenger. Events\n * may still have subscribers if they are delegated to another messenger.\n */\n clearSubscriptions(): void {\n for (const eventType of this.#events.keys()) {\n this.clearEventSubscriptions(eventType);\n }\n }\n\n /**\n * Delegate actions and/or events to another messenger.\n *\n * The messenger these actions/events are delegated to will be able to call these actions and\n * subscribe to these events.\n *\n * Note that the messenger these actions/events are delegated to must still have these\n * actions/events included in its type definition (as part of the Action and Event type\n * parameters). Actions and events are statically type checked, they cannot be delegated\n * dynamically at runtime.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to delegate.\n * @param args.events - The event types to delegate.\n * @param args.messenger - The messenger to delegate to.\n * @template Delegatee - The messenger the actions/events are delegated to.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n delegate<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee>['type'] &\n Action['type'])[],\n DelegatedEvents extends (MessengerEvents<Delegatee>['type'] &\n Event['type'])[],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n for (const actionType of actions ?? []) {\n const delegatedActionHandler = (\n ...args: ExtractActionParameters<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n ): ExtractActionResponse<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n > => {\n // Cast to get more specific type, for this specific action\n // The types get collapsed by `this.#actions`\n const actionHandler = this.getAction(actionType) as\n | ActionHandler<\n MessengerActions<Delegatee> & Action,\n typeof actionType\n >\n | undefined;\n\n if (!actionHandler) {\n throw new Error(\n `A handler for ${actionType} has not been registered`,\n );\n }\n\n return actionHandler(...args);\n };\n let delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets) {\n delegationTargets = new Set<DelegatedMessenger>();\n this.#actionDelegationTargets.set(actionType, delegationTargets);\n }\n if (delegationTargets.has(messenger)) {\n throw new Error(\n `The action '${actionType}' has already been delegated to this messenger`,\n );\n }\n delegationTargets.add(messenger);\n\n messenger._internalRegisterDelegatedActionHandler(\n actionType,\n delegatedActionHandler,\n );\n }\n for (const eventType of events ?? []) {\n const untypedSubscriber = (\n ...payload: ExtractEventPayload<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >\n ): void => {\n messenger._internalPublishDelegated(eventType, ...payload);\n };\n // Cast to get more specific subscriber type for this specific event.\n // The types get collapsed here to the type union of all delegated\n // events, rather than the single subscriber type corresponding to this\n // event.\n const subscriber = untypedSubscriber as ExtractEventHandler<\n MessengerEvents<Delegatee> & Event,\n typeof eventType\n >;\n let delegatedEventSubscriptions =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegatedEventSubscriptions) {\n delegatedEventSubscriptions = new Map();\n this.#subscriptionDelegationTargets.set(\n eventType,\n delegatedEventSubscriptions,\n );\n }\n if (delegatedEventSubscriptions.has(messenger)) {\n throw new Error(\n `The event '${eventType}' has already been delegated to this messenger`,\n );\n }\n delegatedEventSubscriptions.set(messenger, subscriber);\n const getPayload = this.#initialEventPayloadGetters.get(eventType);\n if (getPayload) {\n messenger._internalRegisterDelegatedInitialEventPayload({\n eventType,\n getPayload,\n });\n }\n\n this.#subscribe(eventType, subscriber, { delegation: true });\n }\n }\n\n /**\n * Revoke delegated actions and/or events from another messenger.\n *\n * The messenger these actions/events are delegated to will no longer be able to call these\n * actions or subscribe to these events.\n *\n * @param args - Arguments.\n * @param args.actions - The action types to revoke.\n * @param args.events - The event types to revoke.\n * @param args.messenger - The messenger these actions/events were delegated to.\n * @template Delegatee - The messenger the actions/events are being revoked from.\n * @template DelegatedActions - An array of delegated action types.\n * @template DelegatedEvents - An array of delegated event types.\n */\n revoke<\n Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,\n DelegatedActions extends (MessengerActions<Delegatee>['type'] &\n Action['type'])[],\n DelegatedEvents extends (MessengerEvents<Delegatee>['type'] &\n Event['type'])[],\n >({\n actions,\n events,\n messenger,\n }: {\n actions?: DelegatedActions;\n events?: DelegatedEvents;\n messenger: Delegatee;\n }): void {\n if (messenger === this.#parent) {\n throw new Error('Cannot revoke from parent');\n }\n for (const actionType of actions ?? []) {\n const delegationTargets = this.#actionDelegationTargets.get(actionType);\n if (!delegationTargets?.has(messenger)) {\n // Nothing to revoke\n continue;\n }\n messenger._internalUnregisterDelegatedActionHandler(actionType);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#actionDelegationTargets.delete(actionType);\n }\n }\n for (const eventType of events ?? []) {\n const delegationTargets =\n this.#subscriptionDelegationTargets.get(eventType);\n if (!delegationTargets) {\n // Nothing to revoke\n continue;\n }\n const delegatedSubscriber = delegationTargets.get(messenger);\n if (!delegatedSubscriber) {\n // Nothing to revoke\n continue;\n }\n this.unsubscribe(eventType, delegatedSubscriber);\n delegationTargets.delete(messenger);\n if (delegationTargets.size === 0) {\n this.#subscriptionDelegationTargets.delete(eventType);\n }\n }\n }\n\n /**\n * Register an action handler for an action delegated from another messenger.\n *\n * This will make the registered function available to call via the `call` method.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unique identifier for this action.\n * @param handler - The action handler. This function gets called when the `call` method is\n * invoked with the given action type.\n * @throws Will throw when a handler has been registered for this action type already.\n * @template ActionType - A type union of Action type strings.\n */\n _internalRegisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n // Using wider `ActionConstraint` type here rather than `Action` because the `Action` type is\n // contravariant over the handler parameter type. Using `Action` would lead to a type error\n // here because the messenger we've delegated to supports _additional_ actions.\n handler: ActionHandler<ActionConstraint, ActionType>,\n ): void {\n this.#registerActionHandler(actionType, handler);\n }\n\n /**\n * Unregister an action handler for an action delegated from another messenger.\n *\n * This will prevent this action from being called.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param actionType - The action type. This is a unqiue identifier for this action.\n * @template ActionType - A type union of Action type strings.\n */\n _internalUnregisterDelegatedActionHandler<ActionType extends Action['type']>(\n actionType: ActionType,\n ): void {\n this.#unregisterActionHandler(actionType);\n }\n\n /**\n * Register a function for getting the initial payload for an event that has been delegated from\n * another messenger.\n *\n * This is used for events that represent a state change, where the payload is the state.\n * Registering a function for getting the payload allows event selectors to have a point of\n * comparison the first time state changes.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param args - The arguments to this function\n * @param args.eventType - The event type to register a payload for.\n * @param args.getPayload - A function for retrieving the event payload.\n */\n _internalRegisterDelegatedInitialEventPayload<\n EventType extends Event['type'],\n >({\n eventType,\n getPayload,\n }: {\n eventType: EventType;\n getPayload: () => ExtractEventPayload<Event, EventType>;\n }): void {\n this.#registerInitialEventPayload({ eventType, getPayload });\n }\n\n /**\n * Publish an event that was delegated from another messenger.\n *\n * Publishes the given payload to all subscribers of the given event type.\n *\n * Note that this method should never throw directly. Any errors from\n * subscribers are captured and re-thrown in a timeout handler.\n *\n * Note: This is an internal method. Never access this property from another module. This must be\n * exposed as a public property so that these methods can be called internally on other messenger\n * instances.\n *\n * @deprecated Internal use only. Use the `delegate` method for delegation.\n * @param eventType - The event type. This is a unique identifier for this event.\n * @param payload - The event payload. The type of the parameters for each event handler must\n * match the type of this payload.\n * @template EventType - A type union of Event type strings.\n */\n _internalPublishDelegated<EventType extends Event['type']>(\n eventType: EventType,\n ...payload: ExtractEventPayload<Event, EventType>\n ): void {\n this.#publish(eventType, ...payload);\n }\n\n /**\n * Determine whether the given name is within the current namespace.\n *\n * If the current namespace is MOCK_ANY_NAMESPACE, this check always returns true.\n *\n * @param name - The name to check\n * @returns Whether the name is within the current namespace\n */\n #isInCurrentNamespace(name: string): name is NamespacedName<Namespace> {\n return (\n this.#namespace === MOCK_ANY_NAMESPACE ||\n name.startsWith(`${this.#namespace}:`)\n );\n }\n}\n"]} |
+2
-9
| { | ||
| "name": "@metamask/messenger", | ||
| "version": "1.2.0", | ||
| "version": "2.0.0", | ||
| "description": "A type-safe message bus library", | ||
@@ -18,5 +18,2 @@ "keywords": [ | ||
| }, | ||
| "bin": { | ||
| "messenger-generate-action-types": "./dist/generate-action-types/cli.mjs" | ||
| }, | ||
| "files": [ | ||
@@ -58,4 +55,3 @@ "dist/" | ||
| "dependencies": { | ||
| "@metamask/utils": "^11.9.0", | ||
| "yargs": "^17.7.2" | ||
| "@metamask/utils": "^11.11.0" | ||
| }, | ||
@@ -66,6 +62,3 @@ "devDependencies": { | ||
| "@types/jest": "^29.5.14", | ||
| "@types/yargs": "^17.0.32", | ||
| "deepmerge": "^4.2.2", | ||
| "eslint": "^9.39.1", | ||
| "execa": "^5.0.0", | ||
| "immer": "^9.0.6", | ||
@@ -72,0 +65,0 @@ "jest": "^29.7.0", |
| "use strict"; | ||
| var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| var desc = Object.getOwnPropertyDescriptor(m, k); | ||
| if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
| desc = { enumerable: true, get: function() { return m[k]; } }; | ||
| } | ||
| Object.defineProperty(o, k2, desc); | ||
| }) : (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| o[k2] = m[k]; | ||
| })); | ||
| var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
| Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
| }) : function(o, v) { | ||
| o["default"] = v; | ||
| }); | ||
| var __importStar = (this && this.__importStar) || function (mod) { | ||
| if (mod && mod.__esModule) return mod; | ||
| var result = {}; | ||
| if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); | ||
| __setModuleDefault(result, mod); | ||
| return result; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.checkActionTypesFiles = void 0; | ||
| const fs = __importStar(require("node:fs")); | ||
| const path = __importStar(require("node:path")); | ||
| const generate_content_1 = require("./generate-content.cjs"); | ||
| /** | ||
| * Checks if generated action types files are up to date. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files are up to date. | ||
| */ | ||
| async function checkActionTypesFiles(sources, eslint) { | ||
| let hasErrors = false; | ||
| const fileComparisonJobs = []; | ||
| try { | ||
| for (const source of sources) { | ||
| console.log(`\n🔧 Checking ${source.name}...`); | ||
| const outputDir = path.dirname(source.filePath); | ||
| const baseFileName = path.basename(source.filePath, '.ts'); | ||
| const actualFile = path.join(outputDir, `${baseFileName}-method-action-types.ts`); | ||
| const expectedContent = (0, generate_content_1.generateActionTypesContent)(source); | ||
| const expectedTempFile = actualFile.replace('.ts', '.tmp.ts'); | ||
| try { | ||
| await fs.promises.access(actualFile); | ||
| await fs.promises.writeFile(expectedTempFile, expectedContent, 'utf8'); | ||
| fileComparisonJobs.push({ | ||
| expectedTempFile, | ||
| actualFile, | ||
| baseFileName, | ||
| }); | ||
| } | ||
| catch (error) { | ||
| if (error.code === 'ENOENT') { | ||
| console.error(`❌ ${baseFileName}-method-action-types.ts does not exist`); | ||
| } | ||
| else { | ||
| console.error(`❌ Error reading ${baseFileName}-method-action-types.ts:`, error); | ||
| } | ||
| hasErrors = true; | ||
| } | ||
| } | ||
| if (fileComparisonJobs.length > 0) { | ||
| if (eslint) { | ||
| console.log('\n📝 Running ESLint to compare files...'); | ||
| const results = await eslint.instance.lintFiles(fileComparisonJobs.map((job) => job.expectedTempFile)); | ||
| await eslint.eslintClass.outputFixes(results); | ||
| } | ||
| for (const job of fileComparisonJobs) { | ||
| const expectedContent = await fs.promises.readFile(job.expectedTempFile, 'utf8'); | ||
| const actualContent = await fs.promises.readFile(job.actualFile, 'utf8'); | ||
| if (expectedContent === actualContent) { | ||
| console.log(`✅ ${job.baseFileName}-method-action-types.ts is up to date`); | ||
| } | ||
| else { | ||
| console.error(`❌ ${job.baseFileName}-method-action-types.ts is out of date`); | ||
| hasErrors = true; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| finally { | ||
| for (const job of fileComparisonJobs) { | ||
| try { | ||
| await fs.promises.unlink(job.expectedTempFile); | ||
| } | ||
| catch { | ||
| // Ignore cleanup errors | ||
| } | ||
| } | ||
| } | ||
| if (hasErrors) { | ||
| console.error('\n💥 Some action type files are out of date or missing.'); | ||
| console.error('Run `yarn generate-method-action-types --fix` to update them.'); | ||
| return false; | ||
| } | ||
| console.log('\n🎉 All action type files are up to date!'); | ||
| return true; | ||
| } | ||
| exports.checkActionTypesFiles = checkActionTypesFiles; | ||
| //# sourceMappingURL=check.cjs.map |
| {"version":3,"file":"check.cjs","sourceRoot":"","sources":["../../src/generate-action-types/check.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,4CAA8B;AAC9B,gDAAkC;AAElC,6DAAgE;AAIhE;;;;;;GAMG;AACI,KAAK,UAAU,qBAAqB,CACzC,OAAqB,EACrB,MAAqB;IAErB,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB,MAAM,kBAAkB,GAIlB,EAAE,CAAC;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,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAC1D,OAAO,IAAI,CAAC;AACd,CAAC;AAtGD,sDAsGC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { generateActionTypesContent } from './generate-content';\nimport type { SourceInfo } from './parse-source';\nimport type { ESLint } from './types';\n\n/**\n * Checks if generated action types files are up to date.\n *\n * @param sources - Array of source information objects.\n * @param eslint - Optional ESLint instance and static methods for formatting.\n * @returns Whether all files are up to date.\n */\nexport async function checkActionTypesFiles(\n sources: SourceInfo[],\n eslint: ESLint | null,\n): Promise<boolean> {\n let hasErrors = false;\n\n const fileComparisonJobs: {\n expectedTempFile: string;\n actualFile: string;\n baseFileName: string;\n }[] = [];\n\n try {\n for (const source of sources) {\n console.log(`\\n🔧 Checking ${source.name}...`);\n const outputDir = path.dirname(source.filePath);\n const baseFileName = path.basename(source.filePath, '.ts');\n const actualFile = path.join(\n outputDir,\n `${baseFileName}-method-action-types.ts`,\n );\n\n const expectedContent = generateActionTypesContent(source);\n const expectedTempFile = actualFile.replace('.ts', '.tmp.ts');\n\n try {\n await fs.promises.access(actualFile);\n\n await fs.promises.writeFile(expectedTempFile, expectedContent, 'utf8');\n\n fileComparisonJobs.push({\n expectedTempFile,\n actualFile,\n baseFileName,\n });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n console.error(\n `❌ ${baseFileName}-method-action-types.ts does not exist`,\n );\n } else {\n console.error(\n `❌ Error reading ${baseFileName}-method-action-types.ts:`,\n error,\n );\n }\n hasErrors = true;\n }\n }\n\n if (fileComparisonJobs.length > 0) {\n if (eslint) {\n console.log('\\n📝 Running ESLint to compare files...');\n\n const results = await eslint.instance.lintFiles(\n fileComparisonJobs.map((job) => job.expectedTempFile),\n );\n await eslint.eslintClass.outputFixes(results);\n }\n\n for (const job of fileComparisonJobs) {\n const expectedContent = await fs.promises.readFile(\n job.expectedTempFile,\n 'utf8',\n );\n const actualContent = await fs.promises.readFile(\n job.actualFile,\n 'utf8',\n );\n\n if (expectedContent === actualContent) {\n console.log(\n `✅ ${job.baseFileName}-method-action-types.ts is up to date`,\n );\n } else {\n console.error(\n `❌ ${job.baseFileName}-method-action-types.ts is out of date`,\n );\n hasErrors = true;\n }\n }\n }\n } finally {\n for (const job of fileComparisonJobs) {\n try {\n await fs.promises.unlink(job.expectedTempFile);\n } catch {\n // Ignore cleanup errors\n }\n }\n }\n\n if (hasErrors) {\n console.error('\\n💥 Some action type files are out of date or missing.');\n console.error(\n 'Run `yarn generate-method-action-types --fix` to update them.',\n );\n return false;\n }\n\n console.log('\\n🎉 All action type files are up to date!');\n return true;\n}\n"]} |
| import type { SourceInfo } from "./parse-source.cjs"; | ||
| import type { ESLint } from "./types.cjs"; | ||
| /** | ||
| * Checks if generated action types files are up to date. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files are up to date. | ||
| */ | ||
| export declare function checkActionTypesFiles(sources: SourceInfo[], eslint: ESLint | null): Promise<boolean>; | ||
| //# sourceMappingURL=check.d.cts.map |
| {"version":3,"file":"check.d.cts","sourceRoot":"","sources":["../../src/generate-action-types/check.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,2BAAuB;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAgB;AAEtC;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,UAAU,EAAE,EACrB,MAAM,EAAE,MAAM,GAAG,IAAI,GACpB,OAAO,CAAC,OAAO,CAAC,CAmGlB"} |
| import type { SourceInfo } from "./parse-source.mjs"; | ||
| import type { ESLint } from "./types.mjs"; | ||
| /** | ||
| * Checks if generated action types files are up to date. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files are up to date. | ||
| */ | ||
| export declare function checkActionTypesFiles(sources: SourceInfo[], eslint: ESLint | null): Promise<boolean>; | ||
| //# sourceMappingURL=check.d.mts.map |
| {"version":3,"file":"check.d.mts","sourceRoot":"","sources":["../../src/generate-action-types/check.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,2BAAuB;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAgB;AAEtC;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,UAAU,EAAE,EACrB,MAAM,EAAE,MAAM,GAAG,IAAI,GACpB,OAAO,CAAC,OAAO,CAAC,CAmGlB"} |
| import * as fs from "node:fs"; | ||
| import * as path from "node:path"; | ||
| import { generateActionTypesContent } from "./generate-content.mjs"; | ||
| /** | ||
| * Checks if generated action types files are up to date. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files are up to date. | ||
| */ | ||
| export async function checkActionTypesFiles(sources, eslint) { | ||
| let hasErrors = false; | ||
| const fileComparisonJobs = []; | ||
| try { | ||
| for (const source of sources) { | ||
| console.log(`\n🔧 Checking ${source.name}...`); | ||
| const outputDir = path.dirname(source.filePath); | ||
| const baseFileName = path.basename(source.filePath, '.ts'); | ||
| const actualFile = path.join(outputDir, `${baseFileName}-method-action-types.ts`); | ||
| const expectedContent = generateActionTypesContent(source); | ||
| const expectedTempFile = actualFile.replace('.ts', '.tmp.ts'); | ||
| try { | ||
| await fs.promises.access(actualFile); | ||
| await fs.promises.writeFile(expectedTempFile, expectedContent, 'utf8'); | ||
| fileComparisonJobs.push({ | ||
| expectedTempFile, | ||
| actualFile, | ||
| baseFileName, | ||
| }); | ||
| } | ||
| catch (error) { | ||
| if (error.code === 'ENOENT') { | ||
| console.error(`❌ ${baseFileName}-method-action-types.ts does not exist`); | ||
| } | ||
| else { | ||
| console.error(`❌ Error reading ${baseFileName}-method-action-types.ts:`, error); | ||
| } | ||
| hasErrors = true; | ||
| } | ||
| } | ||
| if (fileComparisonJobs.length > 0) { | ||
| if (eslint) { | ||
| console.log('\n📝 Running ESLint to compare files...'); | ||
| const results = await eslint.instance.lintFiles(fileComparisonJobs.map((job) => job.expectedTempFile)); | ||
| await eslint.eslintClass.outputFixes(results); | ||
| } | ||
| for (const job of fileComparisonJobs) { | ||
| const expectedContent = await fs.promises.readFile(job.expectedTempFile, 'utf8'); | ||
| const actualContent = await fs.promises.readFile(job.actualFile, 'utf8'); | ||
| if (expectedContent === actualContent) { | ||
| console.log(`✅ ${job.baseFileName}-method-action-types.ts is up to date`); | ||
| } | ||
| else { | ||
| console.error(`❌ ${job.baseFileName}-method-action-types.ts is out of date`); | ||
| hasErrors = true; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| finally { | ||
| for (const job of fileComparisonJobs) { | ||
| try { | ||
| await fs.promises.unlink(job.expectedTempFile); | ||
| } | ||
| catch { | ||
| // Ignore cleanup errors | ||
| } | ||
| } | ||
| } | ||
| if (hasErrors) { | ||
| console.error('\n💥 Some action type files are out of date or missing.'); | ||
| console.error('Run `yarn generate-method-action-types --fix` to update them.'); | ||
| return false; | ||
| } | ||
| console.log('\n🎉 All action type files are up to date!'); | ||
| return true; | ||
| } | ||
| //# sourceMappingURL=check.mjs.map |
| {"version":3,"file":"check.mjs","sourceRoot":"","sources":["../../src/generate-action-types/check.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB;AAC9B,OAAO,KAAK,IAAI,kBAAkB;AAElC,OAAO,EAAE,0BAA0B,EAAE,+BAA2B;AAIhE;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,OAAqB,EACrB,MAAqB;IAErB,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB,MAAM,kBAAkB,GAIlB,EAAE,CAAC;IAET,IAAI,CAAC;QACH,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,OAAO,CAAC,GAAG,C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,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { generateActionTypesContent } from './generate-content';\nimport type { SourceInfo } from './parse-source';\nimport type { ESLint } from './types';\n\n/**\n * Checks if generated action types files are up to date.\n *\n * @param sources - Array of source information objects.\n * @param eslint - Optional ESLint instance and static methods for formatting.\n * @returns Whether all files are up to date.\n */\nexport async function checkActionTypesFiles(\n sources: SourceInfo[],\n eslint: ESLint | null,\n): Promise<boolean> {\n let hasErrors = false;\n\n const fileComparisonJobs: {\n expectedTempFile: string;\n actualFile: string;\n baseFileName: string;\n }[] = [];\n\n try {\n for (const source of sources) {\n console.log(`\\n🔧 Checking ${source.name}...`);\n const outputDir = path.dirname(source.filePath);\n const baseFileName = path.basename(source.filePath, '.ts');\n const actualFile = path.join(\n outputDir,\n `${baseFileName}-method-action-types.ts`,\n );\n\n const expectedContent = generateActionTypesContent(source);\n const expectedTempFile = actualFile.replace('.ts', '.tmp.ts');\n\n try {\n await fs.promises.access(actualFile);\n\n await fs.promises.writeFile(expectedTempFile, expectedContent, 'utf8');\n\n fileComparisonJobs.push({\n expectedTempFile,\n actualFile,\n baseFileName,\n });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n console.error(\n `❌ ${baseFileName}-method-action-types.ts does not exist`,\n );\n } else {\n console.error(\n `❌ Error reading ${baseFileName}-method-action-types.ts:`,\n error,\n );\n }\n hasErrors = true;\n }\n }\n\n if (fileComparisonJobs.length > 0) {\n if (eslint) {\n console.log('\\n📝 Running ESLint to compare files...');\n\n const results = await eslint.instance.lintFiles(\n fileComparisonJobs.map((job) => job.expectedTempFile),\n );\n await eslint.eslintClass.outputFixes(results);\n }\n\n for (const job of fileComparisonJobs) {\n const expectedContent = await fs.promises.readFile(\n job.expectedTempFile,\n 'utf8',\n );\n const actualContent = await fs.promises.readFile(\n job.actualFile,\n 'utf8',\n );\n\n if (expectedContent === actualContent) {\n console.log(\n `✅ ${job.baseFileName}-method-action-types.ts is up to date`,\n );\n } else {\n console.error(\n `❌ ${job.baseFileName}-method-action-types.ts is out of date`,\n );\n hasErrors = true;\n }\n }\n }\n } finally {\n for (const job of fileComparisonJobs) {\n try {\n await fs.promises.unlink(job.expectedTempFile);\n } catch {\n // Ignore cleanup errors\n }\n }\n }\n\n if (hasErrors) {\n console.error('\\n💥 Some action type files are out of date or missing.');\n console.error(\n 'Run `yarn generate-method-action-types --fix` to update them.',\n );\n return false;\n }\n\n console.log('\\n🎉 All action type files are up to date!');\n return true;\n}\n"]} |
| #!/usr/bin/env node | ||
| "use strict"; | ||
| var __importDefault = (this && this.__importDefault) || function (mod) { | ||
| return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| const yargs_1 = __importDefault(require("yargs")); | ||
| const check_1 = require("./check.cjs"); | ||
| const fix_1 = require("./fix.cjs"); | ||
| const parse_source_1 = require("./parse-source.cjs"); | ||
| /** | ||
| * Parses the given CLI arguments. | ||
| * | ||
| * @param args - The arguments to parse. | ||
| * @returns The parsed command line arguments. | ||
| */ | ||
| async function parseCommandLineArguments(args) { | ||
| const { check, fix, path: sourcePath, } = await (0, yargs_1.default)(args) | ||
| .command('$0 [path]', 'Generate method action types for controller and service messengers', (yargsInstance) => { | ||
| yargsInstance.positional('path', { | ||
| type: 'string', | ||
| description: 'Path to the folder where controllers/services are located', | ||
| default: 'src', | ||
| }); | ||
| }) | ||
| .option('check', { | ||
| type: 'boolean', | ||
| description: 'Check if generated action type files are up to date', | ||
| default: false, | ||
| }) | ||
| .option('fix', { | ||
| type: 'boolean', | ||
| description: 'Generate/update action type files', | ||
| default: false, | ||
| }) | ||
| .help() | ||
| .check((argv) => { | ||
| if (!argv.check && !argv.fix) { | ||
| throw new Error('Either --check or --fix must be provided.\n'); | ||
| } | ||
| return true; | ||
| }).argv; | ||
| return { | ||
| check, | ||
| fix, | ||
| sourcePath: sourcePath, | ||
| }; | ||
| } | ||
| /** | ||
| * Attempt to load ESLint from the current project. Returns null if unavailable. | ||
| * | ||
| * @returns An ESLint object with instance and static methods, or null if unavailable. | ||
| */ | ||
| async function loadESLint() { | ||
| try { | ||
| const { ESLint: ESLintClass } = await import("eslint"); | ||
| const instance = new ESLintClass({ | ||
| fix: true, | ||
| errorOnUnmatchedPattern: false, | ||
| }); | ||
| return { | ||
| instance, | ||
| eslintClass: ESLintClass, | ||
| }; | ||
| } | ||
| catch { | ||
| console.warn('⚠️ ESLint could not be loaded. Generated files will not be formatted.'); | ||
| return null; | ||
| } | ||
| } | ||
| /** | ||
| * Main entry point for the CLI. | ||
| */ | ||
| async function main() { | ||
| console.warn('⚠️ `messenger-generate-action-types` from @metamask/messenger is deprecated. Use `messenger-action-types` from @metamask/messenger-cli instead.'); | ||
| const { fix, sourcePath } = await parseCommandLineArguments(globalThis.process.argv.slice(2)); | ||
| console.log('🔍 Searching for controllers/services with MESSENGER_EXPOSED_METHODS...'); | ||
| const sources = await (0, parse_source_1.findSourcesWithExposedMethods)(sourcePath); | ||
| if (sources.length === 0) { | ||
| console.log('⚠️ No controllers/services found with MESSENGER_EXPOSED_METHODS'); | ||
| return; | ||
| } | ||
| console.log(`📦 Found ${sources.length} controller(s)/service(s) with exposed methods`); | ||
| const eslint = await loadESLint(); | ||
| if (fix) { | ||
| const success = await (0, fix_1.generateAllActionTypesFiles)(sources, eslint); | ||
| if (success) { | ||
| console.log('\n🎉 All action types generated successfully!'); | ||
| } | ||
| else { | ||
| // eslint-disable-next-line no-restricted-globals | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| else { | ||
| const success = await (0, check_1.checkActionTypesFiles)(sources, eslint); | ||
| if (!success) { | ||
| // eslint-disable-next-line no-restricted-globals | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| } | ||
| main().catch((error) => { | ||
| console.error('❌ Script failed:', error); | ||
| // eslint-disable-next-line no-restricted-globals | ||
| process.exitCode = 1; | ||
| }); | ||
| //# sourceMappingURL=cli.cjs.map |
| {"version":3,"file":"cli.cjs","sourceRoot":"","sources":["../../src/generate-action-types/cli.ts"],"names":[],"mappings":";;;;;;AAEA,kDAA0B;AAE1B,uCAAgD;AAChD,mCAAoD;AACpD,qDAA+D;AAS/D;;;;;GAKG;AACH,KAAK,UAAU,yBAAyB,CACtC,IAAc;IAEd,MAAM,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EAAE,UAAU,GACjB,GAAG,MAAM,IAAA,eAAK,EAAC,IAAI,CAAC;SAClB,OAAO,CACN,WAAW,EACX,oEAAoE,EACpE,CAAC,aAAa,EAAE,EAAE;QAChB,aAAa,CAAC,UAAU,CAAC,MAAM,EAAE;YAC/B,IAAI,EAAE,QAAQ;YACd,WAAW,EACT,2DAA2D;YAC7D,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;IACL,CAAC,CACF;SACA,MAAM,CAAC,OAAO,EAAE;QACf,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,qDAAqD;QAClE,OAAO,EAAE,KAAK;KACf,CAAC;SACD,MAAM,CAAC,KAAK,EAAE;QACb,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,mCAAmC;QAChD,OAAO,EAAE,KAAK;KACf,CAAC;SACD,IAAI,EAAE;SACN,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE;QACd,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;QACjE,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC,IAAI,CAAC;IAEV,OAAO;QACL,KAAK;QACL,GAAG;QACH,UAAU,EAAE,UAAoB;KACjC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,UAAU;IACvB,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,MAAM,UAAU,CAAC;QACvD,MA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AC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC7D,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,iDAAiD;YACjD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,iDAAiD;IACjD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport yargs from 'yargs';\n\nimport { checkActionTypesFiles } from './check';\nimport { generateAllActionTypesFiles } from './fix';\nimport { findSourcesWithExposedMethods } from './parse-source';\nimport type { ESLint } from './types';\n\ntype CommandLineArguments = {\n check: boolean;\n fix: boolean;\n sourcePath: string;\n};\n\n/**\n * Parses the given CLI arguments.\n *\n * @param args - The arguments to parse.\n * @returns The parsed command line arguments.\n */\nasync function parseCommandLineArguments(\n args: string[],\n): Promise<CommandLineArguments> {\n const {\n check,\n fix,\n path: sourcePath,\n } = await yargs(args)\n .command(\n '$0 [path]',\n 'Generate method action types for controller and service messengers',\n (yargsInstance) => {\n yargsInstance.positional('path', {\n type: 'string',\n description:\n 'Path to the folder where controllers/services are located',\n default: 'src',\n });\n },\n )\n .option('check', {\n type: 'boolean',\n description: 'Check if generated action type files are up to date',\n default: false,\n })\n .option('fix', {\n type: 'boolean',\n description: 'Generate/update action type files',\n default: false,\n })\n .help()\n .check((argv) => {\n if (!argv.check && !argv.fix) {\n throw new Error('Either --check or --fix must be provided.\\n');\n }\n return true;\n }).argv;\n\n return {\n check,\n fix,\n sourcePath: sourcePath as string,\n };\n}\n\n/**\n * Attempt to load ESLint from the current project. Returns null if unavailable.\n *\n * @returns An ESLint object with instance and static methods, or null if unavailable.\n */\nasync function loadESLint(): Promise<ESLint | null> {\n try {\n const { ESLint: ESLintClass } = await import('eslint');\n const instance = new ESLintClass({\n fix: true,\n errorOnUnmatchedPattern: false,\n });\n return {\n instance,\n eslintClass: ESLintClass,\n };\n } catch {\n console.warn(\n '⚠️ ESLint could not be loaded. Generated files will not be formatted.',\n );\n return null;\n }\n}\n\n/**\n * Main entry point for the CLI.\n */\nasync function main(): Promise<void> {\n console.warn(\n '⚠️ `messenger-generate-action-types` from @metamask/messenger is deprecated. Use `messenger-action-types` from @metamask/messenger-cli instead.',\n );\n\n const { fix, sourcePath } = await parseCommandLineArguments(\n globalThis.process.argv.slice(2),\n );\n\n console.log(\n '🔍 Searching for controllers/services with MESSENGER_EXPOSED_METHODS...',\n );\n\n const sources = await findSourcesWithExposedMethods(sourcePath);\n\n if (sources.length === 0) {\n console.log(\n '⚠️ No controllers/services found with MESSENGER_EXPOSED_METHODS',\n );\n return;\n }\n\n console.log(\n `📦 Found ${sources.length} controller(s)/service(s) with exposed methods`,\n );\n\n const eslint = await loadESLint();\n\n if (fix) {\n const success = await generateAllActionTypesFiles(sources, eslint);\n if (success) {\n console.log('\\n🎉 All action types generated successfully!');\n } else {\n // eslint-disable-next-line no-restricted-globals\n process.exitCode = 1;\n }\n } else {\n const success = await checkActionTypesFiles(sources, eslint);\n if (!success) {\n // eslint-disable-next-line no-restricted-globals\n process.exitCode = 1;\n }\n }\n}\n\nmain().catch((error) => {\n console.error('❌ Script failed:', error);\n // eslint-disable-next-line no-restricted-globals\n process.exitCode = 1;\n});\n"]} |
| #!/usr/bin/env node | ||
| export {}; | ||
| //# sourceMappingURL=cli.d.cts.map |
| {"version":3,"file":"cli.d.cts","sourceRoot":"","sources":["../../src/generate-action-types/cli.ts"],"names":[],"mappings":""} |
| #!/usr/bin/env node | ||
| export {}; | ||
| //# sourceMappingURL=cli.d.mts.map |
| {"version":3,"file":"cli.d.mts","sourceRoot":"","sources":["../../src/generate-action-types/cli.ts"],"names":[],"mappings":""} |
| #!/usr/bin/env node | ||
| import yargs from "yargs"; | ||
| import { checkActionTypesFiles } from "./check.mjs"; | ||
| import { generateAllActionTypesFiles } from "./fix.mjs"; | ||
| import { findSourcesWithExposedMethods } from "./parse-source.mjs"; | ||
| /** | ||
| * Parses the given CLI arguments. | ||
| * | ||
| * @param args - The arguments to parse. | ||
| * @returns The parsed command line arguments. | ||
| */ | ||
| async function parseCommandLineArguments(args) { | ||
| const { check, fix, path: sourcePath, } = await yargs(args) | ||
| .command('$0 [path]', 'Generate method action types for controller and service messengers', (yargsInstance) => { | ||
| yargsInstance.positional('path', { | ||
| type: 'string', | ||
| description: 'Path to the folder where controllers/services are located', | ||
| default: 'src', | ||
| }); | ||
| }) | ||
| .option('check', { | ||
| type: 'boolean', | ||
| description: 'Check if generated action type files are up to date', | ||
| default: false, | ||
| }) | ||
| .option('fix', { | ||
| type: 'boolean', | ||
| description: 'Generate/update action type files', | ||
| default: false, | ||
| }) | ||
| .help() | ||
| .check((argv) => { | ||
| if (!argv.check && !argv.fix) { | ||
| throw new Error('Either --check or --fix must be provided.\n'); | ||
| } | ||
| return true; | ||
| }).argv; | ||
| return { | ||
| check, | ||
| fix, | ||
| sourcePath: sourcePath, | ||
| }; | ||
| } | ||
| /** | ||
| * Attempt to load ESLint from the current project. Returns null if unavailable. | ||
| * | ||
| * @returns An ESLint object with instance and static methods, or null if unavailable. | ||
| */ | ||
| async function loadESLint() { | ||
| try { | ||
| const { ESLint: ESLintClass } = await import("eslint"); | ||
| const instance = new ESLintClass({ | ||
| fix: true, | ||
| errorOnUnmatchedPattern: false, | ||
| }); | ||
| return { | ||
| instance, | ||
| eslintClass: ESLintClass, | ||
| }; | ||
| } | ||
| catch { | ||
| console.warn('⚠️ ESLint could not be loaded. Generated files will not be formatted.'); | ||
| return null; | ||
| } | ||
| } | ||
| /** | ||
| * Main entry point for the CLI. | ||
| */ | ||
| async function main() { | ||
| console.warn('⚠️ `messenger-generate-action-types` from @metamask/messenger is deprecated. Use `messenger-action-types` from @metamask/messenger-cli instead.'); | ||
| const { fix, sourcePath } = await parseCommandLineArguments(globalThis.process.argv.slice(2)); | ||
| console.log('🔍 Searching for controllers/services with MESSENGER_EXPOSED_METHODS...'); | ||
| const sources = await findSourcesWithExposedMethods(sourcePath); | ||
| if (sources.length === 0) { | ||
| console.log('⚠️ No controllers/services found with MESSENGER_EXPOSED_METHODS'); | ||
| return; | ||
| } | ||
| console.log(`📦 Found ${sources.length} controller(s)/service(s) with exposed methods`); | ||
| const eslint = await loadESLint(); | ||
| if (fix) { | ||
| const success = await generateAllActionTypesFiles(sources, eslint); | ||
| if (success) { | ||
| console.log('\n🎉 All action types generated successfully!'); | ||
| } | ||
| else { | ||
| // eslint-disable-next-line no-restricted-globals | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| else { | ||
| const success = await checkActionTypesFiles(sources, eslint); | ||
| if (!success) { | ||
| // eslint-disable-next-line no-restricted-globals | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| } | ||
| main().catch((error) => { | ||
| console.error('❌ Script failed:', error); | ||
| // eslint-disable-next-line no-restricted-globals | ||
| process.exitCode = 1; | ||
| }); | ||
| //# sourceMappingURL=cli.mjs.map |
| {"version":3,"file":"cli.mjs","sourceRoot":"","sources":["../../src/generate-action-types/cli.ts"],"names":[],"mappings":";AAEA,OAAO,KAAK,cAAc;AAE1B,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,OAAO,EAAE,2BAA2B,EAAE,kBAAc;AACpD,OAAO,EAAE,6BAA6B,EAAE,2BAAuB;AAS/D;;;;;GAKG;AACH,KAAK,UAAU,yBAAyB,CACtC,IAAc;IAEd,MAAM,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EAAE,UAAU,GACjB,GAAG,MAAM,KAAK,CAAC,IAAI,CAAC;SAClB,OAAO,CACN,WAAW,EACX,oEAAoE,EACpE,CAAC,aAAa,EAAE,EAAE;QAChB,aAAa,CAAC,UAAU,CAAC,MAAM,EAAE;YAC/B,IAAI,EAAE,QAAQ;YACd,WAAW,EACT,2DAA2D;YAC7D,OAAO,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AC,CAAC,CACjC,CAAC;IAEF,OAAO,CAAC,GAAG,CACT,yEAAyE,CAC1E,CAAC;IAEF,MAAM,OAAO,GAAG,MAAM,6BAA6B,CAAC,UAAU,CAAC,CAAC;IAEhE,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,CAAC,GAAG,CACT,kEAAkE,CACnE,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,GAAG,CACT,YAAY,OAAO,CAAC,MAAM,gDAAgD,CAC3E,CAAC;IAEF,MAAM,MAAM,GAAG,MAAM,UAAU,EAAE,CAAC;IAElC,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,OAAO,GAAG,MAAM,2BAA2B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACnE,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,+CAA+C,CAAC,CAAC;QAC/D,CAAC;aAAM,CAAC;YACN,iDAAiD;YACjD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,OAAO,GAAG,MAAM,qBAAqB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC7D,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,iDAAiD;YACjD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,iDAAiD;IACjD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport yargs from 'yargs';\n\nimport { checkActionTypesFiles } from './check';\nimport { generateAllActionTypesFiles } from './fix';\nimport { findSourcesWithExposedMethods } from './parse-source';\nimport type { ESLint } from './types';\n\ntype CommandLineArguments = {\n check: boolean;\n fix: boolean;\n sourcePath: string;\n};\n\n/**\n * Parses the given CLI arguments.\n *\n * @param args - The arguments to parse.\n * @returns The parsed command line arguments.\n */\nasync function parseCommandLineArguments(\n args: string[],\n): Promise<CommandLineArguments> {\n const {\n check,\n fix,\n path: sourcePath,\n } = await yargs(args)\n .command(\n '$0 [path]',\n 'Generate method action types for controller and service messengers',\n (yargsInstance) => {\n yargsInstance.positional('path', {\n type: 'string',\n description:\n 'Path to the folder where controllers/services are located',\n default: 'src',\n });\n },\n )\n .option('check', {\n type: 'boolean',\n description: 'Check if generated action type files are up to date',\n default: false,\n })\n .option('fix', {\n type: 'boolean',\n description: 'Generate/update action type files',\n default: false,\n })\n .help()\n .check((argv) => {\n if (!argv.check && !argv.fix) {\n throw new Error('Either --check or --fix must be provided.\\n');\n }\n return true;\n }).argv;\n\n return {\n check,\n fix,\n sourcePath: sourcePath as string,\n };\n}\n\n/**\n * Attempt to load ESLint from the current project. Returns null if unavailable.\n *\n * @returns An ESLint object with instance and static methods, or null if unavailable.\n */\nasync function loadESLint(): Promise<ESLint | null> {\n try {\n const { ESLint: ESLintClass } = await import('eslint');\n const instance = new ESLintClass({\n fix: true,\n errorOnUnmatchedPattern: false,\n });\n return {\n instance,\n eslintClass: ESLintClass,\n };\n } catch {\n console.warn(\n '⚠️ ESLint could not be loaded. Generated files will not be formatted.',\n );\n return null;\n }\n}\n\n/**\n * Main entry point for the CLI.\n */\nasync function main(): Promise<void> {\n console.warn(\n '⚠️ `messenger-generate-action-types` from @metamask/messenger is deprecated. Use `messenger-action-types` from @metamask/messenger-cli instead.',\n );\n\n const { fix, sourcePath } = await parseCommandLineArguments(\n globalThis.process.argv.slice(2),\n );\n\n console.log(\n '🔍 Searching for controllers/services with MESSENGER_EXPOSED_METHODS...',\n );\n\n const sources = await findSourcesWithExposedMethods(sourcePath);\n\n if (sources.length === 0) {\n console.log(\n '⚠️ No controllers/services found with MESSENGER_EXPOSED_METHODS',\n );\n return;\n }\n\n console.log(\n `📦 Found ${sources.length} controller(s)/service(s) with exposed methods`,\n );\n\n const eslint = await loadESLint();\n\n if (fix) {\n const success = await generateAllActionTypesFiles(sources, eslint);\n if (success) {\n console.log('\\n🎉 All action types generated successfully!');\n } else {\n // eslint-disable-next-line no-restricted-globals\n process.exitCode = 1;\n }\n } else {\n const success = await checkActionTypesFiles(sources, eslint);\n if (!success) {\n // eslint-disable-next-line no-restricted-globals\n process.exitCode = 1;\n }\n }\n}\n\nmain().catch((error) => {\n console.error('❌ Script failed:', error);\n // eslint-disable-next-line no-restricted-globals\n process.exitCode = 1;\n});\n"]} |
| "use strict"; | ||
| var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| var desc = Object.getOwnPropertyDescriptor(m, k); | ||
| if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
| desc = { enumerable: true, get: function() { return m[k]; } }; | ||
| } | ||
| Object.defineProperty(o, k2, desc); | ||
| }) : (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| o[k2] = m[k]; | ||
| })); | ||
| var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
| Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
| }) : function(o, v) { | ||
| o["default"] = v; | ||
| }); | ||
| var __importStar = (this && this.__importStar) || function (mod) { | ||
| if (mod && mod.__esModule) return mod; | ||
| var result = {}; | ||
| if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); | ||
| __setModuleDefault(result, mod); | ||
| return result; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.generateAllActionTypesFiles = void 0; | ||
| const fs = __importStar(require("node:fs")); | ||
| const path = __importStar(require("node:path")); | ||
| const generate_content_1 = require("./generate-content.cjs"); | ||
| /** | ||
| * Generates action types files for all controllers/services. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files were generated successfully. | ||
| */ | ||
| async function generateAllActionTypesFiles(sources, eslint) { | ||
| const outputFiles = []; | ||
| for (const source of sources) { | ||
| console.log(`\n🔧 Processing ${source.name}...`); | ||
| const outputDir = path.dirname(source.filePath); | ||
| const baseFileName = path.basename(source.filePath, '.ts'); | ||
| const outputFile = path.join(outputDir, `${baseFileName}-method-action-types.ts`); | ||
| const generatedContent = (0, generate_content_1.generateActionTypesContent)(source); | ||
| await fs.promises.writeFile(outputFile, generatedContent, 'utf8'); | ||
| outputFiles.push(outputFile); | ||
| console.log(`✅ Generated action types for ${source.name}`); | ||
| } | ||
| if (outputFiles.length > 0 && eslint) { | ||
| console.log('\n📝 Running ESLint on generated files...'); | ||
| const results = await eslint.instance.lintFiles(outputFiles); | ||
| await eslint.eslintClass.outputFixes(results); | ||
| const errors = eslint.eslintClass.getErrorResults(results); | ||
| if (errors.length > 0) { | ||
| console.error('❌ ESLint errors:', errors); | ||
| return false; | ||
| } | ||
| console.log('✅ ESLint formatting applied'); | ||
| } | ||
| return true; | ||
| } | ||
| exports.generateAllActionTypesFiles = generateAllActionTypesFiles; | ||
| //# sourceMappingURL=fix.cjs.map |
| {"version":3,"file":"fix.cjs","sourceRoot":"","sources":["../../src/generate-action-types/fix.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,4CAA8B;AAC9B,gDAAkC;AAElC,6DAAgE;AAIhE;;;;;;GAMG;AACI,KAAK,UAAU,2BAA2B,CAC/C,OAAqB,EACrB,MAAqB;IAErB,MAAM,WAAW,GAAa,EAAE,CAAC;IAEjC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,OAAO,CAAC,GAAG,CAAC,mBAAmB,MAAM,CAAC,IAAI,KAAK,CAAC,CAAC;QACjD,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAChD,MAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC3D,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAC1B,SAAS,EACT,GAAG,YAAY,yBAAyB,CACzC,CAAC;QAEF,MAAM,gBAAgB,GAAG,IAAA,6CAA0B,EAAC,MAAM,CAAC,CAAC;QAC5D,MAAM,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,UAAU,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;QAClE,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC7B,OAAO,CAAC,GAAG,CAAC,gCAAgC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,EAAE,CAAC;QACrC,OAAO,CAAC,GAAG,CAAC,2CAA2C,CAAC,CAAC;QAEzD,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAC7D,MAAM,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC9C,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;QAC3D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC;YAC1C,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAnCD,kEAmCC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { generateActionTypesContent } from './generate-content';\nimport type { SourceInfo } from './parse-source';\nimport type { ESLint } from './types';\n\n/**\n * Generates action types files for all controllers/services.\n *\n * @param sources - Array of source information objects.\n * @param eslint - Optional ESLint instance and static methods for formatting.\n * @returns Whether all files were generated successfully.\n */\nexport async function generateAllActionTypesFiles(\n sources: SourceInfo[],\n eslint: ESLint | null,\n): Promise<boolean> {\n const outputFiles: string[] = [];\n\n for (const source of sources) {\n console.log(`\\n🔧 Processing ${source.name}...`);\n const outputDir = path.dirname(source.filePath);\n const baseFileName = path.basename(source.filePath, '.ts');\n const outputFile = path.join(\n outputDir,\n `${baseFileName}-method-action-types.ts`,\n );\n\n const generatedContent = generateActionTypesContent(source);\n await fs.promises.writeFile(outputFile, generatedContent, 'utf8');\n outputFiles.push(outputFile);\n console.log(`✅ Generated action types for ${source.name}`);\n }\n\n if (outputFiles.length > 0 && eslint) {\n console.log('\\n📝 Running ESLint on generated files...');\n\n const results = await eslint.instance.lintFiles(outputFiles);\n await eslint.eslintClass.outputFixes(results);\n const errors = eslint.eslintClass.getErrorResults(results);\n if (errors.length > 0) {\n console.error('❌ ESLint errors:', errors);\n return false;\n }\n console.log('✅ ESLint formatting applied');\n }\n\n return true;\n}\n"]} |
| import type { SourceInfo } from "./parse-source.cjs"; | ||
| import type { ESLint } from "./types.cjs"; | ||
| /** | ||
| * Generates action types files for all controllers/services. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files were generated successfully. | ||
| */ | ||
| export declare function generateAllActionTypesFiles(sources: SourceInfo[], eslint: ESLint | null): Promise<boolean>; | ||
| //# sourceMappingURL=fix.d.cts.map |
| {"version":3,"file":"fix.d.cts","sourceRoot":"","sources":["../../src/generate-action-types/fix.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,2BAAuB;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAgB;AAEtC;;;;;;GAMG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,UAAU,EAAE,EACrB,MAAM,EAAE,MAAM,GAAG,IAAI,GACpB,OAAO,CAAC,OAAO,CAAC,CAgClB"} |
| import type { SourceInfo } from "./parse-source.mjs"; | ||
| import type { ESLint } from "./types.mjs"; | ||
| /** | ||
| * Generates action types files for all controllers/services. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files were generated successfully. | ||
| */ | ||
| export declare function generateAllActionTypesFiles(sources: SourceInfo[], eslint: ESLint | null): Promise<boolean>; | ||
| //# sourceMappingURL=fix.d.mts.map |
| {"version":3,"file":"fix.d.mts","sourceRoot":"","sources":["../../src/generate-action-types/fix.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,2BAAuB;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAgB;AAEtC;;;;;;GAMG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,UAAU,EAAE,EACrB,MAAM,EAAE,MAAM,GAAG,IAAI,GACpB,OAAO,CAAC,OAAO,CAAC,CAgClB"} |
| import * as fs from "node:fs"; | ||
| import * as path from "node:path"; | ||
| import { generateActionTypesContent } from "./generate-content.mjs"; | ||
| /** | ||
| * Generates action types files for all controllers/services. | ||
| * | ||
| * @param sources - Array of source information objects. | ||
| * @param eslint - Optional ESLint instance and static methods for formatting. | ||
| * @returns Whether all files were generated successfully. | ||
| */ | ||
| export async function generateAllActionTypesFiles(sources, eslint) { | ||
| const outputFiles = []; | ||
| for (const source of sources) { | ||
| console.log(`\n🔧 Processing ${source.name}...`); | ||
| const outputDir = path.dirname(source.filePath); | ||
| const baseFileName = path.basename(source.filePath, '.ts'); | ||
| const outputFile = path.join(outputDir, `${baseFileName}-method-action-types.ts`); | ||
| const generatedContent = generateActionTypesContent(source); | ||
| await fs.promises.writeFile(outputFile, generatedContent, 'utf8'); | ||
| outputFiles.push(outputFile); | ||
| console.log(`✅ Generated action types for ${source.name}`); | ||
| } | ||
| if (outputFiles.length > 0 && eslint) { | ||
| console.log('\n📝 Running ESLint on generated files...'); | ||
| const results = await eslint.instance.lintFiles(outputFiles); | ||
| await eslint.eslintClass.outputFixes(results); | ||
| const errors = eslint.eslintClass.getErrorResults(results); | ||
| if (errors.length > 0) { | ||
| console.error('❌ ESLint errors:', errors); | ||
| return false; | ||
| } | ||
| console.log('✅ ESLint formatting applied'); | ||
| } | ||
| return true; | ||
| } | ||
| //# sourceMappingURL=fix.mjs.map |
| {"version":3,"file":"fix.mjs","sourceRoot":"","sources":["../../src/generate-action-types/fix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB;AAC9B,OAAO,KAAK,IAAI,kBAAkB;AAElC,OAAO,EAAE,0BAA0B,EAAE,+BAA2B;AAIhE;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAAqB,EACrB,MAAqB;IAErB,MAAM,WAAW,GAAa,EAAE,CAAC;IAEjC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,OAAO,CAAC,GAAG,CAAC,mBAAmB,MAAM,CAAC,IAAI,KAAK,CAAC,CAAC;QACjD,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAChD,MAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC3D,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAC1B,SAAS,EACT,GAAG,YAAY,yBAAyB,CACzC,CAAC;QAEF,MAAM,gBAAgB,GAAG,0BAA0B,CAAC,MAAM,CAAC,CAAC;QAC5D,MAAM,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,UAAU,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;QAClE,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC7B,OAAO,CAAC,GAAG,CAAC,gCAAgC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,EAAE,CAAC;QACrC,OAAO,CAAC,GAAG,CAAC,2CAA2C,CAAC,CAAC;QAEzD,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAC7D,MAAM,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC9C,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;QAC3D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC;YAC1C,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { generateActionTypesContent } from './generate-content';\nimport type { SourceInfo } from './parse-source';\nimport type { ESLint } from './types';\n\n/**\n * Generates action types files for all controllers/services.\n *\n * @param sources - Array of source information objects.\n * @param eslint - Optional ESLint instance and static methods for formatting.\n * @returns Whether all files were generated successfully.\n */\nexport async function generateAllActionTypesFiles(\n sources: SourceInfo[],\n eslint: ESLint | null,\n): Promise<boolean> {\n const outputFiles: string[] = [];\n\n for (const source of sources) {\n console.log(`\\n🔧 Processing ${source.name}...`);\n const outputDir = path.dirname(source.filePath);\n const baseFileName = path.basename(source.filePath, '.ts');\n const outputFile = path.join(\n outputDir,\n `${baseFileName}-method-action-types.ts`,\n );\n\n const generatedContent = generateActionTypesContent(source);\n await fs.promises.writeFile(outputFile, generatedContent, 'utf8');\n outputFiles.push(outputFile);\n console.log(`✅ Generated action types for ${source.name}`);\n }\n\n if (outputFiles.length > 0 && eslint) {\n console.log('\\n📝 Running ESLint on generated files...');\n\n const results = await eslint.instance.lintFiles(outputFiles);\n await eslint.eslintClass.outputFixes(results);\n const errors = eslint.eslintClass.getErrorResults(results);\n if (errors.length > 0) {\n console.error('❌ ESLint errors:', errors);\n return false;\n }\n console.log('✅ ESLint formatting applied');\n }\n\n return true;\n}\n"]} |
| "use strict"; | ||
| var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| var desc = Object.getOwnPropertyDescriptor(m, k); | ||
| if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
| desc = { enumerable: true, get: function() { return m[k]; } }; | ||
| } | ||
| Object.defineProperty(o, k2, desc); | ||
| }) : (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| o[k2] = m[k]; | ||
| })); | ||
| var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
| Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
| }) : function(o, v) { | ||
| o["default"] = v; | ||
| }); | ||
| var __importStar = (this && this.__importStar) || function (mod) { | ||
| if (mod && mod.__esModule) return mod; | ||
| var result = {}; | ||
| if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); | ||
| __setModuleDefault(result, mod); | ||
| return result; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.generateActionTypesContent = void 0; | ||
| const path = __importStar(require("node:path")); | ||
| /** | ||
| * Generates the content for the action types file. | ||
| * | ||
| * @param source - The source information object (controller or service). | ||
| * @returns The content for the action types file. | ||
| */ | ||
| function generateActionTypesContent(source) { | ||
| const baseFileName = path.basename(source.filePath, '.ts'); | ||
| const sourceImportPath = `./${baseFileName}`; | ||
| let content = `/** | ||
| * This file is auto generated. | ||
| * Do not edit manually. | ||
| */ | ||
| import type { ${source.name} } from '${sourceImportPath}'; | ||
| `; | ||
| const actionTypeNames = []; | ||
| for (const method of source.methods) { | ||
| const capitalizedName = method.name.charAt(0).toUpperCase() + method.name.slice(1); | ||
| const actionTypeName = `${source.name}${capitalizedName}Action`; | ||
| const actionString = `${source.name}:${method.name}`; | ||
| actionTypeNames.push(actionTypeName); | ||
| if (method.jsDoc) { | ||
| content += `${method.jsDoc}\n`; | ||
| } | ||
| content += `export type ${actionTypeName} = { | ||
| type: \`${actionString}\`; | ||
| handler: ${source.name}['${method.name}']; | ||
| };\n\n`; | ||
| } | ||
| if (actionTypeNames.length > 0) { | ||
| const unionTypeName = `${source.name}MethodActions`; | ||
| content += `/** | ||
| * Union of all ${source.name} action types. | ||
| */ | ||
| export type ${unionTypeName} = ${actionTypeNames.join(' | ')};\n`; | ||
| } | ||
| return `${content.trimEnd()}\n`; | ||
| } | ||
| exports.generateActionTypesContent = generateActionTypesContent; | ||
| //# sourceMappingURL=generate-content.cjs.map |
| {"version":3,"file":"generate-content.cjs","sourceRoot":"","sources":["../../src/generate-action-types/generate-content.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gDAAkC;AAIlC;;;;;GAKG;AACH,SAAgB,0BAA0B,CAAC,MAAkB;IAC3D,MAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IAC3D,MAAM,gBAAgB,GAAG,KAAK,YAAY,EAAE,CAAC;IAE7C,IAAI,OAAO,GAAG;;;;;gBAKA,MAAM,CAAC,IAAI,YAAY,gBAAgB;;CAEtD,CAAC;IAEA,MAAM,eAAe,GAAa,EAAE,CAAC;IAErC,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACpC,MAAM,eAAe,GACnB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC7D,MAAM,cAAc,GAAG,GAAG,MAAM,CAAC,IAAI,GAAG,eAAe,QAAQ,CAAC;QAChE,MAAM,YAAY,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QAErD,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAErC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;YACjB,OAAO,IAAI,GAAG,MAAM,CAAC,KAAK,IAAI,CAAC;QACjC,CAAC;QAED,OAAO,IAAI,eAAe,cAAc;YAChC,YAAY;aACX,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI;OACjC,CAAC;IACN,CAAC;IAED,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/B,MAAM,aAAa,GAAG,GAAG,MAAM,CAAC,IAAI,eAAe,CAAC;QACpD,OAAO,IAAI;kBACG,MAAM,CAAC,IAAI;;cAEf,aAAa,MAAM,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;IAChE,CAAC;IAED,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC;AAClC,CAAC;AA1CD,gEA0CC","sourcesContent":["import * as path from 'node:path';\n\nimport type { SourceInfo } from './parse-source';\n\n/**\n * Generates the content for the action types file.\n *\n * @param source - The source information object (controller or service).\n * @returns The content for the action types file.\n */\nexport function generateActionTypesContent(source: SourceInfo): string {\n const baseFileName = path.basename(source.filePath, '.ts');\n const sourceImportPath = `./${baseFileName}`;\n\n let content = `/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ${source.name} } from '${sourceImportPath}';\n\n`;\n\n const actionTypeNames: string[] = [];\n\n for (const method of source.methods) {\n const capitalizedName =\n method.name.charAt(0).toUpperCase() + method.name.slice(1);\n const actionTypeName = `${source.name}${capitalizedName}Action`;\n const actionString = `${source.name}:${method.name}`;\n\n actionTypeNames.push(actionTypeName);\n\n if (method.jsDoc) {\n content += `${method.jsDoc}\\n`;\n }\n\n content += `export type ${actionTypeName} = {\n type: \\`${actionString}\\`;\n handler: ${source.name}['${method.name}'];\n};\\n\\n`;\n }\n\n if (actionTypeNames.length > 0) {\n const unionTypeName = `${source.name}MethodActions`;\n content += `/**\n * Union of all ${source.name} action types.\n */\nexport type ${unionTypeName} = ${actionTypeNames.join(' | ')};\\n`;\n }\n\n return `${content.trimEnd()}\\n`;\n}\n"]} |
| import type { SourceInfo } from "./parse-source.cjs"; | ||
| /** | ||
| * Generates the content for the action types file. | ||
| * | ||
| * @param source - The source information object (controller or service). | ||
| * @returns The content for the action types file. | ||
| */ | ||
| export declare function generateActionTypesContent(source: SourceInfo): string; | ||
| //# sourceMappingURL=generate-content.d.cts.map |
| {"version":3,"file":"generate-content.d.cts","sourceRoot":"","sources":["../../src/generate-action-types/generate-content.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,2BAAuB;AAEjD;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CA0CrE"} |
| import type { SourceInfo } from "./parse-source.mjs"; | ||
| /** | ||
| * Generates the content for the action types file. | ||
| * | ||
| * @param source - The source information object (controller or service). | ||
| * @returns The content for the action types file. | ||
| */ | ||
| export declare function generateActionTypesContent(source: SourceInfo): string; | ||
| //# sourceMappingURL=generate-content.d.mts.map |
| {"version":3,"file":"generate-content.d.mts","sourceRoot":"","sources":["../../src/generate-action-types/generate-content.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,2BAAuB;AAEjD;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CA0CrE"} |
| import * as path from "node:path"; | ||
| /** | ||
| * Generates the content for the action types file. | ||
| * | ||
| * @param source - The source information object (controller or service). | ||
| * @returns The content for the action types file. | ||
| */ | ||
| export function generateActionTypesContent(source) { | ||
| const baseFileName = path.basename(source.filePath, '.ts'); | ||
| const sourceImportPath = `./${baseFileName}`; | ||
| let content = `/** | ||
| * This file is auto generated. | ||
| * Do not edit manually. | ||
| */ | ||
| import type { ${source.name} } from '${sourceImportPath}'; | ||
| `; | ||
| const actionTypeNames = []; | ||
| for (const method of source.methods) { | ||
| const capitalizedName = method.name.charAt(0).toUpperCase() + method.name.slice(1); | ||
| const actionTypeName = `${source.name}${capitalizedName}Action`; | ||
| const actionString = `${source.name}:${method.name}`; | ||
| actionTypeNames.push(actionTypeName); | ||
| if (method.jsDoc) { | ||
| content += `${method.jsDoc}\n`; | ||
| } | ||
| content += `export type ${actionTypeName} = { | ||
| type: \`${actionString}\`; | ||
| handler: ${source.name}['${method.name}']; | ||
| };\n\n`; | ||
| } | ||
| if (actionTypeNames.length > 0) { | ||
| const unionTypeName = `${source.name}MethodActions`; | ||
| content += `/** | ||
| * Union of all ${source.name} action types. | ||
| */ | ||
| export type ${unionTypeName} = ${actionTypeNames.join(' | ')};\n`; | ||
| } | ||
| return `${content.trimEnd()}\n`; | ||
| } | ||
| //# sourceMappingURL=generate-content.mjs.map |
| {"version":3,"file":"generate-content.mjs","sourceRoot":"","sources":["../../src/generate-action-types/generate-content.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,kBAAkB;AAIlC;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CAAC,MAAkB;IAC3D,MAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IAC3D,MAAM,gBAAgB,GAAG,KAAK,YAAY,EAAE,CAAC;IAE7C,IAAI,OAAO,GAAG;;;;;gBAKA,MAAM,CAAC,IAAI,YAAY,gBAAgB;;CAEtD,CAAC;IAEA,MAAM,eAAe,GAAa,EAAE,CAAC;IAErC,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACpC,MAAM,eAAe,GACnB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC7D,MAAM,cAAc,GAAG,GAAG,MAAM,CAAC,IAAI,GAAG,eAAe,QAAQ,CAAC;QAChE,MAAM,YAAY,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QAErD,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAErC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;YACjB,OAAO,IAAI,GAAG,MAAM,CAAC,KAAK,IAAI,CAAC;QACjC,CAAC;QAED,OAAO,IAAI,eAAe,cAAc;YAChC,YAAY;aACX,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI;OACjC,CAAC;IACN,CAAC;IAED,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/B,MAAM,aAAa,GAAG,GAAG,MAAM,CAAC,IAAI,eAAe,CAAC;QACpD,OAAO,IAAI;kBACG,MAAM,CAAC,IAAI;;cAEf,aAAa,MAAM,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;IAChE,CAAC;IAED,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC;AAClC,CAAC","sourcesContent":["import * as path from 'node:path';\n\nimport type { SourceInfo } from './parse-source';\n\n/**\n * Generates the content for the action types file.\n *\n * @param source - The source information object (controller or service).\n * @returns The content for the action types file.\n */\nexport function generateActionTypesContent(source: SourceInfo): string {\n const baseFileName = path.basename(source.filePath, '.ts');\n const sourceImportPath = `./${baseFileName}`;\n\n let content = `/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ${source.name} } from '${sourceImportPath}';\n\n`;\n\n const actionTypeNames: string[] = [];\n\n for (const method of source.methods) {\n const capitalizedName =\n method.name.charAt(0).toUpperCase() + method.name.slice(1);\n const actionTypeName = `${source.name}${capitalizedName}Action`;\n const actionString = `${source.name}:${method.name}`;\n\n actionTypeNames.push(actionTypeName);\n\n if (method.jsDoc) {\n content += `${method.jsDoc}\\n`;\n }\n\n content += `export type ${actionTypeName} = {\n type: \\`${actionString}\\`;\n handler: ${source.name}['${method.name}'];\n};\\n\\n`;\n }\n\n if (actionTypeNames.length > 0) {\n const unionTypeName = `${source.name}MethodActions`;\n content += `/**\n * Union of all ${source.name} action types.\n */\nexport type ${unionTypeName} = ${actionTypeNames.join(' | ')};\\n`;\n }\n\n return `${content.trimEnd()}\\n`;\n}\n"]} |
| "use strict"; | ||
| var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| var desc = Object.getOwnPropertyDescriptor(m, k); | ||
| if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
| desc = { enumerable: true, get: function() { return m[k]; } }; | ||
| } | ||
| Object.defineProperty(o, k2, desc); | ||
| }) : (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| o[k2] = m[k]; | ||
| })); | ||
| var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
| Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
| }) : function(o, v) { | ||
| o["default"] = v; | ||
| }); | ||
| var __importStar = (this && this.__importStar) || function (mod) { | ||
| if (mod && mod.__esModule) return mod; | ||
| var result = {}; | ||
| if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); | ||
| __setModuleDefault(result, mod); | ||
| return result; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.findSourcesWithExposedMethods = exports.parseSourceFile = void 0; | ||
| const utils_1 = require("@metamask/utils"); | ||
| const fs = __importStar(require("node:fs")); | ||
| const path = __importStar(require("node:path")); | ||
| const typescript_1 = require("typescript"); | ||
| /** | ||
| * Extracts JSDoc comment from a method declaration. | ||
| * | ||
| * @param node - The method declaration node. | ||
| * @param source - The source file. | ||
| * @returns The JSDoc comment. | ||
| */ | ||
| function extractJSDoc(node, source) { | ||
| const jsDocTags = (0, typescript_1.getJSDocCommentsAndTags)(node); | ||
| if (jsDocTags.length === 0) { | ||
| return ''; | ||
| } | ||
| const jsDoc = jsDocTags[0]; | ||
| if ((0, typescript_1.isJSDoc)(jsDoc)) { | ||
| const fullText = source.getFullText(); | ||
| const start = jsDoc.getFullStart(); | ||
| const end = jsDoc.getEnd(); | ||
| const rawJsDoc = fullText.substring(start, end).trim(); | ||
| return formatJSDoc(rawJsDoc); | ||
| } | ||
| // istanbul ignore next: defensive check — getJSDocCommentsAndTags always returns JSDoc nodes | ||
| return ''; | ||
| } | ||
| /** | ||
| * Formats JSDoc comments to have consistent indentation for the generated file. | ||
| * | ||
| * @param rawJsDoc - The raw JSDoc comment from the source. | ||
| * @returns The formatted JSDoc comment. | ||
| */ | ||
| function formatJSDoc(rawJsDoc) { | ||
| const lines = rawJsDoc.split('\n'); | ||
| const formattedLines = []; | ||
| for (let i = 0; i < lines.length; i++) { | ||
| const line = lines[i]; | ||
| if (i === 0) { | ||
| formattedLines.push('/**'); | ||
| } | ||
| else if (i === lines.length - 1) { | ||
| formattedLines.push(' */'); | ||
| } | ||
| else { | ||
| const trimmed = line.trim(); | ||
| if (trimmed.startsWith('*')) { | ||
| const content = trimmed.substring(1).trim(); | ||
| formattedLines.push(content ? ` * ${content}` : ' *'); | ||
| } | ||
| else { | ||
| formattedLines.push(trimmed ? ` * ${trimmed}` : ' *'); | ||
| } | ||
| } | ||
| } | ||
| return formattedLines.join('\n'); | ||
| } | ||
| /** | ||
| * Visits AST nodes to find exposed methods and controller/service class. | ||
| * | ||
| * @param context - The visitor context. | ||
| * @returns A function to visit nodes. | ||
| */ | ||
| function createASTVisitor(context) { | ||
| function visitNode(node) { | ||
| if ((0, typescript_1.isVariableStatement)(node)) { | ||
| const declaration = node.declarationList.declarations[0]; | ||
| if ((0, typescript_1.isIdentifier)(declaration.name) && | ||
| declaration.name.text === 'MESSENGER_EXPOSED_METHODS') { | ||
| if (declaration.initializer) { | ||
| let arrayExpression; | ||
| if ((0, typescript_1.isArrayLiteralExpression)(declaration.initializer)) { | ||
| arrayExpression = declaration.initializer; | ||
| } | ||
| else if ((0, typescript_1.isAsExpression)(declaration.initializer) && | ||
| (0, typescript_1.isArrayLiteralExpression)(declaration.initializer.expression)) { | ||
| arrayExpression = declaration.initializer.expression; | ||
| } | ||
| if (arrayExpression) { | ||
| context.exposedMethods = arrayExpression.elements | ||
| .filter(typescript_1.isStringLiteral) | ||
| .map((element) => element.text); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if ((0, typescript_1.isClassDeclaration)(node) && node.name) { | ||
| const classText = node.name.text; | ||
| if (classText.includes('Controller') || classText.includes('Service')) { | ||
| context.className = classText; | ||
| const seenMethods = new Set(); | ||
| for (const member of node.members) { | ||
| if ((0, typescript_1.isMethodDeclaration)(member) && | ||
| member.name && | ||
| (0, typescript_1.isIdentifier)(member.name)) { | ||
| const methodName = member.name.text; | ||
| if (context.exposedMethods.includes(methodName) && | ||
| !seenMethods.has(methodName)) { | ||
| seenMethods.add(methodName); | ||
| const jsDoc = extractJSDoc(member, context.sourceFile); | ||
| context.methods.push({ | ||
| name: methodName, | ||
| jsDoc, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| (0, typescript_1.forEachChild)(node, visitNode); | ||
| } | ||
| return visitNode; | ||
| } | ||
| /** | ||
| * Create a TypeScript program for the given file by locating the nearest | ||
| * tsconfig.json. | ||
| * | ||
| * @param filePath - Absolute path to the source file. | ||
| * @returns A TypeScript program, or null if no tsconfig was found. | ||
| */ | ||
| function createProgramForFile(filePath) { | ||
| const configPath = (0, typescript_1.findConfigFile)(path.dirname(filePath), typescript_1.sys.fileExists.bind(typescript_1.sys), 'tsconfig.json'); | ||
| if (!configPath) { | ||
| return null; | ||
| } | ||
| const { config, error } = (0, typescript_1.readConfigFile)(configPath, typescript_1.sys.readFile.bind(typescript_1.sys)); | ||
| if (error) { | ||
| return null; | ||
| } | ||
| const parsedConfig = (0, typescript_1.parseJsonConfigFileContent)(config, typescript_1.sys, path.dirname(configPath)); | ||
| return (0, typescript_1.createProgram)({ | ||
| rootNames: parsedConfig.fileNames, | ||
| options: parsedConfig.options, | ||
| }); | ||
| } | ||
| /** | ||
| * Find a class declaration with the given name in a source file. | ||
| * | ||
| * @param source - The source file to search. | ||
| * @param className - The class name to look for. | ||
| * @returns The class declaration node, or null if not found. | ||
| */ | ||
| function findClassInSourceFile(source, className) { | ||
| return (source.statements.find((node) => (0, typescript_1.isClassDeclaration)(node) && node.name?.text === className) ?? // istanbul ignore next: class is always found when called from parseSourceFile | ||
| null); | ||
| } | ||
| /** | ||
| * Search through the class hierarchy of a TypeScript type to find the | ||
| * declaration of a method with the given name. | ||
| * | ||
| * @param classType - The class type to search. | ||
| * @param methodName - The method name to look for. | ||
| * @returns The method declaration node, or null if not found. | ||
| */ | ||
| function findMethodInHierarchy(classType, methodName) { | ||
| const symbol = classType.getProperty(methodName); | ||
| if (!symbol) { | ||
| return null; | ||
| } | ||
| const declarations = symbol.getDeclarations(); | ||
| // istanbul ignore next: defensive check — symbols from getProperty always have declarations | ||
| if (!declarations) { | ||
| return null; | ||
| } | ||
| for (const declaration of declarations) { | ||
| if ((0, typescript_1.isMethodDeclaration)(declaration)) { | ||
| return declaration; | ||
| } | ||
| } | ||
| // istanbul ignore next: defensive fallback — property found but not a method declaration | ||
| return null; | ||
| } | ||
| /** | ||
| * Check if a path is a directory. | ||
| * | ||
| * @param pathValue - The path to check. | ||
| * @returns True if the path is a directory, false otherwise. | ||
| */ | ||
| async function isDirectory(pathValue) { | ||
| try { | ||
| const stats = await fs.promises.stat(pathValue); | ||
| return stats.isDirectory(); | ||
| } | ||
| catch (error) { | ||
| if ((0, utils_1.isObject)(error) && | ||
| (0, utils_1.hasProperty)(error, 'code') && | ||
| error.code === 'ENOENT') { | ||
| return false; | ||
| } | ||
| throw error; | ||
| } | ||
| } | ||
| /** | ||
| * Parses a source file to extract exposed methods and their metadata. | ||
| * | ||
| * @param filePath - Path to the controller/service file to parse. | ||
| * @returns Source information or null if parsing fails. | ||
| */ | ||
| async function parseSourceFile(filePath) { | ||
| try { | ||
| const content = await fs.promises.readFile(filePath, 'utf8'); | ||
| const source = (0, typescript_1.createSourceFile)(filePath, content, typescript_1.ScriptTarget.Latest, true); | ||
| const context = { | ||
| exposedMethods: [], | ||
| className: '', | ||
| methods: [], | ||
| sourceFile: source, | ||
| }; | ||
| createASTVisitor(context)(source); | ||
| if (context.exposedMethods.length === 0 || !context.className) { | ||
| return null; | ||
| } | ||
| const foundMethodNames = new Set(context.methods.map((method) => method.name)); | ||
| const inheritedMethodNames = context.exposedMethods.filter((name) => !foundMethodNames.has(name)); | ||
| if (inheritedMethodNames.length > 0) { | ||
| const program = createProgramForFile(filePath); | ||
| const checker = program?.getTypeChecker(); | ||
| const programSourceFile = program?.getSourceFile(filePath); | ||
| (0, utils_1.assert)(checker, `Type checker could not be created for "${filePath}". Ensure a valid tsconfig.json is present.`); | ||
| (0, utils_1.assert)(programSourceFile, `Source file "${filePath}" not found in program.`); | ||
| const classNode = findClassInSourceFile(programSourceFile, context.className); | ||
| (0, utils_1.assert)(classNode, `Class "${context.className}" not found in "${filePath}".`); | ||
| const classType = checker.getTypeAtLocation(classNode); | ||
| for (const methodName of inheritedMethodNames) { | ||
| const methodDeclaration = findMethodInHierarchy(classType, methodName); | ||
| const jsDoc = methodDeclaration | ||
| ? extractJSDoc(methodDeclaration, methodDeclaration.getSourceFile()) | ||
| : ''; | ||
| context.methods.push({ name: methodName, jsDoc }); | ||
| } | ||
| } | ||
| return { | ||
| name: context.className, | ||
| filePath, | ||
| methods: context.methods, | ||
| }; | ||
| } | ||
| catch (error) { | ||
| console.error(`Error parsing ${filePath}:`, error); | ||
| return null; | ||
| } | ||
| } | ||
| exports.parseSourceFile = parseSourceFile; | ||
| /** | ||
| * Recursively get all files in a directory and its subdirectories. | ||
| * | ||
| * @param directory - The directory to search. | ||
| * @returns An array of file paths. | ||
| */ | ||
| const EXCLUDED_DIRECTORIES = new Set([ | ||
| 'node_modules', | ||
| 'dist', | ||
| '.git', | ||
| 'coverage', | ||
| ]); | ||
| async function getFiles(directory) { | ||
| const entries = await fs.promises.readdir(directory, { withFileTypes: true }); | ||
| const files = await Promise.all(entries.map(async (entry) => { | ||
| const fullPath = path.join(directory, entry.name); | ||
| if (entry.isDirectory()) { | ||
| return EXCLUDED_DIRECTORIES.has(entry.name) | ||
| ? [] | ||
| : await getFiles(fullPath); | ||
| } | ||
| return fullPath; | ||
| })); | ||
| return files.flat(); | ||
| } | ||
| /** | ||
| * Finds all source files that have MESSENGER_EXPOSED_METHODS constants. | ||
| * Searches recursively through subdirectories. | ||
| * | ||
| * @param sourcePath - Path to the folder where controllers/services are located. | ||
| * @returns A list of source information objects. | ||
| */ | ||
| async function findSourcesWithExposedMethods(sourcePath) { | ||
| const srcPath = path.resolve(globalThis.process.cwd(), sourcePath); | ||
| const sources = []; | ||
| if (!(await isDirectory(srcPath))) { | ||
| throw new Error(`The specified path is not a directory: ${srcPath}`); | ||
| } | ||
| const srcFiles = await getFiles(srcPath); | ||
| for (const file of srcFiles) { | ||
| if (!file.endsWith('.ts') || file.endsWith('.test.ts')) { | ||
| continue; | ||
| } | ||
| const content = await fs.promises.readFile(file, 'utf8'); | ||
| if (content.includes('MESSENGER_EXPOSED_METHODS')) { | ||
| const sourceInfo = await parseSourceFile(file); | ||
| if (sourceInfo) { | ||
| sources.push(sourceInfo); | ||
| } | ||
| } | ||
| } | ||
| return sources; | ||
| } | ||
| exports.findSourcesWithExposedMethods = findSourcesWithExposedMethods; | ||
| //# sourceMappingURL=parse-source.cjs.map |
| {"version":3,"file":"parse-source.cjs","sourceRoot":"","sources":["../../src/generate-action-types/parse-source.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAgE;AAChE,4CAA8B;AAC9B,gDAAkC;AAUl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AO,CAAC;AACjB,CAAC;AA5BD,sEA4BC","sourcesContent":["import { assert, hasProperty, isObject } from '@metamask/utils';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ArrayLiteralExpression,\n ClassDeclaration,\n MethodDeclaration,\n Node as TSNode,\n Program,\n SourceFile,\n Type,\n} from 'typescript';\nimport {\n ScriptTarget,\n createProgram,\n createSourceFile,\n findConfigFile,\n forEachChild,\n getJSDocCommentsAndTags,\n isArrayLiteralExpression,\n isAsExpression,\n isClassDeclaration,\n isIdentifier,\n isJSDoc,\n isMethodDeclaration,\n isStringLiteral,\n isVariableStatement,\n parseJsonConfigFileContent,\n readConfigFile,\n sys,\n} from 'typescript';\n\nexport type MethodInfo = {\n name: string;\n jsDoc: string;\n};\n\nexport type SourceInfo = {\n name: string;\n filePath: string;\n methods: MethodInfo[];\n};\n\ntype VisitorContext = {\n exposedMethods: string[];\n className: string;\n methods: MethodInfo[];\n sourceFile: SourceFile;\n};\n\n/**\n * Extracts JSDoc comment from a method declaration.\n *\n * @param node - The method declaration node.\n * @param source - The source file.\n * @returns The JSDoc comment.\n */\nfunction extractJSDoc(node: MethodDeclaration, source: SourceFile): string {\n const jsDocTags = getJSDocCommentsAndTags(node);\n if (jsDocTags.length === 0) {\n return '';\n }\n\n const jsDoc = jsDocTags[0];\n if (isJSDoc(jsDoc)) {\n const fullText = source.getFullText();\n const start = jsDoc.getFullStart();\n const end = jsDoc.getEnd();\n const rawJsDoc = fullText.substring(start, end).trim();\n return formatJSDoc(rawJsDoc);\n }\n\n // istanbul ignore next: defensive check — getJSDocCommentsAndTags always returns JSDoc nodes\n return '';\n}\n\n/**\n * Formats JSDoc comments to have consistent indentation for the generated file.\n *\n * @param rawJsDoc - The raw JSDoc comment from the source.\n * @returns The formatted JSDoc comment.\n */\nfunction formatJSDoc(rawJsDoc: string): string {\n const lines = rawJsDoc.split('\\n');\n const formattedLines: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (i === 0) {\n formattedLines.push('/**');\n } else if (i === lines.length - 1) {\n formattedLines.push(' */');\n } else {\n const trimmed = line.trim();\n if (trimmed.startsWith('*')) {\n const content = trimmed.substring(1).trim();\n formattedLines.push(content ? ` * ${content}` : ' *');\n } else {\n formattedLines.push(trimmed ? ` * ${trimmed}` : ' *');\n }\n }\n }\n\n return formattedLines.join('\\n');\n}\n\n/**\n * Visits AST nodes to find exposed methods and controller/service class.\n *\n * @param context - The visitor context.\n * @returns A function to visit nodes.\n */\nfunction createASTVisitor(context: VisitorContext): (node: TSNode) => void {\n function visitNode(node: TSNode): void {\n if (isVariableStatement(node)) {\n const declaration = node.declarationList.declarations[0];\n if (\n isIdentifier(declaration.name) &&\n declaration.name.text === 'MESSENGER_EXPOSED_METHODS'\n ) {\n if (declaration.initializer) {\n let arrayExpression: ArrayLiteralExpression | undefined;\n\n if (isArrayLiteralExpression(declaration.initializer)) {\n arrayExpression = declaration.initializer;\n } else if (\n isAsExpression(declaration.initializer) &&\n isArrayLiteralExpression(declaration.initializer.expression)\n ) {\n arrayExpression = declaration.initializer.expression;\n }\n\n if (arrayExpression) {\n context.exposedMethods = arrayExpression.elements\n .filter(isStringLiteral)\n .map((element) => element.text);\n }\n }\n }\n }\n\n if (isClassDeclaration(node) && node.name) {\n const classText = node.name.text;\n if (classText.includes('Controller') || classText.includes('Service')) {\n context.className = classText;\n\n const seenMethods = new Set<string>();\n for (const member of node.members) {\n if (\n isMethodDeclaration(member) &&\n member.name &&\n isIdentifier(member.name)\n ) {\n const methodName = member.name.text;\n if (\n context.exposedMethods.includes(methodName) &&\n !seenMethods.has(methodName)\n ) {\n seenMethods.add(methodName);\n const jsDoc = extractJSDoc(member, context.sourceFile);\n context.methods.push({\n name: methodName,\n jsDoc,\n });\n }\n }\n }\n }\n }\n\n forEachChild(node, visitNode);\n }\n\n return visitNode;\n}\n\n/**\n * Create a TypeScript program for the given file by locating the nearest\n * tsconfig.json.\n *\n * @param filePath - Absolute path to the source file.\n * @returns A TypeScript program, or null if no tsconfig was found.\n */\nfunction createProgramForFile(filePath: string): Program | null {\n const configPath = findConfigFile(\n path.dirname(filePath),\n sys.fileExists.bind(sys),\n 'tsconfig.json',\n );\n if (!configPath) {\n return null;\n }\n\n const { config, error } = readConfigFile(configPath, sys.readFile.bind(sys));\n\n if (error) {\n return null;\n }\n\n const parsedConfig = parseJsonConfigFileContent(\n config,\n sys,\n path.dirname(configPath),\n );\n\n return createProgram({\n rootNames: parsedConfig.fileNames,\n options: parsedConfig.options,\n });\n}\n\n/**\n * Find a class declaration with the given name in a source file.\n *\n * @param source - The source file to search.\n * @param className - The class name to look for.\n * @returns The class declaration node, or null if not found.\n */\nfunction findClassInSourceFile(\n source: SourceFile,\n className: string,\n): ClassDeclaration | null {\n return (\n source.statements.find(\n (node): node is ClassDeclaration =>\n isClassDeclaration(node) && node.name?.text === className,\n ) ?? // istanbul ignore next: class is always found when called from parseSourceFile\n null\n );\n}\n\n/**\n * Search through the class hierarchy of a TypeScript type to find the\n * declaration of a method with the given name.\n *\n * @param classType - The class type to search.\n * @param methodName - The method name to look for.\n * @returns The method declaration node, or null if not found.\n */\nfunction findMethodInHierarchy(\n classType: Type,\n methodName: string,\n): MethodDeclaration | null {\n const symbol = classType.getProperty(methodName);\n if (!symbol) {\n return null;\n }\n\n const declarations = symbol.getDeclarations();\n // istanbul ignore next: defensive check — symbols from getProperty always have declarations\n if (!declarations) {\n return null;\n }\n\n for (const declaration of declarations) {\n if (isMethodDeclaration(declaration)) {\n return declaration;\n }\n }\n\n // istanbul ignore next: defensive fallback — property found but not a method declaration\n return null;\n}\n\n/**\n * Check if a path is a directory.\n *\n * @param pathValue - The path to check.\n * @returns True if the path is a directory, false otherwise.\n */\nasync function isDirectory(pathValue: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(pathValue);\n return stats.isDirectory();\n } catch (error) {\n if (\n isObject(error) &&\n hasProperty(error, 'code') &&\n error.code === 'ENOENT'\n ) {\n return false;\n }\n\n throw error;\n }\n}\n\n/**\n * Parses a source file to extract exposed methods and their metadata.\n *\n * @param filePath - Path to the controller/service file to parse.\n * @returns Source information or null if parsing fails.\n */\nexport async function parseSourceFile(\n filePath: string,\n): Promise<SourceInfo | null> {\n try {\n const content = await fs.promises.readFile(filePath, 'utf8');\n const source = createSourceFile(\n filePath,\n content,\n ScriptTarget.Latest,\n true,\n );\n\n const context: VisitorContext = {\n exposedMethods: [],\n className: '',\n methods: [],\n sourceFile: source,\n };\n\n createASTVisitor(context)(source);\n\n if (context.exposedMethods.length === 0 || !context.className) {\n return null;\n }\n\n const foundMethodNames = new Set(\n context.methods.map((method) => method.name),\n );\n\n const inheritedMethodNames = context.exposedMethods.filter(\n (name) => !foundMethodNames.has(name),\n );\n\n if (inheritedMethodNames.length > 0) {\n const program = createProgramForFile(filePath);\n const checker = program?.getTypeChecker();\n const programSourceFile = program?.getSourceFile(filePath);\n\n assert(\n checker,\n `Type checker could not be created for \"${filePath}\". Ensure a valid tsconfig.json is present.`,\n );\n\n assert(\n programSourceFile,\n `Source file \"${filePath}\" not found in program.`,\n );\n\n const classNode = findClassInSourceFile(\n programSourceFile,\n context.className,\n );\n\n assert(\n classNode,\n `Class \"${context.className}\" not found in \"${filePath}\".`,\n );\n\n const classType = checker.getTypeAtLocation(classNode);\n for (const methodName of inheritedMethodNames) {\n const methodDeclaration = findMethodInHierarchy(classType, methodName);\n\n const jsDoc = methodDeclaration\n ? extractJSDoc(methodDeclaration, methodDeclaration.getSourceFile())\n : '';\n context.methods.push({ name: methodName, jsDoc });\n }\n }\n\n return {\n name: context.className,\n filePath,\n methods: context.methods,\n };\n } catch (error) {\n console.error(`Error parsing ${filePath}:`, error);\n return null;\n }\n}\n\n/**\n * Recursively get all files in a directory and its subdirectories.\n *\n * @param directory - The directory to search.\n * @returns An array of file paths.\n */\nconst EXCLUDED_DIRECTORIES = new Set([\n 'node_modules',\n 'dist',\n '.git',\n 'coverage',\n]);\n\nasync function getFiles(directory: string): Promise<string[]> {\n const entries = await fs.promises.readdir(directory, { withFileTypes: true });\n const files = await Promise.all(\n entries.map(async (entry) => {\n const fullPath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n return EXCLUDED_DIRECTORIES.has(entry.name)\n ? []\n : await getFiles(fullPath);\n }\n return fullPath;\n }),\n );\n\n return files.flat();\n}\n\n/**\n * Finds all source files that have MESSENGER_EXPOSED_METHODS constants.\n * Searches recursively through subdirectories.\n *\n * @param sourcePath - Path to the folder where controllers/services are located.\n * @returns A list of source information objects.\n */\nexport async function findSourcesWithExposedMethods(\n sourcePath: string,\n): Promise<SourceInfo[]> {\n const srcPath = path.resolve(globalThis.process.cwd(), sourcePath);\n const sources: SourceInfo[] = [];\n\n if (!(await isDirectory(srcPath))) {\n throw new Error(`The specified path is not a directory: ${srcPath}`);\n }\n\n const srcFiles = await getFiles(srcPath);\n\n for (const file of srcFiles) {\n if (!file.endsWith('.ts') || file.endsWith('.test.ts')) {\n continue;\n }\n\n const content = await fs.promises.readFile(file, 'utf8');\n\n if (content.includes('MESSENGER_EXPOSED_METHODS')) {\n const sourceInfo = await parseSourceFile(file);\n if (sourceInfo) {\n sources.push(sourceInfo);\n }\n }\n }\n\n return sources;\n}\n"]} |
| export type MethodInfo = { | ||
| name: string; | ||
| jsDoc: string; | ||
| }; | ||
| export type SourceInfo = { | ||
| name: string; | ||
| filePath: string; | ||
| methods: MethodInfo[]; | ||
| }; | ||
| /** | ||
| * Parses a source file to extract exposed methods and their metadata. | ||
| * | ||
| * @param filePath - Path to the controller/service file to parse. | ||
| * @returns Source information or null if parsing fails. | ||
| */ | ||
| export declare function parseSourceFile(filePath: string): Promise<SourceInfo | null>; | ||
| /** | ||
| * Finds all source files that have MESSENGER_EXPOSED_METHODS constants. | ||
| * Searches recursively through subdirectories. | ||
| * | ||
| * @param sourcePath - Path to the folder where controllers/services are located. | ||
| * @returns A list of source information objects. | ||
| */ | ||
| export declare function findSourcesWithExposedMethods(sourcePath: string): Promise<SourceInfo[]>; | ||
| //# sourceMappingURL=parse-source.d.cts.map |
| {"version":3,"file":"parse-source.d.cts","sourceRoot":"","sources":["../../src/generate-action-types/parse-source.ts"],"names":[],"mappings":"AAgCA,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,UAAU,EAAE,CAAC;CACvB,CAAC;AAsPF;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CA4E5B;AAgCD;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CACjD,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,UAAU,EAAE,CAAC,CA0BvB"} |
| export type MethodInfo = { | ||
| name: string; | ||
| jsDoc: string; | ||
| }; | ||
| export type SourceInfo = { | ||
| name: string; | ||
| filePath: string; | ||
| methods: MethodInfo[]; | ||
| }; | ||
| /** | ||
| * Parses a source file to extract exposed methods and their metadata. | ||
| * | ||
| * @param filePath - Path to the controller/service file to parse. | ||
| * @returns Source information or null if parsing fails. | ||
| */ | ||
| export declare function parseSourceFile(filePath: string): Promise<SourceInfo | null>; | ||
| /** | ||
| * Finds all source files that have MESSENGER_EXPOSED_METHODS constants. | ||
| * Searches recursively through subdirectories. | ||
| * | ||
| * @param sourcePath - Path to the folder where controllers/services are located. | ||
| * @returns A list of source information objects. | ||
| */ | ||
| export declare function findSourcesWithExposedMethods(sourcePath: string): Promise<SourceInfo[]>; | ||
| //# sourceMappingURL=parse-source.d.mts.map |
| {"version":3,"file":"parse-source.d.mts","sourceRoot":"","sources":["../../src/generate-action-types/parse-source.ts"],"names":[],"mappings":"AAgCA,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,UAAU,EAAE,CAAC;CACvB,CAAC;AAsPF;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CA4E5B;AAgCD;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CACjD,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,UAAU,EAAE,CAAC,CA0BvB"} |
| import { assert, hasProperty, isObject } from "@metamask/utils"; | ||
| import * as fs from "node:fs"; | ||
| import * as path from "node:path"; | ||
| import $typescript from "typescript"; | ||
| const { ScriptTarget, createProgram, createSourceFile, findConfigFile, forEachChild, getJSDocCommentsAndTags, isArrayLiteralExpression, isAsExpression, isClassDeclaration, isIdentifier, isJSDoc, isMethodDeclaration, isStringLiteral, isVariableStatement, parseJsonConfigFileContent, readConfigFile, sys } = $typescript; | ||
| /** | ||
| * Extracts JSDoc comment from a method declaration. | ||
| * | ||
| * @param node - The method declaration node. | ||
| * @param source - The source file. | ||
| * @returns The JSDoc comment. | ||
| */ | ||
| function extractJSDoc(node, source) { | ||
| const jsDocTags = getJSDocCommentsAndTags(node); | ||
| if (jsDocTags.length === 0) { | ||
| return ''; | ||
| } | ||
| const jsDoc = jsDocTags[0]; | ||
| if (isJSDoc(jsDoc)) { | ||
| const fullText = source.getFullText(); | ||
| const start = jsDoc.getFullStart(); | ||
| const end = jsDoc.getEnd(); | ||
| const rawJsDoc = fullText.substring(start, end).trim(); | ||
| return formatJSDoc(rawJsDoc); | ||
| } | ||
| // istanbul ignore next: defensive check — getJSDocCommentsAndTags always returns JSDoc nodes | ||
| return ''; | ||
| } | ||
| /** | ||
| * Formats JSDoc comments to have consistent indentation for the generated file. | ||
| * | ||
| * @param rawJsDoc - The raw JSDoc comment from the source. | ||
| * @returns The formatted JSDoc comment. | ||
| */ | ||
| function formatJSDoc(rawJsDoc) { | ||
| const lines = rawJsDoc.split('\n'); | ||
| const formattedLines = []; | ||
| for (let i = 0; i < lines.length; i++) { | ||
| const line = lines[i]; | ||
| if (i === 0) { | ||
| formattedLines.push('/**'); | ||
| } | ||
| else if (i === lines.length - 1) { | ||
| formattedLines.push(' */'); | ||
| } | ||
| else { | ||
| const trimmed = line.trim(); | ||
| if (trimmed.startsWith('*')) { | ||
| const content = trimmed.substring(1).trim(); | ||
| formattedLines.push(content ? ` * ${content}` : ' *'); | ||
| } | ||
| else { | ||
| formattedLines.push(trimmed ? ` * ${trimmed}` : ' *'); | ||
| } | ||
| } | ||
| } | ||
| return formattedLines.join('\n'); | ||
| } | ||
| /** | ||
| * Visits AST nodes to find exposed methods and controller/service class. | ||
| * | ||
| * @param context - The visitor context. | ||
| * @returns A function to visit nodes. | ||
| */ | ||
| function createASTVisitor(context) { | ||
| function visitNode(node) { | ||
| if (isVariableStatement(node)) { | ||
| const declaration = node.declarationList.declarations[0]; | ||
| if (isIdentifier(declaration.name) && | ||
| declaration.name.text === 'MESSENGER_EXPOSED_METHODS') { | ||
| if (declaration.initializer) { | ||
| let arrayExpression; | ||
| if (isArrayLiteralExpression(declaration.initializer)) { | ||
| arrayExpression = declaration.initializer; | ||
| } | ||
| else if (isAsExpression(declaration.initializer) && | ||
| isArrayLiteralExpression(declaration.initializer.expression)) { | ||
| arrayExpression = declaration.initializer.expression; | ||
| } | ||
| if (arrayExpression) { | ||
| context.exposedMethods = arrayExpression.elements | ||
| .filter(isStringLiteral) | ||
| .map((element) => element.text); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if (isClassDeclaration(node) && node.name) { | ||
| const classText = node.name.text; | ||
| if (classText.includes('Controller') || classText.includes('Service')) { | ||
| context.className = classText; | ||
| const seenMethods = new Set(); | ||
| for (const member of node.members) { | ||
| if (isMethodDeclaration(member) && | ||
| member.name && | ||
| isIdentifier(member.name)) { | ||
| const methodName = member.name.text; | ||
| if (context.exposedMethods.includes(methodName) && | ||
| !seenMethods.has(methodName)) { | ||
| seenMethods.add(methodName); | ||
| const jsDoc = extractJSDoc(member, context.sourceFile); | ||
| context.methods.push({ | ||
| name: methodName, | ||
| jsDoc, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| forEachChild(node, visitNode); | ||
| } | ||
| return visitNode; | ||
| } | ||
| /** | ||
| * Create a TypeScript program for the given file by locating the nearest | ||
| * tsconfig.json. | ||
| * | ||
| * @param filePath - Absolute path to the source file. | ||
| * @returns A TypeScript program, or null if no tsconfig was found. | ||
| */ | ||
| function createProgramForFile(filePath) { | ||
| const configPath = findConfigFile(path.dirname(filePath), sys.fileExists.bind(sys), 'tsconfig.json'); | ||
| if (!configPath) { | ||
| return null; | ||
| } | ||
| const { config, error } = readConfigFile(configPath, sys.readFile.bind(sys)); | ||
| if (error) { | ||
| return null; | ||
| } | ||
| const parsedConfig = parseJsonConfigFileContent(config, sys, path.dirname(configPath)); | ||
| return createProgram({ | ||
| rootNames: parsedConfig.fileNames, | ||
| options: parsedConfig.options, | ||
| }); | ||
| } | ||
| /** | ||
| * Find a class declaration with the given name in a source file. | ||
| * | ||
| * @param source - The source file to search. | ||
| * @param className - The class name to look for. | ||
| * @returns The class declaration node, or null if not found. | ||
| */ | ||
| function findClassInSourceFile(source, className) { | ||
| return (source.statements.find((node) => isClassDeclaration(node) && node.name?.text === className) ?? // istanbul ignore next: class is always found when called from parseSourceFile | ||
| null); | ||
| } | ||
| /** | ||
| * Search through the class hierarchy of a TypeScript type to find the | ||
| * declaration of a method with the given name. | ||
| * | ||
| * @param classType - The class type to search. | ||
| * @param methodName - The method name to look for. | ||
| * @returns The method declaration node, or null if not found. | ||
| */ | ||
| function findMethodInHierarchy(classType, methodName) { | ||
| const symbol = classType.getProperty(methodName); | ||
| if (!symbol) { | ||
| return null; | ||
| } | ||
| const declarations = symbol.getDeclarations(); | ||
| // istanbul ignore next: defensive check — symbols from getProperty always have declarations | ||
| if (!declarations) { | ||
| return null; | ||
| } | ||
| for (const declaration of declarations) { | ||
| if (isMethodDeclaration(declaration)) { | ||
| return declaration; | ||
| } | ||
| } | ||
| // istanbul ignore next: defensive fallback — property found but not a method declaration | ||
| return null; | ||
| } | ||
| /** | ||
| * Check if a path is a directory. | ||
| * | ||
| * @param pathValue - The path to check. | ||
| * @returns True if the path is a directory, false otherwise. | ||
| */ | ||
| async function isDirectory(pathValue) { | ||
| try { | ||
| const stats = await fs.promises.stat(pathValue); | ||
| return stats.isDirectory(); | ||
| } | ||
| catch (error) { | ||
| if (isObject(error) && | ||
| hasProperty(error, 'code') && | ||
| error.code === 'ENOENT') { | ||
| return false; | ||
| } | ||
| throw error; | ||
| } | ||
| } | ||
| /** | ||
| * Parses a source file to extract exposed methods and their metadata. | ||
| * | ||
| * @param filePath - Path to the controller/service file to parse. | ||
| * @returns Source information or null if parsing fails. | ||
| */ | ||
| export async function parseSourceFile(filePath) { | ||
| try { | ||
| const content = await fs.promises.readFile(filePath, 'utf8'); | ||
| const source = createSourceFile(filePath, content, ScriptTarget.Latest, true); | ||
| const context = { | ||
| exposedMethods: [], | ||
| className: '', | ||
| methods: [], | ||
| sourceFile: source, | ||
| }; | ||
| createASTVisitor(context)(source); | ||
| if (context.exposedMethods.length === 0 || !context.className) { | ||
| return null; | ||
| } | ||
| const foundMethodNames = new Set(context.methods.map((method) => method.name)); | ||
| const inheritedMethodNames = context.exposedMethods.filter((name) => !foundMethodNames.has(name)); | ||
| if (inheritedMethodNames.length > 0) { | ||
| const program = createProgramForFile(filePath); | ||
| const checker = program?.getTypeChecker(); | ||
| const programSourceFile = program?.getSourceFile(filePath); | ||
| assert(checker, `Type checker could not be created for "${filePath}". Ensure a valid tsconfig.json is present.`); | ||
| assert(programSourceFile, `Source file "${filePath}" not found in program.`); | ||
| const classNode = findClassInSourceFile(programSourceFile, context.className); | ||
| assert(classNode, `Class "${context.className}" not found in "${filePath}".`); | ||
| const classType = checker.getTypeAtLocation(classNode); | ||
| for (const methodName of inheritedMethodNames) { | ||
| const methodDeclaration = findMethodInHierarchy(classType, methodName); | ||
| const jsDoc = methodDeclaration | ||
| ? extractJSDoc(methodDeclaration, methodDeclaration.getSourceFile()) | ||
| : ''; | ||
| context.methods.push({ name: methodName, jsDoc }); | ||
| } | ||
| } | ||
| return { | ||
| name: context.className, | ||
| filePath, | ||
| methods: context.methods, | ||
| }; | ||
| } | ||
| catch (error) { | ||
| console.error(`Error parsing ${filePath}:`, error); | ||
| return null; | ||
| } | ||
| } | ||
| /** | ||
| * Recursively get all files in a directory and its subdirectories. | ||
| * | ||
| * @param directory - The directory to search. | ||
| * @returns An array of file paths. | ||
| */ | ||
| const EXCLUDED_DIRECTORIES = new Set([ | ||
| 'node_modules', | ||
| 'dist', | ||
| '.git', | ||
| 'coverage', | ||
| ]); | ||
| async function getFiles(directory) { | ||
| const entries = await fs.promises.readdir(directory, { withFileTypes: true }); | ||
| const files = await Promise.all(entries.map(async (entry) => { | ||
| const fullPath = path.join(directory, entry.name); | ||
| if (entry.isDirectory()) { | ||
| return EXCLUDED_DIRECTORIES.has(entry.name) | ||
| ? [] | ||
| : await getFiles(fullPath); | ||
| } | ||
| return fullPath; | ||
| })); | ||
| return files.flat(); | ||
| } | ||
| /** | ||
| * Finds all source files that have MESSENGER_EXPOSED_METHODS constants. | ||
| * Searches recursively through subdirectories. | ||
| * | ||
| * @param sourcePath - Path to the folder where controllers/services are located. | ||
| * @returns A list of source information objects. | ||
| */ | ||
| export async function findSourcesWithExposedMethods(sourcePath) { | ||
| const srcPath = path.resolve(globalThis.process.cwd(), sourcePath); | ||
| const sources = []; | ||
| if (!(await isDirectory(srcPath))) { | ||
| throw new Error(`The specified path is not a directory: ${srcPath}`); | ||
| } | ||
| const srcFiles = await getFiles(srcPath); | ||
| for (const file of srcFiles) { | ||
| if (!file.endsWith('.ts') || file.endsWith('.test.ts')) { | ||
| continue; | ||
| } | ||
| const content = await fs.promises.readFile(file, 'utf8'); | ||
| if (content.includes('MESSENGER_EXPOSED_METHODS')) { | ||
| const sourceInfo = await parseSourceFile(file); | ||
| if (sourceInfo) { | ||
| sources.push(sourceInfo); | ||
| } | ||
| } | ||
| } | ||
| return sources; | ||
| } | ||
| //# sourceMappingURL=parse-source.mjs.map |
| {"version":3,"file":"parse-source.mjs","sourceRoot":"","sources":["../../src/generate-action-types/parse-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AAChE,OAAO,KAAK,EAAE,gBAAgB;AAC9B,OAAO,KAAK,IAAI,kBAAkB;;;AAgDlC;;;;;;GAMG;AACH,SAAS,YAAY,CAAC,IAAuB,EAAE,MAAkB;IAC/D,MAAM,SAAS,GAAG,uBAAuB,CAAC,IAAI,CAAC,CAAC;IAChD,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;IAC3B,IAAI,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACnB,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;QACtC,MAAM,KAAK,GAAG,KAAK,CAAC,YAAY,EAAE,CAAC;QACnC,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;QAC3B,MAAM,QAAQ,GAAG,QAAQ,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;QACvD,OAAO,WAAW,CAAC,QAAQ,CAAC,CAAC;IAC/B,CAAC;IAED,6FAA6F;IAC7F,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;;;;GAKG;AACH,SAAS,WAAW,CAAC,QAAgB;IACnC,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnC,MAAM,cAAc,GAAa,EAAE,CAAC;I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CAAC,QAAQ,CAAC,2BAA2B,CAAC,EAAE,CAAC;YAClD,MAAM,UAAU,GAAG,MAAM,eAAe,CAAC,IAAI,CAAC,CAAC;YAC/C,IAAI,UAAU,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { assert, hasProperty, isObject } from '@metamask/utils';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ArrayLiteralExpression,\n ClassDeclaration,\n MethodDeclaration,\n Node as TSNode,\n Program,\n SourceFile,\n Type,\n} from 'typescript';\nimport {\n ScriptTarget,\n createProgram,\n createSourceFile,\n findConfigFile,\n forEachChild,\n getJSDocCommentsAndTags,\n isArrayLiteralExpression,\n isAsExpression,\n isClassDeclaration,\n isIdentifier,\n isJSDoc,\n isMethodDeclaration,\n isStringLiteral,\n isVariableStatement,\n parseJsonConfigFileContent,\n readConfigFile,\n sys,\n} from 'typescript';\n\nexport type MethodInfo = {\n name: string;\n jsDoc: string;\n};\n\nexport type SourceInfo = {\n name: string;\n filePath: string;\n methods: MethodInfo[];\n};\n\ntype VisitorContext = {\n exposedMethods: string[];\n className: string;\n methods: MethodInfo[];\n sourceFile: SourceFile;\n};\n\n/**\n * Extracts JSDoc comment from a method declaration.\n *\n * @param node - The method declaration node.\n * @param source - The source file.\n * @returns The JSDoc comment.\n */\nfunction extractJSDoc(node: MethodDeclaration, source: SourceFile): string {\n const jsDocTags = getJSDocCommentsAndTags(node);\n if (jsDocTags.length === 0) {\n return '';\n }\n\n const jsDoc = jsDocTags[0];\n if (isJSDoc(jsDoc)) {\n const fullText = source.getFullText();\n const start = jsDoc.getFullStart();\n const end = jsDoc.getEnd();\n const rawJsDoc = fullText.substring(start, end).trim();\n return formatJSDoc(rawJsDoc);\n }\n\n // istanbul ignore next: defensive check — getJSDocCommentsAndTags always returns JSDoc nodes\n return '';\n}\n\n/**\n * Formats JSDoc comments to have consistent indentation for the generated file.\n *\n * @param rawJsDoc - The raw JSDoc comment from the source.\n * @returns The formatted JSDoc comment.\n */\nfunction formatJSDoc(rawJsDoc: string): string {\n const lines = rawJsDoc.split('\\n');\n const formattedLines: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (i === 0) {\n formattedLines.push('/**');\n } else if (i === lines.length - 1) {\n formattedLines.push(' */');\n } else {\n const trimmed = line.trim();\n if (trimmed.startsWith('*')) {\n const content = trimmed.substring(1).trim();\n formattedLines.push(content ? ` * ${content}` : ' *');\n } else {\n formattedLines.push(trimmed ? ` * ${trimmed}` : ' *');\n }\n }\n }\n\n return formattedLines.join('\\n');\n}\n\n/**\n * Visits AST nodes to find exposed methods and controller/service class.\n *\n * @param context - The visitor context.\n * @returns A function to visit nodes.\n */\nfunction createASTVisitor(context: VisitorContext): (node: TSNode) => void {\n function visitNode(node: TSNode): void {\n if (isVariableStatement(node)) {\n const declaration = node.declarationList.declarations[0];\n if (\n isIdentifier(declaration.name) &&\n declaration.name.text === 'MESSENGER_EXPOSED_METHODS'\n ) {\n if (declaration.initializer) {\n let arrayExpression: ArrayLiteralExpression | undefined;\n\n if (isArrayLiteralExpression(declaration.initializer)) {\n arrayExpression = declaration.initializer;\n } else if (\n isAsExpression(declaration.initializer) &&\n isArrayLiteralExpression(declaration.initializer.expression)\n ) {\n arrayExpression = declaration.initializer.expression;\n }\n\n if (arrayExpression) {\n context.exposedMethods = arrayExpression.elements\n .filter(isStringLiteral)\n .map((element) => element.text);\n }\n }\n }\n }\n\n if (isClassDeclaration(node) && node.name) {\n const classText = node.name.text;\n if (classText.includes('Controller') || classText.includes('Service')) {\n context.className = classText;\n\n const seenMethods = new Set<string>();\n for (const member of node.members) {\n if (\n isMethodDeclaration(member) &&\n member.name &&\n isIdentifier(member.name)\n ) {\n const methodName = member.name.text;\n if (\n context.exposedMethods.includes(methodName) &&\n !seenMethods.has(methodName)\n ) {\n seenMethods.add(methodName);\n const jsDoc = extractJSDoc(member, context.sourceFile);\n context.methods.push({\n name: methodName,\n jsDoc,\n });\n }\n }\n }\n }\n }\n\n forEachChild(node, visitNode);\n }\n\n return visitNode;\n}\n\n/**\n * Create a TypeScript program for the given file by locating the nearest\n * tsconfig.json.\n *\n * @param filePath - Absolute path to the source file.\n * @returns A TypeScript program, or null if no tsconfig was found.\n */\nfunction createProgramForFile(filePath: string): Program | null {\n const configPath = findConfigFile(\n path.dirname(filePath),\n sys.fileExists.bind(sys),\n 'tsconfig.json',\n );\n if (!configPath) {\n return null;\n }\n\n const { config, error } = readConfigFile(configPath, sys.readFile.bind(sys));\n\n if (error) {\n return null;\n }\n\n const parsedConfig = parseJsonConfigFileContent(\n config,\n sys,\n path.dirname(configPath),\n );\n\n return createProgram({\n rootNames: parsedConfig.fileNames,\n options: parsedConfig.options,\n });\n}\n\n/**\n * Find a class declaration with the given name in a source file.\n *\n * @param source - The source file to search.\n * @param className - The class name to look for.\n * @returns The class declaration node, or null if not found.\n */\nfunction findClassInSourceFile(\n source: SourceFile,\n className: string,\n): ClassDeclaration | null {\n return (\n source.statements.find(\n (node): node is ClassDeclaration =>\n isClassDeclaration(node) && node.name?.text === className,\n ) ?? // istanbul ignore next: class is always found when called from parseSourceFile\n null\n );\n}\n\n/**\n * Search through the class hierarchy of a TypeScript type to find the\n * declaration of a method with the given name.\n *\n * @param classType - The class type to search.\n * @param methodName - The method name to look for.\n * @returns The method declaration node, or null if not found.\n */\nfunction findMethodInHierarchy(\n classType: Type,\n methodName: string,\n): MethodDeclaration | null {\n const symbol = classType.getProperty(methodName);\n if (!symbol) {\n return null;\n }\n\n const declarations = symbol.getDeclarations();\n // istanbul ignore next: defensive check — symbols from getProperty always have declarations\n if (!declarations) {\n return null;\n }\n\n for (const declaration of declarations) {\n if (isMethodDeclaration(declaration)) {\n return declaration;\n }\n }\n\n // istanbul ignore next: defensive fallback — property found but not a method declaration\n return null;\n}\n\n/**\n * Check if a path is a directory.\n *\n * @param pathValue - The path to check.\n * @returns True if the path is a directory, false otherwise.\n */\nasync function isDirectory(pathValue: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(pathValue);\n return stats.isDirectory();\n } catch (error) {\n if (\n isObject(error) &&\n hasProperty(error, 'code') &&\n error.code === 'ENOENT'\n ) {\n return false;\n }\n\n throw error;\n }\n}\n\n/**\n * Parses a source file to extract exposed methods and their metadata.\n *\n * @param filePath - Path to the controller/service file to parse.\n * @returns Source information or null if parsing fails.\n */\nexport async function parseSourceFile(\n filePath: string,\n): Promise<SourceInfo | null> {\n try {\n const content = await fs.promises.readFile(filePath, 'utf8');\n const source = createSourceFile(\n filePath,\n content,\n ScriptTarget.Latest,\n true,\n );\n\n const context: VisitorContext = {\n exposedMethods: [],\n className: '',\n methods: [],\n sourceFile: source,\n };\n\n createASTVisitor(context)(source);\n\n if (context.exposedMethods.length === 0 || !context.className) {\n return null;\n }\n\n const foundMethodNames = new Set(\n context.methods.map((method) => method.name),\n );\n\n const inheritedMethodNames = context.exposedMethods.filter(\n (name) => !foundMethodNames.has(name),\n );\n\n if (inheritedMethodNames.length > 0) {\n const program = createProgramForFile(filePath);\n const checker = program?.getTypeChecker();\n const programSourceFile = program?.getSourceFile(filePath);\n\n assert(\n checker,\n `Type checker could not be created for \"${filePath}\". Ensure a valid tsconfig.json is present.`,\n );\n\n assert(\n programSourceFile,\n `Source file \"${filePath}\" not found in program.`,\n );\n\n const classNode = findClassInSourceFile(\n programSourceFile,\n context.className,\n );\n\n assert(\n classNode,\n `Class \"${context.className}\" not found in \"${filePath}\".`,\n );\n\n const classType = checker.getTypeAtLocation(classNode);\n for (const methodName of inheritedMethodNames) {\n const methodDeclaration = findMethodInHierarchy(classType, methodName);\n\n const jsDoc = methodDeclaration\n ? extractJSDoc(methodDeclaration, methodDeclaration.getSourceFile())\n : '';\n context.methods.push({ name: methodName, jsDoc });\n }\n }\n\n return {\n name: context.className,\n filePath,\n methods: context.methods,\n };\n } catch (error) {\n console.error(`Error parsing ${filePath}:`, error);\n return null;\n }\n}\n\n/**\n * Recursively get all files in a directory and its subdirectories.\n *\n * @param directory - The directory to search.\n * @returns An array of file paths.\n */\nconst EXCLUDED_DIRECTORIES = new Set([\n 'node_modules',\n 'dist',\n '.git',\n 'coverage',\n]);\n\nasync function getFiles(directory: string): Promise<string[]> {\n const entries = await fs.promises.readdir(directory, { withFileTypes: true });\n const files = await Promise.all(\n entries.map(async (entry) => {\n const fullPath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n return EXCLUDED_DIRECTORIES.has(entry.name)\n ? []\n : await getFiles(fullPath);\n }\n return fullPath;\n }),\n );\n\n return files.flat();\n}\n\n/**\n * Finds all source files that have MESSENGER_EXPOSED_METHODS constants.\n * Searches recursively through subdirectories.\n *\n * @param sourcePath - Path to the folder where controllers/services are located.\n * @returns A list of source information objects.\n */\nexport async function findSourcesWithExposedMethods(\n sourcePath: string,\n): Promise<SourceInfo[]> {\n const srcPath = path.resolve(globalThis.process.cwd(), sourcePath);\n const sources: SourceInfo[] = [];\n\n if (!(await isDirectory(srcPath))) {\n throw new Error(`The specified path is not a directory: ${srcPath}`);\n }\n\n const srcFiles = await getFiles(srcPath);\n\n for (const file of srcFiles) {\n if (!file.endsWith('.ts') || file.endsWith('.test.ts')) {\n continue;\n }\n\n const content = await fs.promises.readFile(file, 'utf8');\n\n if (content.includes('MESSENGER_EXPOSED_METHODS')) {\n const sourceInfo = await parseSourceFile(file);\n if (sourceInfo) {\n sources.push(sourceInfo);\n }\n }\n }\n\n return sources;\n}\n"]} |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| //# sourceMappingURL=types.cjs.map |
| {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../../src/generate-action-types/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ESLint as eslintClass } from 'eslint';\n\nexport type ESLint = {\n instance: eslintClass;\n eslintClass: typeof eslintClass;\n};\n"]} |
| import type { ESLint as eslintClass } from "eslint"; | ||
| export type ESLint = { | ||
| instance: eslintClass; | ||
| eslintClass: typeof eslintClass; | ||
| }; | ||
| //# sourceMappingURL=types.d.cts.map |
| {"version":3,"file":"types.d.cts","sourceRoot":"","sources":["../../src/generate-action-types/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,WAAW,EAAE,eAAe;AAEpD,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,EAAE,WAAW,CAAC;IACtB,WAAW,EAAE,OAAO,WAAW,CAAC;CACjC,CAAC"} |
| import type { ESLint as eslintClass } from "eslint"; | ||
| export type ESLint = { | ||
| instance: eslintClass; | ||
| eslintClass: typeof eslintClass; | ||
| }; | ||
| //# sourceMappingURL=types.d.mts.map |
| {"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../../src/generate-action-types/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,WAAW,EAAE,eAAe;AAEpD,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,EAAE,WAAW,CAAC;IACtB,WAAW,EAAE,OAAO,WAAW,CAAC;CACjC,CAAC"} |
| export {}; | ||
| //# sourceMappingURL=types.mjs.map |
| {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../../src/generate-action-types/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ESLint as eslintClass } from 'eslint';\n\nexport type ESLint = {\n instance: eslintClass;\n eslintClass: typeof eslintClass;\n};\n"]} |
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
2
-33.33%10
-23.08%0
-100%274614
-30.83%20
-70.59%1287
-46.95%- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated