@metamask/snaps-utils 6.1.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 (560) hide show
  1. package/CHANGELOG.md +18 -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/index.d.ts +1 -6
  330. package/dist/types/json-rpc.d.ts +1 -1
  331. package/dist/types/localization.d.ts +1 -1
  332. package/dist/types/manifest/index.d.ts +0 -1
  333. package/dist/types/manifest/manifest.d.ts +1 -1
  334. package/dist/types/manifest/node.d.ts +2 -0
  335. package/dist/types/manifest/validation.d.ts +5 -5
  336. package/dist/types/node.d.ts +8 -0
  337. package/dist/types/structs.d.ts +0 -20
  338. package/dist/types/ui.d.ts +7 -0
  339. package/dist/types/virtual-file/index.d.ts +0 -1
  340. package/dist/types/virtual-file/node.d.ts +2 -0
  341. package/dist/types.js +28 -0
  342. package/dist/types.js.map +1 -0
  343. package/dist/types.mjs +28 -0
  344. package/dist/types.mjs.map +1 -0
  345. package/dist/ui.js +12 -0
  346. package/dist/ui.js.map +1 -0
  347. package/dist/ui.mjs +12 -0
  348. package/dist/ui.mjs.map +1 -0
  349. package/dist/validation.js +24 -0
  350. package/dist/validation.js.map +1 -0
  351. package/dist/validation.mjs +24 -0
  352. package/dist/validation.mjs.map +1 -0
  353. package/dist/versions.js +12 -0
  354. package/dist/versions.js.map +1 -0
  355. package/dist/versions.mjs +12 -0
  356. package/dist/versions.mjs.map +1 -0
  357. package/dist/virtual-file/VirtualFile.js +9 -0
  358. package/dist/virtual-file/VirtualFile.js.map +1 -0
  359. package/dist/virtual-file/VirtualFile.mjs +9 -0
  360. package/dist/virtual-file/VirtualFile.mjs.map +1 -0
  361. package/dist/virtual-file/index.js +10 -0
  362. package/dist/virtual-file/index.js.map +1 -0
  363. package/dist/virtual-file/index.mjs +10 -0
  364. package/dist/virtual-file/index.mjs.map +1 -0
  365. package/dist/virtual-file/node.js +17 -0
  366. package/dist/virtual-file/node.js.map +1 -0
  367. package/dist/virtual-file/node.mjs +17 -0
  368. package/dist/virtual-file/node.mjs.map +1 -0
  369. package/dist/virtual-file/toVirtualFile.js +12 -0
  370. package/dist/virtual-file/toVirtualFile.js.map +1 -0
  371. package/dist/virtual-file/toVirtualFile.mjs +12 -0
  372. package/dist/virtual-file/toVirtualFile.mjs.map +1 -0
  373. package/package.json +23 -38
  374. package/dist/cjs/array.js +0 -23
  375. package/dist/cjs/array.js.map +0 -1
  376. package/dist/cjs/auxiliary-files.js +0 -27
  377. package/dist/cjs/auxiliary-files.js.map +0 -1
  378. package/dist/cjs/base64.js +0 -44
  379. package/dist/cjs/base64.js.map +0 -1
  380. package/dist/cjs/bytes.js +0 -23
  381. package/dist/cjs/bytes.js.map +0 -1
  382. package/dist/cjs/caveats.js +0 -48
  383. package/dist/cjs/caveats.js.map +0 -1
  384. package/dist/cjs/checksum.js +0 -43
  385. package/dist/cjs/checksum.js.map +0 -1
  386. package/dist/cjs/cronjob.js +0 -77
  387. package/dist/cjs/cronjob.js.map +0 -1
  388. package/dist/cjs/deep-clone.js +0 -22
  389. package/dist/cjs/deep-clone.js.map +0 -1
  390. package/dist/cjs/default-endowments.js +0 -49
  391. package/dist/cjs/default-endowments.js.map +0 -1
  392. package/dist/cjs/derivation-paths.js +0 -300
  393. package/dist/cjs/derivation-paths.js.map +0 -1
  394. package/dist/cjs/entropy.js +0 -23
  395. package/dist/cjs/entropy.js.map +0 -1
  396. package/dist/cjs/errors.js +0 -221
  397. package/dist/cjs/errors.js.map +0 -1
  398. package/dist/cjs/eval-worker.js +0 -44
  399. package/dist/cjs/eval-worker.js.map +0 -1
  400. package/dist/cjs/eval.js +0 -77
  401. package/dist/cjs/eval.js.map +0 -1
  402. package/dist/cjs/fs.js +0 -126
  403. package/dist/cjs/fs.js.map +0 -1
  404. package/dist/cjs/handler-types.js +0 -34
  405. package/dist/cjs/handler-types.js.map +0 -1
  406. package/dist/cjs/handlers.js +0 -173
  407. package/dist/cjs/handlers.js.map +0 -1
  408. package/dist/cjs/icon.js +0 -66
  409. package/dist/cjs/icon.js.map +0 -1
  410. package/dist/cjs/iframe.js +0 -59
  411. package/dist/cjs/iframe.js.map +0 -1
  412. package/dist/cjs/index.browser.js +0 -49
  413. package/dist/cjs/index.browser.js.map +0 -1
  414. package/dist/cjs/index.executionenv.js +0 -27
  415. package/dist/cjs/index.executionenv.js.map +0 -1
  416. package/dist/cjs/index.js +0 -54
  417. package/dist/cjs/index.js.map +0 -1
  418. package/dist/cjs/json-rpc.js +0 -81
  419. package/dist/cjs/json-rpc.js.map +0 -1
  420. package/dist/cjs/json.js +0 -16
  421. package/dist/cjs/json.js.map +0 -1
  422. package/dist/cjs/localization.js +0 -113
  423. package/dist/cjs/localization.js.map +0 -1
  424. package/dist/cjs/logging.js +0 -40
  425. package/dist/cjs/logging.js.map +0 -1
  426. package/dist/cjs/manifest/index.browser.js +0 -20
  427. package/dist/cjs/manifest/index.browser.js.map +0 -1
  428. package/dist/cjs/manifest/index.js +0 -21
  429. package/dist/cjs/manifest/index.js.map +0 -1
  430. package/dist/cjs/manifest/manifest.js +0 -283
  431. package/dist/cjs/manifest/manifest.js.map +0 -1
  432. package/dist/cjs/manifest/validation.js +0 -244
  433. package/dist/cjs/manifest/validation.js.map +0 -1
  434. package/dist/cjs/mock.js +0 -128
  435. package/dist/cjs/mock.js.map +0 -1
  436. package/dist/cjs/namespace.js +0 -136
  437. package/dist/cjs/namespace.js.map +0 -1
  438. package/dist/cjs/npm.js +0 -96
  439. package/dist/cjs/npm.js.map +0 -1
  440. package/dist/cjs/path.js +0 -21
  441. package/dist/cjs/path.js.map +0 -1
  442. package/dist/cjs/post-process.js +0 -328
  443. package/dist/cjs/post-process.js.map +0 -1
  444. package/dist/cjs/snaps.js +0 -232
  445. package/dist/cjs/snaps.js.map +0 -1
  446. package/dist/cjs/strings.js +0 -21
  447. package/dist/cjs/strings.js.map +0 -1
  448. package/dist/cjs/structs.js +0 -210
  449. package/dist/cjs/structs.js.map +0 -1
  450. package/dist/cjs/types.js +0 -104
  451. package/dist/cjs/types.js.map +0 -1
  452. package/dist/cjs/ui.js +0 -53
  453. package/dist/cjs/ui.js.map +0 -1
  454. package/dist/cjs/validation.js +0 -24
  455. package/dist/cjs/validation.js.map +0 -1
  456. package/dist/cjs/versions.js +0 -47
  457. package/dist/cjs/versions.js.map +0 -1
  458. package/dist/cjs/virtual-file/VirtualFile.js +0 -92
  459. package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
  460. package/dist/cjs/virtual-file/index.browser.js +0 -20
  461. package/dist/cjs/virtual-file/index.browser.js.map +0 -1
  462. package/dist/cjs/virtual-file/index.js +0 -21
  463. package/dist/cjs/virtual-file/index.js.map +0 -1
  464. package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
  465. package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
  466. package/dist/esm/array.js +0 -13
  467. package/dist/esm/array.js.map +0 -1
  468. package/dist/esm/auxiliary-files.js +0 -23
  469. package/dist/esm/auxiliary-files.js.map +0 -1
  470. package/dist/esm/base64.js +0 -36
  471. package/dist/esm/base64.js.map +0 -1
  472. package/dist/esm/bytes.js +0 -18
  473. package/dist/esm/bytes.js.map +0 -1
  474. package/dist/esm/caveats.js +0 -38
  475. package/dist/esm/caveats.js.map +0 -1
  476. package/dist/esm/checksum.js +0 -41
  477. package/dist/esm/checksum.js.map +0 -1
  478. package/dist/esm/cronjob.js +0 -59
  479. package/dist/esm/cronjob.js.map +0 -1
  480. package/dist/esm/deep-clone.js +0 -7
  481. package/dist/esm/deep-clone.js.map +0 -1
  482. package/dist/esm/default-endowments.js +0 -39
  483. package/dist/esm/default-endowments.js.map +0 -1
  484. package/dist/esm/derivation-paths.js +0 -287
  485. package/dist/esm/derivation-paths.js.map +0 -1
  486. package/dist/esm/entropy.js +0 -6
  487. package/dist/esm/entropy.js.map +0 -1
  488. package/dist/esm/errors.js +0 -211
  489. package/dist/esm/errors.js.map +0 -1
  490. package/dist/esm/eval-worker.js +0 -40
  491. package/dist/esm/eval-worker.js.map +0 -1
  492. package/dist/esm/eval.js +0 -65
  493. package/dist/esm/eval.js.map +0 -1
  494. package/dist/esm/fs.js +0 -136
  495. package/dist/esm/fs.js.map +0 -1
  496. package/dist/esm/handler-types.js +0 -16
  497. package/dist/esm/handler-types.js.map +0 -1
  498. package/dist/esm/handlers.js +0 -119
  499. package/dist/esm/handlers.js.map +0 -1
  500. package/dist/esm/icon.js +0 -51
  501. package/dist/esm/icon.js.map +0 -1
  502. package/dist/esm/iframe.js +0 -49
  503. package/dist/esm/iframe.js.map +0 -1
  504. package/dist/esm/index.browser.js +0 -32
  505. package/dist/esm/index.browser.js.map +0 -1
  506. package/dist/esm/index.executionenv.js +0 -10
  507. package/dist/esm/index.executionenv.js.map +0 -1
  508. package/dist/esm/index.js +0 -37
  509. package/dist/esm/index.js.map +0 -1
  510. package/dist/esm/json-rpc.js +0 -79
  511. package/dist/esm/json-rpc.js.map +0 -1
  512. package/dist/esm/json.js +0 -17
  513. package/dist/esm/json.js.map +0 -1
  514. package/dist/esm/localization.js +0 -115
  515. package/dist/esm/localization.js.map +0 -1
  516. package/dist/esm/logging.js +0 -59
  517. package/dist/esm/logging.js.map +0 -1
  518. package/dist/esm/manifest/index.browser.js +0 -3
  519. package/dist/esm/manifest/index.browser.js.map +0 -1
  520. package/dist/esm/manifest/index.js +0 -4
  521. package/dist/esm/manifest/index.js.map +0 -1
  522. package/dist/esm/manifest/manifest.js +0 -307
  523. package/dist/esm/manifest/manifest.js.map +0 -1
  524. package/dist/esm/manifest/validation.js +0 -190
  525. package/dist/esm/manifest/validation.js.map +0 -1
  526. package/dist/esm/mock.js +0 -111
  527. package/dist/esm/mock.js.map +0 -1
  528. package/dist/esm/namespace.js +0 -113
  529. package/dist/esm/namespace.js.map +0 -1
  530. package/dist/esm/npm.js +0 -85
  531. package/dist/esm/npm.js.map +0 -1
  532. package/dist/esm/path.js +0 -17
  533. package/dist/esm/path.js.map +0 -1
  534. package/dist/esm/post-process.js +0 -333
  535. package/dist/esm/post-process.js.map +0 -1
  536. package/dist/esm/snaps.js +0 -217
  537. package/dist/esm/snaps.js.map +0 -1
  538. package/dist/esm/strings.js +0 -11
  539. package/dist/esm/strings.js.map +0 -1
  540. package/dist/esm/structs.js +0 -295
  541. package/dist/esm/structs.js.map +0 -1
  542. package/dist/esm/types.js +0 -78
  543. package/dist/esm/types.js.map +0 -1
  544. package/dist/esm/ui.js +0 -50
  545. package/dist/esm/ui.js.map +0 -1
  546. package/dist/esm/validation.js +0 -19
  547. package/dist/esm/validation.js.map +0 -1
  548. package/dist/esm/versions.js +0 -41
  549. package/dist/esm/versions.js.map +0 -1
  550. package/dist/esm/virtual-file/VirtualFile.js +0 -82
  551. package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
  552. package/dist/esm/virtual-file/index.browser.js +0 -3
  553. package/dist/esm/virtual-file/index.browser.js.map +0 -1
  554. package/dist/esm/virtual-file/index.js +0 -4
  555. package/dist/esm/virtual-file/index.js.map +0 -1
  556. package/dist/esm/virtual-file/toVirtualFile.js +0 -26
  557. package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
  558. package/dist/types/index.browser.d.ts +0 -30
  559. package/dist/types/manifest/index.browser.d.ts +0 -1
  560. package/dist/types/virtual-file/index.browser.d.ts +0 -1
