@metamask/snaps-utils 6.0.0 → 7.0.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 (562) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/dist/array.js +8 -0
  3. package/dist/array.js.map +1 -0
  4. package/dist/array.mjs +8 -0
  5. package/dist/array.mjs.map +1 -0
  6. package/dist/auxiliary-files.js +12 -0
  7. package/dist/auxiliary-files.js.map +1 -0
  8. package/dist/auxiliary-files.mjs +12 -0
  9. package/dist/auxiliary-files.mjs.map +1 -0
  10. package/dist/base64.js +13 -0
  11. package/dist/base64.js.map +1 -0
  12. package/dist/base64.mjs +13 -0
  13. package/dist/base64.mjs.map +1 -0
  14. package/dist/bytes.js +10 -0
  15. package/dist/bytes.js.map +1 -0
  16. package/dist/bytes.mjs +10 -0
  17. package/dist/bytes.mjs.map +1 -0
  18. package/dist/caveats.js +8 -0
  19. package/dist/caveats.js.map +1 -0
  20. package/dist/caveats.mjs +8 -0
  21. package/dist/caveats.mjs.map +1 -0
  22. package/dist/checksum.js +13 -0
  23. package/dist/checksum.js.map +1 -0
  24. package/dist/checksum.mjs +13 -0
  25. package/dist/checksum.mjs.map +1 -0
  26. package/dist/chunk-224S5XKL.js +32 -0
  27. package/dist/chunk-224S5XKL.js.map +1 -0
  28. package/dist/chunk-2G4HD42C.mjs +22 -0
  29. package/dist/chunk-2G4HD42C.mjs.map +1 -0
  30. package/dist/chunk-2IVFF3AA.mjs +211 -0
  31. package/dist/chunk-2IVFF3AA.mjs.map +1 -0
  32. package/dist/chunk-2QS3W66J.js +64 -0
  33. package/dist/chunk-2QS3W66J.js.map +1 -0
  34. package/dist/chunk-2XF32FCF.js +1 -0
  35. package/dist/chunk-2XF32FCF.js.map +1 -0
  36. package/dist/chunk-32B4YQM7.mjs +103 -0
  37. package/dist/chunk-32B4YQM7.mjs.map +1 -0
  38. package/dist/chunk-3SARO5TJ.mjs +18 -0
  39. package/dist/chunk-3SARO5TJ.mjs.map +1 -0
  40. package/dist/chunk-3TH3NLQL.js +169 -0
  41. package/dist/chunk-3TH3NLQL.js.map +1 -0
  42. package/dist/chunk-3ZSMMNQB.mjs +41 -0
  43. package/dist/chunk-3ZSMMNQB.mjs.map +1 -0
  44. package/dist/chunk-43EBXDVP.mjs +30 -0
  45. package/dist/chunk-43EBXDVP.mjs.map +1 -0
  46. package/dist/chunk-4GBOSMF7.mjs +33 -0
  47. package/dist/chunk-4GBOSMF7.mjs.map +1 -0
  48. package/dist/chunk-4IKNNAVC.mjs +30 -0
  49. package/dist/chunk-4IKNNAVC.mjs.map +1 -0
  50. package/dist/chunk-4UMDRHDR.js +95 -0
  51. package/dist/chunk-4UMDRHDR.js.map +1 -0
  52. package/dist/chunk-6CTV7VW5.mjs +20 -0
  53. package/dist/chunk-6CTV7VW5.mjs.map +1 -0
  54. package/dist/chunk-6H32HLTZ.js +10 -0
  55. package/dist/chunk-6H32HLTZ.js.map +1 -0
  56. package/dist/chunk-6WBLB5BX.js +9 -0
  57. package/dist/chunk-6WBLB5BX.js.map +1 -0
  58. package/dist/chunk-7H5TGXZ5.js +70 -0
  59. package/dist/chunk-7H5TGXZ5.js.map +1 -0
  60. package/dist/chunk-7KKLGQNE.js +38 -0
  61. package/dist/chunk-7KKLGQNE.js.map +1 -0
  62. package/dist/chunk-7PNGOFLU.js +22 -0
  63. package/dist/chunk-7PNGOFLU.js.map +1 -0
  64. package/dist/chunk-7T3N2ZGQ.mjs +107 -0
  65. package/dist/chunk-7T3N2ZGQ.mjs.map +1 -0
  66. package/dist/chunk-7XA5VYYV.mjs +9 -0
  67. package/dist/chunk-7XA5VYYV.mjs.map +1 -0
  68. package/dist/chunk-B2DMAQNK.mjs +8 -0
  69. package/dist/chunk-B2DMAQNK.mjs.map +1 -0
  70. package/dist/chunk-B3YQVRPE.js +107 -0
  71. package/dist/chunk-B3YQVRPE.js.map +1 -0
  72. package/dist/chunk-DK3IYVMP.mjs +1 -0
  73. package/dist/chunk-DK3IYVMP.mjs.map +1 -0
  74. package/dist/chunk-DKSB4FMW.mjs +74 -0
  75. package/dist/chunk-DKSB4FMW.mjs.map +1 -0
  76. package/dist/chunk-F33RMB76.js +69 -0
  77. package/dist/chunk-F33RMB76.js.map +1 -0
  78. package/dist/chunk-FJH6DDEL.mjs +193 -0
  79. package/dist/chunk-FJH6DDEL.mjs.map +1 -0
  80. package/dist/chunk-FTY3BOF7.js +9 -0
  81. package/dist/chunk-FTY3BOF7.js.map +1 -0
  82. package/dist/chunk-GK4IJQVW.js +409 -0
  83. package/dist/chunk-GK4IJQVW.js.map +1 -0
  84. package/dist/chunk-GMC2A3D7.js +211 -0
  85. package/dist/chunk-GMC2A3D7.js.map +1 -0
  86. package/dist/chunk-GW5NQXN4.mjs +151 -0
  87. package/dist/chunk-GW5NQXN4.mjs.map +1 -0
  88. package/dist/chunk-H34N3OWO.mjs +169 -0
  89. package/dist/chunk-H34N3OWO.mjs.map +1 -0
  90. package/dist/chunk-H636DAOG.js +193 -0
  91. package/dist/chunk-H636DAOG.js.map +1 -0
  92. package/dist/chunk-HOTDTMNP.mjs +21 -0
  93. package/dist/chunk-HOTDTMNP.mjs.map +1 -0
  94. package/dist/chunk-HWFLO7W5.mjs +281 -0
  95. package/dist/chunk-HWFLO7W5.mjs.map +1 -0
  96. package/dist/chunk-I3BUOULW.js +18 -0
  97. package/dist/chunk-I3BUOULW.js.map +1 -0
  98. package/dist/chunk-IIDK6BRC.mjs +1 -0
  99. package/dist/chunk-IIDK6BRC.mjs.map +1 -0
  100. package/dist/chunk-IUNNN6HN.mjs +29 -0
  101. package/dist/chunk-IUNNN6HN.mjs.map +1 -0
  102. package/dist/chunk-IWENO6LT.js +20 -0
  103. package/dist/chunk-IWENO6LT.js.map +1 -0
  104. package/dist/chunk-JGMGNLZW.mjs +38 -0
  105. package/dist/chunk-JGMGNLZW.mjs.map +1 -0
  106. package/dist/chunk-JV7OA3FD.js +1 -0
  107. package/dist/chunk-JV7OA3FD.js.map +1 -0
  108. package/dist/chunk-KEXZDQAN.js +50 -0
  109. package/dist/chunk-KEXZDQAN.js.map +1 -0
  110. package/dist/chunk-KWQKGJSV.js +152 -0
  111. package/dist/chunk-KWQKGJSV.js.map +1 -0
  112. package/dist/chunk-LEFOMYX3.mjs +1 -0
  113. package/dist/chunk-LEFOMYX3.mjs.map +1 -0
  114. package/dist/chunk-LHIPBIPS.mjs +32 -0
  115. package/dist/chunk-LHIPBIPS.mjs.map +1 -0
  116. package/dist/chunk-LOW2T4MV.mjs +50 -0
  117. package/dist/chunk-LOW2T4MV.mjs.map +1 -0
  118. package/dist/chunk-MJABESWH.js +20 -0
  119. package/dist/chunk-MJABESWH.js.map +1 -0
  120. package/dist/chunk-MSUZTHYT.js +9 -0
  121. package/dist/chunk-MSUZTHYT.js.map +1 -0
  122. package/dist/chunk-MYSBDK36.mjs +1 -0
  123. package/dist/chunk-MYSBDK36.mjs.map +1 -0
  124. package/dist/chunk-N52KMB25.mjs +109 -0
  125. package/dist/chunk-N52KMB25.mjs.map +1 -0
  126. package/dist/chunk-O3XKEEJV.mjs +249 -0
  127. package/dist/chunk-O3XKEEJV.mjs.map +1 -0
  128. package/dist/chunk-O4PW77JW.mjs +1 -0
  129. package/dist/chunk-O4PW77JW.mjs.map +1 -0
  130. package/dist/chunk-OQSLMZJN.js +281 -0
  131. package/dist/chunk-OQSLMZJN.js.map +1 -0
  132. package/dist/chunk-P5V6S2PA.mjs +69 -0
  133. package/dist/chunk-P5V6S2PA.mjs.map +1 -0
  134. package/dist/chunk-PHUTP7NB.js +25 -0
  135. package/dist/chunk-PHUTP7NB.js.map +1 -0
  136. package/dist/chunk-Q5T57UNN.js +1 -0
  137. package/dist/chunk-Q5T57UNN.js.map +1 -0
  138. package/dist/chunk-Q7FGULTV.js +8 -0
  139. package/dist/chunk-Q7FGULTV.js.map +1 -0
  140. package/dist/chunk-QF3LHIJ5.mjs +9 -0
  141. package/dist/chunk-QF3LHIJ5.mjs.map +1 -0
  142. package/dist/chunk-QJTAFTW7.js +30 -0
  143. package/dist/chunk-QJTAFTW7.js.map +1 -0
  144. package/dist/chunk-QWEXXUTO.mjs +10 -0
  145. package/dist/chunk-QWEXXUTO.mjs.map +1 -0
  146. package/dist/chunk-QYFDFOWT.js +41 -0
  147. package/dist/chunk-QYFDFOWT.js.map +1 -0
  148. package/dist/chunk-R4BBIGBN.js +18 -0
  149. package/dist/chunk-R4BBIGBN.js.map +1 -0
  150. package/dist/chunk-R7UAMO2U.js +21 -0
  151. package/dist/chunk-R7UAMO2U.js.map +1 -0
  152. package/dist/chunk-RRPU7M4Y.js +29 -0
  153. package/dist/chunk-RRPU7M4Y.js.map +1 -0
  154. package/dist/chunk-RS5HE55U.js +109 -0
  155. package/dist/chunk-RS5HE55U.js.map +1 -0
  156. package/dist/chunk-TUAHXE75.mjs +21 -0
  157. package/dist/chunk-TUAHXE75.mjs.map +1 -0
  158. package/dist/chunk-TURGGK5F.mjs +59 -0
  159. package/dist/chunk-TURGGK5F.mjs.map +1 -0
  160. package/dist/chunk-UGQQ5DJ4.mjs +50 -0
  161. package/dist/chunk-UGQQ5DJ4.mjs.map +1 -0
  162. package/dist/chunk-VGWELVCX.mjs +18 -0
  163. package/dist/chunk-VGWELVCX.mjs.map +1 -0
  164. package/dist/chunk-VMUXXXJC.js +103 -0
  165. package/dist/chunk-VMUXXXJC.js.map +1 -0
  166. package/dist/chunk-WDGBH5CP.js +249 -0
  167. package/dist/chunk-WDGBH5CP.js.map +1 -0
  168. package/dist/chunk-WJOAEPZ7.js +30 -0
  169. package/dist/chunk-WJOAEPZ7.js.map +1 -0
  170. package/dist/chunk-XC5E26VE.mjs +20 -0
  171. package/dist/chunk-XC5E26VE.mjs.map +1 -0
  172. package/dist/chunk-XDEHYKW2.js +1 -0
  173. package/dist/chunk-XDEHYKW2.js.map +1 -0
  174. package/dist/chunk-XEY3KVEH.js +21 -0
  175. package/dist/chunk-XEY3KVEH.js.map +1 -0
  176. package/dist/chunk-XKXHM3PC.mjs +9 -0
  177. package/dist/chunk-XKXHM3PC.mjs.map +1 -0
  178. package/dist/chunk-XRGYWWT7.js +151 -0
  179. package/dist/chunk-XRGYWWT7.js.map +1 -0
  180. package/dist/chunk-XWFKTDB3.js +50 -0
  181. package/dist/chunk-XWFKTDB3.js.map +1 -0
  182. package/dist/chunk-Y3F7VUZB.mjs +409 -0
  183. package/dist/chunk-Y3F7VUZB.mjs.map +1 -0
  184. package/dist/chunk-YF4PGFCO.js +1 -0
  185. package/dist/chunk-YF4PGFCO.js.map +1 -0
  186. package/dist/chunk-YLT6CNSL.mjs +64 -0
  187. package/dist/chunk-YLT6CNSL.mjs.map +1 -0
  188. package/dist/chunk-Z4J4GUGG.mjs +152 -0
  189. package/dist/chunk-Z4J4GUGG.mjs.map +1 -0
  190. package/dist/chunk-ZLFA4R5X.js +56 -0
  191. package/dist/chunk-ZLFA4R5X.js.map +1 -0
  192. package/dist/chunk-ZRVOIW3H.js +74 -0
  193. package/dist/chunk-ZRVOIW3H.js.map +1 -0
  194. package/dist/chunk-ZVXX2CTH.mjs +95 -0
  195. package/dist/chunk-ZVXX2CTH.mjs.map +1 -0
  196. package/dist/chunk-ZXCNX3ZB.mjs +70 -0
  197. package/dist/chunk-ZXCNX3ZB.mjs.map +1 -0
  198. package/dist/cronjob.js +20 -0
  199. package/dist/cronjob.js.map +1 -0
  200. package/dist/cronjob.mjs +20 -0
  201. package/dist/cronjob.mjs.map +1 -0
  202. package/dist/deep-clone.js +8 -0
  203. package/dist/deep-clone.js.map +1 -0
  204. package/dist/deep-clone.mjs +8 -0
  205. package/dist/deep-clone.mjs.map +1 -0
  206. package/dist/default-endowments.js +8 -0
  207. package/dist/default-endowments.js.map +1 -0
  208. package/dist/default-endowments.mjs +8 -0
  209. package/dist/default-endowments.mjs.map +1 -0
  210. package/dist/derivation-paths.js +13 -0
  211. package/dist/derivation-paths.js.map +1 -0
  212. package/dist/derivation-paths.mjs +13 -0
  213. package/dist/derivation-paths.mjs.map +1 -0
  214. package/dist/entropy.js +10 -0
  215. package/dist/entropy.js.map +1 -0
  216. package/dist/entropy.mjs +10 -0
  217. package/dist/entropy.mjs.map +1 -0
  218. package/dist/errors.js +20 -0
  219. package/dist/errors.js.map +1 -0
  220. package/dist/errors.mjs +20 -0
  221. package/dist/errors.mjs.map +1 -0
  222. package/dist/eval-worker.js +43 -0
  223. package/dist/eval-worker.js.map +1 -0
  224. package/dist/eval-worker.mjs +43 -0
  225. package/dist/eval-worker.mjs.map +1 -0
  226. package/dist/eval.js +17 -0
  227. package/dist/eval.js.map +1 -0
  228. package/dist/eval.mjs +17 -0
  229. package/dist/eval.mjs.map +1 -0
  230. package/dist/fs.js +28 -0
  231. package/dist/fs.js.map +1 -0
  232. package/dist/fs.mjs +28 -0
  233. package/dist/fs.mjs.map +1 -0
  234. package/dist/handler-types.js +10 -0
  235. package/dist/handler-types.js.map +1 -0
  236. package/dist/handler-types.mjs +10 -0
  237. package/dist/handler-types.mjs.map +1 -0
  238. package/dist/handlers.js +35 -0
  239. package/dist/handlers.js.map +1 -0
  240. package/dist/handlers.mjs +35 -0
  241. package/dist/handlers.mjs.map +1 -0
  242. package/dist/icon.js +14 -0
  243. package/dist/icon.js.map +1 -0
  244. package/dist/icon.mjs +14 -0
  245. package/dist/icon.mjs.map +1 -0
  246. package/dist/iframe.js +8 -0
  247. package/dist/iframe.js.map +1 -0
  248. package/dist/iframe.mjs +8 -0
  249. package/dist/iframe.mjs.map +1 -0
  250. package/dist/index.executionenv.js +134 -0
  251. package/dist/index.executionenv.js.map +1 -0
  252. package/dist/index.executionenv.mjs +134 -0
  253. package/dist/index.executionenv.mjs.map +1 -0
  254. package/dist/index.js +378 -0
  255. package/dist/index.js.map +1 -0
  256. package/dist/index.mjs +378 -0
  257. package/dist/index.mjs.map +1 -0
  258. package/dist/json-rpc.js +18 -0
  259. package/dist/json-rpc.js.map +1 -0
  260. package/dist/json-rpc.mjs +18 -0
  261. package/dist/json-rpc.mjs.map +1 -0
  262. package/dist/json.js +8 -0
  263. package/dist/json.js.map +1 -0
  264. package/dist/json.mjs +8 -0
  265. package/dist/json.mjs.map +1 -0
  266. package/dist/localization.js +23 -0
  267. package/dist/localization.js.map +1 -0
  268. package/dist/localization.mjs +23 -0
  269. package/dist/localization.mjs.map +1 -0
  270. package/dist/logging.js +14 -0
  271. package/dist/logging.js.map +1 -0
  272. package/dist/logging.mjs +14 -0
  273. package/dist/logging.mjs.map +1 -0
  274. package/dist/manifest/index.js +59 -0
  275. package/dist/manifest/index.js.map +1 -0
  276. package/dist/manifest/index.mjs +59 -0
  277. package/dist/manifest/index.mjs.map +1 -0
  278. package/dist/manifest/manifest.js +42 -0
  279. package/dist/manifest/manifest.js.map +1 -0
  280. package/dist/manifest/manifest.mjs +42 -0
  281. package/dist/manifest/manifest.mjs.map +1 -0
  282. package/dist/manifest/node.js +85 -0
  283. package/dist/manifest/node.js.map +1 -0
  284. package/dist/manifest/node.mjs +85 -0
  285. package/dist/manifest/node.mjs.map +1 -0
  286. package/dist/manifest/validation.js +58 -0
  287. package/dist/manifest/validation.js.map +1 -0
  288. package/dist/manifest/validation.mjs +58 -0
  289. package/dist/manifest/validation.mjs.map +1 -0
  290. package/dist/mock.js +13 -0
  291. package/dist/mock.js.map +1 -0
  292. package/dist/mock.mjs +13 -0
  293. package/dist/mock.mjs.map +1 -0
  294. package/dist/namespace.js +44 -0
  295. package/dist/namespace.js.map +1 -0
  296. package/dist/namespace.mjs +44 -0
  297. package/dist/namespace.mjs.map +1 -0
  298. package/dist/node.js +448 -0
  299. package/dist/node.js.map +1 -0
  300. package/dist/node.mjs +448 -0
  301. package/dist/node.mjs.map +1 -0
  302. package/dist/npm.js +32 -0
  303. package/dist/npm.js.map +1 -0
  304. package/dist/npm.mjs +32 -0
  305. package/dist/npm.mjs.map +1 -0
  306. package/dist/path.js +8 -0
  307. package/dist/path.js.map +1 -0
  308. package/dist/path.mjs +8 -0
  309. package/dist/path.mjs.map +1 -0
  310. package/dist/post-process.js +10 -0
  311. package/dist/post-process.js.map +1 -0
  312. package/dist/post-process.mjs +10 -0
  313. package/dist/post-process.mjs.map +1 -0
  314. package/dist/snaps.js +48 -0
  315. package/dist/snaps.js.map +1 -0
  316. package/dist/snaps.mjs +48 -0
  317. package/dist/snaps.mjs.map +1 -0
  318. package/dist/strings.js +8 -0
  319. package/dist/strings.js.map +1 -0
  320. package/dist/strings.mjs +8 -0
  321. package/dist/strings.mjs.map +1 -0
  322. package/dist/structs.js +31 -0
  323. package/dist/structs.js.map +1 -0
  324. package/dist/structs.mjs +31 -0
  325. package/dist/structs.mjs.map +1 -0
  326. package/dist/tsconfig.build.tsbuildinfo +1 -0
  327. package/dist/types/bytes.d.ts +1 -1
  328. package/dist/types/checksum.d.ts +1 -1
  329. package/dist/types/icon.d.ts +16 -1
  330. package/dist/types/index.d.ts +1 -6
  331. package/dist/types/json-rpc.d.ts +1 -1
  332. package/dist/types/localization.d.ts +1 -1
  333. package/dist/types/manifest/index.d.ts +0 -1
  334. package/dist/types/manifest/manifest.d.ts +1 -1
  335. package/dist/types/manifest/node.d.ts +2 -0
  336. package/dist/types/manifest/validation.d.ts +5 -5
  337. package/dist/types/node.d.ts +8 -0
  338. package/dist/types/post-process.d.ts +1 -1
  339. package/dist/types/structs.d.ts +0 -20
  340. package/dist/types/ui.d.ts +7 -0
  341. package/dist/types/virtual-file/index.d.ts +0 -1
  342. package/dist/types/virtual-file/node.d.ts +2 -0
  343. package/dist/types.js +28 -0
  344. package/dist/types.js.map +1 -0
  345. package/dist/types.mjs +28 -0
  346. package/dist/types.mjs.map +1 -0
  347. package/dist/ui.js +12 -0
  348. package/dist/ui.js.map +1 -0
  349. package/dist/ui.mjs +12 -0
  350. package/dist/ui.mjs.map +1 -0
  351. package/dist/validation.js +24 -0
  352. package/dist/validation.js.map +1 -0
  353. package/dist/validation.mjs +24 -0
  354. package/dist/validation.mjs.map +1 -0
  355. package/dist/versions.js +12 -0
  356. package/dist/versions.js.map +1 -0
  357. package/dist/versions.mjs +12 -0
  358. package/dist/versions.mjs.map +1 -0
  359. package/dist/virtual-file/VirtualFile.js +9 -0
  360. package/dist/virtual-file/VirtualFile.js.map +1 -0
  361. package/dist/virtual-file/VirtualFile.mjs +9 -0
  362. package/dist/virtual-file/VirtualFile.mjs.map +1 -0
  363. package/dist/virtual-file/index.js +10 -0
  364. package/dist/virtual-file/index.js.map +1 -0
  365. package/dist/virtual-file/index.mjs +10 -0
  366. package/dist/virtual-file/index.mjs.map +1 -0
  367. package/dist/virtual-file/node.js +17 -0
  368. package/dist/virtual-file/node.js.map +1 -0
  369. package/dist/virtual-file/node.mjs +17 -0
  370. package/dist/virtual-file/node.mjs.map +1 -0
  371. package/dist/virtual-file/toVirtualFile.js +12 -0
  372. package/dist/virtual-file/toVirtualFile.js.map +1 -0
  373. package/dist/virtual-file/toVirtualFile.mjs +12 -0
  374. package/dist/virtual-file/toVirtualFile.mjs.map +1 -0
  375. package/package.json +24 -40
  376. package/dist/cjs/array.js +0 -23
  377. package/dist/cjs/array.js.map +0 -1
  378. package/dist/cjs/auxiliary-files.js +0 -27
  379. package/dist/cjs/auxiliary-files.js.map +0 -1
  380. package/dist/cjs/base64.js +0 -44
  381. package/dist/cjs/base64.js.map +0 -1
  382. package/dist/cjs/bytes.js +0 -23
  383. package/dist/cjs/bytes.js.map +0 -1
  384. package/dist/cjs/caveats.js +0 -48
  385. package/dist/cjs/caveats.js.map +0 -1
  386. package/dist/cjs/checksum.js +0 -43
  387. package/dist/cjs/checksum.js.map +0 -1
  388. package/dist/cjs/cronjob.js +0 -77
  389. package/dist/cjs/cronjob.js.map +0 -1
  390. package/dist/cjs/deep-clone.js +0 -22
  391. package/dist/cjs/deep-clone.js.map +0 -1
  392. package/dist/cjs/default-endowments.js +0 -49
  393. package/dist/cjs/default-endowments.js.map +0 -1
  394. package/dist/cjs/derivation-paths.js +0 -300
  395. package/dist/cjs/derivation-paths.js.map +0 -1
  396. package/dist/cjs/entropy.js +0 -23
  397. package/dist/cjs/entropy.js.map +0 -1
  398. package/dist/cjs/errors.js +0 -221
  399. package/dist/cjs/errors.js.map +0 -1
  400. package/dist/cjs/eval-worker.js +0 -44
  401. package/dist/cjs/eval-worker.js.map +0 -1
  402. package/dist/cjs/eval.js +0 -77
  403. package/dist/cjs/eval.js.map +0 -1
  404. package/dist/cjs/fs.js +0 -126
  405. package/dist/cjs/fs.js.map +0 -1
  406. package/dist/cjs/handler-types.js +0 -34
  407. package/dist/cjs/handler-types.js.map +0 -1
  408. package/dist/cjs/handlers.js +0 -173
  409. package/dist/cjs/handlers.js.map +0 -1
  410. package/dist/cjs/icon.js +0 -37
  411. package/dist/cjs/icon.js.map +0 -1
  412. package/dist/cjs/iframe.js +0 -59
  413. package/dist/cjs/iframe.js.map +0 -1
  414. package/dist/cjs/index.browser.js +0 -49
  415. package/dist/cjs/index.browser.js.map +0 -1
  416. package/dist/cjs/index.executionenv.js +0 -27
  417. package/dist/cjs/index.executionenv.js.map +0 -1
  418. package/dist/cjs/index.js +0 -54
  419. package/dist/cjs/index.js.map +0 -1
  420. package/dist/cjs/json-rpc.js +0 -81
  421. package/dist/cjs/json-rpc.js.map +0 -1
  422. package/dist/cjs/json.js +0 -16
  423. package/dist/cjs/json.js.map +0 -1
  424. package/dist/cjs/localization.js +0 -113
  425. package/dist/cjs/localization.js.map +0 -1
  426. package/dist/cjs/logging.js +0 -40
  427. package/dist/cjs/logging.js.map +0 -1
  428. package/dist/cjs/manifest/index.browser.js +0 -20
  429. package/dist/cjs/manifest/index.browser.js.map +0 -1
  430. package/dist/cjs/manifest/index.js +0 -21
  431. package/dist/cjs/manifest/index.js.map +0 -1
  432. package/dist/cjs/manifest/manifest.js +0 -275
  433. package/dist/cjs/manifest/manifest.js.map +0 -1
  434. package/dist/cjs/manifest/validation.js +0 -244
  435. package/dist/cjs/manifest/validation.js.map +0 -1
  436. package/dist/cjs/mock.js +0 -128
  437. package/dist/cjs/mock.js.map +0 -1
  438. package/dist/cjs/namespace.js +0 -136
  439. package/dist/cjs/namespace.js.map +0 -1
  440. package/dist/cjs/npm.js +0 -96
  441. package/dist/cjs/npm.js.map +0 -1
  442. package/dist/cjs/path.js +0 -21
  443. package/dist/cjs/path.js.map +0 -1
  444. package/dist/cjs/post-process.js +0 -328
  445. package/dist/cjs/post-process.js.map +0 -1
  446. package/dist/cjs/snaps.js +0 -232
  447. package/dist/cjs/snaps.js.map +0 -1
  448. package/dist/cjs/strings.js +0 -21
  449. package/dist/cjs/strings.js.map +0 -1
  450. package/dist/cjs/structs.js +0 -210
  451. package/dist/cjs/structs.js.map +0 -1
  452. package/dist/cjs/types.js +0 -104
  453. package/dist/cjs/types.js.map +0 -1
  454. package/dist/cjs/ui.js +0 -53
  455. package/dist/cjs/ui.js.map +0 -1
  456. package/dist/cjs/validation.js +0 -24
  457. package/dist/cjs/validation.js.map +0 -1
  458. package/dist/cjs/versions.js +0 -47
  459. package/dist/cjs/versions.js.map +0 -1
  460. package/dist/cjs/virtual-file/VirtualFile.js +0 -92
  461. package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
  462. package/dist/cjs/virtual-file/index.browser.js +0 -20
  463. package/dist/cjs/virtual-file/index.browser.js.map +0 -1
  464. package/dist/cjs/virtual-file/index.js +0 -21
  465. package/dist/cjs/virtual-file/index.js.map +0 -1
  466. package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
  467. package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
  468. package/dist/esm/array.js +0 -13
  469. package/dist/esm/array.js.map +0 -1
  470. package/dist/esm/auxiliary-files.js +0 -23
  471. package/dist/esm/auxiliary-files.js.map +0 -1
  472. package/dist/esm/base64.js +0 -36
  473. package/dist/esm/base64.js.map +0 -1
  474. package/dist/esm/bytes.js +0 -18
  475. package/dist/esm/bytes.js.map +0 -1
  476. package/dist/esm/caveats.js +0 -38
  477. package/dist/esm/caveats.js.map +0 -1
  478. package/dist/esm/checksum.js +0 -41
  479. package/dist/esm/checksum.js.map +0 -1
  480. package/dist/esm/cronjob.js +0 -59
  481. package/dist/esm/cronjob.js.map +0 -1
  482. package/dist/esm/deep-clone.js +0 -7
  483. package/dist/esm/deep-clone.js.map +0 -1
  484. package/dist/esm/default-endowments.js +0 -39
  485. package/dist/esm/default-endowments.js.map +0 -1
  486. package/dist/esm/derivation-paths.js +0 -287
  487. package/dist/esm/derivation-paths.js.map +0 -1
  488. package/dist/esm/entropy.js +0 -6
  489. package/dist/esm/entropy.js.map +0 -1
  490. package/dist/esm/errors.js +0 -211
  491. package/dist/esm/errors.js.map +0 -1
  492. package/dist/esm/eval-worker.js +0 -40
  493. package/dist/esm/eval-worker.js.map +0 -1
  494. package/dist/esm/eval.js +0 -65
  495. package/dist/esm/eval.js.map +0 -1
  496. package/dist/esm/fs.js +0 -136
  497. package/dist/esm/fs.js.map +0 -1
  498. package/dist/esm/handler-types.js +0 -16
  499. package/dist/esm/handler-types.js.map +0 -1
  500. package/dist/esm/handlers.js +0 -119
  501. package/dist/esm/handlers.js.map +0 -1
  502. package/dist/esm/icon.js +0 -11
  503. package/dist/esm/icon.js.map +0 -1
  504. package/dist/esm/iframe.js +0 -49
  505. package/dist/esm/iframe.js.map +0 -1
  506. package/dist/esm/index.browser.js +0 -32
  507. package/dist/esm/index.browser.js.map +0 -1
  508. package/dist/esm/index.executionenv.js +0 -10
  509. package/dist/esm/index.executionenv.js.map +0 -1
  510. package/dist/esm/index.js +0 -37
  511. package/dist/esm/index.js.map +0 -1
  512. package/dist/esm/json-rpc.js +0 -79
  513. package/dist/esm/json-rpc.js.map +0 -1
  514. package/dist/esm/json.js +0 -17
  515. package/dist/esm/json.js.map +0 -1
  516. package/dist/esm/localization.js +0 -115
  517. package/dist/esm/localization.js.map +0 -1
  518. package/dist/esm/logging.js +0 -59
  519. package/dist/esm/logging.js.map +0 -1
  520. package/dist/esm/manifest/index.browser.js +0 -3
  521. package/dist/esm/manifest/index.browser.js.map +0 -1
  522. package/dist/esm/manifest/index.js +0 -4
  523. package/dist/esm/manifest/index.js.map +0 -1
  524. package/dist/esm/manifest/manifest.js +0 -299
  525. package/dist/esm/manifest/manifest.js.map +0 -1
  526. package/dist/esm/manifest/validation.js +0 -190
  527. package/dist/esm/manifest/validation.js.map +0 -1
  528. package/dist/esm/mock.js +0 -111
  529. package/dist/esm/mock.js.map +0 -1
  530. package/dist/esm/namespace.js +0 -113
  531. package/dist/esm/namespace.js.map +0 -1
  532. package/dist/esm/npm.js +0 -85
  533. package/dist/esm/npm.js.map +0 -1
  534. package/dist/esm/path.js +0 -17
  535. package/dist/esm/path.js.map +0 -1
  536. package/dist/esm/post-process.js +0 -333
  537. package/dist/esm/post-process.js.map +0 -1
  538. package/dist/esm/snaps.js +0 -217
  539. package/dist/esm/snaps.js.map +0 -1
  540. package/dist/esm/strings.js +0 -11
  541. package/dist/esm/strings.js.map +0 -1
  542. package/dist/esm/structs.js +0 -295
  543. package/dist/esm/structs.js.map +0 -1
  544. package/dist/esm/types.js +0 -78
  545. package/dist/esm/types.js.map +0 -1
  546. package/dist/esm/ui.js +0 -50
  547. package/dist/esm/ui.js.map +0 -1
  548. package/dist/esm/validation.js +0 -19
  549. package/dist/esm/validation.js.map +0 -1
  550. package/dist/esm/versions.js +0 -41
  551. package/dist/esm/versions.js.map +0 -1
  552. package/dist/esm/virtual-file/VirtualFile.js +0 -82
  553. package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
  554. package/dist/esm/virtual-file/index.browser.js +0 -3
  555. package/dist/esm/virtual-file/index.browser.js.map +0 -1
  556. package/dist/esm/virtual-file/index.js +0 -4
  557. package/dist/esm/virtual-file/index.js.map +0 -1
  558. package/dist/esm/virtual-file/toVirtualFile.js +0 -26
  559. package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
  560. package/dist/types/index.browser.d.ts +0 -30
  561. package/dist/types/manifest/index.browser.d.ts +0 -1
  562. package/dist/types/virtual-file/index.browser.d.ts +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","auxiliaryFiles","localizationFiles","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAQA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AACrC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,aAAa,QAAQ,aAAa;AAI3C,SAASC,cAAc,EAAEC,2BAA2B,EAAEC,GAAG,QAAQ,UAAU;AAG3E,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,m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G,WACPA,OAAOC,IAAI,KAAKrF,eAAesF,OAAO,IACtCpG,SAASkG,OAAOvD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAesF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
