@metamask/snaps-utils 0.34.0-flask.1 → 0.35.0-flask.1

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 (249) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/cjs/array.js +23 -0
  3. package/dist/cjs/array.js.map +1 -0
  4. package/dist/cjs/caveats.js +33 -0
  5. package/dist/cjs/caveats.js.map +1 -0
  6. package/dist/cjs/checksum.js +38 -0
  7. package/dist/cjs/checksum.js.map +1 -0
  8. package/dist/cjs/cronjob.js +84 -0
  9. package/dist/cjs/cronjob.js.map +1 -0
  10. package/dist/cjs/deep-clone.js +22 -0
  11. package/dist/cjs/deep-clone.js.map +1 -0
  12. package/dist/cjs/default-endowments.js +49 -0
  13. package/dist/cjs/default-endowments.js.map +1 -0
  14. package/dist/cjs/entropy.js +23 -0
  15. package/dist/cjs/entropy.js.map +1 -0
  16. package/dist/cjs/enum.js +16 -0
  17. package/dist/cjs/enum.js.map +1 -0
  18. package/dist/{eval-worker.js → cjs/eval-worker.js} +22 -21
  19. package/dist/cjs/eval-worker.js.map +1 -0
  20. package/dist/cjs/eval.js +29 -0
  21. package/dist/cjs/eval.js.map +1 -0
  22. package/dist/cjs/fs.js +126 -0
  23. package/dist/cjs/fs.js.map +1 -0
  24. package/dist/cjs/handlers.js +6 -0
  25. package/dist/cjs/handlers.js.map +1 -0
  26. package/dist/cjs/icon.js +37 -0
  27. package/dist/cjs/icon.js.map +1 -0
  28. package/dist/{iframe.js → cjs/iframe.js} +14 -9
  29. package/dist/cjs/iframe.js.map +1 -0
  30. package/dist/cjs/index.browser.js +40 -0
  31. package/dist/cjs/index.browser.js.map +1 -0
  32. package/dist/cjs/index.executionenv.js +24 -0
  33. package/dist/cjs/index.executionenv.js.map +1 -0
  34. package/dist/cjs/index.js +45 -0
  35. package/dist/cjs/index.js.map +1 -0
  36. package/dist/cjs/json-rpc.js +46 -0
  37. package/dist/cjs/json-rpc.js.map +1 -0
  38. package/dist/cjs/json.js +16 -0
  39. package/dist/cjs/json.js.map +1 -0
  40. package/dist/cjs/logging.js +40 -0
  41. package/dist/cjs/logging.js.map +1 -0
  42. package/dist/cjs/manifest/index.browser.js +20 -0
  43. package/dist/cjs/manifest/index.browser.js.map +1 -0
  44. package/dist/cjs/manifest/index.js +21 -0
  45. package/dist/cjs/manifest/index.js.map +1 -0
  46. package/dist/cjs/manifest/manifest.js +239 -0
  47. package/dist/cjs/manifest/manifest.js.map +1 -0
  48. package/dist/cjs/manifest/validation.js +183 -0
  49. package/dist/cjs/manifest/validation.js.map +1 -0
  50. package/dist/cjs/mock.js +128 -0
  51. package/dist/cjs/mock.js.map +1 -0
  52. package/dist/cjs/namespace.js +124 -0
  53. package/dist/cjs/namespace.js.map +1 -0
  54. package/dist/cjs/npm.js +81 -0
  55. package/dist/cjs/npm.js.map +1 -0
  56. package/dist/cjs/path.js +21 -0
  57. package/dist/cjs/path.js.map +1 -0
  58. package/dist/cjs/post-process.js +328 -0
  59. package/dist/cjs/post-process.js.map +1 -0
  60. package/dist/cjs/snaps.js +230 -0
  61. package/dist/cjs/snaps.js.map +1 -0
  62. package/dist/cjs/types.js +117 -0
  63. package/dist/cjs/types.js.map +1 -0
  64. package/dist/cjs/validation.js +22 -0
  65. package/dist/cjs/validation.js.map +1 -0
  66. package/dist/cjs/versions.js +47 -0
  67. package/dist/cjs/versions.js.map +1 -0
  68. package/dist/cjs/virtual-file/VirtualFile.js +85 -0
  69. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -0
  70. package/dist/cjs/virtual-file/index.browser.js +20 -0
  71. package/dist/cjs/virtual-file/index.browser.js.map +1 -0
  72. package/dist/cjs/virtual-file/index.js +21 -0
  73. package/dist/cjs/virtual-file/index.js.map +1 -0
  74. package/dist/cjs/virtual-file/toVirtualFile.js +33 -0
  75. package/dist/cjs/virtual-file/toVirtualFile.js.map +1 -0
  76. package/dist/esm/array.js +13 -0
  77. package/dist/esm/array.js.map +1 -0
  78. package/dist/esm/caveats.js +23 -0
  79. package/dist/esm/caveats.js.map +1 -0
  80. package/dist/esm/checksum.js +36 -0
  81. package/dist/esm/checksum.js.map +1 -0
  82. package/dist/esm/cronjob.js +66 -0
  83. package/dist/esm/cronjob.js.map +1 -0
  84. package/dist/esm/deep-clone.js +7 -0
  85. package/dist/esm/deep-clone.js.map +1 -0
  86. package/dist/{default-endowments.js → esm/default-endowments.js} +3 -6
  87. package/dist/esm/default-endowments.js.map +1 -0
  88. package/dist/esm/entropy.js +6 -0
  89. package/dist/esm/entropy.js.map +1 -0
  90. package/dist/esm/enum.js +12 -0
  91. package/dist/esm/enum.js.map +1 -0
  92. package/dist/esm/eval-worker.js +47 -0
  93. package/dist/esm/eval-worker.js.map +1 -0
  94. package/dist/esm/eval.js +25 -0
  95. package/dist/esm/eval.js.map +1 -0
  96. package/dist/{fs.js → esm/fs.js} +33 -55
  97. package/dist/esm/fs.js.map +1 -0
  98. package/dist/esm/handlers.js +3 -0
  99. package/dist/esm/handlers.js.map +1 -0
  100. package/dist/esm/icon.js +11 -0
  101. package/dist/esm/icon.js.map +1 -0
  102. package/dist/esm/iframe.js +49 -0
  103. package/dist/esm/iframe.js.map +1 -0
  104. package/dist/esm/index.browser.js +23 -0
  105. package/dist/esm/index.browser.js.map +1 -0
  106. package/dist/esm/index.executionenv.js +7 -0
  107. package/dist/esm/index.executionenv.js.map +1 -0
  108. package/dist/esm/index.js +28 -0
  109. package/dist/esm/index.js.map +1 -0
  110. package/dist/esm/json-rpc.js +39 -0
  111. package/dist/esm/json-rpc.js.map +1 -0
  112. package/dist/esm/json.js +17 -0
  113. package/dist/esm/json.js.map +1 -0
  114. package/dist/{logging.js → esm/logging.js} +6 -14
  115. package/dist/esm/logging.js.map +1 -0
  116. package/dist/esm/manifest/index.browser.js +3 -0
  117. package/dist/esm/manifest/index.browser.js.map +1 -0
  118. package/dist/esm/manifest/index.js +4 -0
  119. package/dist/esm/manifest/index.js.map +1 -0
  120. package/dist/{manifest → esm/manifest}/manifest.js +91 -107
  121. package/dist/esm/manifest/manifest.js.map +1 -0
  122. package/dist/esm/manifest/validation.js +152 -0
  123. package/dist/esm/manifest/validation.js.map +1 -0
  124. package/dist/{mock.js → esm/mock.js} +40 -42
  125. package/dist/esm/mock.js.map +1 -0
  126. package/dist/esm/namespace.js +110 -0
  127. package/dist/esm/namespace.js.map +1 -0
  128. package/dist/{npm.js → esm/npm.js} +23 -30
  129. package/dist/esm/npm.js.map +1 -0
  130. package/dist/esm/path.js +17 -0
  131. package/dist/esm/path.js.map +1 -0
  132. package/dist/{post-process.js → esm/post-process.js} +110 -99
  133. package/dist/esm/post-process.js.map +1 -0
  134. package/dist/esm/snaps.js +215 -0
  135. package/dist/esm/snaps.js.map +1 -0
  136. package/dist/esm/types.js +85 -0
  137. package/dist/esm/types.js.map +1 -0
  138. package/dist/esm/validation.js +17 -0
  139. package/dist/esm/validation.js.map +1 -0
  140. package/dist/{versions.js → esm/versions.js} +15 -18
  141. package/dist/esm/versions.js.map +1 -0
  142. package/dist/{virtual-file → esm/virtual-file}/VirtualFile.js +47 -33
  143. package/dist/esm/virtual-file/VirtualFile.js.map +1 -0
  144. package/dist/esm/virtual-file/index.browser.js +3 -0
  145. package/dist/esm/virtual-file/index.browser.js.map +1 -0
  146. package/dist/esm/virtual-file/index.js +4 -0
  147. package/dist/esm/virtual-file/index.js.map +1 -0
  148. package/dist/esm/virtual-file/toVirtualFile.js +26 -0
  149. package/dist/esm/virtual-file/toVirtualFile.js.map +1 -0
  150. package/dist/types/array.d.ts +10 -0
  151. package/dist/{caveats.d.ts → types/caveats.d.ts} +0 -4
  152. package/dist/types/enum.d.ts +30 -0
  153. package/dist/{handlers.d.ts → types/handlers.d.ts} +1 -38
  154. package/dist/{index.browser.d.ts → types/index.browser.d.ts} +3 -1
  155. package/dist/{index.d.ts → types/index.d.ts} +3 -1
  156. package/dist/types/index.executionenv.d.ts +4 -0
  157. package/dist/types/json.d.ts +13 -0
  158. package/dist/{manifest → types/manifest}/validation.d.ts +6 -69
  159. package/dist/types/namespace.d.ts +124 -0
  160. package/dist/{types.d.ts → types/types.d.ts} +2 -5
  161. package/package.json +52 -25
  162. package/dist/caveats.js +0 -35
  163. package/dist/caveats.js.map +0 -1
  164. package/dist/checksum.js +0 -42
  165. package/dist/checksum.js.map +0 -1
  166. package/dist/cronjob.js +0 -71
  167. package/dist/cronjob.js.map +0 -1
  168. package/dist/deep-clone.js +0 -9
  169. package/dist/deep-clone.js.map +0 -1
  170. package/dist/default-endowments.js.map +0 -1
  171. package/dist/entropy.js +0 -8
  172. package/dist/entropy.js.map +0 -1
  173. package/dist/eval-worker.js.map +0 -1
  174. package/dist/eval.js +0 -27
  175. package/dist/eval.js.map +0 -1
  176. package/dist/fs.js.map +0 -1
  177. package/dist/handlers.js +0 -3
  178. package/dist/handlers.js.map +0 -1
  179. package/dist/icon.js +0 -17
  180. package/dist/icon.js.map +0 -1
  181. package/dist/iframe.js.map +0 -1
  182. package/dist/iframe.test.browser.js +0 -15
  183. package/dist/iframe.test.browser.js.map +0 -1
  184. package/dist/index.browser.js +0 -36
  185. package/dist/index.browser.js.map +0 -1
  186. package/dist/index.js +0 -41
  187. package/dist/index.js.map +0 -1
  188. package/dist/json-rpc.js +0 -46
  189. package/dist/json-rpc.js.map +0 -1
  190. package/dist/logging.js.map +0 -1
  191. package/dist/manifest/index.browser.js +0 -18
  192. package/dist/manifest/index.browser.js.map +0 -1
  193. package/dist/manifest/index.js +0 -19
  194. package/dist/manifest/index.js.map +0 -1
  195. package/dist/manifest/manifest.js.map +0 -1
  196. package/dist/manifest/validation.js +0 -146
  197. package/dist/manifest/validation.js.map +0 -1
  198. package/dist/mock.js.map +0 -1
  199. package/dist/namespace.d.ts +0 -275
  200. package/dist/namespace.js +0 -225
  201. package/dist/namespace.js.map +0 -1
  202. package/dist/notification.d.ts +0 -66
  203. package/dist/notification.js +0 -58
  204. package/dist/notification.js.map +0 -1
  205. package/dist/npm.js.map +0 -1
  206. package/dist/path.js +0 -21
  207. package/dist/path.js.map +0 -1
  208. package/dist/post-process.js.map +0 -1
  209. package/dist/snaps.js +0 -212
  210. package/dist/snaps.js.map +0 -1
  211. package/dist/types.js +0 -103
  212. package/dist/types.js.map +0 -1
  213. package/dist/validation.js +0 -21
  214. package/dist/validation.js.map +0 -1
  215. package/dist/versions.js.map +0 -1
  216. package/dist/virtual-file/VirtualFile.js.map +0 -1
  217. package/dist/virtual-file/index.browser.js +0 -18
  218. package/dist/virtual-file/index.browser.js.map +0 -1
  219. package/dist/virtual-file/index.js +0 -19
  220. package/dist/virtual-file/index.js.map +0 -1
  221. package/dist/virtual-file/toVirtualFile.js +0 -30
  222. package/dist/virtual-file/toVirtualFile.js.map +0 -1
  223. /package/dist/{checksum.d.ts → types/checksum.d.ts} +0 -0
  224. /package/dist/{cronjob.d.ts → types/cronjob.d.ts} +0 -0
  225. /package/dist/{deep-clone.d.ts → types/deep-clone.d.ts} +0 -0
  226. /package/dist/{default-endowments.d.ts → types/default-endowments.d.ts} +0 -0
  227. /package/dist/{entropy.d.ts → types/entropy.d.ts} +0 -0
  228. /package/dist/{eval-worker.d.ts → types/eval-worker.d.ts} +0 -0
  229. /package/dist/{eval.d.ts → types/eval.d.ts} +0 -0
  230. /package/dist/{fs.d.ts → types/fs.d.ts} +0 -0
  231. /package/dist/{icon.d.ts → types/icon.d.ts} +0 -0
  232. /package/dist/{iframe.d.ts → types/iframe.d.ts} +0 -0
  233. /package/dist/{iframe.test.browser.d.ts → types/iframe.test.browser.d.ts} +0 -0
  234. /package/dist/{json-rpc.d.ts → types/json-rpc.d.ts} +0 -0
  235. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  236. /package/dist/{manifest → types/manifest}/index.browser.d.ts +0 -0
  237. /package/dist/{manifest → types/manifest}/index.d.ts +0 -0
  238. /package/dist/{manifest → types/manifest}/manifest.d.ts +0 -0
  239. /package/dist/{mock.d.ts → types/mock.d.ts} +0 -0
  240. /package/dist/{npm.d.ts → types/npm.d.ts} +0 -0
  241. /package/dist/{path.d.ts → types/path.d.ts} +0 -0
  242. /package/dist/{post-process.d.ts → types/post-process.d.ts} +0 -0
  243. /package/dist/{snaps.d.ts → types/snaps.d.ts} +0 -0
  244. /package/dist/{validation.d.ts → types/validation.d.ts} +0 -0
  245. /package/dist/{versions.d.ts → types/versions.d.ts} +0 -0
  246. /package/dist/{virtual-file → types/virtual-file}/VirtualFile.d.ts +0 -0
  247. /package/dist/{virtual-file → types/virtual-file}/index.browser.d.ts +0 -0
  248. /package/dist/{virtual-file → types/virtual-file}/index.d.ts +0 -0
  249. /package/dist/{virtual-file → types/virtual-file}/toVirtualFile.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/deep-clone.ts"],"sourcesContent":["import rfdc from 'rfdc';\n\nexport const deepClone = rfdc({ proto: false, circles: false });\n"],"names":["rfdc","deepClone","proto","circles"],"mappings":"AAAA,OAAOA,UAAU,OAAO;AAExB,OAAO,MAAMC,YAAYD,KAAK;IAAEE,OAAO;IAAOC,SAAS;AAAM,GAAG"}
