@metamask-previews/base-controller 7.0.0-preview-9d310688 → 7.0.0-preview-09a2ffd5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/BaseControllerV1.js +12 -0
  2. package/dist/BaseControllerV1.js.map +1 -0
  3. package/dist/BaseControllerV1.mjs +11 -168
  4. package/dist/BaseControllerV1.mjs.map +1 -1
  5. package/dist/BaseControllerV2.js +14 -0
  6. package/dist/BaseControllerV2.js.map +1 -0
  7. package/dist/BaseControllerV2.mjs +12 -173
  8. package/dist/BaseControllerV2.mjs.map +1 -1
  9. package/dist/ControllerMessenger.js +9 -0
  10. package/dist/ControllerMessenger.js.map +1 -0
  11. package/dist/ControllerMessenger.mjs +7 -232
  12. package/dist/ControllerMessenger.mjs.map +1 -1
  13. package/dist/RestrictedControllerMessenger.js +8 -0
  14. package/dist/RestrictedControllerMessenger.js.map +1 -0
  15. package/dist/RestrictedControllerMessenger.mjs +6 -218
  16. package/dist/RestrictedControllerMessenger.mjs.map +1 -1
  17. package/dist/chunk-CDPVS6H4.js +145 -0
  18. package/dist/chunk-CDPVS6H4.js.map +1 -0
  19. package/dist/chunk-GHGTKX3N.mjs +251 -0
  20. package/dist/chunk-GHGTKX3N.mjs.map +1 -0
  21. package/dist/chunk-K2UEDATB.mjs +239 -0
  22. package/dist/chunk-K2UEDATB.mjs.map +1 -0
  23. package/dist/chunk-PQONVO7O.js +239 -0
  24. package/dist/chunk-PQONVO7O.js.map +1 -0
  25. package/dist/chunk-THTMQ73R.mjs +145 -0
  26. package/dist/chunk-THTMQ73R.mjs.map +1 -0
  27. package/dist/chunk-WJADFPC6.js +251 -0
  28. package/dist/chunk-WJADFPC6.js.map +1 -0
  29. package/dist/chunk-XUI43LEZ.mjs +30 -0
  30. package/dist/chunk-XUI43LEZ.mjs.map +1 -0
  31. package/dist/chunk-Z4BLTVTB.js +30 -0
  32. package/dist/chunk-Z4BLTVTB.js.map +1 -0
  33. package/dist/chunk-Z5HOIP7I.js +140 -0
  34. package/dist/chunk-Z5HOIP7I.js.map +1 -0
  35. package/dist/chunk-ZQJW5EWL.mjs +140 -0
  36. package/dist/chunk-ZQJW5EWL.mjs.map +1 -0
  37. package/dist/index.js +28 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/index.mjs +27 -4
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/tsconfig.build.tsbuildinfo +1 -0
  42. package/dist/{BaseControllerV1.d.mts → types/BaseControllerV1.d.ts} +3 -3
  43. package/dist/types/BaseControllerV1.d.ts.map +1 -0
  44. package/dist/{BaseControllerV2.d.cts → types/BaseControllerV2.d.ts} +6 -6
  45. package/dist/types/BaseControllerV2.d.ts.map +1 -0
  46. package/dist/{ControllerMessenger.d.mts → types/ControllerMessenger.d.ts} +2 -2
  47. package/dist/types/ControllerMessenger.d.ts.map +1 -0
  48. package/dist/{RestrictedControllerMessenger.d.mts → types/RestrictedControllerMessenger.d.ts} +2 -2
  49. package/dist/types/RestrictedControllerMessenger.d.ts.map +1 -0
  50. package/dist/{index.d.cts → types/index.d.ts} +9 -9
  51. package/dist/types/index.d.ts.map +1 -0
  52. package/package.json +7 -12
  53. package/dist/BaseControllerV1.cjs +0 -174
  54. package/dist/BaseControllerV1.cjs.map +0 -1
  55. package/dist/BaseControllerV1.d.cts +0 -140
  56. package/dist/BaseControllerV1.d.cts.map +0 -1
  57. package/dist/BaseControllerV1.d.mts.map +0 -1
  58. package/dist/BaseControllerV2.cjs +0 -182
  59. package/dist/BaseControllerV2.cjs.map +0 -1
  60. package/dist/BaseControllerV2.d.cts.map +0 -1
  61. package/dist/BaseControllerV2.d.mts +0 -199
  62. package/dist/BaseControllerV2.d.mts.map +0 -1
  63. package/dist/ControllerMessenger.cjs +0 -238
  64. package/dist/ControllerMessenger.cjs.map +0 -1
  65. package/dist/ControllerMessenger.d.cts +0 -217
  66. package/dist/ControllerMessenger.d.cts.map +0 -1
  67. package/dist/ControllerMessenger.d.mts.map +0 -1
  68. package/dist/RestrictedControllerMessenger.cjs +0 -224
  69. package/dist/RestrictedControllerMessenger.cjs.map +0 -1
  70. package/dist/RestrictedControllerMessenger.d.cts +0 -186
  71. package/dist/RestrictedControllerMessenger.d.cts.map +0 -1
  72. package/dist/RestrictedControllerMessenger.d.mts.map +0 -1
  73. package/dist/index.cjs +0 -16
  74. package/dist/index.cjs.map +0 -1
  75. package/dist/index.d.cts.map +0 -1
  76. package/dist/index.d.mts +0 -9
  77. package/dist/index.d.mts.map +0 -1
