@metamask/snaps-utils 3.0.0 → 3.2.0

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 (72) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/cjs/auxiliary-files.js +40 -0
  3. package/dist/cjs/auxiliary-files.js.map +1 -0
  4. package/dist/cjs/errors.js +353 -3
  5. package/dist/cjs/errors.js.map +1 -1
  6. package/dist/cjs/eval-worker.js +2 -2
  7. package/dist/cjs/eval-worker.js.map +1 -1
  8. package/dist/cjs/handler-types.js +31 -0
  9. package/dist/cjs/handler-types.js.map +1 -0
  10. package/dist/cjs/handlers.js +24 -27
  11. package/dist/cjs/handlers.js.map +1 -1
  12. package/dist/cjs/index.browser.js +2 -0
  13. package/dist/cjs/index.browser.js.map +1 -1
  14. package/dist/cjs/index.executionenv.js +2 -0
  15. package/dist/cjs/index.executionenv.js.map +1 -1
  16. package/dist/cjs/index.js +9 -0
  17. package/dist/cjs/index.js.map +1 -1
  18. package/dist/cjs/manifest/manifest.js +25 -5
  19. package/dist/cjs/manifest/manifest.js.map +1 -1
  20. package/dist/cjs/manifest/validation.js +6 -1
  21. package/dist/cjs/manifest/validation.js.map +1 -1
  22. package/dist/cjs/npm.js +5 -3
  23. package/dist/cjs/npm.js.map +1 -1
  24. package/dist/cjs/snaps.js +3 -2
  25. package/dist/cjs/snaps.js.map +1 -1
  26. package/dist/cjs/types.js +0 -5
  27. package/dist/cjs/types.js.map +1 -1
  28. package/dist/cjs/validation.js.map +1 -1
  29. package/dist/cjs/virtual-file/VirtualFile.js +6 -0
  30. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -1
  31. package/dist/esm/auxiliary-files.js +28 -0
  32. package/dist/esm/auxiliary-files.js.map +1 -0
  33. package/dist/esm/errors.js +350 -1
  34. package/dist/esm/errors.js.map +1 -1
  35. package/dist/esm/eval-worker.js +1 -1
  36. package/dist/esm/eval-worker.js.map +1 -1
  37. package/dist/esm/handler-types.js +13 -0
  38. package/dist/esm/handler-types.js.map +1 -0
  39. package/dist/esm/handlers.js +7 -10
  40. package/dist/esm/handlers.js.map +1 -1
  41. package/dist/esm/index.browser.js +2 -0
  42. package/dist/esm/index.browser.js.map +1 -1
  43. package/dist/esm/index.executionenv.js +2 -0
  44. package/dist/esm/index.executionenv.js.map +1 -1
  45. package/dist/esm/index.js +3 -0
  46. package/dist/esm/index.js.map +1 -1
  47. package/dist/esm/manifest/manifest.js +30 -5
  48. package/dist/esm/manifest/manifest.js.map +1 -1
  49. package/dist/esm/manifest/validation.js +3 -1
  50. package/dist/esm/manifest/validation.js.map +1 -1
  51. package/dist/esm/npm.js +5 -3
  52. package/dist/esm/npm.js.map +1 -1
  53. package/dist/esm/snaps.js +3 -2
  54. package/dist/esm/snaps.js.map +1 -1
  55. package/dist/esm/types.js +0 -2
  56. package/dist/esm/types.js.map +1 -1
  57. package/dist/esm/validation.js.map +1 -1
  58. package/dist/esm/virtual-file/VirtualFile.js +7 -1
  59. package/dist/esm/virtual-file/VirtualFile.js.map +1 -1
  60. package/dist/types/auxiliary-files.d.ts +13 -0
  61. package/dist/types/errors.d.ts +182 -0
  62. package/dist/types/handler-types.d.ts +31 -0
  63. package/dist/types/handlers.d.ts +49 -36
  64. package/dist/types/index.browser.d.ts +2 -0
  65. package/dist/types/index.d.ts +3 -0
  66. package/dist/types/index.executionenv.d.ts +2 -0
  67. package/dist/types/manifest/manifest.d.ts +11 -1
  68. package/dist/types/manifest/validation.d.ts +6 -2
  69. package/dist/types/snaps.d.ts +13 -6
  70. package/dist/types/types.d.ts +8 -9
  71. package/dist/types/validation.d.ts +2 -2
  72. package/package.json +17 -18