@@ -1,10 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEFAULT_ENDOWMENTS = void 0;
4
1
  /**
5
2
  * Global JavaScript APIs exposed by default to all snaps.
6
- */
7
- exports.DEFAULT_ENDOWMENTS = Object.freeze([
3
+ */ export const DEFAULT_ENDOWMENTS = Object.freeze([
8
4
  'atob',
9
5
  'btoa',
10
6
  'BigInt',
@@ -37,6 +33,7 @@ exports.DEFAULT_ENDOWMENTS = Object.freeze([
37
33
  // https://github.com/MetaMask/snaps-monorepo/issues/662
38
34
  // https://github.com/MetaMask/snaps-monorepo/discussions/678
39
35
  'AbortController',
40
- 'AbortSignal',
36
+ 'AbortSignal'
41
37
  ]);
38
+
42
39
  //# sourceMappingURL=default-endowments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/default-endowments.ts"],"sourcesContent":["/**\n * Global JavaScript APIs exposed by default to all snaps.\n */\nexport const DEFAULT_ENDOWMENTS: readonly string[] = Object.freeze([\n 'atob',\n 'btoa',\n 'BigInt',\n 'console',\n 'crypto',\n 'Date',\n 'Math',\n 'setTimeout',\n 'clearTimeout',\n 'SubtleCrypto',\n 'TextDecoder',\n 'TextEncoder',\n 'URL',\n 'setInterval',\n 'clearInterval',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array',\n 'DataView',\n 'ArrayBuffer',\n // Used by fetch, but also as API for some packages that don't do network connections\n // https://github.com/MetaMask/snaps-monorepo/issues/662\n // https://github.com/MetaMask/snaps-monorepo/discussions/678\n 'AbortController',\n 'AbortSignal',\n]);\n"],"names":["DEFAULT_ENDOWMENTS","Object","freeze"],"mappings":"AAAA;;CAEC,GACD,OAAO,MAAMA,qBAAwCC,OAAOC,MAAM,CAAC;IACjE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,qFAAqF;IACrF,wDAAwD;IACxD,6DAA6D;IAC7D;IACA;CACD,EAAE"}
@@ -0,0 +1,6 @@
1
+ // 0xd36e6170 - 0x80000000
2
+ export const SIP_6_MAGIC_VALUE = `1399742832'`;
3
+ // `${bytesToNumber(keccak256('Snaps state encryption').slice(0, 4))}'`
4
+ export const STATE_ENCRYPTION_MAGIC_VALUE = `572232532'`;
5
+
6
+ //# sourceMappingURL=entropy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/entropy.ts"],"sourcesContent":["// 0xd36e6170 - 0x80000000\nexport const SIP_6_MAGIC_VALUE = `1399742832'` as `${number}'`;\n\n// `${bytesToNumber(keccak256('Snaps state encryption').slice(0, 4))}'`\nexport const STATE_ENCRYPTION_MAGIC_VALUE = `572232532'` as `${number}'`;\n\nexport type MagicValue =\n | typeof SIP_6_MAGIC_VALUE\n | typeof STATE_ENCRYPTION_MAGIC_VALUE;\n"],"names":["SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE"],"mappings":"AAAA,0BAA0B;AAC1B,OAAO,MAAMA,oBAAoB,CAAC,WAAW,CAAC,CAAiB;AAE/D,uEAAuE;AACvE,OAAO,MAAMC,+BAA+B,CAAC,UAAU,CAAC,CAAiB"}
@@ -0,0 +1,12 @@
1
+ import { literal } from 'superstruct';
2
+ /**
3
+ * Superstruct struct for validating an enum value. This allows using both the
4
+ * enum string values and the enum itself as values.
5
+ *
6
+ * @param constant - The enum to validate against.
7
+ * @returns The superstruct struct.
8
+ */ export function enumValue(constant) {
9
+ return literal(constant);
10
+ }
11
+
12
+ //# sourceMappingURL=enum.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import { literal, Struct } from 'superstruct';\n\n/**\n * Get the enum values as union type. This allows using both the enum string\n * values and the enum itself as values.\n *\n * Note: This only works for string enums.\n *\n * @example\n * ```typescript\n * enum Foo {\n * Bar = 'bar',\n * Baz = 'baz',\n * }\n *\n * type FooValue = EnumToUnion<Foo>;\n * // FooValue is 'bar' | 'baz'\n *\n * const foo: FooValue = Foo.Bar; // Works\n * const foo: FooValue = 'bar'; // Also works\n * ```\n */\nexport type EnumToUnion<Type extends string> = `${Type}`;\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, EnumToUnion<Type>> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["literal","enumValue","constant"],"mappings":"AAAA,SAASA,OAAO,QAAgB,cAAc;AAwB9C;;;;;;CAMC,GACD,OAAO,SAASC,UACdC,QAAc;IAEd,OAAOF,QAAQE;AACjB"}
@@ -0,0 +1,47 @@
1
+ // eslint-disable-next-line import/no-unassigned-import
2
+ import 'ses/lockdown';
3
+ import { readFileSync } from 'fs';
4
+ import { generateMockEndowments } from './mock';
5
+ import { SNAP_EXPORT_NAMES } from './types';
6
+ lockdown({
7
+ consoleTaming: 'unsafe',
8
+ errorTaming: 'unsafe',
9
+ mathTaming: 'unsafe',
10
+ dateTaming: 'unsafe',
11
+ overrideTaming: 'severe',
12
+ // We disable domain taming, because it does not work in certain cases when
13
+ // running tests. This is unlikely to be a problem in production, because
14
+ // Node.js domains are deprecated.
15
+ domainTaming: 'unsafe'
16
+ });
17
+ /**
18
+ * Get mock endowments that don't do anything. This is useful for running the
19
+ * eval, for snaps that try to communicate with the extension on initialisation,
20
+ * for example.
21
+ *
22
+ * @returns The mock endowments.
23
+ */ function getMockEndowments() {
24
+ const endowments = generateMockEndowments();
25
+ return {
26
+ ...endowments,
27
+ window: endowments,
28
+ self: endowments
29
+ };
30
+ }
31
+ const snapFilePath = process.argv[2];
32
+ const snapModule = {
33
+ exports: {}
34
+ };
35
+ new Compartment({
36
+ ...getMockEndowments(),
37
+ module: snapModule,
38
+ exports: snapModule.exports
39
+ }).evaluate(readFileSync(snapFilePath, 'utf8'));
40
+ const invalidExports = Object.keys(snapModule.exports).filter((snapExport)=>!SNAP_EXPORT_NAMES.includes(snapExport));
41
+ if (invalidExports.length > 0) {
42
+ // eslint-disable-next-line no-console
43
+ console.warn(`Invalid snap exports detected:\n${invalidExports.join('\n')}`);
44
+ }
45
+ setTimeout(()=>process.exit(0), 1000); // Hack to ensure worker exits
46
+
47
+ //# sourceMappingURL=eval-worker.js.map
@@ -0,0 +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 { generateMockEndowments } from './mock';\nimport { HandlerType, 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":["readFileSync","generateMockEndowments","SNAP_EXPORT_NAMES","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","invalidExports","Object","keys","filter","snapExport","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe;AAEtB,SAASA,YAAY,QAAQ,KAAK;AAElC,SAASC,sBAAsB,QAAQ,SAAS;AAChD,SAAsBC,iBAAiB,QAAQ,UAAU;AAIzDC,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,aAAaV;IACnB,OAAO;QACL,GAAGU,UAAU;QACbC,QAAQD;QACRE,MAAMF;IACR;AACF;AAEA,MAAMG,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGT,mBAAmB;IACtBU,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACrB,aAAac,cAAc;AAEvC,MAAMQ,iBAAiBC,OAAOC,IAAI,CAACP,WAAWC,OAAO,EAAEO,MAAM,CAC3D,CAACC,aAAe,CAACxB,kBAAkByB,QAAQ,CAACD;AAG9C,IAAIJ,eAAeM,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAER,eAAeS,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMjB,QAAQkB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
@@ -0,0 +1,25 @@
1
+ import { fork } from 'child_process';
2
+ import { join } from 'path';
3
+ import { validateFilePath } from './fs';
4
+ /**
5
+ * Spawn a new process to run the provided bundle in.
6
+ *
7
+ * @param bundlePath - The path to the bundle to run.
8
+ * @returns `null` if the worker ran successfully.
9
+ * @throws If the worker failed to run successfully.
10
+ */ export async function evalBundle(bundlePath) {
11
+ await validateFilePath(bundlePath);
12
+ return new Promise((resolve, reject)=>{
13
+ const worker = fork(join(__dirname, 'eval-worker.js'), [
14
+ bundlePath
15
+ ]);
16
+ worker.on('exit', (exitCode)=>{
17
+ if (exitCode === 0) {
18
+ return resolve(null);
19
+ }
20
+ return reject(new Error(`Process exited with non-zero exit code: ${exitCode}`));
21
+ });
22
+ });
23
+ }
24
+
25
+ //# sourceMappingURL=eval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/eval.ts"],"sourcesContent":["import { fork } from 'child_process';\nimport { join } from 'path';\n\nimport { validateFilePath } from './fs';\n\n/**\n * Spawn a new process to run the provided bundle in.\n *\n * @param bundlePath - The path to the bundle to run.\n * @returns `null` if the worker ran successfully.\n * @throws If the worker failed to run successfully.\n */\nexport async function evalBundle(bundlePath: string): Promise<null> {\n await validateFilePath(bundlePath);\n\n return new Promise((resolve, reject) => {\n const worker = fork(join(__dirname, 'eval-worker.js'), [bundlePath]);\n\n worker.on('exit', (exitCode: number) => {\n if (exitCode === 0) {\n return resolve(null);\n }\n\n return reject(\n new Error(`Process exited with non-zero exit code: ${exitCode}`),\n );\n });\n });\n}\n"],"names":["fork","join","validateFilePath","evalBundle","bundlePath","Promise","resolve","reject","worker","__dirname","on","exitCode","Error"],"mappings":"AAAA,SAASA,IAAI,QAAQ,gBAAgB;AACrC,SAASC,IAAI,QAAQ,OAAO;AAE5B,SAASC,gBAAgB,QAAQ,OAAO;AAExC;;;;;;CAMC,GACD,OAAO,eAAeC,WAAWC,UAAkB;IACjD,MAAMF,iBAAiBE;IAEvB,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B,MAAMC,SAASR,KAAKC,KAAKQ,WAAW,mBAAmB;YAACL;SAAW;QAEnEI,OAAOE,EAAE,CAAC,QAAQ,CAACC;YACjB,IAAIA,aAAa,GAAG;gBAClB,OAAOL,QAAQ;YACjB;YAEA,OAAOC,OACL,IAAIK,MAAM,CAAC,wCAAwC,EAAED,SAAS,CAAC;QAEnE;IACF;AACF"}
@@ -1,13 +1,8 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.useTemporaryFile = exports.validateDirPath = exports.validateFilePath = exports.validateOutfileName = exports.getOutfilePath = exports.readJsonFile = exports.isFile = exports.isDirectory = void 0;
7
- const fs_1 = require("fs");
8
- const os_1 = __importDefault(require("os"));
9
- const path_1 = __importDefault(require("path"));
10
- const virtual_file_1 = require("./virtual-file");
1
+ import { promises as fs } from 'fs';
2
+ import os from 'os';
3
+ import pathUtils from 'path';
4
+ import { parseJson } from './json';
5
+ import { readVirtualFile } from './virtual-file';
11
6
  /**
12
7
  * Checks whether the given path string resolves to an existing directory, and
13
8
  * optionally creates the directory if it doesn't exist.
@@ -15,64 +10,57 @@ const virtual_file_1 = require("./virtual-file");
15
10
  * @param pathString - The path string to check.
16
11
  * @param createDir - Whether to create the directory if it doesn't exist.
17
12
  * @returns Whether the given path is an existing directory.
18
- */
19
- async function isDirectory(pathString, createDir) {
13
+ */ export async function isDirectory(pathString, createDir) {
20
14
  try {
21
- const stats = await fs_1.promises.stat(pathString);
15
+ const stats = await fs.stat(pathString);
22
16
  return stats.isDirectory();
23
- }
24
- catch (error) {
17
+ } catch (error) {
25
18
  if (error.code === 'ENOENT') {
26
19
  if (!createDir) {
27
20
  return false;
28
21
  }
29
- await fs_1.promises.mkdir(pathString, { recursive: true });
22
+ await fs.mkdir(pathString, {
23
+ recursive: true
24
+ });
30
25
  return true;
31
26
  }
32
27
  return false;
33
28
  }
34
29
  }
35
- exports.isDirectory = isDirectory;
36
30
  /**
37
31
  * Checks whether the given path string resolves to an existing file.
38
32
  *
39
33
  * @param pathString - The path string to check.
40
34
  * @returns Whether the given path is an existing file.
41
- */
42
- async function isFile(pathString) {
35
+ */ export async function isFile(pathString) {
43
36
  try {
44
- const stats = await fs_1.promises.stat(pathString);
37
+ const stats = await fs.stat(pathString);
45
38
  return stats.isFile();
46
- }
47
- catch (error) {
39
+ } catch (error) {
48
40
  return false;
49
41
  }
50
42
  }
51
- exports.isFile = isFile;
52
43
  /**
53
44
  * Reads a `.json` file, parses its contents, and returns them.
54
45
  *
55
46
  * @param pathString - The path to the JSON file.
56
47
  * @returns The parsed contents of the JSON file.
57
- */
58
- async function readJsonFile(pathString) {
48
+ */ export async function readJsonFile(pathString) {
59
49
  if (!pathString.endsWith('.json')) {
60
50
  throw new Error('The specified file must be a ".json" file.');
61
51
  }
62
52
  let file;
63
53
  try {
64
- file = await (0, virtual_file_1.readVirtualFile)(pathString, 'utf8');
65
- }
66
- catch (error) {
54
+ file = await readVirtualFile(pathString, 'utf8');
55
+ } catch (error) {
67
56
  if (error.code === 'ENOENT') {
68
57
  throw new Error(`Could not find '${pathString}'. Please ensure that the file exists.`);
69
58
  }
70
59
  throw error;
71
60
  }
72
- file.result = JSON.parse(file.toString());
61
+ file.result = parseJson(file.toString());
73
62
  return file;
74
63
  }
75
- exports.readJsonFile = readJsonFile;
76
64
  /**
77
65
  * Gets the complete out file path from an output file name and parent
78
66
  * directory path.
@@ -80,11 +68,9 @@ exports.readJsonFile = readJsonFile;
80
68
  * @param outDir - The path to the out file's parent directory.
81
69
  * @param outFileName - The out file's name.
82
70
  * @returns The complete path to the out file.
83
- */
84
- function getOutfilePath(outDir, outFileName) {
85
- return path_1.default.join(outDir, outFileName || 'bundle.js');
71
+ */ export function getOutfilePath(outDir, outFileName) {
72
+ return pathUtils.join(outDir, outFileName || 'bundle.js');
86
73
  }
87
- exports.getOutfilePath = getOutfilePath;
88
74
  /**
89
75
  * Ensures that the outfile name is just a `.js` file name.
90
76
  * Throws on validation failure.
@@ -92,31 +78,25 @@ exports.getOutfilePath = getOutfilePath;
92
78
  * @param filename - The file name to validate.
93
79
  * @returns `true` if validation succeeded.
94
80
  * @throws If the file name is invalid.
95
- */
96
- function validateOutfileName(filename) {
97
- if (!filename.endsWith('.js') ||
98
- filename === '.js' ||
99
- path_1.default.basename(filename) !== filename) {
81
+ */ export function validateOutfileName(filename) {
82
+ if (!filename.endsWith('.js') || filename === '.js' || pathUtils.basename(filename) !== filename) {
100
83
  throw new Error(`Invalid outfile name: ${filename}. Must be a .js file`);
101
84
  }
102
85
  return true;
103
86
  }
104
- exports.validateOutfileName = validateOutfileName;
105
87
  /**
106
88
  * Validates a file path. Throws on validation failure.
107
89
  *
108
90
  * @param filePath - The file path to validate.
109
91
  * @returns `true` if validation succeeded.
110
92
  * @throws If the path does not resolve to a file.
111
- */
112
- async function validateFilePath(filePath) {
93
+ */ export async function validateFilePath(filePath) {
113
94
  const exists = await isFile(filePath);
114
95
  if (!exists) {
115
96
  throw new Error(`Invalid params: '${filePath}' is not a file or does not exist.`);
116
97
  }
117
98
  return true;
118
99
  }
119
- exports.validateFilePath = validateFilePath;
120
100
  /**
121
101
  * Validates a directory path. Throws on validation failure.
122
102
  *
@@ -124,15 +104,13 @@ exports.validateFilePath = validateFilePath;
124
104
  * @param createDir - Whether to create the directory if it doesn't exist.
125
105
  * @returns `true` if validation succeeded or the directory was created.
126
106
  * @throws If the directory does not exist or could not be created.
127
- */
128
- async function validateDirPath(dirPath, createDir) {
107
+ */ export async function validateDirPath(dirPath, createDir) {
129
108
  const exists = await isDirectory(dirPath, createDir);
130
109
  if (!exists) {
131
110
  throw new Error(`Invalid params: '${dirPath}' is not a directory or could not be created.`);
132
111
  }
133
112
  return true;
134
113
  }
135
- exports.validateDirPath = validateDirPath;
136
114
  /**
137
115
  * Creates a temporary file with a given name and content, writes it to disk and calls the provided function.
138
116
  * This function handles deletion of the temporary file after usage.
@@ -140,19 +118,19 @@ exports.validateDirPath = validateDirPath;
140
118
  * @param fileName - The name of the temporary file.
141
119
  * @param fileContents - The content of the temporary file.
142
120
  * @param fn - The callback function to call when the temporary file has been created.
143
- */
144
- async function useTemporaryFile(fileName, fileContents, fn) {
145
- const filePath = path_1.default.join(os_1.default.tmpdir(), fileName);
146
- await fs_1.promises.mkdir(path_1.default.dirname(filePath), { recursive: true });
147
- await fs_1.promises.writeFile(filePath, fileContents);
121
+ */ export async function useTemporaryFile(fileName, fileContents, fn) {
122
+ const filePath = pathUtils.join(os.tmpdir(), fileName);
123
+ await fs.mkdir(pathUtils.dirname(filePath), {
124
+ recursive: true
125
+ });
126
+ await fs.writeFile(filePath, fileContents);
148
127
  try {
149
128
  await fn(filePath);
150
- }
151
- finally {
129
+ } finally{
152
130
  if (await isFile(filePath)) {
153
- await fs_1.promises.unlink(filePath);
131
+ await fs.unlink(filePath);
154
132
  }
155
133
  }
156
134
  }
157
- exports.useTemporaryFile = useTemporaryFile;
135
+
158
136
  //# sourceMappingURL=fs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/fs.ts"],"sourcesContent":["import { Json } from '@metamask/utils';\nimport { promises as fs } from 'fs';\nimport os from 'os';\nimport pathUtils from 'path';\n\nimport { parseJson } from './json';\nimport { readVirtualFile, VirtualFile } from './virtual-file';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns Whether the given path is an existing directory.\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n await fs.mkdir(pathString, { recursive: true });\n return true;\n }\n\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check.\n * @returns Whether the given path is an existing file.\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile<Type extends Json = Json>(\n pathString: string,\n): Promise<VirtualFile<Type>> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n let file;\n try {\n file = await readVirtualFile(pathString, 'utf8');\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `Could not find '${pathString}'. Please ensure that the file exists.`,\n );\n }\n\n throw error;\n }\n file.result = parseJson(file.toString());\n return file as VirtualFile<Type>;\n}\n\n/**\n * Gets the complete out file path from an output file name and parent\n * directory path.\n *\n * @param outDir - The path to the out file's parent directory.\n * @param outFileName - The out file's name.\n * @returns The complete path to the out file.\n */\nexport function getOutfilePath(outDir: string, outFileName: string): string {\n return pathUtils.join(outDir, outFileName || 'bundle.js');\n}\n\n/**\n * Ensures that the outfile name is just a `.js` file name.\n * Throws on validation failure.\n *\n * @param filename - The file name to validate.\n * @returns `true` if validation succeeded.\n * @throws If the file name is invalid.\n */\nexport function validateOutfileName(filename: string): boolean {\n if (\n !filename.endsWith('.js') ||\n filename === '.js' ||\n pathUtils.basename(filename) !== filename\n ) {\n throw new Error(`Invalid outfile name: ${filename}. Must be a .js file`);\n }\n return true;\n}\n\n/**\n * Validates a file path. Throws on validation failure.\n *\n * @param filePath - The file path to validate.\n * @returns `true` if validation succeeded.\n * @throws If the path does not resolve to a file.\n */\nexport async function validateFilePath(filePath: string): Promise<boolean> {\n const exists = await isFile(filePath);\n if (!exists) {\n throw new Error(\n `Invalid params: '${filePath}' is not a file or does not exist.`,\n );\n }\n return true;\n}\n\n/**\n * Validates a directory path. Throws on validation failure.\n *\n * @param dirPath - The directory path to validate.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns `true` if validation succeeded or the directory was created.\n * @throws If the directory does not exist or could not be created.\n */\nexport async function validateDirPath(\n dirPath: string,\n createDir: boolean,\n): Promise<boolean> {\n const exists = await isDirectory(dirPath, createDir);\n if (!exists) {\n throw new Error(\n `Invalid params: '${dirPath}' is not a directory or could not be created.`,\n );\n }\n return true;\n}\n\n/**\n * Creates a temporary file with a given name and content, writes it to disk and calls the provided function.\n * This function handles deletion of the temporary file after usage.\n *\n * @param fileName - The name of the temporary file.\n * @param fileContents - The content of the temporary file.\n * @param fn - The callback function to call when the temporary file has been created.\n */\nexport async function useTemporaryFile(\n fileName: string,\n fileContents: string,\n fn: (path: string) => Promise<unknown>,\n): Promise<void> {\n const filePath = pathUtils.join(os.tmpdir(), fileName);\n await fs.mkdir(pathUtils.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, fileContents);\n try {\n await fn(filePath);\n } finally {\n if (await isFile(filePath)) {\n await fs.unlink(filePath);\n }\n }\n}\n"],"names":["promises","fs","os","pathUtils","parseJson","readVirtualFile","isDirectory","pathString","createDir","stats","stat","error","code","mkdir","recursive","isFile","readJsonFile","endsWith","Error","file","result","toString","getOutfilePath","outDir","outFileName","join","validateOutfileName","filename","basename","validateFilePath","filePath","exists","validateDirPath","dirPath","useTemporaryFile","fileName","fileContents","fn","tmpdir","dirname","writeFile","unlink"],"mappings":"AACA,SAASA,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,QAAQ,KAAK;AACpB,OAAOC,eAAe,OAAO;AAE7B,SAASC,SAAS,QAAQ,SAAS;AACnC,SAASC,eAAe,QAAqB,iBAAiB;AAE9D;;;;;;;CAOC,GACD,OAAO,eAAeC,YACpBC,UAAkB,EAClBC,SAAkB;IAElB,IAAI;QACF,MAAMC,QAAQ,MAAMR,GAAGS,IAAI,CAACH;QAC5B,OAAOE,MAAMH,WAAW;IAC1B,EAAE,OAAOK,OAAO;QACd,IAAIA,MAAMC,IAAI,KAAK,UAAU;YAC3B,IAAI,CAACJ,WAAW;gBACd,OAAO;YACT;YAEA,MAAMP,GAAGY,KAAK,CAACN,YAAY;gBAAEO,WAAW;YAAK;YAC7C,OAAO;QACT;QAEA,OAAO;IACT;AACF;AAEA;;;;;CAKC,GACD,OAAO,eAAeC,OAAOR,UAAkB;IAC7C,IAAI;QACF,MAAME,QAAQ,MAAMR,GAAGS,IAAI,CAACH;QAC5B,OAAOE,MAAMM,MAAM;IACrB,EAAE,OAAOJ,OAAO;QACd,OAAO;IACT;AACF;AAEA;;;;;CAKC,GACD,OAAO,eAAeK,aACpBT,UAAkB;IAElB,IAAI,CAACA,WAAWU,QAAQ,CAAC,UAAU;QACjC,MAAM,IAAIC,MAAM;IAClB;IAEA,IAAIC;IACJ,IAAI;QACFA,OAAO,MAAMd,gBAAgBE,YAAY;IAC3C,EAAE,OAAOI,OAAO;QACd,IAAIA,MAAMC,IAAI,KAAK,UAAU;YAC3B,MAAM,IAAIM,MACR,CAAC,gBAAgB,EAAEX,WAAW,sCAAsC,CAAC;QAEzE;QAEA,MAAMI;IACR;IACAQ,KAAKC,MAAM,GAAGhB,UAAUe,KAAKE,QAAQ;IACrC,OAAOF;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,eAAeC,MAAc,EAAEC,WAAmB;IAChE,OAAOrB,UAAUsB,IAAI,CAACF,QAAQC,eAAe;AAC/C;AAEA;;;;;;;CAOC,GACD,OAAO,SAASE,oBAAoBC,QAAgB;IAClD,IACE,CAACA,SAASV,QAAQ,CAAC,UACnBU,aAAa,SACbxB,UAAUyB,QAAQ,CAACD,cAAcA,UACjC;QACA,MAAM,IAAIT,MAAM,CAAC,sBAAsB,EAAES,SAAS,oBAAoB,CAAC;IACzE;IACA,OAAO;AACT;AAEA;;;;;;CAMC,GACD,OAAO,eAAeE,iBAAiBC,QAAgB;IACrD,MAAMC,SAAS,MAAMhB,OAAOe;IAC5B,IAAI,CAACC,QAAQ;QACX,MAAM,IAAIb,MACR,CAAC,iBAAiB,EAAEY,SAAS,kCAAkC,CAAC;IAEpE;IACA,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeE,gBACpBC,OAAe,EACfzB,SAAkB;IAElB,MAAMuB,SAAS,MAAMzB,YAAY2B,SAASzB;IAC1C,IAAI,CAACuB,QAAQ;QACX,MAAM,IAAIb,MACR,CAAC,iBAAiB,EAAEe,QAAQ,6CAA6C,CAAC;IAE9E;IACA,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeC,iBACpBC,QAAgB,EAChBC,YAAoB,EACpBC,EAAsC;IAEtC,MAAMP,WAAW3B,UAAUsB,IAAI,CAACvB,GAAGoC,MAAM,IAAIH;IAC7C,MAAMlC,GAAGY,KAAK,CAACV,UAAUoC,OAAO,CAACT,WAAW;QAAEhB,WAAW;IAAK;IAC9D,MAAMb,GAAGuC,SAAS,CAACV,UAAUM;IAC7B,IAAI;QACF,MAAMC,GAAGP;IACX,SAAU;QACR,IAAI,MAAMf,OAAOe,WAAW;YAC1B,MAAM7B,GAAGwC,MAAM,CAACX;QAClB;IACF;AACF"}
@@ -0,0 +1,3 @@
1
+ export { };
2
+
3
+ //# sourceMappingURL=handlers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import { Component } from '@metamask/snaps-ui';\nimport { Json, JsonRpcRequest } from '@metamask/utils';\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<\n Params extends Json[] | Record<string, Json> | undefined =\n | Json[]\n | Record<string, Json>\n | undefined,\n> = (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n}) => Promise<unknown>;\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = {\n content: Component | null;\n};\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<\n Params extends Json[] | Record<string, Json> | undefined =\n | Json[]\n | Record<string, Json>\n | undefined,\n> = (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n onRpcRequest?: OnRpcRequestHandler;\n onTransaction?: OnTransactionHandler;\n onCronjob?: OnCronjobHandler;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":[],"mappings":"AAAA,WAgF8C"}
@@ -0,0 +1,11 @@
1
+ import { assert } from '@metamask/utils';
2
+ import isSvg from 'is-svg';
3
+ export const SVG_MAX_BYTE_SIZE = 100000;
4
+ export const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(SVG_MAX_BYTE_SIZE / 1000)}kb`;
5
+ export const assertIsSnapIcon = (icon)=>{
6
+ assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in ".svg".');
7
+ assert(Buffer.byteLength(icon.value, 'utf8') <= SVG_MAX_BYTE_SIZE, `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`);
8
+ assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');
9
+ };
10
+
11
+ //# sourceMappingURL=icon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/icon.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport isSvg from 'is-svg';\n\nimport { VirtualFile } from './virtual-file';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\nexport const assertIsSnapIcon = (icon: VirtualFile) => {\n assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in \".svg\".');\n\n assert(\n Buffer.byteLength(icon.value, 'utf8') <= SVG_MAX_BYTE_SIZE,\n `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n\n assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');\n};\n"],"names":["assert","isSvg","SVG_MAX_BYTE_SIZE","SVG_MAX_BYTE_SIZE_TEXT","Math","floor","assertIsSnapIcon","icon","path","endsWith","Buffer","byteLength","value","toString"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AACzC,OAAOC,WAAW,SAAS;AAI3B,OAAO,MAAMC,oBAAoB,OAAQ;AACzC,OAAO,MAAMC,yBAAyB,CAAC,EAAEC,KAAKC,KAAK,CACjDH,oBAAoB,MACpB,EAAE,CAAC,CAAC;AAEN,OAAO,MAAMI,mBAAmB,CAACC;IAC/BP,OAAOO,KAAKC,IAAI,CAACC,QAAQ,CAAC,SAAS;IAEnCT,OACEU,OAAOC,UAAU,CAACJ,KAAKK,KAAK,EAAE,WAAWV,mBACzC,CAAC,mDAAmD,EAAEC,uBAAuB,CAAC,CAAC;IAGjFH,OAAOC,MAAMM,KAAKM,QAAQ,KAAK;AACjC,EAAE"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Creates the iframe to be used as the execution environment. This may run
3
+ * forever if the iframe never loads, but the promise should be wrapped in
4
+ * an initialization timeout in the SnapController.
5
+ *
6
+ * @param uri - The iframe URI.
7
+ * @param id - The ID to assign to the iframe.
8
+ * @param sandbox - Whether to enable the sandbox attribute.
9
+ * @returns A promise that resolves to the contentWindow of the iframe.
10
+ */ export async function createWindow(uri, id, sandbox = true) {
11
+ return await new Promise((resolve, reject)=>{
12
+ const iframe = document.createElement('iframe');
13
+ // The order of operations appears to matter for everything except this
14
+ // attribute. We may as well set it here.
15
+ iframe.setAttribute('id', id);
16
+ iframe.setAttribute('data-testid', 'snaps-iframe');
17
+ if (sandbox) {
18
+ // For the sandbox property to have any effect it needs to be set before the iframe is appended.
19
+ // We apply this property as a principle of least authority (POLA)
20
+ // measure.
21
+ // Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox
22
+ iframe.setAttribute('sandbox', 'allow-scripts');
23
+ }
24
+ // In the past, we've had problems that appear to be symptomatic of the
25
+ // iframe firing the `load` event before its scripts are actually loaded,
26
+ // which has prevented snaps from executing properly. Therefore, we set
27
+ // the `src` attribute and append the iframe to the DOM before attaching
28
+ // the `load` listener.
29
+ //
30
+ // `load` should only fire when "all dependent resources" have been
31
+ // loaded, which includes scripts.
32
+ //
33
+ // MDN article for `load` event: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
34
+ // Re: `load` firing twice: https://stackoverflow.com/questions/10781880/dynamically-created-iframe-triggers-onload-event-twice/15880489#15880489
35
+ iframe.setAttribute('src', uri);
36
+ document.body.appendChild(iframe);
37
+ iframe.addEventListener('load', ()=>{
38
+ if (iframe.contentWindow) {
39
+ resolve(iframe.contentWindow);
40
+ } else {
41
+ // We don't know of a case when this would happen, but better to fail
42
+ // fast if it does.
43
+ reject(new Error(`iframe.contentWindow not present on load for job "${id}".`));
44
+ }
45
+ });
46
+ });
47
+ }
48
+
49
+ //# sourceMappingURL=iframe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/iframe.ts"],"sourcesContent":["/**\n * Creates the iframe to be used as the execution environment. This may run\n * forever if the iframe never loads, but the promise should be wrapped in\n * an initialization timeout in the SnapController.\n *\n * @param uri - The iframe URI.\n * @param id - The ID to assign to the iframe.\n * @param sandbox - Whether to enable the sandbox attribute.\n * @returns A promise that resolves to the contentWindow of the iframe.\n */\nexport async function createWindow(\n uri: string,\n id: string,\n sandbox = true,\n): Promise<Window> {\n return await new Promise((resolve, reject) => {\n const iframe = document.createElement('iframe');\n // The order of operations appears to matter for everything except this\n // attribute. We may as well set it here.\n iframe.setAttribute('id', id);\n iframe.setAttribute('data-testid', 'snaps-iframe');\n\n if (sandbox) {\n // For the sandbox property to have any effect it needs to be set before the iframe is appended.\n // We apply this property as a principle of least authority (POLA)\n // measure.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox\n iframe.setAttribute('sandbox', 'allow-scripts');\n }\n\n // In the past, we've had problems that appear to be symptomatic of the\n // iframe firing the `load` event before its scripts are actually loaded,\n // which has prevented snaps from executing properly. Therefore, we set\n // the `src` attribute and append the iframe to the DOM before attaching\n // the `load` listener.\n //\n // `load` should only fire when \"all dependent resources\" have been\n // loaded, which includes scripts.\n //\n // MDN article for `load` event: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event\n // Re: `load` firing twice: https://stackoverflow.com/questions/10781880/dynamically-created-iframe-triggers-onload-event-twice/15880489#15880489\n iframe.setAttribute('src', uri);\n document.body.appendChild(iframe);\n\n iframe.addEventListener('load', () => {\n if (iframe.contentWindow) {\n resolve(iframe.contentWindow);\n } else {\n // We don't know of a case when this would happen, but better to fail\n // fast if it does.\n reject(\n new Error(\n `iframe.contentWindow not present on load for job \"${id}\".`,\n ),\n );\n }\n });\n });\n}\n"],"names":["createWindow","uri","id","sandbox","Promise","resolve","reject","iframe","document","createElement","setAttribute","body","appendChild","addEventListener","contentWindow","Error"],"mappings":"AAAA;;;;;;;;;CASC,GACD,OAAO,eAAeA,aACpBC,GAAW,EACXC,EAAU,EACVC,UAAU,IAAI;IAEd,OAAO,MAAM,IAAIC,QAAQ,CAACC,SAASC;QACjC,MAAMC,SAASC,SAASC,aAAa,CAAC;QACtC,uEAAuE;QACvE,yCAAyC;QACzCF,OAAOG,YAAY,CAAC,MAAMR;QAC1BK,OAAOG,YAAY,CAAC,eAAe;QAEnC,IAAIP,SAAS;YACX,gGAAgG;YAChG,kEAAkE;YAClE,WAAW;YACX,qFAAqF;YACrFI,OAAOG,YAAY,CAAC,WAAW;QACjC;QAEA,uEAAuE;QACvE,yEAAyE;QACzE,uEAAuE;QACvE,wEAAwE;QACxE,uBAAuB;QACvB,EAAE;QACF,mEAAmE;QACnE,kCAAkC;QAClC,EAAE;QACF,mGAAmG;QACnG,iJAAiJ;QACjJH,OAAOG,YAAY,CAAC,OAAOT;QAC3BO,SAASG,IAAI,CAACC,WAAW,CAACL;QAE1BA,OAAOM,gBAAgB,CAAC,QAAQ;YAC9B,IAAIN,OAAOO,aAAa,EAAE;gBACxBT,QAAQE,OAAOO,aAAa;YAC9B,OAAO;gBACL,qEAAqE;gBACrE,mBAAmB;gBACnBR,OACE,IAAIS,MACF,CAAC,kDAAkD,EAAEb,GAAG,EAAE,CAAC;YAGjE;QACF;IACF;AACF"}
@@ -0,0 +1,23 @@
1
+ export * from './array';
2
+ export * from './caveats';
3
+ export * from './checksum';
4
+ export * from './cronjob';
5
+ export * from './deep-clone';
6
+ export * from './default-endowments';
7
+ export * from './entropy';
8
+ export * from './enum';
9
+ export * from './handlers';
10
+ export * from './iframe';
11
+ export * from './json';
12
+ export * from './json-rpc';
13
+ export * from './logging';
14
+ export * from './manifest/index.browser';
15
+ export * from './namespace';
16
+ export * from './path';
17
+ export * from './snaps';
18
+ export * from './types';
19
+ export * from './validation';
20
+ export * from './versions';
21
+ export * from './virtual-file/index.browser';
22
+
23
+ //# sourceMappingURL=index.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
@@ -0,0 +1,7 @@
1
+ // Special entrypoint for execution environments for bundle sizing reasons
2
+ export * from './handlers';
3
+ export * from './logging';
4
+ export * from './namespace';
5
+ export * from './types';
6
+
7
+ //# sourceMappingURL=index.executionenv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.executionenv.ts"],"sourcesContent":["// Special entrypoint for execution environments for bundle sizing reasons\nexport * from './handlers';\nexport * from './logging';\nexport * from './namespace';\nexport * from './types';\n"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,cAAc;AAC5B,cAAc,UAAU"}
@@ -0,0 +1,28 @@
1
+ export * from './array';
2
+ export * from './caveats';
3
+ export * from './cronjob';
4
+ export * from './checksum';
5
+ export * from './deep-clone';
6
+ export * from './default-endowments';
7
+ export * from './entropy';
8
+ export * from './enum';
9
+ export * from './eval';
10
+ export * from './fs';
11
+ export * from './handlers';
12
+ export * from './iframe';
13
+ export * from './json';
14
+ export * from './json-rpc';
15
+ export * from './logging';
16
+ export * from './manifest';
17
+ export * from './mock';
18
+ export * from './namespace';
19
+ export * from './npm';
20
+ export * from './path';
21
+ export * from './post-process';
22
+ export * from './snaps';
23
+ export * from './types';
24
+ export * from './validation';
25
+ export * from './versions';
26
+ export * from './virtual-file';
27
+
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
@@ -0,0 +1,39 @@
1
+ import { isJsonRpcFailure, isJsonRpcSuccess, assertStruct } from '@metamask/utils';
2
+ import { boolean, object, optional, refine } from 'superstruct';
3
+ export const RpcOriginsStruct = refine(object({
4
+ dapps: optional(boolean()),
5
+ snaps: optional(boolean())
6
+ }), 'RPC origins', (value)=>{
7
+ if (!Object.values(value).some(Boolean)) {
8
+ throw new Error('Must specify at least one JSON-RPC origin');
9
+ }
10
+ return true;
11
+ });
12
+ /**
13
+ * Asserts that the given value is a valid {@link RpcOrigins} object.
14
+ *
15
+ * @param value - The value to assert.
16
+ * @param ErrorWrapper - An optional error wrapper to use. Defaults to
17
+ * {@link AssertionError}.
18
+ * @throws If the value is not a valid {@link RpcOrigins} object.
19
+ */ export function assertIsRpcOrigins(value, // eslint-disable-next-line @typescript-eslint/naming-convention
20
+ ErrorWrapper) {
21
+ assertStruct(value, RpcOriginsStruct, 'Invalid JSON-RPC origins', ErrorWrapper);
22
+ }
23
+ /**
24
+ * Assert that the given value is a successful JSON-RPC response. If the value
25
+ * is not a success response, an error is thrown. If the value is an JSON-RPC
26
+ * error, the error message is included in the thrown error.
27
+ *
28
+ * @param value - The value to check.
29
+ * @throws If the value is not a JSON-RPC success response.
30
+ */ export function assertIsJsonRpcSuccess(value) {
31
+ if (!isJsonRpcSuccess(value)) {
32
+ if (isJsonRpcFailure(value)) {
33
+ throw new Error(`JSON-RPC request failed: ${value.error.message}`);
34
+ }
35
+ throw new Error('Invalid JSON-RPC response.');
36
+ }
37
+ }
38
+
39
+ //# sourceMappingURL=json-rpc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/json-rpc.ts"],"sourcesContent":["import {\n isJsonRpcFailure,\n isJsonRpcSuccess,\n Json,\n JsonRpcSuccess,\n AssertionErrorConstructor,\n assertStruct,\n} from '@metamask/utils';\nimport { boolean, Infer, object, optional, refine } from 'superstruct';\n\nexport const RpcOriginsStruct = refine(\n object({\n dapps: optional(boolean()),\n snaps: optional(boolean()),\n }),\n 'RPC origins',\n (value) => {\n if (!Object.values(value).some(Boolean)) {\n throw new Error('Must specify at least one JSON-RPC origin');\n }\n\n return true;\n },\n);\n\nexport type RpcOrigins = Infer<typeof RpcOriginsStruct>;\n\n/**\n * Asserts that the given value is a valid {@link RpcOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link RpcOrigins} object.\n */\nexport function assertIsRpcOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is RpcOrigins {\n assertStruct(\n value,\n RpcOriginsStruct,\n 'Invalid JSON-RPC origins',\n ErrorWrapper,\n );\n}\n\n/**\n * Assert that the given value is a successful JSON-RPC response. If the value\n * is not a success response, an error is thrown. If the value is an JSON-RPC\n * error, the error message is included in the thrown error.\n *\n * @param value - The value to check.\n * @throws If the value is not a JSON-RPC success response.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n): asserts value is JsonRpcSuccess<Json> {\n if (!isJsonRpcSuccess(value)) {\n if (isJsonRpcFailure(value)) {\n throw new Error(`JSON-RPC request failed: ${value.error.message}`);\n }\n\n throw new Error('Invalid JSON-RPC response.');\n }\n}\n"],"names":["isJsonRpcFailure","isJsonRpcSuccess","assertStruct","boolean","object","optional","refine","RpcOriginsStruct","dapps","snaps","value","Object","values","some","Boolean","Error","assertIsRpcOrigins","ErrorWrapper","assertIsJsonRpcSuccess","error","message"],"mappings":"AAAA,SACEA,gBAAgB,EAChBC,gBAAgB,EAIhBC,YAAY,QACP,kBAAkB;AACzB,SAASC,OAAO,EAASC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,QAAQ,cAAc;AAEvE,OAAO,MAAMC,mBAAmBD,OAC9BF,OAAO;IACLI,OAAOH,SAASF;IAChBM,OAAOJ,SAASF;AAClB,IACA,eACA,CAACO;IACC,IAAI,CAACC,OAAOC,MAAM,CAACF,OAAOG,IAAI,CAACC,UAAU;QACvC,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;AACT,GACA;AAIF;;;;;;;CAOC,GACD,OAAO,SAASC,mBACdN,KAAc,EACd,gEAAgE;AAChEO,YAAwC;IAExCf,aACEQ,OACAH,kBACA,4BACAU;AAEJ;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,uBACdR,KAAc;IAEd,IAAI,CAACT,iBAAiBS,QAAQ;QAC5B,IAAIV,iBAAiBU,QAAQ;YAC3B,MAAM,IAAIK,MAAM,CAAC,yBAAyB,EAAEL,MAAMS,KAAK,CAACC,OAAO,CAAC,CAAC;QACnE;QAEA,MAAM,IAAIL,MAAM;IAClB;AACF"}
@@ -0,0 +1,17 @@
1
+ import { getSafeJson } from '@metamask/utils';
2
+ // TODO: Upstream this to @metamask/utils
3
+ /**
4
+ * Parse JSON safely.
5
+ *
6
+ * Does multiple kinds of validation and strips unwanted properties like
7
+ * `__proto__` and `constructor`.
8
+ *
9
+ * @param json - A JSON string to be parsed.
10
+ * @returns The parsed JSON object.
11
+ * @template Type - The type of the JSON object. The type is not actually
12
+ * checked, but it is used to infer the return type.
13
+ */ export function parseJson(json) {
14
+ return getSafeJson(JSON.parse(json));
15
+ }
16
+
17
+ //# sourceMappingURL=json.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/json.ts"],"sourcesContent":["import { getSafeJson, Json } from '@metamask/utils';\n\n// TODO: Upstream this to @metamask/utils\n\n/**\n * Parse JSON safely.\n *\n * Does multiple kinds of validation and strips unwanted properties like\n * `__proto__` and `constructor`.\n *\n * @param json - A JSON string to be parsed.\n * @returns The parsed JSON object.\n * @template Type - The type of the JSON object. The type is not actually\n * checked, but it is used to infer the return type.\n */\nexport function parseJson<Type extends Json = Json>(json: string) {\n return getSafeJson<Type>(JSON.parse(json));\n}\n"],"names":["getSafeJson","parseJson","json","JSON","parse"],"mappings":"AAAA,SAASA,WAAW,QAAc,kBAAkB;AAEpD,yCAAyC;AAEzC;;;;;;;;;;CAUC,GACD,OAAO,SAASC,UAAoCC,IAAY;IAC9D,OAAOF,YAAkBG,KAAKC,KAAK,CAACF;AACtC"}