@@ -0,0 +1,12 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+ var _chunkZ5HOIP7Ijs = require('./chunk-Z5HOIP7I.js');
6
+ require('./chunk-Z4BLTVTB.js');
7
+
8
+
9
+
10
+
11
+ exports.BaseControllerV1 = _chunkZ5HOIP7Ijs.BaseControllerV1; exports.default = _chunkZ5HOIP7Ijs.BaseControllerV1_default; exports.isBaseControllerV1 = _chunkZ5HOIP7Ijs.isBaseControllerV1;
12
+ //# sourceMappingURL=BaseControllerV1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,169 +1,12 @@
1
- /**
2
- * Determines if the given controller is an instance of `BaseControllerV1`
3
- *
4
- * @param controller - Controller instance to check
5
- * @returns True if the controller is an instance of `BaseControllerV1`
6
- */
7
- export function isBaseControllerV1(controller) {
8
- return ('name' in controller &&
9
- typeof controller.name === 'string' &&
10
- 'config' in controller &&
11
- typeof controller.config === 'object' &&
12
- 'defaultConfig' in controller &&
13
- typeof controller.defaultConfig === 'object' &&
14
- 'state' in controller &&
15
- typeof controller.state === 'object' &&
16
- 'defaultState' in controller &&
17
- typeof controller.defaultState === 'object' &&
18
- 'disabled' in controller &&
19
- typeof controller.disabled === 'boolean' &&
20
- 'subscribe' in controller &&
21
- typeof controller.subscribe === 'function');
22
- }
23
- /**
24
- * @deprecated This class has been renamed to BaseControllerV1 and is no longer recommended for use for controllers. Please use BaseController (formerly BaseControllerV2) instead.
25
- *
26
- * Controller class that provides configuration, state management, and subscriptions.
27
- *
28
- * The core purpose of every controller is to maintain an internal data object
29
- * called "state". Each controller is responsible for its own state, and all global wallet state
30
- * is tracked in a controller as state.
31
- */
32
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
33
- // eslint-disable-next-line @typescript-eslint/naming-convention
34
- export class BaseControllerV1 {
35
- /**
36
- * Creates a BaseControllerV1 instance. Both initial state and initial
37
- * configuration options are merged with defaults upon initialization.
38
- *
39
- * @param config - Initial options used to configure this controller.
40
- * @param state - Initial state to set on this controller.
41
- */
42
- constructor(config = {}, state = {}) {
43
- /**
44
- * Default options used to configure this controller
45
- */
46
- this.defaultConfig = {};
47
- /**
48
- * Default state set on this controller
49
- */
50
- this.defaultState = {};
51
- /**
52
- * Determines if listeners are notified of state changes
53
- */
54
- this.disabled = false;
55
- /**
56
- * Name of this controller used during composition
57
- */
58
- this.name = 'BaseController';
59
- this.internalConfig = this.defaultConfig;
60
- this.internalState = this.defaultState;
61
- this.internalListeners = [];
62
- this.initialState = state;
63
- this.initialConfig = config;
64
- }
65
- /**
66
- * Enables the controller. This sets each config option as a member
67
- * variable on this instance and triggers any defined setters. This
68
- * also sets initial state and triggers any listeners.
69
- *
70
- * @returns This controller instance.
71
- */
72
- initialize() {
73
- this.internalState = this.defaultState;
74
- this.internalConfig = this.defaultConfig;
75
- this.configure(this.initialConfig);
76
- this.update(this.initialState);
77
- return this;
78
- }
79
- /**
80
- * Retrieves current controller configuration options.
81
- *
82
- * @returns The current configuration.
83
- */
84
- get config() {
85
- return this.internalConfig;
86
- }
87
- /**
88
- * Retrieves current controller state.
89
- *
90
- * @returns The current state.
91
- */
92
- get state() {
93
- return this.internalState;
94
- }
95
- /**
96
- * Updates controller configuration.
97
- *
98
- * @param config - New configuration options.
99
- * @param overwrite - Overwrite config instead of merging.
100
- * @param fullUpdate - Boolean that defines if the update is partial or not.
101
- */
102
- configure(config, overwrite = false, fullUpdate = true) {
103
- if (fullUpdate) {
104
- this.internalConfig = overwrite
105
- ? config
106
- : Object.assign(this.internalConfig, config);
107
- for (const key of Object.keys(this.internalConfig)) {
108
- const value = this.internalConfig[key];
109
- if (value !== undefined) {
110
- this[key] = value;
111
- }
112
- }
113
- }
114
- else {
115
- for (const key of Object.keys(config)) {
116
- /* istanbul ignore else */
117
- if (this.internalConfig[key] !== undefined) {
118
- const value = config[key];
119
- this.internalConfig[key] = value;
120
- this[key] = value;
121
- }
122
- }
123
- }
124
- }
125
- /**
126
- * Notifies all subscribed listeners of current state.
127
- */
128
- notify() {
129
- if (this.disabled) {
130
- return;
131
- }
132
- this.internalListeners.forEach((listener) => {
133
- listener(this.internalState);
134
- });
135
- }
136
- /**
137
- * Adds new listener to be notified of state changes.
138
- *
139
- * @param listener - The callback triggered when state changes.
140
- */
141
- subscribe(listener) {
142
- this.internalListeners.push(listener);
143
- }
144
- /**
145
- * Removes existing listener from receiving state changes.
146
- *
147
- * @param listener - The callback to remove.
148
- * @returns `true` if a listener is found and unsubscribed.
149
- */
150
- unsubscribe(listener) {
151
- const index = this.internalListeners.findIndex((cb) => listener === cb);
152
- index > -1 && this.internalListeners.splice(index, 1);
153
- return index > -1;
154
- }
155
- /**
156
- * Updates controller state.
157
- *
158
- * @param state - The new state.
159
- * @param overwrite - Overwrite state instead of merging.
160
- */
161
- update(state, overwrite = false) {
162
- this.internalState = overwrite
163
- ? Object.assign({}, state)
164
- : Object.assign({}, this.internalState, state);
165
- this.notify();
166
- }
167
- }
168
- export default BaseControllerV1;
1
+ import {
2
+ BaseControllerV1,
3
+ BaseControllerV1_default,
4
+ isBaseControllerV1
5
+ } from "./chunk-ZQJW5EWL.mjs";
6
+ import "./chunk-XUI43LEZ.mjs";
7
+ export {
8
+ BaseControllerV1,
9
+ BaseControllerV1_default as default,
10
+ isBaseControllerV1
11
+ };
169
12
  //# sourceMappingURL=BaseControllerV1.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":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KAAK,CAAC;iBACrC;aACF;SACF;IACH,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,OAAO;SACR;QAED,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;YAC1C,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,SAAS,CAAC,QAAqB;QAC7B,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC;IAED;;;;;OAKG;IACH,WAAW,CAAC,QAAqB;QAC/B,MAAM,KAAK,GAAG,IAAI,CAAC,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC;QACxE,KAAK,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QACtD,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC;IACpB,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,KAAiB,EAAE,SAAS,GAAG,KAAK;QACzC,IAAI,CAAC,aAAa,GAAG,SAAS;YAC5B,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAU,CAAC;YAC/B,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QACjD,IAAI,CAAC,MAAM,EAAE,CAAC;IAChB,CAAC;CACF;AAED,eAAe,gBAAgB,CAAC","sourcesContent":["import type { PublicInterface } from '@metamask/utils';\n\nimport type { ControllerInstance } from './BaseControllerV2';\n\n/**\n * Determines if the given controller is an instance of `BaseControllerV1`\n *\n * @param controller - Controller instance to check\n * @returns True if the controller is an instance of `BaseControllerV1`\n */\nexport function isBaseControllerV1(\n controller: ControllerInstance,\n): controller is BaseControllerV1Instance {\n return (\n 'name' in controller &&\n typeof controller.name === 'string' &&\n 'config' in controller &&\n typeof controller.config === 'object' &&\n 'defaultConfig' in controller &&\n typeof controller.defaultConfig === 'object' &&\n 'state' in controller &&\n typeof controller.state === 'object' &&\n 'defaultState' in controller &&\n typeof controller.defaultState === 'object' &&\n 'disabled' in controller &&\n typeof controller.disabled === 'boolean' &&\n 'subscribe' in controller &&\n typeof controller.subscribe === 'function'\n );\n}\n\n/**\n * State change callbacks\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type Listener<T> = (state: T) => void;\n\n/**\n * @type BaseConfig\n *\n * Base controller configuration\n * @property disabled - Determines if this controller is enabled\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface BaseConfig {\n disabled?: boolean;\n}\n\n/**\n * @type BaseState\n *\n * Base state representation\n * @property name - Unique name for this controller\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface BaseState {\n name?: string;\n}\n\n/**\n * The narrowest supertype for `BaseControllerV1` config objects.\n * This type can be assigned to any `BaseControllerV1` config object.\n */\nexport type ConfigConstraint = BaseConfig & object;\n\n/**\n * The narrowest supertype for `BaseControllerV1` state objects.\n * This type can be assigned to any `BaseControllerV1` state object.\n */\nexport type StateConstraint = BaseState & object;\n\n/**\n * The widest subtype of all controller instances that extend from `BaseControllerV1`.\n * Any `BaseControllerV1` instance can be assigned to this type.\n */\nexport type BaseControllerV1Instance = PublicInterface<\n BaseControllerV1<ConfigConstraint, StateConstraint>\n>;\n\n/**\n * @deprecated This class has been renamed to BaseControllerV1 and is no longer recommended for use for controllers. Please use BaseController (formerly BaseControllerV2) instead.\n *\n * Controller class that provides configuration, state management, and subscriptions.\n *\n * The core purpose of every controller is to maintain an internal data object\n * called \"state\". Each controller is responsible for its own state, and all global wallet state\n * is tracked in a controller as state.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class BaseControllerV1<C extends BaseConfig, S extends BaseState> {\n /**\n * Default options used to configure this controller\n */\n defaultConfig: C = {} as never;\n\n /**\n * Default state set on this controller\n */\n defaultState: S = {} as never;\n\n /**\n * Determines if listeners are notified of state changes\n */\n disabled = false;\n\n /**\n * Name of this controller used during composition\n */\n name = 'BaseController';\n\n private readonly initialConfig: Partial<C>;\n\n private readonly initialState: Partial<S>;\n\n private internalConfig: C = this.defaultConfig;\n\n private internalState: S = this.defaultState;\n\n private readonly internalListeners: Listener<S>[] = [];\n\n /**\n * Creates a BaseControllerV1 instance. Both initial state and initial\n * configuration options are merged with defaults upon initialization.\n *\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(config: Partial<C> = {}, state: Partial<S> = {}) {\n this.initialState = state;\n this.initialConfig = config;\n }\n\n /**\n * Enables the controller. This sets each config option as a member\n * variable on this instance and triggers any defined setters. This\n * also sets initial state and triggers any listeners.\n *\n * @returns This controller instance.\n */\n protected initialize() {\n this.internalState = this.defaultState;\n this.internalConfig = this.defaultConfig;\n this.configure(this.initialConfig);\n this.update(this.initialState);\n return this;\n }\n\n /**\n * Retrieves current controller configuration options.\n *\n * @returns The current configuration.\n */\n get config() {\n return this.internalConfig;\n }\n\n /**\n * Retrieves current controller state.\n *\n * @returns The current state.\n */\n get state() {\n return this.internalState;\n }\n\n /**\n * Updates controller configuration.\n *\n * @param config - New configuration options.\n * @param overwrite - Overwrite config instead of merging.\n * @param fullUpdate - Boolean that defines if the update is partial or not.\n */\n configure(config: Partial<C>, overwrite = false, fullUpdate = true) {\n if (fullUpdate) {\n this.internalConfig = overwrite\n ? (config as C)\n : Object.assign(this.internalConfig, config);\n\n for (const key of Object.keys(this.internalConfig) as (keyof C)[]) {\n const value = this.internalConfig[key];\n if (value !== undefined) {\n (this as unknown as C)[key] = value;\n }\n }\n } else {\n for (const key of Object.keys(config) as (keyof C)[]) {\n /* istanbul ignore else */\n if (this.internalConfig[key] !== undefined) {\n const value = (config as C)[key];\n this.internalConfig[key] = value;\n (this as unknown as C)[key] = value;\n }\n }\n }\n }\n\n /**\n * Notifies all subscribed listeners of current state.\n */\n notify() {\n if (this.disabled) {\n return;\n }\n\n this.internalListeners.forEach((listener) => {\n listener(this.internalState);\n });\n }\n\n /**\n * Adds new listener to be notified of state changes.\n *\n * @param listener - The callback triggered when state changes.\n */\n subscribe(listener: Listener<S>) {\n this.internalListeners.push(listener);\n }\n\n /**\n * Removes existing listener from receiving state changes.\n *\n * @param listener - The callback to remove.\n * @returns `true` if a listener is found and unsubscribed.\n */\n unsubscribe(listener: Listener<S>) {\n const index = this.internalListeners.findIndex((cb) => listener === cb);\n index > -1 && this.internalListeners.splice(index, 1);\n return index > -1;\n }\n\n /**\n * Updates controller state.\n *\n * @param state - The new state.\n * @param overwrite - Overwrite state instead of merging.\n */\n update(state: Partial<S>, overwrite = false) {\n this.internalState = overwrite\n ? Object.assign({}, state as S)\n : Object.assign({}, this.internalState, state);\n this.notify();\n }\n}\n\nexport default BaseControllerV1;\n"]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,14 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+ var _chunkCDPVS6H4js = require('./chunk-CDPVS6H4.js');