package/CHANGELOG.md CHANGED
@@ -6,6 +6,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.2.0]
10
+ ### Added
11
+ - Add support for links in custom UI and notifications ([#1814](https://github.com/MetaMask/snaps/pull/1814))
12
+
13
+ ## [3.1.0]
14
+ ### Added
15
+ - Add static file API ([#1836](https://github.com/MetaMask/snaps/pull/1836), [#1858](https://github.com/MetaMask/snaps/pull/1858))
16
+
17
+ ### Changed
18
+ - Update multiple MetaMask dependencies ([#1841](https://github.com/MetaMask/snaps/pull/1841))
19
+ - Bump Babel packages from `^7.20.12` to `^7.23.2` ([#1862](https://github.com/MetaMask/snaps/pull/1862))
20
+
9
21
  ## [3.0.0]
10
22
  ### Added
11
23
  - Add keyring export and endowment ([#1787](https://github.com/MetaMask/snaps/pull/1787))
@@ -59,7 +71,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
59
71
  - The version of the package no longer needs to match the version of all other
60
72
  MetaMask Snaps packages.
61
73
 
62
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.0.0...HEAD
74
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.2.0...HEAD
75
+ [3.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.1.0...@metamask/snaps-utils@3.2.0
76
+ [3.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.0.0...@metamask/snaps-utils@3.1.0
63
77
  [3.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@2.0.1...@metamask/snaps-utils@3.0.0
64
78
  [2.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@2.0.0...@metamask/snaps-utils@2.0.1
65
79
  [2.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@0.38.4-flask.1...@metamask/snaps-utils@2.0.0
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ AuxiliaryFileEncoding: function() {
13
+ return AuxiliaryFileEncoding;
14
+ },
15
+ encodeAuxiliaryFile: function() {
16
+ return encodeAuxiliaryFile;
17
+ }
18
+ });
19
+ const _utils = require("@metamask/utils");
20
+ const _base = require("@scure/base");
21
+ var AuxiliaryFileEncoding;
22
+ (function(AuxiliaryFileEncoding) {
23
+ AuxiliaryFileEncoding["Base64"] = 'base64';
24
+ AuxiliaryFileEncoding["Hex"] = 'hex';
25
+ AuxiliaryFileEncoding["Utf8"] = 'utf8';
26
+ })(AuxiliaryFileEncoding || (AuxiliaryFileEncoding = {}));
27
+ function encodeAuxiliaryFile(value, encoding) {
28
+ // Input is assumed to be the stored file in base64.
29
+ if (encoding === AuxiliaryFileEncoding.Base64) {
30
+ return value;
31
+ }
32
+ // TODO: Use @metamask/utils for this
33
+ const decoded = _base.base64.decode(value);
34
+ if (encoding === AuxiliaryFileEncoding.Utf8) {
35
+ return (0, _utils.bytesToString)(decoded);
36
+ }
37
+ return (0, _utils.bytesToHex)(decoded);
38
+ }
39
+
40
+ //# sourceMappingURL=auxiliary-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nexport enum AuxiliaryFileEncoding {\n Base64 = 'base64',\n Hex = 'hex',\n Utf8 = 'utf8',\n}\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["encodeAuxiliaryFile","AuxiliaryFileEncoding","Base64","Hex","Utf8","value","encoding","decoded","base64","decode","bytesToString","bytesToHex"],"mappings":";;;;;;;;;;;;;;IAgBgBA,mBAAmB;eAAnBA;;;uBAhB0B;sBACnB;IAEhB;UAAKC,qBAAqB;IAArBA,sBACVC,YAAS;IADCD,sBAEVE,SAAM;IAFIF,sBAGVG,UAAO;GAHGH,0BAAAA;AAaL,SAASD,oBACdK,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaL,sBAAsBC,MAAM,EAAE;QAC7C,OAAOG;IACT;IAEA,qCAAqC;IACrC,MAAME,UAAUC,YAAM,CAACC,MAAM,CAACJ;IAC9B,IAAIC,aAAaL,sBAAsBG,IAAI,EAAE;QAC3C,OAAOM,IAAAA,oBAAa,EAACH;IACvB;IAEA,OAAOI,IAAAA,iBAAU,EAACJ;AACpB"}
@@ -2,18 +2,368 @@
2
2
  Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
- Object.defineProperty(exports, "getErrorMessage", {
6
- enumerable: true,
7
- get: function() {
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ getErrorMessage: function() {
8
13
  return getErrorMessage;
14
+ },
15
+ getErrorStack: function() {
16
+ return getErrorStack;
17
+ },
18
+ getErrorCode: function() {
19
+ return getErrorCode;
20
+ },
21
+ getErrorData: function() {
22
+ return getErrorData;
23
+ },
24
+ SNAP_ERROR_WRAPPER_CODE: function() {
25
+ return SNAP_ERROR_WRAPPER_CODE;
26
+ },
27
+ SNAP_ERROR_WRAPPER_MESSAGE: function() {
28
+ return SNAP_ERROR_WRAPPER_MESSAGE;
29
+ },
30
+ SNAP_ERROR_CODE: function() {
31
+ return SNAP_ERROR_CODE;
32
+ },
33
+ SNAP_ERROR_MESSAGE: function() {
34
+ return SNAP_ERROR_MESSAGE;
35
+ },
36
+ WrappedSnapError: function() {
37
+ return WrappedSnapError;
38
+ },
39
+ SnapError: function() {
40
+ return SnapError;
41
+ },
42
+ isSnapError: function() {
43
+ return isSnapError;
44
+ },
45
+ isSerializedSnapError: function() {
46
+ return isSerializedSnapError;
47
+ },
48
+ isWrappedSnapError: function() {
49
+ return isWrappedSnapError;
50
+ },
51
+ unwrapError: function() {
52
+ return unwrapError;
9
53
  }
10
54
  });
55
+ const _rpcerrors = require("@metamask/rpc-errors");
11
56
  const _utils = require("@metamask/utils");
57
+ function _check_private_redeclaration(obj, privateCollection) {
58
+ if (privateCollection.has(obj)) {
59
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
60
+ }
61
+ }
62
+ function _class_apply_descriptor_get(receiver, descriptor) {
63
+ if (descriptor.get) {
64
+ return descriptor.get.call(receiver);
65
+ }
66
+ return descriptor.value;
67
+ }
68
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
69
+ if (descriptor.set) {
70
+ descriptor.set.call(receiver, value);
71
+ } else {
72
+ if (!descriptor.writable) {
73
+ throw new TypeError("attempted to set read only private field");
74
+ }
75
+ descriptor.value = value;
76
+ }
77
+ }
78
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
79
+ if (!privateMap.has(receiver)) {
80
+ throw new TypeError("attempted to " + action + " private field on non-instance");
81
+ }
82
+ return privateMap.get(receiver);
83
+ }
84
+ function _class_private_field_get(receiver, privateMap) {
85
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
86
+ return _class_apply_descriptor_get(receiver, descriptor);
87
+ }
88
+ function _class_private_field_init(obj, privateMap, value) {
89
+ _check_private_redeclaration(obj, privateMap);
90
+ privateMap.set(obj, value);
91
+ }
92
+ function _class_private_field_set(receiver, privateMap, value) {
93
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
94
+ _class_apply_descriptor_set(receiver, descriptor, value);
95
+ return value;
96
+ }
12
97
  function getErrorMessage(error) {
13
98
  if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'message') && typeof error.message === 'string') {
14
99
  return error.message;
15
100
  }
16
101
  return String(error);
17
102
  }
103
+ function getErrorStack(error) {
104
+ if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'stack') && typeof error.stack === 'string') {
105
+ return error.stack;
106
+ }
107
+ return undefined;
108
+ }
109
+ function getErrorCode(error) {
110
+ if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'code') && typeof error.code === 'number' && Number.isInteger(error.code)) {
111
+ return error.code;
112
+ }
113
+ return _rpcerrors.errorCodes.rpc.internal;
114
+ }
115
+ function getErrorData(error) {
116
+ if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'data') && typeof error.data === 'object' && error.data !== null && (0, _utils.isValidJson)(error.data) && !Array.isArray(error.data)) {
117
+ return error.data;
118
+ }
119
+ return {};
120
+ }
121
+ const SNAP_ERROR_WRAPPER_CODE = -31001;
122
+ const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';
123
+ const SNAP_ERROR_CODE = -31002;
124
+ const SNAP_ERROR_MESSAGE = 'Snap Error';
125
+ var _error = /*#__PURE__*/ new WeakMap(), _message = /*#__PURE__*/ new WeakMap(), _stack = /*#__PURE__*/ new WeakMap();
126
+ class WrappedSnapError extends Error {
127
+ /**
128
+ * The error name.
129
+ *
130
+ * @returns The error name.
131
+ */ get name() {
132
+ return 'WrappedSnapError';
133
+ }
134
+ /**
135
+ * The error message.
136
+ *
137
+ * @returns The error message.
138
+ */ get message() {
139
+ return _class_private_field_get(this, _message);
140
+ }
141
+ /**
142
+ * The error stack.
143
+ *
144
+ * @returns The error stack.
145
+ */ get stack() {
146
+ return _class_private_field_get(this, _stack);
147
+ }
148
+ /**
149
+ * Convert the error to a JSON object.
150
+ *
151
+ * @returns The JSON object.
152
+ */ toJSON() {
153
+ const cause = isSnapError(_class_private_field_get(this, _error)) ? _class_private_field_get(this, _error).serialize() : (0, _rpcerrors.serializeCause)(_class_private_field_get(this, _error));
154
+ return {
155
+ code: SNAP_ERROR_WRAPPER_CODE,
156
+ message: SNAP_ERROR_WRAPPER_MESSAGE,
157
+ data: {
158
+ cause
159
+ }
160
+ };
161
+ }
162
+ /**
163
+ * Serialize the error to a JSON object. This is called by
164
+ * `@metamask/rpc-errors` when serializing the error.
165
+ *
166
+ * @returns The JSON object.
167
+ */ serialize() {
168
+ return this.toJSON();
169
+ }
170
+ /**
171
+ * Create a new `WrappedSnapError`.
172
+ *
173
+ * @param error - The error to create the `WrappedSnapError` from.
174
+ */ constructor(error){
175
+ const message = getErrorMessage(error);
176
+ super(message);
177
+ _class_private_field_init(this, _error, {
178
+ writable: true,
179
+ value: void 0
180
+ });
181
+ _class_private_field_init(this, _message, {
182
+ writable: true,
183
+ value: void 0
184
+ });
185
+ _class_private_field_init(this, _stack, {
186
+ writable: true,
187
+ value: void 0
188
+ });
189
+ _class_private_field_set(this, _error, error);
190
+ _class_private_field_set(this, _message, message);
191
+ _class_private_field_set(this, _stack, getErrorStack(error));
192
+ }
193
+ }
194
+ var _code = /*#__PURE__*/ new WeakMap(), _message1 = /*#__PURE__*/ new WeakMap(), _data = /*#__PURE__*/ new WeakMap(), _stack1 = /*#__PURE__*/ new WeakMap();
195
+ class SnapError extends Error {
196
+ /**
197
+ * The error name.
198
+ *
199
+ * @returns The error name.
200
+ */ get name() {
201
+ return 'SnapError';
202
+ }
203
+ /**
204
+ * The error code.
205
+ *
206
+ * @returns The error code.
207
+ */ get code() {
208
+ return _class_private_field_get(this, _code);
209
+ }
210
+ /**
211
+ * The error message.
212
+ *
213
+ * @returns The error message.
214
+ */ get message() {
215
+ return _class_private_field_get(this, _message1);
216
+ }
217
+ /**
218
+ * Additional data for the error.
219
+ *
220
+ * @returns Additional data for the error.
221
+ */ get data() {
222
+ return _class_private_field_get(this, _data);
223
+ }
224
+ /**
225
+ * The error stack.
226
+ *
227
+ * @returns The error stack.
228
+ */ get stack() {
229
+ return _class_private_field_get(this, _stack1);
230
+ }
231
+ /**
232
+ * Convert the error to a JSON object.
233
+ *
234
+ * @returns The JSON object.
235
+ */ toJSON() {
236
+ return {
237
+ code: SNAP_ERROR_CODE,
238
+ message: SNAP_ERROR_MESSAGE,
239
+ data: {
240
+ cause: {
241
+ code: this.code,
242
+ message: this.message,
243
+ stack: this.stack,
244
+ data: this.data
245
+ }
246
+ }
247
+ };
248
+ }
249
+ /**
250
+ * Serialize the error to a JSON object. This is called by
251
+ * `@metamask/rpc-errors` when serializing the error.
252
+ *
253
+ * @returns The JSON object.
254
+ */ serialize() {
255
+ return this.toJSON();
256
+ }
257
+ /**
258
+ * Create a new `SnapError`.
259
+ *
260
+ * @param error - The error to create the `SnapError` from. If this is a
261
+ * `string`, it will be used as the error message. If this is an `Error`, its
262
+ * `message` property will be used as the error message. If this is a
263
+ * `JsonRpcError`, its `message` property will be used as the error message
264
+ * and its `code` property will be used as the error code. Otherwise, the
265
+ * error will be converted to a string and used as the error message.
266
+ * @param data - Additional data to include in the error. This will be merged
267
+ * with the error data, if any.
268
+ */ constructor(error, data = {}){
269
+ const message = getErrorMessage(error);
270
+ super(message);
271
+ _class_private_field_init(this, _code, {
272
+ writable: true,
273
+ value: void 0
274
+ });
275
+ _class_private_field_init(this, _message1, {
276
+ writable: true,
277
+ value: void 0
278
+ });
279
+ _class_private_field_init(this, _data, {
280
+ writable: true,
281
+ value: void 0
282
+ });
283
+ _class_private_field_init(this, _stack1, {
284
+ writable: true,
285
+ value: void 0
286
+ });
287
+ _class_private_field_set(this, _message1, message);
288
+ _class_private_field_set(this, _code, getErrorCode(error));
289
+ _class_private_field_set(this, _data, {
290
+ ...getErrorData(error),
291
+ ...data
292
+ });
293
+ _class_private_field_set(this, _stack1, super.stack);
294
+ }
295
+ }
296
+ function isSnapError(error) {
297
+ if ((0, _utils.isObject)(error) && 'serialize' in error && typeof error.serialize === 'function') {
298
+ const serialized = error.serialize();
299
+ return (0, _utils.isJsonRpcError)(serialized) && isSerializedSnapError(serialized);
300
+ }
301
+ return false;
302
+ }
303
+ function isSerializedSnapError(error) {
304
+ return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;
305
+ }
306
+ function isWrappedSnapError(error) {
307
+ return (0, _utils.isJsonRpcError)(error) && error.code === SNAP_ERROR_WRAPPER_CODE && error.message === SNAP_ERROR_WRAPPER_MESSAGE;
308
+ }
309
+ /**
310
+ * Get a JSON-RPC error with the given code, message, stack, and data.
311
+ *
312
+ * @param code - The error code.
313
+ * @param message - The error message.
314
+ * @param stack - The error stack.
315
+ * @param data - Additional data for the error.
316
+ * @returns The JSON-RPC error.
317
+ */ function getJsonRpcError(code, message, stack, data) {
318
+ const error = new _rpcerrors.JsonRpcError(code, message, data);
319
+ error.stack = stack;
320
+ return error;
321
+ }
322
+ function unwrapError(error) {
323
+ // This logic is a bit complicated, but it's necessary to handle all the
324
+ // different types of errors that can be thrown by a Snap.
325
+ // If the error is a wrapped Snap error, unwrap it.
326
+ if (isWrappedSnapError(error)) {
327
+ // The wrapped error can be a JSON-RPC error, or an unknown error. If it's
328
+ // a JSON-RPC error, we can unwrap it further.
329
+ if ((0, _utils.isJsonRpcError)(error.data.cause)) {
330
+ // If the JSON-RPC error is a wrapped Snap error, unwrap it further.
331
+ if (isSerializedSnapError(error.data.cause)) {
332
+ const { code, message, stack, data } = error.data.cause.data.cause;
333
+ return [
334
+ getJsonRpcError(code, message, stack, data),
335
+ true
336
+ ];
337
+ }
338
+ // Otherwise, we use the original JSON-RPC error.
339
+ const { code, message, stack, data } = error.data.cause;
340
+ return [
341
+ getJsonRpcError(code, message, stack, data),
342
+ false
343
+ ];
344
+ }
345
+ // Otherwise, we throw an internal error with the wrapped error as the
346
+ // message.
347
+ return [
348
+ getJsonRpcError(_rpcerrors.errorCodes.rpc.internal, getErrorMessage(error.data.cause), getErrorStack(error.data.cause)),
349
+ false
350
+ ];
351
+ }
352
+ // The error can be a non-wrapped JSON-RPC error, in which case we can just
353
+ // re-throw it with the same code, message, and data.
354
+ if ((0, _utils.isJsonRpcError)(error)) {
355
+ const { code, message, stack, data } = error;
356
+ return [
357
+ getJsonRpcError(code, message, stack, data),
358
+ false
359
+ ];
360
+ }
361
+ // If the error is not a wrapped error, we don't know how to handle it, so we
362
+ // throw an internal error with the error as the message.
363
+ return [
364
+ getJsonRpcError(_rpcerrors.errorCodes.rpc.internal, getErrorMessage(error), getErrorStack(error)),
365
+ false
366
+ ];
367
+ }
18
368
 
19
369
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import { hasProperty, isObject } from '@metamask/utils';\n\n/**\n * Get the error message from an unknown error type.\n *\n * - If the error is an object with a `message` property, return the message.\n * - Otherwise, return the error converted to a string.\n *\n * @param error - The error to get the message from.\n * @returns The error message.\n */\nexport function getErrorMessage(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return String(error);\n}\n"],"names":["getErrorMessage","error","isObject","hasProperty","message","String"],"mappings":";;;;+BAWgBA;;;eAAAA;;;uBAXsB;AAW/B,SAASA,gBAAgBC,KAAc;IAC5C,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,cACnB,OAAOA,MAAMG,OAAO,KAAK,UACzB;QACA,OAAOH,MAAMG,OAAO;IACtB;IAEA,OAAOC,OAAOJ;AAChB"}
1
+ {"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcError } from '@metamask/utils';\nimport {\n hasProperty,\n isJsonRpcError,\n isObject,\n isValidJson,\n} from '@metamask/utils';\n\n/**\n * Get the error message from an unknown error type.\n *\n * - If the error is an object with a `message` property, return the message.\n * - Otherwise, return the error converted to a string.\n *\n * @param error - The error to get the message from.\n * @returns The error message.\n */\nexport function getErrorMessage(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return String(error);\n}\n\n/**\n * Get the error stack from an unknown error type.\n *\n * @param error - The error to get the stack from.\n * @returns The error stack, or undefined if the error does not have a valid\n * stack.\n */\nexport function getErrorStack(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'stack') &&\n typeof error.stack === 'string'\n ) {\n return error.stack;\n }\n\n return undefined;\n}\n\n/**\n * Get the error code from an unknown error type.\n *\n * @param error - The error to get the code from.\n * @returns The error code, or `-32603` if the error does not have a valid code.\n */\nexport function getErrorCode(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'code') &&\n typeof error.code === 'number' &&\n Number.isInteger(error.code)\n ) {\n return error.code;\n }\n\n return errorCodes.rpc.internal;\n}\n\n/**\n * Get the error data from an unknown error type.\n *\n * @param error - The error to get the data from.\n * @returns The error data, or an empty object if the error does not have valid\n * data.\n */\nexport function getErrorData(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'data') &&\n typeof error.data === 'object' &&\n error.data !== null &&\n isValidJson(error.data) &&\n !Array.isArray(error.data)\n ) {\n return error.data;\n }\n\n return {};\n}\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport const SNAP_ERROR_CODE = -31002;\nexport const SNAP_ERROR_MESSAGE = 'Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport type SerializedSnapError = {\n code: typeof SNAP_ERROR_CODE;\n message: typeof SNAP_ERROR_MESSAGE;\n data: {\n cause: JsonRpcError & {\n data: Record<string, Json>;\n };\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error);\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * A generic error which can be thrown by a Snap, without it causing the Snap to\n * crash.\n */\nexport class SnapError extends Error {\n readonly #code: number;\n\n readonly #message: string;\n\n readonly #data: Record<string, Json>;\n\n readonly #stack?: string;\n\n /**\n * Create a new `SnapError`.\n *\n * @param error - The error to create the `SnapError` from. If this is a\n * `string`, it will be used as the error message. If this is an `Error`, its\n * `message` property will be used as the error message. If this is a\n * `JsonRpcError`, its `message` property will be used as the error message\n * and its `code` property will be used as the error code. Otherwise, the\n * error will be converted to a string and used as the error message.\n * @param data - Additional data to include in the error. This will be merged\n * with the error data, if any.\n */\n constructor(\n error: string | Error | JsonRpcError,\n data: Record<string, Json> = {},\n ) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#message = message;\n this.#code = getErrorCode(error);\n this.#data = { ...getErrorData(error), ...data };\n this.#stack = super.stack;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'SnapError';\n }\n\n /**\n * The error code.\n *\n * @returns The error code.\n */\n get code() {\n return this.#code;\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * Additional data for the error.\n *\n * @returns Additional data for the error.\n */\n get data() {\n return this.#data;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapError {\n return {\n code: SNAP_ERROR_CODE,\n message: SNAP_ERROR_MESSAGE,\n data: {\n cause: {\n code: this.code,\n message: this.message,\n stack: this.stack,\n data: this.data,\n },\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if an object is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSnapError(error: unknown): error is SnapError {\n if (\n isObject(error) &&\n 'serialize' in error &&\n typeof error.serialize === 'function'\n ) {\n const serialized = error.serialize();\n return isJsonRpcError(serialized) && isSerializedSnapError(serialized);\n }\n\n return false;\n}\n\n/**\n * Check if a JSON-RPC error is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSerializedSnapError(\n error: JsonRpcError,\n): error is SerializedSnapError {\n return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n"],"names":["getErrorMessage","getErrorStack","getErrorCode","getErrorData","SNAP_ERROR_WRAPPER_CODE","SNAP_ERROR_WRAPPER_MESSAGE","SNAP_ERROR_CODE","SNAP_ERROR_MESSAGE","WrappedSnapError","SnapError","isSnapError","isSerializedSnapError","isWrappedSnapError","unwrapError","error","isObject","hasProperty","message","String","stack","undefined","code","Number","isInteger","errorCodes","rpc","internal","data","isValidJson","Array","isArray","Error","name","toJSON","cause","serialize","serializeCause","constructor","serialized","isJsonRpcError","getJsonRpcError","RpcError"],"mappings":";;;;;;;;;;;IAuBgBA,eAAe;eAAfA;;IAmBAC,aAAa;eAAbA;;IAkBAC,YAAY;eAAZA;;IAoBAC,YAAY;eAAZA;;IAeHC,uBAAuB;eAAvBA;;IACAC,0BAA0B;eAA1BA;;IAEAC,eAAe;eAAfA;;IACAC,kBAAkB;eAAlBA;;IAoBAC,gBAAgB;eAAhBA;;IAkFAC,SAAS;eAATA;;IAoHGC,WAAW;eAAXA;;IAmBAC,qBAAqB;eAArBA;;IAYAC,kBAAkB;eAAlBA;;IAwCAC,WAAW;eAAXA;;;2BAhYT;uBAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAASb,gBAAgBc,KAAc;IAC5C,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,cACnB,OAAOA,MAAMG,OAAO,KAAK,UACzB;QACA,OAAOH,MAAMG,OAAO;IACtB;IAEA,OAAOC,OAAOJ;AAChB;AASO,SAASb,cAAca,KAAc;IAC1C,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,YACnB,OAAOA,MAAMK,KAAK,KAAK,UACvB;QACA,OAAOL,MAAMK,KAAK;IACpB;IAEA,OAAOC;AACT;AAQO,SAASlB,aAAaY,KAAc;IACzC,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,WACnB,OAAOA,MAAMO,IAAI,KAAK,YACtBC,OAAOC,SAAS,CAACT,MAAMO,IAAI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,GAAG,CAACC,QAAQ,EACvB1B,gBAAgBc,MAAMa,IAAI,CAACO,KAAK,GAChCjC,cAAca,MAAMa,IAAI,CAACO,KAAK;YAEhC;SACD;IACH;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,IAAIK,IAAAA,qBAAc,EAACzB,QAAQ;QACzB,MAAM,EAAEO,IAAI,EAAEJ,OAAO,EAAEE,KAAK,EAAEQ,IAAI,EAAE,GAAGb;QACvC,OAAO;YAAC0B,gBAAgBnB,MAAMJ,SAASE,OAAOQ;YAAO;SAAM;IAC7D;IAEA,6EAA6E;IAC7E,yDAAyD;IACzD,OAAO;QACLa,gBACEhB,qBAAU,CAACC,GAAG,CAACC,QAAQ,EACvB1B,gBAAgBc,QAChBb,cAAca;QAEhB;KACD;AACH"}
@@ -5,8 +5,8 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  require("ses/lockdown");
7
7
  const _fs = require("fs");
8
+ const _handlertypes = require("./handler-types");
8
9
  const _mock = require("./mock");
9
- const _types = require("./types");
10
10
  lockdown({
11
11
  consoleTaming: 'unsafe',
12
12
  errorTaming: 'unsafe',
@@ -41,7 +41,7 @@ new Compartment({
41
41
  module: snapModule,
42
42
  exports: snapModule.exports
43
43
  }).evaluate((0, _fs.readFileSync)(snapFilePath, 'utf8'));
44
- const invalidExports = Object.keys(snapModule.exports).filter((snapExport)=>!_types.SNAP_EXPORT_NAMES.includes(snapExport));
44
+ const invalidExports = Object.keys(snapModule.exports).filter((snapExport)=>!_handlertypes.SNAP_EXPORT_NAMES.includes(snapExport));
45
45
  if (invalidExports.length > 0) {
46
46
  // eslint-disable-next-line no-console
47
47
  console.warn(`Invalid snap exports detected:\n${invalidExports.join('\n')}`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handlers';\nimport { generateMockEndowments } from './mock';\nimport { SNAP_EXPORT_NAMES } from './types';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","generateMockEndowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;sBAGU;uBACL;AAIlCA,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA;;;;;;CAMC,GACD,SAASC;IACP,MAAMC,aAAaC,IAAAA,4BAAsB;IACzC,OAAO;QACL,GAAGD,UAAU;QACbE,QAAQF;QACRG,MAAMH;IACR;AACF;AAEA,MAAMI,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGV,mBAAmB;IACtBW,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACC,IAAAA,gBAAY,EAACR,cAAc;AAEvC,MAAMS,iBAAiBC,OAAOC,IAAI,CAACR,WAAWC,OAAO,EAAEQ,MAAM,CAC3D,CAACC,aAAe,CAACC,wBAAiB,CAACC,QAAQ,CAACF;AAG9C,IAAIJ,eAAeO,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAET,eAAeU,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMnB,QAAQoB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
1
+ {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","generateMockEndowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;8BAGK;sBACK;AAIvCA,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA;;;;;;CAMC,GACD,SAASC;IACP,MAAMC,aAAaC,IAAAA,4BAAsB;IACzC,OAAO;QACL,GAAGD,UAAU;QACbE,QAAQF;QACRG,MAAMH;IACR;AACF;AAEA,MAAMI,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGV,mBAAmB;IACtBW,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACC,IAAAA,gBAAY,EAACR,cAAc;AAEvC,MAAMS,iBAAiBC,OAAOC,IAAI,CAACR,WAAWC,OAAO,EAAEQ,MAAM,CAC3D,CAACC,aAAe,CAACC,+BAAiB,CAACC,QAAQ,CAACF;AAG9C,IAAIJ,eAAeO,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAET,eAAeU,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMnB,QAAQoB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ HandlerType: function() {
13
+ return HandlerType;
14
+ },
15
+ SNAP_EXPORT_NAMES: function() {
16
+ return SNAP_EXPORT_NAMES;
17
+ }
18
+ });
19
+ var HandlerType;
20
+ (function(HandlerType) {
21
+ HandlerType["OnRpcRequest"] = 'onRpcRequest';
22
+ HandlerType["OnTransaction"] = 'onTransaction';
23
+ HandlerType["OnCronjob"] = 'onCronjob';
24
+ HandlerType["OnInstall"] = 'onInstall';
25
+ HandlerType["OnUpdate"] = 'onUpdate';
26
+ HandlerType["OnNameLookup"] = 'onNameLookup';
27
+ HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
28
+ })(HandlerType || (HandlerType = {}));
29
+ const SNAP_EXPORT_NAMES = Object.values(HandlerType);
30
+
31
+ //# sourceMappingURL=handler-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["SNAP_EXPORT_NAMES","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","Object","values"],"mappings":";;;;;;;;;;;;;;IAkCaA,iBAAiB;eAAjBA;;;IAlCN;UAAKC,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;IALDL,YAMVM,kBAAe;IANLN,YAOVO,sBAAmB;GAPTP,gBAAAA;AAkCL,MAAMD,oBAAoBS,OAAOC,MAAM,CAACT"}
@@ -9,71 +9,64 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- HandlerType: function() {
13
- return HandlerType;
14
- },
15
12
  SeverityLevel: function() {
16
13
  return SeverityLevel;
17
14
  },
18
15
  SNAP_EXPORTS: function() {
19
16
  return SNAP_EXPORTS;
17
+ },
18
+ OnTransactionResponseStruct: function() {
19
+ return OnTransactionResponseStruct;
20
20
  }
21
21
  });
22
- var HandlerType;
23
- (function(HandlerType) {
24
- HandlerType["OnRpcRequest"] = 'onRpcRequest';
25
- HandlerType["OnTransaction"] = 'onTransaction';
26
- HandlerType["OnCronjob"] = 'onCronjob';
27
- HandlerType["OnInstall"] = 'onInstall';
28
- HandlerType["OnUpdate"] = 'onUpdate';
29
- HandlerType["OnNameLookup"] = 'onNameLookup';
30
- HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
31
- })(HandlerType || (HandlerType = {}));
22
+ const _snapsui = require("@metamask/snaps-ui");
23
+ const _superstruct = require("superstruct");
24
+ const _handlertypes = require("./handler-types");
32
25
  const SNAP_EXPORTS = {
33
- [HandlerType.OnRpcRequest]: {
34
- type: HandlerType.OnRpcRequest,
26
+ [_handlertypes.HandlerType.OnRpcRequest]: {
27
+ type: _handlertypes.HandlerType.OnRpcRequest,
35
28
  required: true,
36
29
  validator: (snapExport)=>{
37
30
  return typeof snapExport === 'function';
38
31
  }
39
32
  },
40
- [HandlerType.OnTransaction]: {
41
- type: HandlerType.OnTransaction,
33
+ [_handlertypes.HandlerType.OnTransaction]: {
34
+ type: _handlertypes.HandlerType.OnTransaction,
42
35
  required: true,
43
36
  validator: (snapExport)=>{
44
37
  return typeof snapExport === 'function';
45
38
  }
46
39
  },
47
- [HandlerType.OnCronjob]: {
48
- type: HandlerType.OnCronjob,
40
+ [_handlertypes.HandlerType.OnCronjob]: {
41
+ type: _handlertypes.HandlerType.OnCronjob,
49
42
  required: true,
50
43
  validator: (snapExport)=>{
51
44
  return typeof snapExport === 'function';
52
45
  }
53
46
  },
54
- [HandlerType.OnNameLookup]: {
55
- type: HandlerType.OnNameLookup,
47
+ [_handlertypes.HandlerType.OnNameLookup]: {
48
+ type: _handlertypes.HandlerType.OnNameLookup,
56
49
  required: true,
57
50
  validator: (snapExport)=>{
58
51
  return typeof snapExport === 'function';
59
52
  }
60
53
  },
61
- [HandlerType.OnInstall]: {
62
- type: HandlerType.OnInstall,
54
+ [_handlertypes.HandlerType.OnInstall]: {
55
+ type: _handlertypes.HandlerType.OnInstall,
63
56
  required: false,
64
57
  validator: (snapExport)=>{
65
58
  return typeof snapExport === 'function';
66
59
  }
67
60
  },
68
- [HandlerType.OnUpdate]: {
69
- type: HandlerType.OnUpdate,
61
+ [_handlertypes.HandlerType.OnUpdate]: {
62
+ type: _handlertypes.HandlerType.OnUpdate,
70
63
  required: false,
71
64
  validator: (snapExport)=>{
72
65
  return typeof snapExport === 'function';
73
66
  }
74
67
  },
75
- [HandlerType.OnKeyringRequest]: {
76
- type: HandlerType.OnKeyringRequest,
68
+ [_handlertypes.HandlerType.OnKeyringRequest]: {
69
+ type: _handlertypes.HandlerType.OnKeyringRequest,
77
70
  required: true,
78
71
  validator: (snapExport)=>{
79
72
  return typeof snapExport === 'function';
@@ -84,5 +77,9 @@ var SeverityLevel;
84
77
  (function(SeverityLevel) {
85
78
  SeverityLevel["Critical"] = 'critical';
86
79
  })(SeverityLevel || (SeverityLevel = {}));
80
+ const OnTransactionResponseStruct = (0, _superstruct.object)({
81
+ content: _snapsui.ComponentStruct,
82
+ severity: (0, _superstruct.optional)((0, _superstruct.literal)(SeverityLevel.Critical))
83
+ });
87
84
 
88
85
  //# sourceMappingURL=handlers.js.map