@@ -1,11 +0,0 @@
1
- /**
2
- * Indent a message by adding a number of spaces to the beginning of each line.
3
- *
4
- * @param message - The message to indent.
5
- * @param spaces - The number of spaces to indent by. Defaults to 2.
6
- * @returns The indented message.
7
- */ export function indent(message, spaces = 2) {
8
- return message.replace(/^/gmu, ' '.repeat(spaces));
9
- }
10
-
11
- //# sourceMappingURL=strings.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/strings.ts"],"sourcesContent":["/**\n * Indent a message by adding a number of spaces to the beginning of each line.\n *\n * @param message - The message to indent.\n * @param spaces - The number of spaces to indent by. Defaults to 2.\n * @returns The indented message.\n */\nexport function indent(message: string, spaces = 2) {\n return message.replace(/^/gmu, ' '.repeat(spaces));\n}\n"],"names":["indent","message","spaces","replace","repeat"],"mappings":"AAAA;;;;;;CAMC,GACD,OAAO,SAASA,OAAOC,OAAe,EAAEC,SAAS,CAAC;IAChD,OAAOD,QAAQE,OAAO,CAAC,QAAQ,IAAIC,MAAM,CAACF;AAC5C"}
@@ -1,295 +0,0 @@
1
- import { union } from '@metamask/snaps-sdk';
2
- import { assert, isObject } from '@metamask/utils';
3
- import { bold, green, red } from 'chalk';
4
- import { resolve } from 'path';
5
- import { is, validate, type as superstructType, Struct, StructError, create, string, coerce as superstructCoerce } from 'superstruct';
6
- import { indent } from './strings';
7
- /**
8
- * Colorize a value with a color function. This is useful for colorizing values
9
- * in error messages. If colorization is disabled, the original value is
10
- * returned.
11
- *
12
- * @param value - The value to colorize.
13
- * @param colorFunction - The color function to use.
14
- * @param enabled - Whether to colorize the value.
15
- * @returns The colorized value, or the original value if colorization is
16
- * disabled.
17
- */ function color(value, colorFunction, enabled) {
18
- if (enabled) {
19
- return colorFunction(value);
20
- }
21
- return value;
22
- }
23
- /**
24
- * A wrapper of `superstruct`'s `string` struct that coerces a value to a string
25
- * and resolves it relative to the current working directory. This is useful
26
- * for specifying file paths in a configuration file, as it allows the user to
27
- * use both relative and absolute paths.
28
- *
29
- * @returns The `superstruct` struct, which validates that the value is a
30
- * string, and resolves it relative to the current working directory.
31
- * @example
32
- * ```ts
33
- * const config = struct({
34
- * file: file(),
35
- * // ...
36
- * });
37
- *
38
- * const value = create({ file: 'path/to/file' }, config);
39
- * console.log(value.file); // /process/cwd/path/to/file
40
- * ```
41
- */ export function file() {
42
- return superstructCoerce(string(), string(), (value)=>{
43
- return resolve(process.cwd(), value);
44
- });
45
- }
46
- /**
47
- * Define a struct, and also define the name of the struct as the given name.
48
- *
49
- * This is useful for improving the error messages returned by `superstruct`.
50
- *
51
- * @param name - The name of the struct.
52
- * @param struct - The struct.
53
- * @returns The struct.
54
- */ export function named(name, struct) {
55
- return new Struct({
56
- ...struct,
57
- type: name
58
- });
59
- }
60
- export class SnapsStructError extends StructError {
61
- constructor(struct, prefix, suffix, failure, failures, colorize = true){
62
- super(failure, failures);
63
- this.name = 'SnapsStructError';
64
- this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
65
- ...failures()
66
- ], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
67
- }
68
- }
69
- /**
70
- * Converts an array to a generator function that yields the items in the
71
- * array.
72
- *
73
- * @param array - The array.
74
- * @returns A generator function.
75
- * @yields The items in the array.
76
- */ export function* arrayToGenerator(array) {
77
- for (const item of array){
78
- yield item;
79
- }
80
- }
81
- /**
82
- * Returns a `SnapsStructError` with the given prefix and suffix.
83
- *
84
- * @param options - The options.
85
- * @param options.struct - The struct that caused the error.
86
- * @param options.prefix - The prefix to add to the error message.
87
- * @param options.suffix - The suffix to add to the error message. Defaults to
88
- * an empty string.
89
- * @param options.error - The `superstruct` error to wrap.
90
- * @param options.colorize - Whether to colorize the value. Defaults to `true`.
91
- * @returns The `SnapsStructError`.
92
- */ export function getError({ struct, prefix, suffix = '', error, colorize }) {
93
- return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
94
- }
95
- /**
96
- * A wrapper of `superstruct`'s `create` function that throws a
97
- * `SnapsStructError` instead of a `StructError`. This is useful for improving
98
- * the error messages returned by `superstruct`.
99
- *
100
- * @param value - The value to validate.
101
- * @param struct - The `superstruct` struct to validate the value against.
102
- * @param prefix - The prefix to add to the error message.
103
- * @param suffix - The suffix to add to the error message. Defaults to an empty
104
- * string.
105
- * @returns The validated value.
106
- */ export function createFromStruct(value, struct, prefix, suffix = '') {
107
- try {
108
- return create(value, struct);
109
- } catch (error) {
110
- if (error instanceof StructError) {
111
- throw getError({
112
- struct,
113
- prefix,
114
- suffix,
115
- error
116
- });
117
- }
118
- throw error;
119
- }
120
- }
121
- /**
122
- * Get a struct from a failure path.
123
- *
124
- * @param struct - The struct.
125
- * @param path - The failure path.
126
- * @returns The struct at the failure path.
127
- */ export function getStructFromPath(struct, path) {
128
- return path.reduce((result, key)=>{
129
- if (isObject(struct.schema) && struct.schema[key]) {
130
- return struct.schema[key];
131
- }
132
- return result;
133
- }, struct);
134
- }
135
- /**
136
- * Get the union struct names from a struct.
137
- *
138
- * @param struct - The struct.
139
- * @param colorize - Whether to colorize the value. Defaults to `true`.
140
- * @returns The union struct names, or `null` if the struct is not a union
141
- * struct.
142
- */ export function getUnionStructNames(struct, colorize = true) {
143
- if (Array.isArray(struct.schema)) {
144
- return struct.schema.map(({ type })=>color(type, green, colorize));
145
- }
146
- return null;
147
- }
148
- /**
149
- * Get an error prefix from a `superstruct` failure. This is useful for
150
- * formatting the error message returned by `superstruct`.
151
- *
152
- * @param failure - The `superstruct` failure.
153
- * @param colorize - Whether to colorize the value. Defaults to `true`.
154
- * @returns The error prefix.
155
- */ export function getStructErrorPrefix(failure, colorize = true) {
156
- if (failure.type === 'never' || failure.path.length === 0) {
157
- return '';
158
- }
159
- return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;
160
- }
161
- /**
162
- * Get a string describing the failure. This is similar to the `message`
163
- * property of `superstruct`'s `Failure` type, but formats the value in a more
164
- * readable way.
165
- *
166
- * @param struct - The struct that caused the failure.
167
- * @param failure - The `superstruct` failure.
168
- * @param colorize - Whether to colorize the value. Defaults to `true`.
169
- * @returns A string describing the failure.
170
- */ export function getStructFailureMessage(struct, failure, colorize = true) {
171
- const received = color(JSON.stringify(failure.value), red, colorize);
172
- const prefix = getStructErrorPrefix(failure, colorize);
173
- if (failure.type === 'union') {
174
- const childStruct = getStructFromPath(struct, failure.path);
175
- const unionNames = getUnionStructNames(childStruct, colorize);
176
- if (unionNames) {
177
- return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
178
- }
179
- return `${prefix}${failure.message}.`;
180
- }
181
- if (failure.type === 'literal') {
182
- // Superstruct's failure does not provide information about which literal
183
- // value was expected, so we need to parse the message to get the literal.
184
- const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', red, colorize)}`);
185
- return `${prefix}${message}.`;
186
- }
187
- if (failure.type === 'never') {
188
- return `Unknown key: ${color(failure.path.join('.'), bold, colorize)}, received: ${received}.`;
189
- }
190
- if (failure.refinement === 'size') {
191
- const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', green, colorize)} and ${color('$2', green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', red, colorize)}`).replace(/a array/u, 'an array');
192
- return `${prefix}${message}.`;
193
- }
194
- return `${prefix}Expected a value of type ${color(failure.type, green, colorize)}, but received: ${received}.`;
195
- }
196
- /**
197
- * Get a string describing the errors. This formats all the errors in a
198
- * human-readable way.
199
- *
200
- * @param struct - The struct that caused the failures.
201
- * @param failures - The `superstruct` failures.
202
- * @param colorize - Whether to colorize the value. Defaults to `true`.
203
- * @returns A string describing the errors.
204
- */ export function getStructErrorMessage(struct, failures, colorize = true) {
205
- const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure, colorize)}`));
206
- return formattedFailures.join('\n');
207
- }
208
- /**
209
- * Validate a union struct, and throw readable errors if the value does not
210
- * satisfy the struct. This is useful for improving the error messages returned
211
- * by `superstruct`.
212
- *
213
- * @param value - The value to validate.
214
- * @param struct - The `superstruct` union struct to validate the value against.
215
- * This struct must be a union of object structs, and must have at least one
216
- * shared key to validate against.
217
- * @param structKey - The key to validate against. This key must be present in
218
- * all the object structs in the union struct, and is expected to be a literal
219
- * value.
220
- * @param coerce - Whether to coerce the value to satisfy the struct. Defaults
221
- * to `false`.
222
- * @returns The validated value.
223
- * @throws If the value does not satisfy the struct.
224
- * @example
225
- * const struct = union([
226
- * object({ type: literal('a'), value: string() }),
227
- * object({ type: literal('b'), value: number() }),
228
- * object({ type: literal('c'), value: boolean() }),
229
- * // ...
230
- * ]);
231
- *
232
- * // At path: type — Expected the value to be one of: "a", "b", "c", but received: "d".
233
- * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');
234
- *
235
- * // At path: value — Expected a value of type string, but received: 42.
236
- * validateUnion({ type: 'a', value: 42 }, struct, 'value');
237
- */ export function validateUnion(value, struct, structKey, coerce = false) {
238
- assert(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
239
- assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');
240
- const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
241
- const key = superstructType({
242
- [structKey]: union(keyUnion)
243
- });
244
- const [keyError] = validate(value, key, {
245
- coerce
246
- });
247
- if (keyError) {
248
- throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
249
- }
250
- // At this point it's guaranteed that the value is an object, so we can safely
251
- // cast it to a Record.
252
- const objectValue = value;
253
- const objectStructs = struct.schema.filter((innerStruct)=>is(objectValue[structKey], innerStruct.schema[structKey]));
254
- assert(objectStructs.length > 0, 'Expected a struct to match the value.');
255
- // We need to validate the value against all the object structs that match the
256
- // struct key, and return the first validated value.
257
- const validationResults = objectStructs.map((objectStruct)=>validate(objectValue, objectStruct, {
258
- coerce
259
- }));
260
- const validatedValue = validationResults.find(([error])=>!error);
261
- if (validatedValue) {
262
- return validatedValue[1];
263
- }
264
- assert(validationResults[0][0], 'Expected at least one error.');
265
- // If there is no validated value, we need to find the error with the least
266
- // number of failures (with the assumption that it's the most specific error).
267
- const validationError = validationResults.reduce((error, [innerError])=>{
268
- assert(innerError, 'Expected an error.');
269
- if (innerError.failures().length < error.failures().length) {
270
- return innerError;
271
- }
272
- return error;
273
- }, validationResults[0][0]);
274
- throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
275
- }
276
- /**
277
- * Create a value with the coercion logic of a union struct, and throw readable
278
- * errors if the value does not satisfy the struct. This is useful for improving
279
- * the error messages returned by `superstruct`.
280
- *
281
- * @param value - The value to validate.
282
- * @param struct - The `superstruct` union struct to validate the value against.
283
- * This struct must be a union of object structs, and must have at least one
284
- * shared key to validate against.
285
- * @param structKey - The key to validate against. This key must be present in
286
- * all the object structs in the union struct, and is expected to be a literal
287
- * value.
288
- * @returns The validated value.
289
- * @throws If the value does not satisfy the struct.
290
- * @see validateUnion
291
- */ export function createUnion(value, struct, structKey) {
292
- return validateUnion(value, struct, structKey, true);
293
- }
294
-
295
- //# sourceMappingURL=structs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { union } from '@metamask/snaps-sdk';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport {\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n string,\n coerce as superstructCoerce,\n} from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * Colorize a value with a color function. This is useful for colorizing values\n * in error messages. If colorization is disabled, the original value is\n * returned.\n *\n * @param value - The value to colorize.\n * @param colorFunction - The color function to use.\n * @param enabled - Whether to colorize the value.\n * @returns The colorized value, or the original value if colorization is\n * disabled.\n */\nfunction color(\n value: string,\n colorFunction: (value: string) => string,\n enabled: boolean,\n) {\n if (enabled) {\n return colorFunction(value);\n }\n\n return value;\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return superstructCoerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n colorize = true,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(\n struct,\n [...failures()],\n colorize,\n )}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n colorize?: boolean;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @param options.colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n colorize,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(\n struct,\n prefix,\n suffix,\n error,\n () => arrayToGenerator(error.failures()),\n colorize,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n colorize = true,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => color(type, green, colorize));\n }\n\n return null;\n}\n\n/**\n * Get an error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure, colorize = true) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n colorize = true,\n) {\n const received = color(JSON.stringify(failure.value), red, colorize);\n const prefix = getStructErrorPrefix(failure, colorize);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct, colorize);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(\n /the literal `(.+)`,/u,\n `the value to be \\`${color('$1', green, colorize)}\\`,`,\n )\n .replace(\n /, but received: (.+)/u,\n `, but received: ${color('$1', red, colorize)}`,\n );\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${color(\n failure.path.join('.'),\n bold,\n colorize,\n )}, received: ${received}.`;\n }\n\n if (failure.refinement === 'size') {\n const message = failure.message\n .replace(\n /length between `(\\d+)` and `(\\d+)`/u,\n `length between ${color('$1', green, colorize)} and ${color(\n '$2',\n green,\n colorize,\n )},`,\n )\n .replace(/length of `(\\d+)`/u, `length of ${color('$1', red, colorize)}`)\n .replace(/a array/u, 'an array');\n\n return `${prefix}${message}.`;\n }\n\n return `${prefix}Expected a value of type ${color(\n failure.type,\n green,\n colorize,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n colorize = true,\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure, colorize)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n\n/**\n * Validate a union struct, and throw readable errors if the value does not\n * satisfy the struct. This is useful for improving the error messages returned\n * by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @param coerce - Whether to coerce the value to satisfy the struct. Defaults\n * to `false`.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @example\n * const struct = union([\n * object({ type: literal('a'), value: string() }),\n * object({ type: literal('b'), value: number() }),\n * object({ type: literal('c'), value: boolean() }),\n * // ...\n * ]);\n *\n * // At path: type — Expected the value to be one of: \"a\", \"b\", \"c\", but received: \"d\".\n * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');\n *\n * // At path: value — Expected a value of type string, but received: 42.\n * validateUnion({ type: 'a', value: 42 }, struct, 'value');\n */\nexport function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n coerce = false,\n) {\n assert(\n struct.schema,\n 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.',\n );\n assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');\n\n const keyUnion = struct.schema.map(\n (innerStruct) => innerStruct.schema[structKey],\n // This is guaranteed to be a non-empty array by the assertion above. We\n // need to cast it since `superstruct` requires a non-empty array of structs\n // for the `union` struct.\n ) as NonEmptyArray<Struct>;\n\n const key = superstructType({\n [structKey]: union(keyUnion),\n });\n\n const [keyError] = validate(value, key, { coerce });\n if (keyError) {\n throw new Error(\n getStructFailureMessage(key, keyError.failures()[0], false),\n );\n }\n\n // At this point it's guaranteed that the value is an object, so we can safely\n // cast it to a Record.\n const objectValue = value as Record<PropertyKey, unknown>;\n const objectStructs = struct.schema.filter((innerStruct) =>\n is(objectValue[structKey], innerStruct.schema[structKey]),\n );\n\n assert(objectStructs.length > 0, 'Expected a struct to match the value.');\n\n // We need to validate the value against all the object structs that match the\n // struct key, and return the first validated value.\n const validationResults = objectStructs.map((objectStruct) =>\n validate(objectValue, objectStruct, { coerce }),\n );\n\n const validatedValue = validationResults.find(([error]) => !error);\n if (validatedValue) {\n return validatedValue[1];\n }\n\n assert(validationResults[0][0], 'Expected at least one error.');\n\n // If there is no validated value, we need to find the error with the least\n // number of failures (with the assumption that it's the most specific error).\n const validationError = validationResults.reduce((error, [innerError]) => {\n assert(innerError, 'Expected an error.');\n if (innerError.failures().length < error.failures().length) {\n return innerError;\n }\n\n return error;\n }, validationResults[0][0]);\n\n throw new Error(\n getStructFailureMessage(struct, validationError.failures()[0], false),\n );\n}\n\n/**\n * Create a value with the coercion logic of a union struct, and throw readable\n * errors if the value does not satisfy the struct. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @see validateUnion\n */\nexport function createUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n) {\n return validateUnion(value, struct, structKey, true);\n}\n"],"names":["union","assert","isObject","bold","green","red","resolve","is","validate","type","superstructType","Struct","StructError","create","string","coerce","superstructCoerce","indent","color","value","colorFunction","enabled","file","process","cwd","named","name","struct","SnapsStructError","constructor","prefix","suffix","failure","failures","colorize","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","schema","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","JSON","stringify","childStruct","unionNames","replace","refinement","formattedFailures","validateUnion","structKey","keyUnion","innerStruct","keyError","Error","objectValue","objectStructs","filter","validationResults","objectStruct","validatedValue","find","validationError","innerError","createUnion"],"mappings":"AAAA,SAASA,KAAK,QAAQ,sBAAsB;AAE5C,SAASC,MAAM,EAAEC,QAAQ,QAAQ,kBAAkB;AACnD,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SACEC,EAAE,EACFC,QAAQ,EACRC,QAAQC,eAAJ,EACJC,MAAM,EACNC,WAAW,EACXC,MAAM,EACNC,MAAM,EACNC,UAAUC,iBAAiB,QACtB,cAAc;AAGrB,SAASC,MAAM,QAAQ,YAAY;AA6BnC;;;;;;;;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c;YAAE5D;QAAO;IAG/C,MAAM6D,iBAAiBF,kBAAkBG,IAAI,CAAC,CAAC,CAACpC,MAAM,GAAK,CAACA;IAC5D,IAAImC,gBAAgB;QAClB,OAAOA,cAAc,CAAC,EAAE;IAC1B;IAEA3E,OAAOyE,iBAAiB,CAAC,EAAE,CAAC,EAAE,EAAE;IAEhC,2EAA2E;IAC3E,8EAA8E;IAC9E,MAAMI,kBAAkBJ,kBAAkB7B,MAAM,CAAC,CAACJ,OAAO,CAACsC,WAAW;QACnE9E,OAAO8E,YAAY;QACnB,IAAIA,WAAW9C,QAAQ,GAAGqB,MAAM,GAAGb,MAAMR,QAAQ,GAAGqB,MAAM,EAAE;YAC1D,OAAOyB;QACT;QAEA,OAAOtC;IACT,GAAGiC,iBAAiB,CAAC,EAAE,CAAC,EAAE;IAE1B,MAAM,IAAIJ,MACRd,wBAAwB7B,QAAQmD,gBAAgB7C,QAAQ,EAAE,CAAC,EAAE,EAAE;AAEnE;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAAS+C,YACd7D,KAAc,EACdQ,MAA4B,EAC5BuC,SAAqB;IAErB,OAAOD,cAAc9C,OAAOQ,QAAQuC,WAAW;AACjD"}
package/dist/esm/types.js DELETED
@@ -1,78 +0,0 @@
1
- import { assertStruct, VersionStruct } from '@metamask/utils';
2
- import { instance, is, object, optional, pattern, refine, size, string, type, union, assert as assertSuperstruct } from 'superstruct';
3
- export var NpmSnapFileNames;
4
- (function(NpmSnapFileNames) {
5
- NpmSnapFileNames["PackageJson"] = 'package.json';
6
- NpmSnapFileNames["Manifest"] = 'snap.manifest.json';
7
- })(NpmSnapFileNames || (NpmSnapFileNames = {}));
8
- export const NameStruct = size(pattern(string(), /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/u), 1, 214);
9
- // Note we use `type` instead of `object` here, because the latter does not
10
- // allow unknown keys.
11
- export const NpmSnapPackageJsonStruct = type({
12
- version: VersionStruct,
13
- name: NameStruct,
14
- main: optional(size(string(), 1, Infinity)),
15
- repository: optional(object({
16
- type: size(string(), 1, Infinity),
17
- url: size(string(), 1, Infinity)
18
- }))
19
- });
20
- /**
21
- * Check if the given value is a valid {@link NpmSnapPackageJson} object.
22
- *
23
- * @param value - The value to check.
24
- * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.
25
- */ export function isNpmSnapPackageJson(value) {
26
- return is(value, NpmSnapPackageJsonStruct);
27
- }
28
- /**
29
- * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.
30
- *
31
- * @param value - The value to check.
32
- * @throws If the value is not a valid {@link NpmSnapPackageJson} object.
33
- */ export function assertIsNpmSnapPackageJson(value) {
34
- assertStruct(value, NpmSnapPackageJsonStruct, `"${NpmSnapFileNames.PackageJson}" is invalid`);
35
- }
36
- export var SnapIdPrefixes;
37
- (function(SnapIdPrefixes) {
38
- SnapIdPrefixes["npm"] = 'npm:';
39
- SnapIdPrefixes["local"] = 'local:';
40
- })(SnapIdPrefixes || (SnapIdPrefixes = {}));
41
- export var SnapValidationFailureReason;
42
- (function(SnapValidationFailureReason) {
43
- SnapValidationFailureReason["NameMismatch"] = '"name" field mismatch';
44
- SnapValidationFailureReason["VersionMismatch"] = '"version" field mismatch';
45
- SnapValidationFailureReason["RepositoryMismatch"] = '"repository" field mismatch';
46
- SnapValidationFailureReason["ShasumMismatch"] = '"shasum" field mismatch';
47
- })(SnapValidationFailureReason || (SnapValidationFailureReason = {}));
48
- export var SNAP_STREAM_NAMES;
49
- (function(SNAP_STREAM_NAMES) {
50
- SNAP_STREAM_NAMES["JSON_RPC"] = 'jsonRpc';
51
- SNAP_STREAM_NAMES["COMMAND"] = 'command';
52
- })(SNAP_STREAM_NAMES || (SNAP_STREAM_NAMES = {}));
53
- export const uri = (opts = {})=>refine(union([
54
- string(),
55
- instance(URL)
56
- ]), 'uri', (value)=>{
57
- try {
58
- const url = new URL(value);
59
- const UrlStruct = type(opts);
60
- assertSuperstruct(url, UrlStruct);
61
- return true;
62
- } catch {
63
- return `Expected URL, got "${value.toString()}".`;
64
- }
65
- });
66
- /**
67
- * Returns whether a given value is a valid URL.
68
- *
69
- * @param url - The value to check.
70
- * @param opts - Optional constraints for url checking.
71
- * @returns Whether `url` is valid URL or not.
72
- */ export function isValidUrl(url, opts = {}) {
73
- return is(url, uri(opts));
74
- }
75
- // redefining here to avoid circular dependency
76
- export const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';
77
-
78
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile<LocalizationFile>[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles' | 'localizationFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["assertStruct","VersionStruct","instance","is","object","optional","pattern","refine","size","string","type","union","assert","assertSuperstruct","NpmSnapFileNames","PackageJson","Manifest","NameStruct","NpmSnapPackageJsonStruct","version","name","main","Infinity","repository","url","isNpmSnapPackageJson","value","assertIsNpmSnapPackageJson","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON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C,CAAC,GAC5CjC,OAAOI,MAAM;QAACF;QAAUP,SAASuC;KAAK,GAAG,OAAO,CAACf;QAC/C,IAAI;YACF,MAAMF,MAAM,IAAIiB,IAAIf;YAEpB,MAAMgB,YAAYhC,KAAK8B;YACvB3B,kBAAkBW,KAAKkB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEhB,MAAMiB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF,GAAG;AAEL;;;;;;CAMC,GACD,OAAO,SAASC,WACdpB,GAAY,EACZgB,OAAwB,CAAC,CAAC;IAE1B,OAAOrC,GAAGqB,KAAKe,IAAIC;AACrB;AAEA,+CAA+C;AAC/C,OAAO,MAAMK,6BAA6B,cAAc"}
package/dist/esm/ui.js DELETED
@@ -1,50 +0,0 @@
1
- import { NodeType } from '@metamask/snaps-sdk';
2
- import { assert, AssertionError } from '@metamask/utils';
3
- const MARKDOWN_LINK_REGEX = RegExp("\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)", "giu");
4
- const ALLOWED_PROTOCOLS = [
5
- 'https:',
6
- 'mailto:'
7
- ];
8
- /**
9
- * Searches for markdown links in a string and checks them against the phishing list.
10
- *
11
- * @param text - The text to verify.
12
- * @param isOnPhishingList - The function that checks the link against the
13
- * phishing list.
14
- * @throws If the text contains a link that is not allowed.
15
- */ export function validateTextLinks(text, isOnPhishingList) {
16
- const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);
17
- for (const { groups } of matches){
18
- const link = groups?.url;
19
- /* This case should never happen with the regex but the TS type allows for undefined */ /* istanbul ignore next */ if (!link) {
20
- continue;
21
- }
22
- try {
23
- const url = new URL(link);
24
- assert(ALLOWED_PROTOCOLS.includes(url.protocol), `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`);
25
- const hostname = url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;
26
- assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');
27
- } catch (error) {
28
- throw new Error(`Invalid URL: ${error instanceof AssertionError ? error.message : 'Unable to parse URL.'}`);
29
- }
30
- }
31
- }
32
- /**
33
- * Search for links in UI components and check that the URL they are trying to
34
- * pass in is not in the phishing list.
35
- *
36
- * @param component - The custom UI component.
37
- * @param isOnPhishingList - The function that checks the link against the
38
- * phishing list.
39
- * @throws If the component contains a link that is not allowed.
40
- */ export function validateComponentLinks(component, isOnPhishingList) {
41
- const { type } = component;
42
- if (type === NodeType.Panel) {
43
- component.children.forEach((node)=>validateComponentLinks(node, isOnPhishingList));
44
- }
45
- if (type === NodeType.Text) {
46
- validateTextLinks(component.value, isOnPhishingList);
47
- }
48
- }
49
-
50
- //# sourceMappingURL=ui.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError } from '@metamask/utils';\n\nconst MARKDOWN_LINK_REGEX = /\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)/giu;\n\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Searches for markdown links in a string and checks them against the phishing list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);\n\n for (const { groups } of matches) {\n const link = groups?.url;\n\n /* This case should never happen with the regex but the TS type allows for undefined */\n /* istanbul ignore next */\n if (!link) {\n continue;\n }\n\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError\n ? error.message\n : 'Unable to parse URL.'\n }`,\n );\n }\n }\n}\n\n/**\n * Search for links in UI components and check that the URL they are trying to\n * pass in is not in the phishing list.\n *\n * @param component - The custom UI component.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the component contains a link that is not allowed.\n */\nexport function validateComponentLinks(\n component: Component,\n isOnPhishingList: (url: string) => boolean,\n) {\n const { type } = component;\n if (type === NodeType.Panel) {\n component.children.forEach((node) =>\n validateComponentLinks(node, isOnPhishingList),\n );\n }\n\n if (type === NodeType.Text) {\n validateTextLinks(component.value, isOnPhishingList);\n }\n}\n"],"names":["NodeType","assert","AssertionError","MARKDOWN_LINK_REGEX","ALLOWED_PROTOCOLS","validateTextLinks","text","isOnPhishingList","matches","String","prototype","matchAll","call","groups","link","url","URL","includes","protocol","join","hostname","pathname","split","error","Error","message","validateComponentLinks","component","type","Panel","children","forEach","node","Text","value"],"mappings":"AACA,SAASA,QAAQ,QAAQ,sBAAsB;AAC/C,SAASC,MAAM,EAAEC,cAAc,QAAQ,kBAAkB;AAEzD,MAAMC,sBAAsB;AAE5B,MAAMC,oBAAoB;IAAC;IAAU;CAAU;AAE/C;;;;;;;CAOC,GACD,OAAO,SAASC,kBACdC,IAAY,EACZC,gBAA0C;IAE1C,MAAMC,UAAUC,OAAOC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACN,MAAMH;IAErD,KAAK,MAAM,EAAEU,MAAM,EAAE,IAAIL,QAAS;QAChC,MAAMM,OAAOD,QAAQE;QAErB,qFAAqF,GACrF,wBAAwB,GACxB,IAAI,CAACD,MAAM;YACT;QACF;QAEA,IAAI;YACF,MAAMC,MAAM,IAAIC,IAAIF;YACpBb,OACEG,kBAAkBa,QAAQ,CAACF,IAAIG,QAAQ,GACvC,CAAC,yBAAyB,EAAEd,kBAAkBe,IAAI,CAAC,MAAM,CAAC,CAAC;YAG7D,MAAMC,WACJL,IAAIG,QAAQ,KAAK,YAAYH,IAAIM,QAAQ,CAACC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAGP,IAAIK,QAAQ;YAExEnB,OAAO,CAACM,iBAAiBa,WAAW;QACtC,EAAE,OAAOG,OAAO;YACd,MAAM,IAAIC,MACR,CAAC,aAAa,EACZD,iBAAiBrB,iBACbqB,MAAME,OAAO,GACb,uBACL,CAAC;QAEN;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,uBACdC,SAAoB,EACpBpB,gBAA0C;IAE1C,MAAM,EAAEqB,IAAI,EAAE,GAAGD;IACjB,IAAIC,SAAS5B,SAAS6B,KAAK,EAAE;QAC3BF,UAAUG,QAAQ,CAACC,OAAO,CAAC,CAACC,OAC1BN,uBAAuBM,MAAMzB;IAEjC;IAEA,IAAIqB,SAAS5B,SAASiC,IAAI,EAAE;QAC1B5B,kBAAkBsB,UAAUO,KAAK,EAAE3B;IACrC;AACF"}
@@ -1,19 +0,0 @@
1
- import { assertIsSnapIcon } from './icon';
2
- import { validateSnapManifestLocalizations } from './localization';
3
- import { assertIsSnapManifest } from './manifest/validation';
4
- import { validateSnapShasum } from './snaps';
5
- /**
6
- * Validates the files contained in a fetched snap.
7
- *
8
- * @param files - All potentially included files in a fetched snap.
9
- * @throws If any of the files are considered invalid.
10
- */ export async function validateFetchedSnap(files) {
11
- assertIsSnapManifest(files.manifest.result);
12
- await validateSnapShasum(files);
13
- validateSnapManifestLocalizations(files.manifest.result, files.localizationFiles.map((file)=>file.result));
14
- if (files.svgIcon) {
15
- assertIsSnapIcon(files.svgIcon);
16
- }
17
- }
18
-
19
- //# sourceMappingURL=validation.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateSnapManifestLocalizations } from './localization';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport async function validateFetchedSnap(\n files: FetchedSnapFiles,\n): Promise<void> {\n assertIsSnapManifest(files.manifest.result);\n await validateSnapShasum(files);\n validateSnapManifestLocalizations(\n files.manifest.result,\n files.localizationFiles.map((file) => file.result),\n );\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["assertIsSnapIcon","validateSnapManifestLocalizations","assertIsSnapManifest","validateSnapShasum","validateFetchedSnap","files","manifest","result","localizationFiles","map","file","svgIcon"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,iCAAiC,QAAQ,iBAAiB;AACnE,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,kBAAkB,QAAQ,UAAU;AAG7C;;;;;CAKC,GACD,OAAO,eAAeC,oBACpBC,KAAuB;IAEvBH,qBAAqBG,MAAMC,QAAQ,CAACC,MAAM;IAC1C,MAAMJ,mBAAmBE;IACzBJ,kCACEI,MAAMC,QAAQ,CAACC,MAAM,EACrBF,MAAMG,iBAAiB,CAACC,GAAG,CAAC,CAACC,OAASA,KAAKH,MAAM;IAGnD,IAAIF,MAAMM,OAAO,EAAE;QACjBX,iBAAiBK,MAAMM,OAAO;IAChC;AACF"}
@@ -1,41 +0,0 @@
1
- import { VersionRangeStruct } from '@metamask/utils';
2
- import { maxSatisfying as maxSatisfyingSemver } from 'semver';
3
- import { validate } from 'superstruct';
4
- export const DEFAULT_REQUESTED_SNAP_VERSION = '*';
5
- /**
6
- * Return the highest version in the list that satisfies the range, or `null` if
7
- * none of them do. For the satisfaction check, pre-release versions will only
8
- * be checked if no satisfactory non-prerelease version is found first.
9
- *
10
- * @param versions - The list of version to check.
11
- * @param versionRange - The SemVer version range to check against.
12
- * @returns The highest version in the list that satisfies the range,
13
- * or `null` if none of them do.
14
- */ export function getTargetVersion(versions, versionRange) {
15
- const maxSatisfyingNonPreRelease = maxSatisfyingSemver(versions, versionRange);
16
- // By default don't use pre-release versions
17
- if (maxSatisfyingNonPreRelease) {
18
- return maxSatisfyingNonPreRelease;
19
- }
20
- // If no satisfying release version is found by default, try pre-release versions
21
- return maxSatisfyingSemver(versions, versionRange, {
22
- includePrerelease: true
23
- });
24
- }
25
- /**
26
- * Parse a version received by some subject attempting to access a snap.
27
- *
28
- * @param version - The received version value.
29
- * @returns `*` if the version is `undefined` or `latest", otherwise returns
30
- * the specified version.
31
- */ export function resolveVersionRange(version) {
32
- if (version === undefined || version === 'latest') {
33
- return [
34
- undefined,
35
- DEFAULT_REQUESTED_SNAP_VERSION
36
- ];
37
- }
38
- return validate(version, VersionRangeStruct);
39
- }
40
-
41
- //# sourceMappingURL=versions.js.map