@@ -1,333 +0,0 @@
1
- // eslint-disable-next-line @typescript-eslint/no-shadow
2
- import { transformSync, template } from '@babel/core';
3
- import { binaryExpression, isUnaryExpression, isUpdateExpression, stringLiteral, templateElement, templateLiteral } from '@babel/types';
4
- export var PostProcessWarning;
5
- (function(PostProcessWarning) {
6
- PostProcessWarning["UnsafeMathRandom"] = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.';
7
- })(PostProcessWarning || (PostProcessWarning = {}));
8
- // The RegEx below consists of multiple groups joined by a boolean OR.
9
- // Each part consists of two groups which capture a part of each string
10
- // which needs to be split up, e.g., `<!--` is split into `<!` and `--`.
11
- const TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\(.*?\))/gu;
12
- // An empty template element, i.e., a part of a template literal without any
13
- // value ("").
14
- const EMPTY_TEMPLATE_ELEMENT = templateElement({
15
- raw: '',
16
- cooked: ''
17
- });
18
- const evalWrapper = template.statement(`
19
- (1, REF)(ARGS)
20
- `);
21
- const objectEvalWrapper = template.statement(`
22
- (1, OBJECT.REF)
23
- `);
24
- const regeneratorRuntimeWrapper = template.statement(`
25
- var regeneratorRuntime;
26
- `);
27
- /**
28
- * Breaks up tokens that would otherwise result in SES errors. The tokens are
29
- * broken up in a non-destructive way where possible. Currently works with:
30
- * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,
31
- * `>`.
32
- * - `import(n)` statements, broken up into `import`, `(n)`.
33
- *
34
- * @param value - The string value to break up.
35
- * @returns The string split into an array, in a way that it can be joined
36
- * together to form the same string, but with the tokens separated into single
37
- * array elements.
38
- */ function breakTokens(value) {
39
- const tokens = value.split(TOKEN_REGEX);
40
- return tokens// TODO: The `split` above results in some values being `undefined`.
41
- // There may be a better solution to avoid having to filter those out.
42
- .filter((token)=>token !== '' && token !== undefined);
43
- }
44
- /**
45
- * Breaks up tokens that would otherwise result in SES errors. The tokens are
46
- * broken up in a non-destructive way where possible. Currently works with:
47
- * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,
48
- * `>`.
49
- * - `import(n)` statements, broken up into `import`, `(n)`.
50
- *
51
- * @param value - The string value to break up.
52
- * @returns The string split into a tuple consisting of the new template
53
- * elements and string literal expressions.
54
- */ function breakTokensTemplateLiteral(value) {
55
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
56
- // @ts-ignore `matchAll` is not available in ES2017, but this code
57
- // should only be used in environments where the function is supported.
58
- const matches = Array.from(value.matchAll(TOKEN_REGEX));
59
- if (matches.length > 0) {
60
- const output = matches.reduce(([elements, expressions], rawMatch, index, values)=>{
61
- const [, first, last] = rawMatch.filter((raw)=>raw !== undefined);
62
- // Slice the text in front of the match, which does not need to be
63
- // broken up.
64
- const prefix = value.slice(index === 0 ? 0 : values[index - 1].index + values[index - 1][0].length, rawMatch.index);
65
- return [
66
- [
67
- ...elements,
68
- templateElement({
69
- raw: getRawTemplateValue(prefix),
70
- cooked: prefix
71
- }),
72
- EMPTY_TEMPLATE_ELEMENT
73
- ],
74
- [
75
- ...expressions,
76
- stringLiteral(first),
77
- stringLiteral(last)
78
- ]
79
- ];
80
- }, [
81
- [],
82
- []
83
- ]);
84
- // Add the text after the last match to the output.
85
- const lastMatch = matches[matches.length - 1];
86
- const suffix = value.slice(lastMatch.index + lastMatch[0].length);
87
- return [
88
- [
89
- ...output[0],
90
- templateElement({
91
- raw: getRawTemplateValue(suffix),
92
- cooked: suffix
93
- })
94
- ],
95
- output[1]
96
- ];
97
- }
98
- // If there are no matches, simply return the original value.
99
- return [
100
- [
101
- templateElement({
102
- raw: getRawTemplateValue(value),
103
- cooked: value
104
- })
105
- ],
106
- []
107
- ];
108
- }
109
- /**
110
- * Get a raw template literal value from a cooked value. This adds a backslash
111
- * before every '`', '\' and '${' characters.
112
- *
113
- * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613
114
- * @param value - The cooked string to get the raw string for.
115
- * @returns The value as raw value.
116
- */ function getRawTemplateValue(value) {
117
- return value.replace(/\\|`|\$\{/gu, '\\$&');
118
- }
119
- /**
120
- * Post process code with AST such that it can be evaluated in SES.
121
- *
122
- * Currently:
123
- * - Makes all direct calls to eval indirect.
124
- * - Handles certain Babel-related edge cases.
125
- * - Removes the `Buffer` provided by Browserify.
126
- * - Optionally removes comments.
127
- * - Breaks up tokens that would otherwise result in SES errors, such as HTML
128
- * comment tags `<!--` and `-->` and `import(n)` statements.
129
- *
130
- * @param code - The code to post process.
131
- * @param options - The post-process options.
132
- * @param options.stripComments - Whether to strip comments. Defaults to `true`.
133
- * @param options.sourceMap - Whether to generate a source map for the modified
134
- * code. See also `inputSourceMap`.
135
- * @param options.inputSourceMap - The source map for the input code. When
136
- * provided, the source map will be used to generate a source map for the
137
- * modified code. This ensures that the source map is correct for the modified
138
- * code, and still points to the original source. If not provided, a new source
139
- * map will be generated instead.
140
- * @returns An object containing the modified code, and source map, or null if
141
- * the provided code is null.
142
- */ export function postProcessBundle(code, { stripComments = true, sourceMap: sourceMaps, inputSourceMap } = {}) {
143
- const warnings = new Set();
144
- const pre = ({ ast })=>{
145
- ast.comments?.forEach((comment)=>{
146
- // Break up tokens that could be parsed as HTML comment terminators. The
147
- // regular expressions below are written strangely so as to avoid the
148
- // appearance of such tokens in our source code. For reference:
149
- // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
150
- comment.value = comment.value.replace(new RegExp(`<!${'--'}`, 'gu'), '< !--').replace(new RegExp(`${'--'}>`, 'gu'), '-- >').replace(/import(\(.*\))/gu, 'import\\$1');
151
- });
152
- };
153
- const visitor = {
154
- FunctionExpression (path) {
155
- const { node } = path;
156
- // Browserify provides the `Buffer` global as an argument to modules that
157
- // use it, but this does not work in SES. Since we pass in `Buffer` as an
158
- // endowment, we can simply remove the argument.
159
- //
160
- // Note that this only removes `Buffer` from a wrapped function
161
- // expression, e.g., `(function (Buffer) { ... })`. Regular functions
162
- // are not affected.
163
- //
164
- // TODO: Since we're working on the AST level, we could check the scope
165
- // of the function expression, and possibly prevent false positives?
166
- if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {
167
- node.params = node.params.filter((param)=>!(param.type === 'Identifier' && param.name === 'Buffer'));
168
- }
169
- },
170
- CallExpression (path) {
171
- const { node } = path;
172
- // Replace `eval(foo)` with `(1, eval)(foo)`.
173
- if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {
174
- path.replaceWith(evalWrapper({
175
- REF: node.callee,
176
- ARGS: node.arguments
177
- }));
178
- }
179
- // Detect the use of `Math.random()` and add a warning.
180
- if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.object.name === 'Math' && node.callee.property.type === 'Identifier' && node.callee.property.name === 'random') {
181
- warnings.add(PostProcessWarning.UnsafeMathRandom);
182
- }
183
- },
184
- MemberExpression (path) {
185
- const { node } = path;
186
- // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.
187
- if (node.property.type === 'Identifier' && node.property.name === 'eval' && // We only apply this to MemberExpressions that are the callee of CallExpression
188
- path.parent.type === 'CallExpression' && path.parent.callee === node) {
189
- path.replaceWith(objectEvalWrapper({
190
- OBJECT: node.object,
191
- REF: node.property
192
- }));
193
- }
194
- },
195
- Identifier (path) {
196
- const { node } = path;
197
- // Insert `regeneratorRuntime` global if it's used in the code.
198
- if (node.name === 'regeneratorRuntime') {
199
- const program = path.findParent((parent)=>parent.node.type === 'Program');
200
- // We know that `program` is a Program node here, but this keeps
201
- // TypeScript happy.
202
- if (program?.node.type === 'Program') {
203
- const body = program.node.body[0];
204
- // This stops it from inserting `regeneratorRuntime` multiple times.
205
- if (body.type === 'VariableDeclaration' && body.declarations[0].id.name === 'regeneratorRuntime') {
206
- return;
207
- }
208
- program?.node.body.unshift(regeneratorRuntimeWrapper());
209
- }
210
- }
211
- },
212
- TemplateLiteral (path) {
213
- const { node } = path;
214
- // This checks if the template literal was visited before. Without this,
215
- // it would cause an infinite loop resulting in a stack overflow. We can't
216
- // skip the path here, because we need to visit the children of the node.
217
- if (path.getData('visited')) {
218
- return;
219
- }
220
- // Break up tokens that could be parsed as HTML comment terminators, or
221
- // `import()` statements.
222
- // For reference:
223
- // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
224
- // - https://github.com/MetaMask/snaps-monorepo/issues/505
225
- const [replacementQuasis, replacementExpressions] = node.quasis.reduce(([elements, expressions], quasi, index)=>{
226
- // Note: Template literals have two variants, "cooked" and "raw". Here
227
- // we use the cooked version.
228
- // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
229
- const tokens = breakTokensTemplateLiteral(quasi.value.cooked);
230
- // Only update the node if something changed.
231
- if (tokens[0].length <= 1) {
232
- return [
233
- [
234
- ...elements,
235
- quasi
236
- ],
237
- [
238
- ...expressions,
239
- node.expressions[index]
240
- ]
241
- ];
242
- }
243
- return [
244
- [
245
- ...elements,
246
- ...tokens[0]
247
- ],
248
- [
249
- ...expressions,
250
- ...tokens[1],
251
- node.expressions[index]
252
- ]
253
- ];
254
- }, [
255
- [],
256
- []
257
- ]);
258
- path.replaceWith(templateLiteral(replacementQuasis, replacementExpressions.filter((expression)=>expression !== undefined)));
259
- path.setData('visited', true);
260
- },
261
- StringLiteral (path) {
262
- const { node } = path;
263
- // Break up tokens that could be parsed as HTML comment terminators, or
264
- // `import()` statements.
265
- // For reference:
266
- // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
267
- // - https://github.com/MetaMask/snaps-monorepo/issues/505
268
- const tokens = breakTokens(node.value);
269
- // Only update the node if the string literal was broken up.
270
- if (tokens.length <= 1) {
271
- return;
272
- }
273
- const replacement = tokens.slice(1).reduce((acc, value)=>binaryExpression('+', acc, stringLiteral(value)), stringLiteral(tokens[0]));
274
- path.replaceWith(replacement);
275
- path.skip();
276
- },
277
- BinaryExpression (path) {
278
- const { node } = path;
279
- const errorMessage = 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' + 'these comments is ambiguous, and differs per browser and environment. If you want ' + 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' + 'and `a < ! --b`.';
280
- if (node.operator === '<' && isUnaryExpression(node.right) && isUpdateExpression(node.right.argument) && node.right.argument.operator === '--' && node.left.end && node.right.argument.argument.start) {
281
- const expression = code.slice(node.left.end, node.right.argument.argument.start);
282
- if (expression.includes('<!--')) {
283
- throw new Error(errorMessage);
284
- }
285
- }
286
- if (node.operator === '>' && isUpdateExpression(node.left) && node.left.operator === '--' && node.left.argument.end && node.right.start) {
287
- const expression = code.slice(node.left.argument.end, node.right.start);
288
- if (expression.includes('-->')) {
289
- throw new Error(errorMessage);
290
- }
291
- }
292
- }
293
- };
294
- try {
295
- const file = transformSync(code, {
296
- // Prevent Babel from searching for a config file.
297
- configFile: false,
298
- parserOpts: {
299
- // Strict mode isn't enabled by default, so we need to enable it here.
300
- strictMode: true,
301
- // If this is disabled, the AST does not include any comments. This is
302
- // useful for performance reasons, and we use it for stripping comments.
303
- attachComment: !stripComments
304
- },
305
- // By default, Babel optimises bundles that exceed 500 KB, but that
306
- // results in characters which look like HTML comments, which breaks SES.
307
- compact: false,
308
- // This configures Babel to generate a new source map from the existing
309
- // source map if specified. If `sourceMap` is `true` but an input source
310
- // map is not provided, a new source map will be generated instead.
311
- inputSourceMap,
312
- sourceMaps,
313
- plugins: [
314
- ()=>({
315
- pre,
316
- visitor
317
- })
318
- ]
319
- });
320
- if (!file?.code) {
321
- throw new Error('Bundled code is empty.');
322
- }
323
- return {
324
- code: file.code,
325
- sourceMap: file.map,
326
- warnings: Array.from(warnings)
327
- };
328
- } catch (error) {
329
- throw new Error(`Failed to post process code:\n${error.message}`);
330
- }
331
- }
332
-
333
- //# sourceMappingURL=post-process.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["transformSync","template","binaryExpression","isUnaryExpression","isUpdateExpression","stringLiteral","templateElement","templateLiteral","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","raw","cooked","evalWrapper","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","lastMatch","suffix","replace","postProcessBundle","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","expression","setData","StringLiteral","replacement","acc","skip","BinaryExpression","errorMessage","operator","right","argument","left","end","start","includes","Error","file","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;AAExD,SAASA,aAAa,EAAEC,QAAQ,QAAQ,cAAc;AAEtD,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,kBAAkB,EAClBC,aAAa,EACbC,eAAe,EACfC,eAAe,QACV,eAAe;WAgDf;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBL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,217 +0,0 @@
1
- function _define_property(obj, key, value) {
2
- if (key in obj) {
3
- Object.defineProperty(obj, key, {
4
- value: value,
5
- enumerable: true,
6
- configurable: true,
7
- writable: true
8
- });
9
- } else {
10
- obj[key] = value;
11
- }
12
- return obj;
13
- }
14
- import { assert, isObject, assertStruct } from '@metamask/utils';
15
- import { base64 } from '@scure/base';
16
- import stableStringify from 'fast-json-stable-stringify';
17
- import { empty, enums, intersection, literal, pattern, refine, string, union, validate } from 'superstruct';
18
- import validateNPMPackage from 'validate-npm-package-name';
19
- import { SnapCaveatType } from './caveats';
20
- import { checksumFiles } from './checksum';
21
- import { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';
22
- // This RegEx matches valid npm package names (with some exceptions) and space-
23
- // separated alphanumerical words, optionally with dashes and underscores.
24
- // The RegEx consists of two parts. The first part matches space-separated
25
- // words. It is based on the following Stackoverflow answer:
26
- // https://stackoverflow.com/a/34974982
27
- // The second part, after the pipe operator, is the same RegEx used for the
28
- // `name` field of the official package.json JSON Schema, except that we allow
29
- // mixed-case letters. It was originally copied from:
30
- // https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138
31
- export const PROPOSED_NAME_REGEX = /^(?:[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;
32
- export var SnapStatus;
33
- (function(SnapStatus) {
34
- SnapStatus["Installing"] = 'installing';
35
- SnapStatus["Updating"] = 'updating';
36
- SnapStatus["Running"] = 'running';
37
- SnapStatus["Stopped"] = 'stopped';
38
- SnapStatus["Crashed"] = 'crashed';
39
- })(SnapStatus || (SnapStatus = {}));
40
- export var SnapStatusEvents;
41
- (function(SnapStatusEvents) {
42
- SnapStatusEvents["Start"] = 'START';
43
- SnapStatusEvents["Stop"] = 'STOP';
44
- SnapStatusEvents["Crash"] = 'CRASH';
45
- SnapStatusEvents["Update"] = 'UPDATE';
46
- })(SnapStatusEvents || (SnapStatusEvents = {}));
47
- /**
48
- * An error indicating that a Snap validation failure is programmatically
49
- * fixable during development.
50
- */ export class ProgrammaticallyFixableSnapError extends Error {
51
- constructor(message, reason){
52
- super(message);
53
- _define_property(this, "reason", void 0);
54
- this.reason = reason;
55
- }
56
- }
57
- /**
58
- * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.
59
- *
60
- * @param manifest - The manifest itself.
61
- * @returns A virtual file containing the checksummable manifest.
62
- */ function getChecksummableManifest(manifest) {
63
- const manifestCopy = manifest.clone();
64
- delete manifestCopy.result.source.shasum;
65
- // We use fast-json-stable-stringify to deterministically serialize the JSON
66
- // This is required before checksumming so we get reproducible checksums across platforms etc
67
- manifestCopy.value = stableStringify(manifestCopy.result);
68
- return manifestCopy;
69
- }
70
- /**
71
- * Calculates the Base64-encoded SHA-256 digest of all required Snap files.
72
- *
73
- * @param files - All required Snap files to be included in the checksum.
74
- * @returns The Base64-encoded SHA-256 digest of the source code.
75
- */ export async function getSnapChecksum(files) {
76
- const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } = files;
77
- const all = [
78
- getChecksummableManifest(manifest),
79
- sourceCode,
80
- svgIcon,
81
- ...auxiliaryFiles,
82
- ...localizationFiles
83
- ].filter((file)=>file !== undefined);
84
- return base64.encode(await checksumFiles(all));
85
- }
86
- /**
87
- * Checks whether the `source.shasum` property of a Snap manifest matches the
88
- * shasum of the snap.
89
- *
90
- * @param files - All required Snap files to be included in the checksum.
91
- * @param errorMessage - The error message to throw if validation fails.
92
- */ export async function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
93
- if (files.manifest.result.source.shasum !== await getSnapChecksum(files)) {
94
- throw new ProgrammaticallyFixableSnapError(errorMessage, SnapValidationFailureReason.ShasumMismatch);
95
- }
96
- }
97
- export const LOCALHOST_HOSTNAMES = [
98
- 'localhost',
99
- '127.0.0.1',
100
- '[::1]'
101
- ];
102
- // Require snap ids to only consist of printable ASCII characters
103
- export const BaseSnapIdStruct = pattern(string(), /^[\x21-\x7E]*$/u);
104
- const LocalSnapIdSubUrlStruct = uri({
105
- protocol: enums([
106
- 'http:',
107
- 'https:'
108
- ]),
109
- hostname: enums(LOCALHOST_HOSTNAMES),
110
- hash: empty(string()),
111
- search: empty(string())
112
- });
113
- export const LocalSnapIdStruct = refine(BaseSnapIdStruct, 'local Snap Id', (value)=>{
114
- if (!value.startsWith(SnapIdPrefixes.local)) {
115
- return `Expected local snap ID, got "${value}".`;
116
- }
117
- const [error] = validate(value.slice(SnapIdPrefixes.local.length), LocalSnapIdSubUrlStruct);
118
- return error ?? true;
119
- });
120
- export const NpmSnapIdStruct = intersection([
121
- BaseSnapIdStruct,
122
- uri({
123
- protocol: literal(SnapIdPrefixes.npm),
124
- pathname: refine(string(), 'package name', function*(value) {
125
- const normalized = value.startsWith('/') ? value.slice(1) : value;
126
- const { errors, validForNewPackages, warnings } = validateNPMPackage(normalized);
127
- if (!validForNewPackages) {
128
- if (errors === undefined) {
129
- assert(warnings !== undefined);
130
- yield* warnings;
131
- } else {
132
- yield* errors;
133
- }
134
- }
135
- return true;
136
- }),
137
- search: empty(string()),
138
- hash: empty(string())
139
- })
140
- ]);
141
- export const HttpSnapIdStruct = intersection([
142
- BaseSnapIdStruct,
143
- uri({
144
- protocol: enums([
145
- 'http:',
146
- 'https:'
147
- ]),
148
- search: empty(string()),
149
- hash: empty(string())
150
- })
151
- ]);
152
- export const SnapIdStruct = union([
153
- NpmSnapIdStruct,
154
- LocalSnapIdStruct
155
- ]);
156
- /**
157
- * Extracts the snap prefix from a snap ID.
158
- *
159
- * @param snapId - The snap ID to extract the prefix from.
160
- * @returns The snap prefix from a snap id, e.g. `npm:`.
161
- */ export function getSnapPrefix(snapId) {
162
- const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix)=>snapId.startsWith(possiblePrefix));
163
- if (prefix !== undefined) {
164
- return prefix;
165
- }
166
- throw new Error(`Invalid or no prefix found for "${snapId}"`);
167
- }
168
- /**
169
- * Strips snap prefix from a full snap ID.
170
- *
171
- * @param snapId - The snap ID to strip.
172
- * @returns The stripped snap ID.
173
- */ export function stripSnapPrefix(snapId) {
174
- return snapId.replace(getSnapPrefix(snapId), '');
175
- }
176
- /**
177
- * Assert that the given value is a valid snap ID.
178
- *
179
- * @param value - The value to check.
180
- * @throws If the value is not a valid snap ID.
181
- */ export function assertIsValidSnapId(value) {
182
- assertStruct(value, SnapIdStruct, 'Invalid snap ID');
183
- }
184
- /**
185
- * Typeguard to ensure a chainId follows the CAIP-2 standard.
186
- *
187
- * @param chainId - The chainId being tested.
188
- * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.
189
- */ export function isCaipChainId(chainId) {
190
- return typeof chainId === 'string' && RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u").test(chainId);
191
- }
192
- /**
193
- * Utility function to check if an origin has permission (and caveat) for a particular snap.
194
- *
195
- * @param permissions - An origin's permissions object.
196
- * @param snapId - The id of the snap.
197
- * @returns A boolean based on if an origin has the specified snap.
198
- */ export function isSnapPermitted(permissions, snapId) {
199
- return Boolean((permissions?.wallet_snap?.caveats?.find((caveat)=>caveat.type === SnapCaveatType.SnapIds) ?? {}).value?.[snapId]);
200
- }
201
- /**
202
- * Checks whether the passed in requestedPermissions is a valid
203
- * permission request for a `wallet_snap` permission.
204
- *
205
- * @param requestedPermissions - The requested permissions.
206
- * @throws If the criteria is not met.
207
- */ export function verifyRequestedSnapPermissions(requestedPermissions) {
208
- assert(isObject(requestedPermissions), 'Requested permissions must be an object.');
209
- const { wallet_snap: walletSnapPermission } = requestedPermissions;
210
- assert(isObject(walletSnapPermission), 'wallet_snap is missing from the requested permissions.');
211
- const { caveats } = walletSnapPermission;
212
- assert(Array.isArray(caveats) && caveats.length === 1, 'wallet_snap must have a caveat property with a single-item array value.');
213
- const [caveat] = caveats;
214
- assert(isObject(caveat) && caveat.type === SnapCaveatType.SnapIds && isObject(caveat.value), `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`);
215
- }
216
-
217
- //# sourceMappingURL=snaps.js.map
@@ -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,YA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