7
+ require('./chunk-Z4BLTVTB.js');
8
+
9
+
10
+
11
+
12
+
13
+ exports.BaseController = _chunkCDPVS6H4js.BaseController; exports.getAnonymizedState = _chunkCDPVS6H4js.getAnonymizedState; exports.getPersistentState = _chunkCDPVS6H4js.getPersistentState; exports.isBaseController = _chunkCDPVS6H4js.isBaseController;
14
+ //# sourceMappingURL=BaseControllerV2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,175 +1,14 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1
+ import {
2
+ BaseController,
3
+ getAnonymizedState,
4
+ getPersistentState,
5
+ isBaseController
6
+ } from "./chunk-THTMQ73R.mjs";
7
+ import "./chunk-XUI43LEZ.mjs";
8
+ export {
9
+ BaseController,
10
+ getAnonymizedState,
11
+ getPersistentState,
12
+ isBaseController
6
13
  };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _BaseController_internalState;
13
- import { enablePatches, produceWithPatches, applyPatches, freeze } from "immer";
14
- enablePatches();
15
- /**
16
- * Determines if the given controller is an instance of `BaseController`
17
- *
18
- * @param controller - Controller instance to check
19
- * @returns True if the controller is an instance of `BaseController`
20
- */
21
- export function isBaseController(controller) {
22
- return ('name' in controller &&
23
- typeof controller.name === 'string' &&
24
- 'state' in controller &&
25
- typeof controller.state === 'object' &&
26
- 'metadata' in controller &&
27
- typeof controller.metadata === 'object');
28
- }
29
- /**
30
- * Controller class that provides state management, subscriptions, and state metadata
31
- */
32
- export class BaseController {
33
- /**
34
- * Creates a BaseController instance.
35
- *
36
- * @param options - Controller options.
37
- * @param options.messenger - Controller messaging system.
38
- * @param options.metadata - ControllerState metadata, describing how to "anonymize" the state, and which
39
- * parts should be persisted.
40
- * @param options.name - The name of the controller, used as a namespace for events and actions.
41
- * @param options.state - Initial controller state.
42
- */
43
- constructor({ messenger, metadata, name, state, }) {
44
- _BaseController_internalState.set(this, void 0);
45
- this.messagingSystem = messenger;
46
- this.name = name;
47
- // Here we use `freeze` from Immer to enforce that the state is deeply
48
- // immutable. Note that this is a runtime check, not a compile-time check.
49
- // That is, unlike `Object.freeze`, this does not narrow the type
50
- // recursively to `Readonly`. The equivalent in Immer is `Immutable`, but
51
- // `Immutable` does not handle recursive types such as our `Json` type.
52
- __classPrivateFieldSet(this, _BaseController_internalState, freeze(state, true), "f");
53
- this.metadata = metadata;
54
- this.messagingSystem.registerActionHandler(`${name}:getState`, () => this.state);
55
- this.messagingSystem.registerInitialEventPayload({
56
- eventType: `${name}:stateChange`,
57
- getPayload: () => [this.state, []],
58
- });
59
- }
60
- /**
61
- * Retrieves current controller state.
62
- *
63
- * @returns The current state.
64
- */
65
- get state() {
66
- return __classPrivateFieldGet(this, _BaseController_internalState, "f");
67
- }
68
- set state(_) {
69
- throw new Error(`Controller state cannot be directly mutated; use 'update' method instead.`);
70
- }
71
- /**
72
- * Updates controller state. Accepts a callback that is passed a draft copy
73
- * of the controller state. If a value is returned, it is set as the new
74
- * state. Otherwise, any changes made within that callback to the draft are
75
- * applied to the controller state.
76
- *
77
- * @param callback - Callback for updating state, passed a draft state
78
- * object. Return a new state object or mutate the draft to update state.
79
- * @returns An object that has the next state, patches applied in the update and inverse patches to
80
- * rollback the update.
81
- */
82
- update(callback) {
83
- // We run into ts2589, "infinite type depth", if we don't cast
84
- // produceWithPatches here.
85
- const [nextState, patches, inversePatches] = produceWithPatches(__classPrivateFieldGet(this, _BaseController_internalState, "f"), callback);
86
- __classPrivateFieldSet(this, _BaseController_internalState, nextState, "f");
87
- this.messagingSystem.publish(`${this.name}:stateChange`, nextState, patches);
88
- return { nextState, patches, inversePatches };
89
- }
90
- /**
91
- * Applies immer patches to the current state. The patches come from the
92
- * update function itself and can either be normal or inverse patches.
93
- *
94
- * @param patches - An array of immer patches that are to be applied to make
95
- * or undo changes.
96
- */
97
- applyPatches(patches) {
98
- const nextState = applyPatches(__classPrivateFieldGet(this, _BaseController_internalState, "f"), patches);
99
- __classPrivateFieldSet(this, _BaseController_internalState, nextState, "f");
100
- this.messagingSystem.publish(`${this.name}:stateChange`, nextState, patches);
101
- }
102
- /**
103
- * Prepares the controller for garbage collection. This should be extended
104
- * by any subclasses to clean up any additional connections or events.
105
- *
106
- * The only cleanup performed here is to remove listeners. While technically
107
- * this is not required to ensure this instance is garbage collected, it at
108
- * least ensures this instance won't be responsible for preventing the
109
- * listeners from being garbage collected.
110
- */
111
- destroy() {
112
- this.messagingSystem.clearEventSubscriptions(`${this.name}:stateChange`);
113
- }
114
- }
115
- _BaseController_internalState = new WeakMap();
116
- /**
117
- * Returns an anonymized representation of the controller state.
118
- *
119
- * By "anonymized" we mean that it should not contain any information that could be personally
120
- * identifiable.
121
- *
122
- * @param state - The controller state.
123
- * @param metadata - The controller state metadata, which describes how to derive the
124
- * anonymized state.
125
- * @returns The anonymized controller state.
126
- */
127
- export function getAnonymizedState(state, metadata) {
128
- return deriveStateFromMetadata(state, metadata, 'anonymous');
129
- }
130
- /**
131
- * Returns the subset of state that should be persisted.
132
- *
133
- * @param state - The controller state.
134
- * @param metadata - The controller state metadata, which describes which pieces of state should be persisted.
135
- * @returns The subset of controller state that should be persisted.
136
- */
137
- export function getPersistentState(state, metadata) {
138
- return deriveStateFromMetadata(state, metadata, 'persist');
139
- }
140
- /**
141
- * Use the metadata to derive state according to the given metadata property.
142
- *
143
- * @param state - The full controller state.
144
- * @param metadata - The controller metadata.
145
- * @param metadataProperty - The metadata property to use to derive state.
146
- * @returns The metadata-derived controller state.
147
- */
148
- function deriveStateFromMetadata(state, metadata, metadataProperty) {
149
- return Object.keys(state).reduce((derivedState, key) => {
150
- try {
151
- const stateMetadata = metadata[key];
152
- if (!stateMetadata) {
153
- throw new Error(`No metadata found for '${String(key)}'`);
154
- }
155
- const propertyMetadata = stateMetadata[metadataProperty];
156
- const stateProperty = state[key];
157
- if (typeof propertyMetadata === 'function') {
158
- derivedState[key] = propertyMetadata(stateProperty);
159
- }
160
- else if (propertyMetadata) {
161
- derivedState[key] = stateProperty;
162
- }
163
- return derivedState;
164
- }
165
- catch (error) {
166
- // Throw error after timeout so that it is captured as a console error
167
- // (and by Sentry) without interrupting state-related operations
168
- setTimeout(() => {
169
- throw error;
170
- });
171
- return derivedState;
172
- }
173
- }, {});
174
- }
175
14
  //# sourceMappingURL=BaseControllerV2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseControllerV2.mjs","sourceRoot":"","sources":["../src/BaseControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc;AAahF,aAAa,EAAE,CAAC;AAEhB;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAC9B,UAA8B;IAE9B,OAAO,CACL,MAAM,IAAI,UAAU;QACpB,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ;QACnC,OAAO,IAAI,UAAU;QACrB,OAAO,UAAU,CAAC,KAAK,KAAK,QAAQ;QACpC,UAAU,IAAI,UAAU;QACxB,OAAO,UAAU,CAAC,QAAQ,KAAK,QAAQ,CACxC,CAAC;AACJ,CAAC;AAsJD;;GAEG;AACH,MAAM,OAAO,cAAc;IA0BzB;;;;;;;;;OASG;IACH,YAAY,EACV,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,KAAK,GAMN;QAjCD,gDAAgC;QAkC9B,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,sEAAsE;QACtE,0EAA0E;QAC1E,iEAAiE;QACjE,yEAAyE;QACzE,uEAAuE;QACvE,uBAAA,IAAI,iCAAkB,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,MAAA,CAA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AAC,GAAG,EAAE;gBACd,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,OAAO,YAAY,CAAC;SACrB;IACH,CAAC,EAAE,EAAW,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import type { Json, PublicInterface } from '@metamask/utils';\nimport { enablePatches, produceWithPatches, applyPatches, freeze } from 'immer';\nimport type { Draft, Patch } from 'immer';\n\nimport type {\n BaseControllerV1Instance,\n StateConstraint as StateConstraintV1,\n} from './BaseControllerV1';\nimport type { ActionConstraint, EventConstraint } from './ControllerMessenger';\nimport type {\n RestrictedControllerMessenger,\n RestrictedControllerMessengerConstraint,\n} from './RestrictedControllerMessenger';\n\nenablePatches();\n\n/**\n * Determines if the given controller is an instance of `BaseController`\n *\n * @param controller - Controller instance to check\n * @returns True if the controller is an instance of `BaseController`\n */\nexport function isBaseController(\n controller: ControllerInstance,\n): controller is BaseControllerInstance {\n return (\n 'name' in controller &&\n typeof controller.name === 'string' &&\n 'state' in controller &&\n typeof controller.state === 'object' &&\n 'metadata' in controller &&\n typeof controller.metadata === 'object'\n );\n}\n\n/**\n * A type that constrains the state of all controllers.\n *\n * In other words, the narrowest supertype encompassing all controller state.\n */\nexport type StateConstraint = Record<string, Json>;\n\n/**\n * A universal supertype for the controller state object, encompassing both `BaseControllerV1` and `BaseControllerV2` state.\n */\n// TODO: Remove once BaseControllerV2 migrations are completed for all controllers.\nexport type LegacyControllerStateConstraint =\n | StateConstraintV1\n | StateConstraint;\n\n/**\n * A state change listener.\n *\n * This function will get called for each state change, and is given a copy of\n * the new state along with a set of patches describing the changes since the\n * last update.\n *\n * @param state - The new controller state.\n * @param patches - A list of patches describing any changes (see here for more\n * information: https://immerjs.github.io/immer/docs/patches)\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type Listener<T> = (state: T, patches: Patch[]) => void;\n\n/**\n * An function to derive state.\n *\n * This function will accept one piece of the controller state (one property),\n * and will return some derivation of that state.\n *\n * @param value - A piece of controller state.\n * @returns Something derived from controller state.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type StateDeriver<T extends Json> = (value: T) => Json;\n\n/**\n * State metadata.\n *\n * This metadata describes which parts of state should be persisted, and how to\n * get an anonymized representation of the state.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type StateMetadata<T extends StateConstraint> = {\n [P in keyof T]-?: StatePropertyMetadata<T[P]>;\n};\n\n/**\n * Metadata for a single state property\n *\n * @property persist - Indicates whether this property should be persisted\n * (`true` for persistent, `false` for transient), or is set to a function\n * that derives the persistent state from the state.\n * @property anonymous - Indicates whether this property is already anonymous,\n * (`true` for anonymous, `false` if it has potential to be personally\n * identifiable), or is set to a function that returns an anonymized\n * representation of this state.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type StatePropertyMetadata<T extends Json> = {\n persist: boolean | StateDeriver<T>;\n anonymous: boolean | StateDeriver<T>;\n};\n\n/**\n * A universal supertype of `StateDeriver` types.\n * This type can be assigned to any `StateDeriver` type.\n */\nexport type StateDeriverConstraint = (value: never) => Json;\n\n/**\n * A universal supertype of `StatePropertyMetadata` types.\n * This type can be assigned to any `StatePropertyMetadata` type.\n */\nexport type StatePropertyMetadataConstraint = {\n [P in 'anonymous' | 'persist']: boolean | StateDeriverConstraint;\n};\n\n/**\n * A universal supertype of `StateMetadata` types.\n * This type can be assigned to any `StateMetadata` type.\n */\nexport type StateMetadataConstraint = Record<\n string,\n StatePropertyMetadataConstraint\n>;\n\n/**\n * The widest subtype of all controller instances that inherit from `BaseController` (formerly `BaseControllerV2`).\n * Any `BaseController` subclass instance can be assigned to this type.\n */\nexport type BaseControllerInstance = Omit<\n PublicInterface<\n BaseController<\n string,\n StateConstraint,\n RestrictedControllerMessengerConstraint\n >\n >,\n 'metadata'\n> & {\n metadata: StateMetadataConstraint;\n};\n\n/**\n * A widest subtype of all controller instances that inherit from `BaseController` (formerly `BaseControllerV2`) or `BaseControllerV1`.\n * Any `BaseController` or `BaseControllerV1` subclass instance can be assigned to this type.\n */\n// TODO: Remove once BaseControllerV2 migrations are completed for all controllers.\nexport type ControllerInstance =\n | BaseControllerV1Instance\n | BaseControllerInstance;\n\nexport type ControllerGetStateAction<\n ControllerName extends string,\n ControllerState extends StateConstraint,\n> = {\n type: `${ControllerName}:getState`;\n handler: () => ControllerState;\n};\n\nexport type ControllerStateChangeEvent<\n ControllerName extends string,\n ControllerState extends StateConstraint,\n> = {\n type: `${ControllerName}:stateChange`;\n payload: [ControllerState, Patch[]];\n};\n\nexport type ControllerActions<\n ControllerName extends string,\n ControllerState extends StateConstraint,\n> = ControllerGetStateAction<ControllerName, ControllerState>;\n\nexport type ControllerEvents<\n ControllerName extends string,\n ControllerState extends StateConstraint,\n> = ControllerStateChangeEvent<ControllerName, ControllerState>;\n\n/**\n * Controller class that provides state management, subscriptions, and state metadata\n */\nexport class BaseController<\n ControllerName extends string,\n ControllerState extends StateConstraint,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n messenger extends RestrictedControllerMessenger<\n ControllerName,\n ActionConstraint | ControllerActions<ControllerName, ControllerState>,\n EventConstraint | ControllerEvents<ControllerName, ControllerState>,\n string,\n string\n >,\n> {\n #internalState: ControllerState;\n\n protected messagingSystem: messenger;\n\n /**\n * The name of the controller.\n *\n * This is used by the ComposableController to construct a composed application state.\n */\n public readonly name: ControllerName;\n\n public readonly metadata: StateMetadata<ControllerState>;\n\n /**\n * Creates a BaseController instance.\n *\n * @param options - Controller options.\n * @param options.messenger - Controller messaging system.\n * @param options.metadata - ControllerState metadata, describing how to \"anonymize\" the state, and which\n * parts should be persisted.\n * @param options.name - The name of the controller, used as a namespace for events and actions.\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n metadata,\n name,\n state,\n }: {\n messenger: messenger;\n metadata: StateMetadata<ControllerState>;\n name: ControllerName;\n state: ControllerState;\n }) {\n this.messagingSystem = messenger;\n this.name = name;\n // Here we use `freeze` from Immer to enforce that the state is deeply\n // immutable. Note that this is a runtime check, not a compile-time check.\n // That is, unlike `Object.freeze`, this does not narrow the type\n // recursively to `Readonly`. The equivalent in Immer is `Immutable`, but\n // `Immutable` does not handle recursive types such as our `Json` type.\n this.#internalState = freeze(state, true);\n this.metadata = metadata;\n\n this.messagingSystem.registerActionHandler(\n `${name}:getState`,\n () => this.state,\n );\n\n this.messagingSystem.registerInitialEventPayload({\n eventType: `${name}:stateChange`,\n getPayload: () => [this.state, []],\n });\n }\n\n /**\n * Retrieves current controller state.\n *\n * @returns The current state.\n */\n get state() {\n return this.#internalState;\n }\n\n set state(_) {\n throw new Error(\n `Controller state cannot be directly mutated; use 'update' method instead.`,\n );\n }\n\n /**\n * Updates controller state. Accepts a callback that is passed a draft copy\n * of the controller state. If a value is returned, it is set as the new\n * state. Otherwise, any changes made within that callback to the draft are\n * applied to the controller state.\n *\n * @param callback - Callback for updating state, passed a draft state\n * object. Return a new state object or mutate the draft to update state.\n * @returns An object that has the next state, patches applied in the update and inverse patches to\n * rollback the update.\n */\n protected update(\n callback: (state: Draft<ControllerState>) => void | ControllerState,\n ): {\n nextState: ControllerState;\n patches: Patch[];\n inversePatches: Patch[];\n } {\n // We run into ts2589, \"infinite type depth\", if we don't cast\n // produceWithPatches here.\n const [nextState, patches, inversePatches] = (\n produceWithPatches as unknown as (\n state: ControllerState,\n cb: typeof callback,\n ) => [ControllerState, Patch[], Patch[]]\n )(this.#internalState, callback);\n\n this.#internalState = nextState;\n this.messagingSystem.publish(\n `${this.name}:stateChange`,\n nextState,\n patches,\n );\n\n return { nextState, patches, inversePatches };\n }\n\n /**\n * Applies immer patches to the current state. The patches come from the\n * update function itself and can either be normal or inverse patches.\n *\n * @param patches - An array of immer patches that are to be applied to make\n * or undo changes.\n */\n protected applyPatches(patches: Patch[]) {\n const nextState = applyPatches(this.#internalState, patches);\n this.#internalState = nextState;\n this.messagingSystem.publish(\n `${this.name}:stateChange`,\n nextState,\n patches,\n );\n }\n\n /**\n * Prepares the controller for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n *\n * The only cleanup performed here is to remove listeners. While technically\n * this is not required to ensure this instance is garbage collected, it at\n * least ensures this instance won't be responsible for preventing the\n * listeners from being garbage collected.\n */\n protected destroy() {\n this.messagingSystem.clearEventSubscriptions(`${this.name}:stateChange`);\n }\n}\n\n/**\n * Returns an anonymized representation of the controller state.\n *\n * By \"anonymized\" we mean that it should not contain any information that could be personally\n * identifiable.\n *\n * @param state - The controller state.\n * @param metadata - The controller state metadata, which describes how to derive the\n * anonymized state.\n * @returns The anonymized controller state.\n */\nexport function getAnonymizedState<ControllerState extends StateConstraint>(\n state: ControllerState,\n metadata: StateMetadata<ControllerState>,\n): Record<keyof ControllerState, Json> {\n return deriveStateFromMetadata(state, metadata, 'anonymous');\n}\n\n/**\n * Returns the subset of state that should be persisted.\n *\n * @param state - The controller state.\n * @param metadata - The controller state metadata, which describes which pieces of state should be persisted.\n * @returns The subset of controller state that should be persisted.\n */\nexport function getPersistentState<ControllerState extends StateConstraint>(\n state: ControllerState,\n metadata: StateMetadata<ControllerState>,\n): Record<keyof ControllerState, Json> {\n return deriveStateFromMetadata(state, metadata, 'persist');\n}\n\n/**\n * Use the metadata to derive state according to the given metadata property.\n *\n * @param state - The full controller state.\n * @param metadata - The controller metadata.\n * @param metadataProperty - The metadata property to use to derive state.\n * @returns The metadata-derived controller state.\n */\nfunction deriveStateFromMetadata<ControllerState extends StateConstraint>(\n state: ControllerState,\n metadata: StateMetadata<ControllerState>,\n metadataProperty: 'anonymous' | 'persist',\n): Record<keyof ControllerState, Json> {\n return (Object.keys(state) as (keyof ControllerState)[]).reduce<\n Record<keyof ControllerState, Json>\n >((derivedState, key) => {\n try {\n const stateMetadata = metadata[key];\n if (!stateMetadata) {\n throw new Error(`No metadata found for '${String(key)}'`);\n }\n const propertyMetadata = stateMetadata[metadataProperty];\n const stateProperty = state[key];\n if (typeof propertyMetadata === 'function') {\n derivedState[key] = propertyMetadata(stateProperty);\n } else if (propertyMetadata) {\n derivedState[key] = stateProperty;\n }\n return derivedState;\n } catch (error) {\n // Throw error after timeout so that it is captured as a console error\n // (and by Sentry) without interrupting state-related operations\n setTimeout(() => {\n throw error;\n });\n return derivedState;\n }\n }, {} as never);\n}\n"]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,9 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkPQONVO7Ojs = require('./chunk-PQONVO7O.js');
4
+ require('./chunk-WJADFPC6.js');
5
+ require('./chunk-Z4BLTVTB.js');
6
+
7
+
8
+ exports.ControllerMessenger = _chunkPQONVO7Ojs.ControllerMessenger;
9
+ //# sourceMappingURL=ControllerMessenger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}