@metamask/snaps-utils 7.8.0 → 8.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 (332) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/dist/array.js +1 -1
  3. package/dist/array.mjs +1 -1
  4. package/dist/auxiliary-files.js +1 -1
  5. package/dist/auxiliary-files.mjs +1 -1
  6. package/dist/base64.js +1 -1
  7. package/dist/base64.mjs +1 -1
  8. package/dist/bytes.js +1 -1
  9. package/dist/bytes.mjs +1 -1
  10. package/dist/caveats.js +1 -1
  11. package/dist/caveats.mjs +1 -1
  12. package/dist/checksum.js +1 -1
  13. package/dist/checksum.mjs +1 -1
  14. package/dist/{chunk-5I5WPAVD.js → chunk-37EUH3KZ.js} +13 -13
  15. package/dist/{chunk-FLSK6ISS.mjs → chunk-3N27GIUS.mjs} +4 -1
  16. package/dist/chunk-3N27GIUS.mjs.map +1 -0
  17. package/dist/{chunk-SB43G2RI.js → chunk-3OXW5H4F.js} +5 -5
  18. package/dist/{chunk-K6BCBPXF.js → chunk-3RFGTBEP.js} +11 -11
  19. package/dist/{chunk-JMDSN227.mjs → chunk-3RUWAMJT.mjs} +7 -1
  20. package/dist/chunk-4BGZ2CHC.mjs +22 -0
  21. package/dist/chunk-4BGZ2CHC.mjs.map +1 -0
  22. package/dist/chunk-4RYTYEUQ.mjs +33 -0
  23. package/dist/chunk-4RYTYEUQ.mjs.map +1 -0
  24. package/dist/{chunk-VOPTAKVG.js → chunk-53QXTM77.js} +4 -1
  25. package/dist/chunk-53QXTM77.js.map +1 -0
  26. package/dist/chunk-5FTBWYCW.mjs +27 -0
  27. package/dist/chunk-5FTBWYCW.mjs.map +1 -0
  28. package/dist/chunk-5MABKEV7.mjs +66 -0
  29. package/dist/chunk-5MABKEV7.mjs.map +1 -0
  30. package/dist/chunk-5UAPBOKO.js +37 -0
  31. package/dist/chunk-5UAPBOKO.js.map +1 -0
  32. package/dist/chunk-6YJWU77L.js +19 -0
  33. package/dist/chunk-6YJWU77L.js.map +1 -0
  34. package/dist/chunk-7T7FYH77.mjs +37 -0
  35. package/dist/chunk-7T7FYH77.mjs.map +1 -0
  36. package/dist/chunk-BPK5BH7K.js +27 -0
  37. package/dist/chunk-BPK5BH7K.js.map +1 -0
  38. package/dist/chunk-CPG2UGAA.js +25 -0
  39. package/dist/chunk-CPG2UGAA.js.map +1 -0
  40. package/dist/chunk-DKO64Y4H.mjs +27 -0
  41. package/dist/chunk-DKO64Y4H.mjs.map +1 -0
  42. package/dist/chunk-EYWMVDCD.mjs +25 -0
  43. package/dist/chunk-EYWMVDCD.mjs.map +1 -0
  44. package/dist/chunk-FA4QIZH6.js +1 -0
  45. package/dist/{chunk-KSRDEGBC.js → chunk-FBZ5SU7X.js} +11 -1
  46. package/dist/chunk-FBZ5SU7X.js.map +1 -0
  47. package/dist/chunk-GIVJAZ2Q.mjs +248 -0
  48. package/dist/chunk-GIVJAZ2Q.mjs.map +1 -0
  49. package/dist/chunk-GJAVOB7B.js +24 -0
  50. package/dist/chunk-GJAVOB7B.js.map +1 -0
  51. package/dist/{chunk-ZXHR322P.mjs → chunk-GXSTPU7D.mjs} +4 -4
  52. package/dist/chunk-HY4W6BUH.mjs +24 -0
  53. package/dist/chunk-HY4W6BUH.mjs.map +1 -0
  54. package/dist/{chunk-X3XJN63W.mjs → chunk-IELPPZJP.mjs} +11 -1
  55. package/dist/chunk-IELPPZJP.mjs.map +1 -0
  56. package/dist/{chunk-YNOZU43P.mjs → chunk-IPUL74MZ.mjs} +3 -3
  57. package/dist/chunk-IVDERT5W.js +22 -0
  58. package/dist/chunk-IVDERT5W.js.map +1 -0
  59. package/dist/chunk-JETPRED3.js +248 -0
  60. package/dist/chunk-JETPRED3.js.map +1 -0
  61. package/dist/chunk-L2DHOOBX.js +33 -0
  62. package/dist/chunk-L2DHOOBX.js.map +1 -0
  63. package/dist/chunk-LQSEBGOX.js +34 -0
  64. package/dist/chunk-LQSEBGOX.js.map +1 -0
  65. package/dist/chunk-MDOG3S4V.mjs +34 -0
  66. package/dist/chunk-MDOG3S4V.mjs.map +1 -0
  67. package/dist/chunk-MFGLB75H.mjs +22 -0
  68. package/dist/chunk-MFGLB75H.mjs.map +1 -0
  69. package/dist/chunk-MQURBEO4.mjs +16 -0
  70. package/dist/chunk-MQURBEO4.mjs.map +1 -0
  71. package/dist/{chunk-PZNIU23I.js → chunk-MWAZGSRO.js} +2 -22
  72. package/dist/chunk-MWAZGSRO.js.map +1 -0
  73. package/dist/{chunk-AJNKQYKP.mjs → chunk-N2JAYIUP.mjs} +2 -22
  74. package/dist/chunk-N2JAYIUP.mjs.map +1 -0
  75. package/dist/chunk-N4MA537G.js +22 -0
  76. package/dist/chunk-N4MA537G.js.map +1 -0
  77. package/dist/chunk-NNYGTNHP.mjs +1 -0
  78. package/dist/{chunk-H35ZUVQT.mjs → chunk-NSVVZNSD.mjs} +3 -13
  79. package/dist/chunk-NSVVZNSD.mjs.map +1 -0
  80. package/dist/chunk-PAOTMYIM.mjs +69 -0
  81. package/dist/chunk-PAOTMYIM.mjs.map +1 -0
  82. package/dist/chunk-PO5BBHHX.mjs +22 -0
  83. package/dist/chunk-PO5BBHHX.mjs.map +1 -0
  84. package/dist/{chunk-VWGXNUMD.mjs → chunk-PZF4KWU2.mjs} +2 -2
  85. package/dist/chunk-QD3LTING.js +34 -0
  86. package/dist/chunk-QD3LTING.js.map +1 -0
  87. package/dist/chunk-RNMJQSVQ.js +69 -0
  88. package/dist/chunk-RNMJQSVQ.js.map +1 -0
  89. package/dist/chunk-RRFKK45V.mjs +15 -0
  90. package/dist/chunk-RRFKK45V.mjs.map +1 -0
  91. package/dist/{chunk-PHUTP7NB.js → chunk-S3BWTUTZ.js} +9 -3
  92. package/dist/chunk-SKKANJ45.mjs +19 -0
  93. package/dist/chunk-SKKANJ45.mjs.map +1 -0
  94. package/dist/chunk-SYYDKPK3.js +15 -0
  95. package/dist/chunk-SYYDKPK3.js.map +1 -0
  96. package/dist/chunk-T5ZOOZ46.js +22 -0
  97. package/dist/chunk-T5ZOOZ46.js.map +1 -0
  98. package/dist/{chunk-RD6BN2TQ.js → chunk-TAMKWZ4E.js} +8 -18
  99. package/dist/chunk-TAMKWZ4E.js.map +1 -0
  100. package/dist/chunk-TYWGZIOF.mjs +34 -0
  101. package/dist/chunk-TYWGZIOF.mjs.map +1 -0
  102. package/dist/chunk-VBYSWMSU.js +66 -0
  103. package/dist/chunk-VBYSWMSU.js.map +1 -0
  104. package/dist/chunk-VEPYH26P.js +27 -0
  105. package/dist/chunk-VEPYH26P.js.map +1 -0
  106. package/dist/chunk-VWLBM7XM.js +1 -0
  107. package/dist/chunk-W7A3BYUP.mjs +1 -0
  108. package/dist/chunk-YL2EHYAA.js +16 -0
  109. package/dist/chunk-YL2EHYAA.js.map +1 -0
  110. package/dist/constants.js +1 -1
  111. package/dist/constants.mjs +1 -1
  112. package/dist/cronjob.js +1 -1
  113. package/dist/cronjob.mjs +1 -1
  114. package/dist/deep-clone.js +1 -1
  115. package/dist/deep-clone.mjs +1 -1
  116. package/dist/default-endowments.js +1 -1
  117. package/dist/default-endowments.mjs +1 -1
  118. package/dist/derivation-paths.js +3 -3
  119. package/dist/derivation-paths.mjs +2 -2
  120. package/dist/entropy.js +1 -1
  121. package/dist/entropy.mjs +1 -1
  122. package/dist/errors.js +3 -3
  123. package/dist/errors.mjs +2 -2
  124. package/dist/eval-worker.js +1 -1
  125. package/dist/eval-worker.mjs +1 -1
  126. package/dist/eval.js +1 -1
  127. package/dist/eval.mjs +1 -1
  128. package/dist/fs.js +1 -1
  129. package/dist/fs.mjs +1 -1
  130. package/dist/handler-types.js +1 -1
  131. package/dist/handler-types.mjs +1 -1
  132. package/dist/handlers.js +1 -1
  133. package/dist/handlers.mjs +1 -1
  134. package/dist/icon.js +1 -1
  135. package/dist/icon.mjs +1 -1
  136. package/dist/iframe.js +1 -1
  137. package/dist/iframe.mjs +1 -1
  138. package/dist/index.executionenv.js +5 -11
  139. package/dist/index.executionenv.mjs +9 -15
  140. package/dist/index.js +12 -19
  141. package/dist/index.mjs +16 -23
  142. package/dist/json-rpc.js +1 -1
  143. package/dist/json-rpc.mjs +1 -1
  144. package/dist/json.js +1 -1
  145. package/dist/json.mjs +1 -1
  146. package/dist/localization.js +1 -1
  147. package/dist/localization.mjs +1 -1
  148. package/dist/logging.js +1 -1
  149. package/dist/logging.mjs +1 -1
  150. package/dist/manifest/index.js +6 -6
  151. package/dist/manifest/index.mjs +5 -5
  152. package/dist/manifest/manifest.js +23 -9
  153. package/dist/manifest/manifest.mjs +24 -10
  154. package/dist/manifest/node.js +23 -9
  155. package/dist/manifest/node.mjs +24 -10
  156. package/dist/manifest/validation.js +6 -6
  157. package/dist/manifest/validation.mjs +5 -5
  158. package/dist/manifest/validator-types.js +1 -0
  159. package/dist/manifest/validator-types.js.map +1 -0
  160. package/dist/manifest/validator-types.mjs +1 -0
  161. package/dist/manifest/validator-types.mjs.map +1 -0
  162. package/dist/manifest/validator.js +44 -0
  163. package/dist/manifest/validator.js.map +1 -0
  164. package/dist/manifest/validator.mjs +44 -0
  165. package/dist/manifest/validator.mjs.map +1 -0
  166. package/dist/manifest/validators/checksum.js +15 -0
  167. package/dist/manifest/validators/checksum.js.map +1 -0
  168. package/dist/manifest/validators/checksum.mjs +15 -0
  169. package/dist/manifest/validators/checksum.mjs.map +1 -0
  170. package/dist/manifest/validators/expected-files.js +9 -0
  171. package/dist/manifest/validators/expected-files.js.map +1 -0
  172. package/dist/manifest/validators/expected-files.mjs +9 -0
  173. package/dist/manifest/validators/expected-files.mjs.map +1 -0
  174. package/dist/manifest/validators/icon-declared.js +8 -0
  175. package/dist/manifest/validators/icon-declared.js.map +1 -0
  176. package/dist/manifest/validators/icon-declared.mjs +8 -0
  177. package/dist/manifest/validators/icon-declared.mjs.map +1 -0
  178. package/dist/manifest/validators/icon-dimensions.js +10 -0
  179. package/dist/manifest/validators/icon-dimensions.js.map +1 -0
  180. package/dist/manifest/validators/icon-dimensions.mjs +10 -0
  181. package/dist/manifest/validators/icon-dimensions.mjs.map +1 -0
  182. package/dist/manifest/validators/icon-missing.js +8 -0
  183. package/dist/manifest/validators/icon-missing.js.map +1 -0
  184. package/dist/manifest/validators/icon-missing.mjs +8 -0
  185. package/dist/manifest/validators/icon-missing.mjs.map +1 -0
  186. package/dist/manifest/validators/index.js +80 -0
  187. package/dist/manifest/validators/index.js.map +1 -0
  188. package/dist/manifest/validators/index.mjs +80 -0
  189. package/dist/manifest/validators/index.mjs.map +1 -0
  190. package/dist/manifest/validators/is-localization-file.js +12 -0
  191. package/dist/manifest/validators/is-localization-file.js.map +1 -0
  192. package/dist/manifest/validators/is-localization-file.mjs +12 -0
  193. package/dist/manifest/validators/is-localization-file.mjs.map +1 -0
  194. package/dist/manifest/validators/is-package-json.js +11 -0
  195. package/dist/manifest/validators/is-package-json.js.map +1 -0
  196. package/dist/manifest/validators/is-package-json.mjs +11 -0
  197. package/dist/manifest/validators/is-package-json.mjs.map +1 -0
  198. package/dist/manifest/validators/is-snap-icon.js +10 -0
  199. package/dist/manifest/validators/is-snap-icon.js.map +1 -0
  200. package/dist/manifest/validators/is-snap-icon.mjs +10 -0
  201. package/dist/manifest/validators/is-snap-icon.mjs.map +1 -0
  202. package/dist/manifest/validators/is-snap-manifest.js +23 -0
  203. package/dist/manifest/validators/is-snap-manifest.js.map +1 -0
  204. package/dist/manifest/validators/is-snap-manifest.mjs +23 -0
  205. package/dist/manifest/validators/is-snap-manifest.mjs.map +1 -0
  206. package/dist/manifest/validators/manifest-localization.js +10 -0
  207. package/dist/manifest/validators/manifest-localization.js.map +1 -0
  208. package/dist/manifest/validators/manifest-localization.mjs +10 -0
  209. package/dist/manifest/validators/manifest-localization.mjs.map +1 -0
  210. package/dist/manifest/validators/package-json-recommended-fields.js +8 -0
  211. package/dist/manifest/validators/package-json-recommended-fields.js.map +1 -0
  212. package/dist/manifest/validators/package-json-recommended-fields.mjs +8 -0
  213. package/dist/manifest/validators/package-json-recommended-fields.mjs.map +1 -0
  214. package/dist/manifest/validators/package-name-match.js +9 -0
  215. package/dist/manifest/validators/package-name-match.js.map +1 -0
  216. package/dist/manifest/validators/package-name-match.mjs +9 -0
  217. package/dist/manifest/validators/package-name-match.mjs.map +1 -0
  218. package/dist/manifest/validators/repository-match.js +10 -0
  219. package/dist/manifest/validators/repository-match.js.map +1 -0
  220. package/dist/manifest/validators/repository-match.mjs +10 -0
  221. package/dist/manifest/validators/repository-match.mjs.map +1 -0
  222. package/dist/manifest/validators/version-match.js +9 -0
  223. package/dist/manifest/validators/version-match.js.map +1 -0
  224. package/dist/manifest/validators/version-match.mjs +9 -0
  225. package/dist/manifest/validators/version-match.mjs.map +1 -0
  226. package/dist/mock.js +1 -1
  227. package/dist/mock.mjs +1 -1
  228. package/dist/namespace.js +1 -1
  229. package/dist/namespace.mjs +1 -1
  230. package/dist/node.js +29 -28
  231. package/dist/node.mjs +35 -34
  232. package/dist/path.js +1 -1
  233. package/dist/path.mjs +1 -1
  234. package/dist/post-process.js +1 -1
  235. package/dist/post-process.mjs +1 -1
  236. package/dist/promise.js +2 -0
  237. package/dist/promise.js.map +1 -0
  238. package/dist/promise.mjs +2 -0
  239. package/dist/promise.mjs.map +1 -0
  240. package/dist/snaps.js +4 -6
  241. package/dist/snaps.mjs +3 -5
  242. package/dist/strings.js +1 -1
  243. package/dist/strings.mjs +1 -1
  244. package/dist/structs.js +3 -3
  245. package/dist/structs.mjs +2 -2
  246. package/dist/svg.js +1 -1
  247. package/dist/svg.mjs +1 -1
  248. package/dist/tsconfig.build.tsbuildinfo +1 -1
  249. package/dist/types/cronjob.d.ts +3 -3
  250. package/dist/types/derivation-paths.d.ts +1 -1
  251. package/dist/types/entropy.d.ts +1 -1
  252. package/dist/types/errors.d.ts +1 -1
  253. package/dist/types/eval.d.ts +1 -1
  254. package/dist/types/handler-types.d.ts +1 -1
  255. package/dist/types/handlers.d.ts +56 -7
  256. package/dist/types/index.d.ts +1 -0
  257. package/dist/types/json-rpc.d.ts +2 -2
  258. package/dist/types/localization.d.ts +1 -1
  259. package/dist/types/manifest/manifest.d.ts +30 -40
  260. package/dist/types/manifest/validation.d.ts +6 -6
  261. package/dist/types/manifest/validator-types.d.ts +34 -0
  262. package/dist/types/manifest/validator.d.ts +22 -0
  263. package/dist/types/manifest/validators/checksum.d.ts +5 -0
  264. package/dist/types/manifest/validators/expected-files.d.ts +5 -0
  265. package/dist/types/manifest/validators/icon-declared.d.ts +5 -0
  266. package/dist/types/manifest/validators/icon-dimensions.d.ts +5 -0
  267. package/dist/types/manifest/validators/icon-missing.d.ts +5 -0
  268. package/dist/types/manifest/validators/index.d.ts +14 -0
  269. package/dist/types/manifest/validators/is-localization-file.d.ts +5 -0
  270. package/dist/types/manifest/validators/is-package-json.d.ts +5 -0
  271. package/dist/types/manifest/validators/is-snap-icon.d.ts +5 -0
  272. package/dist/types/manifest/validators/is-snap-manifest.d.ts +5 -0
  273. package/dist/types/manifest/validators/manifest-localization.d.ts +5 -0
  274. package/dist/types/manifest/validators/package-json-recommended-fields.d.ts +5 -0
  275. package/dist/types/manifest/validators/package-name-match.d.ts +5 -0
  276. package/dist/types/manifest/validators/repository-match.d.ts +5 -0
  277. package/dist/types/manifest/validators/version-match.d.ts +5 -0
  278. package/dist/types/namespace.d.ts +5 -5
  279. package/dist/types/node.d.ts +0 -1
  280. package/dist/types/post-process.d.ts +3 -3
  281. package/dist/types/promise.d.ts +1 -0
  282. package/dist/types/snaps.d.ts +10 -18
  283. package/dist/types/structs.d.ts +2 -2
  284. package/dist/types/types.d.ts +9 -33
  285. package/dist/types/virtual-file/VirtualFile.d.ts +4 -4
  286. package/dist/types/virtual-file/toVirtualFile.d.ts +1 -1
  287. package/dist/types.js +3 -9
  288. package/dist/types.mjs +2 -8
  289. package/dist/ui.js +1 -1
  290. package/dist/ui.mjs +1 -1
  291. package/dist/validation.js +7 -7
  292. package/dist/validation.mjs +6 -6
  293. package/dist/versions.js +1 -1
  294. package/dist/versions.mjs +1 -1
  295. package/dist/virtual-file/VirtualFile.js +1 -1
  296. package/dist/virtual-file/VirtualFile.mjs +1 -1
  297. package/dist/virtual-file/index.js +1 -1
  298. package/dist/virtual-file/index.mjs +1 -1
  299. package/dist/virtual-file/node.js +1 -1
  300. package/dist/virtual-file/node.mjs +1 -1
  301. package/dist/virtual-file/toVirtualFile.js +1 -1
  302. package/dist/virtual-file/toVirtualFile.mjs +1 -1
  303. package/package.json +6 -6
  304. package/dist/chunk-25ESL4NL.js +0 -409
  305. package/dist/chunk-25ESL4NL.js.map +0 -1
  306. package/dist/chunk-AJNKQYKP.mjs.map +0 -1
  307. package/dist/chunk-F6G67XQ4.js +0 -1
  308. package/dist/chunk-FLSK6ISS.mjs.map +0 -1
  309. package/dist/chunk-H35ZUVQT.mjs.map +0 -1
  310. package/dist/chunk-KCECQM3L.mjs +0 -409
  311. package/dist/chunk-KCECQM3L.mjs.map +0 -1
  312. package/dist/chunk-KSRDEGBC.js.map +0 -1
  313. package/dist/chunk-OYZPBNHS.mjs +0 -1
  314. package/dist/chunk-PZNIU23I.js.map +0 -1
  315. package/dist/chunk-RD6BN2TQ.js.map +0 -1
  316. package/dist/chunk-VOPTAKVG.js.map +0 -1
  317. package/dist/chunk-X3XJN63W.mjs.map +0 -1
  318. package/dist/npm.js +0 -35
  319. package/dist/npm.mjs +0 -35
  320. package/dist/types/npm.d.ts +0 -19
  321. /package/dist/{chunk-5I5WPAVD.js.map → chunk-37EUH3KZ.js.map} +0 -0
  322. /package/dist/{chunk-SB43G2RI.js.map → chunk-3OXW5H4F.js.map} +0 -0
  323. /package/dist/{chunk-K6BCBPXF.js.map → chunk-3RFGTBEP.js.map} +0 -0
  324. /package/dist/{chunk-JMDSN227.mjs.map → chunk-3RUWAMJT.mjs.map} +0 -0
  325. /package/dist/{chunk-F6G67XQ4.js.map → chunk-FA4QIZH6.js.map} +0 -0
  326. /package/dist/{chunk-ZXHR322P.mjs.map → chunk-GXSTPU7D.mjs.map} +0 -0
  327. /package/dist/{chunk-YNOZU43P.mjs.map → chunk-IPUL74MZ.mjs.map} +0 -0
  328. /package/dist/{chunk-OYZPBNHS.mjs.map → chunk-NNYGTNHP.mjs.map} +0 -0
  329. /package/dist/{chunk-VWGXNUMD.mjs.map → chunk-PZF4KWU2.mjs.map} +0 -0
  330. /package/dist/{chunk-PHUTP7NB.js.map → chunk-S3BWTUTZ.js.map} +0 -0
  331. /package/dist/{npm.js.map → chunk-VWLBM7XM.js.map} +0 -0
  332. /package/dist/{npm.mjs.map → chunk-W7A3BYUP.mjs.map} +0 -0
@@ -1,409 +0,0 @@
1
- import {
2
- assertIsSnapManifest
3
- } from "./chunk-ZXHR322P.mjs";
4
- import {
5
- ProgrammaticallyFixableSnapError,
6
- getSnapChecksum,
7
- validateSnapShasum
8
- } from "./chunk-H35ZUVQT.mjs";
9
- import {
10
- getValidatedLocalizationFiles,
11
- validateSnapManifestLocalizations
12
- } from "./chunk-CJK7DDV2.mjs";
13
- import {
14
- assertIsSnapIcon,
15
- getSvgDimensions
16
- } from "./chunk-PTOH2SVI.mjs";
17
- import {
18
- SnapValidationFailureReason,
19
- assertIsNpmSnapPackageJson
20
- } from "./chunk-AJNKQYKP.mjs";
21
- import {
22
- readJsonFile
23
- } from "./chunk-X3UZCGO5.mjs";
24
- import {
25
- readVirtualFile
26
- } from "./chunk-XZNJFDBF.mjs";
27
- import {
28
- VirtualFile
29
- } from "./chunk-DE22V5AO.mjs";
30
- import {
31
- deepClone
32
- } from "./chunk-Z2JQNSVL.mjs";
33
-
34
- // src/manifest/manifest.ts
35
- import { getErrorMessage } from "@metamask/snaps-sdk";
36
- import { assertExhaustive, assert, isPlainObject } from "@metamask/utils";
37
- import deepEqual from "fast-deep-equal";
38
- import { promises as fs } from "fs";
39
- import pathUtils from "path";
40
- var MANIFEST_SORT_ORDER = {
41
- $schema: 1,
42
- version: 2,
43
- description: 3,
44
- proposedName: 4,
45
- repository: 5,
46
- source: 6,
47
- initialConnections: 7,
48
- initialPermissions: 8,
49
- manifestVersion: 9
50
- };
51
- async function checkManifest(basePath, writeManifest = true, sourceCode, writeFileFn = fs.writeFile) {
52
- const warnings = [];
53
- const errors = [];
54
- let updated = false;
55
- const manifestPath = pathUtils.join(basePath, "snap.manifest.json" /* Manifest */);
56
- const manifestFile = await readJsonFile(manifestPath);
57
- const unvalidatedManifest = manifestFile.result;
58
- const packageFile = await readJsonFile(
59
- pathUtils.join(basePath, "package.json" /* PackageJson */)
60
- );
61
- const auxiliaryFilePaths = getSnapFilePaths(
62
- unvalidatedManifest,
63
- (manifest2) => manifest2?.source?.files
64
- );
65
- const localizationFilePaths = getSnapFilePaths(
66
- unvalidatedManifest,
67
- (manifest2) => manifest2?.source?.locales
68
- );
69
- const snapFiles = {
70
- manifest: manifestFile,
71
- packageJson: packageFile,
72
- sourceCode: await getSnapSourceCode(
73
- basePath,
74
- unvalidatedManifest,
75
- sourceCode
76
- ),
77
- svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
78
- // Intentionally pass null as the encoding here since the files may be binary
79
- auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths, null) ?? [],
80
- localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
81
- };
82
- let manifest;
83
- try {
84
- ({ manifest } = await validateNpmSnap(snapFiles));
85
- } catch (error) {
86
- if (error instanceof ProgrammaticallyFixableSnapError) {
87
- errors.push(error.message);
88
- const partiallyValidatedFiles = snapFiles;
89
- let isInvalid = true;
90
- let currentError = error;
91
- const maxAttempts = Object.keys(SnapValidationFailureReason).length;
92
- for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {
93
- manifest = await fixManifest(
94
- manifest ? { ...partiallyValidatedFiles, manifest } : partiallyValidatedFiles,
95
- currentError
96
- );
97
- try {
98
- await validateNpmSnapManifest({
99
- ...partiallyValidatedFiles,
100
- manifest
101
- });
102
- isInvalid = false;
103
- } catch (nextValidationError) {
104
- currentError = nextValidationError;
105
- if (!(nextValidationError instanceof ProgrammaticallyFixableSnapError) || attempts === maxAttempts && !isInvalid) {
106
- throw new Error(
107
- `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:
108
- ${error.message}`
109
- );
110
- }
111
- errors.push(currentError.message);
112
- }
113
- }
114
- updated = true;
115
- } else {
116
- throw error;
117
- }
118
- }
119
- assert(manifest);
120
- const validatedManifest = manifest.result;
121
- const recommendedFields = ["repository"];
122
- const missingRecommendedFields = recommendedFields.filter(
123
- (key) => !validatedManifest[key]
124
- );
125
- if (missingRecommendedFields.length > 0) {
126
- warnings.push(
127
- `Missing recommended package.json properties:
128
- ${missingRecommendedFields.reduce(
129
- (allMissing, currentField) => {
130
- return `${allMissing} ${currentField}
131
- `;
132
- },
133
- ""
134
- )}`
135
- );
136
- }
137
- if (!snapFiles.svgIcon) {
138
- warnings.push(
139
- "No icon found in the Snap manifest. It is recommended to include an icon for the Snap. See https://docs.metamask.io/snaps/how-to/design-a-snap/#guidelines-at-a-glance for more information."
140
- );
141
- }
142
- const iconDimensions = snapFiles.svgIcon && getSvgDimensions(snapFiles.svgIcon.toString());
143
- if (iconDimensions && iconDimensions.height !== iconDimensions.width) {
144
- warnings.push(
145
- "The icon in the Snap manifest is not square. It is recommended to use a square icon for the Snap."
146
- );
147
- }
148
- if (writeManifest) {
149
- try {
150
- const newManifest = `${JSON.stringify(
151
- getWritableManifest(validatedManifest),
152
- null,
153
- 2
154
- )}
155
- `;
156
- if (updated || newManifest !== manifestFile.value) {
157
- await writeFileFn(
158
- pathUtils.join(basePath, "snap.manifest.json" /* Manifest */),
159
- newManifest
160
- );
161
- }
162
- } catch (error) {
163
- throw new Error(`Failed to update snap.manifest.json: ${error.message}`);
164
- }
165
- }
166
- return { manifest: validatedManifest, updated, warnings, errors };
167
- }
168
- async function fixManifest(snapFiles, error) {
169
- const { manifest, packageJson } = snapFiles;
170
- const clonedFile = manifest.clone();
171
- const manifestCopy = clonedFile.result;
172
- switch (error.reason) {
173
- case '"name" field mismatch' /* NameMismatch */:
174
- manifestCopy.source.location.npm.packageName = packageJson.result.name;
175
- break;
176
- case '"version" field mismatch' /* VersionMismatch */:
177
- manifestCopy.version = packageJson.result.version;
178
- break;
179
- case '"repository" field mismatch' /* RepositoryMismatch */:
180
- manifestCopy.repository = packageJson.result.repository ? deepClone(packageJson.result.repository) : void 0;
181
- break;
182
- case '"shasum" field mismatch' /* ShasumMismatch */:
183
- manifestCopy.source.shasum = await getSnapChecksum(snapFiles);
184
- break;
185
- default:
186
- assertExhaustive(error.reason);
187
- }
188
- clonedFile.result = manifestCopy;
189
- clonedFile.value = JSON.stringify(manifestCopy);
190
- return clonedFile;
191
- }
192
- async function getSnapSourceCode(basePath, manifest, sourceCode) {
193
- if (!isPlainObject(manifest)) {
194
- return void 0;
195
- }
196
- const sourceFilePath = manifest.source?.location?.npm?.filePath;
197
- if (!sourceFilePath) {
198
- return void 0;
199
- }
200
- if (sourceCode) {
201
- return new VirtualFile({
202
- path: pathUtils.join(basePath, sourceFilePath),
203
- value: sourceCode
204
- });
205
- }
206
- try {
207
- const virtualFile = await readVirtualFile(
208
- pathUtils.join(basePath, sourceFilePath),
209
- "utf8"
210
- );
211
- return virtualFile;
212
- } catch (error) {
213
- throw new Error(
214
- `Failed to read snap bundle file: ${getErrorMessage(error)}`
215
- );
216
- }
217
- }
218
- async function getSnapIcon(basePath, manifest) {
219
- if (!isPlainObject(manifest)) {
220
- return void 0;
221
- }
222
- const iconPath = manifest.source?.location?.npm?.iconPath;
223
- if (!iconPath) {
224
- return void 0;
225
- }
226
- try {
227
- const virtualFile = await readVirtualFile(
228
- pathUtils.join(basePath, iconPath),
229
- "utf8"
230
- );
231
- return virtualFile;
232
- } catch (error) {
233
- throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);
234
- }
235
- }
236
- function getSnapFilePaths(manifest, selector) {
237
- if (!isPlainObject(manifest)) {
238
- return void 0;
239
- }
240
- const snapManifest = manifest;
241
- const paths = selector(snapManifest);
242
- if (!Array.isArray(paths)) {
243
- return void 0;
244
- }
245
- return paths;
246
- }
247
- async function getSnapFiles(basePath, paths, encoding = "utf8") {
248
- if (!paths) {
249
- return void 0;
250
- }
251
- try {
252
- return await Promise.all(
253
- paths.map(
254
- async (filePath) => readVirtualFile(pathUtils.join(basePath, filePath), encoding)
255
- )
256
- );
257
- } catch (error) {
258
- throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);
259
- }
260
- }
261
- function getWritableManifest(manifest) {
262
- const { repository, ...remaining } = manifest;
263
- const keys = Object.keys(
264
- repository ? { ...remaining, repository } : remaining
265
- );
266
- const writableManifest = keys.sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b]).reduce(
267
- (result, key) => ({
268
- ...result,
269
- [key]: manifest[key]
270
- }),
271
- {}
272
- );
273
- return writableManifest;
274
- }
275
- async function validateNpmSnapManifest({
276
- manifest,
277
- packageJson,
278
- sourceCode,
279
- svgIcon,
280
- auxiliaryFiles,
281
- localizationFiles
282
- }) {
283
- const packageJsonName = packageJson.result.name;
284
- const packageJsonVersion = packageJson.result.version;
285
- const packageJsonRepository = packageJson.result.repository;
286
- const manifestPackageName = manifest.result.source.location.npm.packageName;
287
- const manifestPackageVersion = manifest.result.version;
288
- const manifestRepository = manifest.result.repository;
289
- if (packageJsonName !== manifestPackageName) {
290
- throw new ProgrammaticallyFixableSnapError(
291
- `"${"snap.manifest.json" /* Manifest */}" npm package name ("${manifestPackageName}") does not match the "${"package.json" /* PackageJson */}" "name" field ("${packageJsonName}").`,
292
- '"name" field mismatch' /* NameMismatch */
293
- );
294
- }
295
- if (packageJsonVersion !== manifestPackageVersion) {
296
- throw new ProgrammaticallyFixableSnapError(
297
- `"${"snap.manifest.json" /* Manifest */}" npm package version ("${manifestPackageVersion}") does not match the "${"package.json" /* PackageJson */}" "version" field ("${packageJsonVersion}").`,
298
- '"version" field mismatch' /* VersionMismatch */
299
- );
300
- }
301
- if (
302
- // The repository may be `undefined` in package.json but can only be defined
303
- // or `null` in the Snap manifest due to TS@<4.4 issues.
304
- (packageJsonRepository || manifestRepository) && !deepEqual(packageJsonRepository, manifestRepository)
305
- ) {
306
- throw new ProgrammaticallyFixableSnapError(
307
- `"${"snap.manifest.json" /* Manifest */}" "repository" field does not match the "${"package.json" /* PackageJson */}" "repository" field.`,
308
- '"repository" field mismatch' /* RepositoryMismatch */
309
- );
310
- }
311
- await validateSnapShasum(
312
- { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },
313
- `"${"snap.manifest.json" /* Manifest */}" "shasum" field does not match computed shasum.`
314
- );
315
- }
316
-
317
- // src/npm.ts
318
- var EXPECTED_SNAP_FILES = [
319
- "manifest",
320
- "packageJson",
321
- "sourceCode"
322
- ];
323
- var SnapFileNameFromKey = {
324
- manifest: "snap.manifest.json" /* Manifest */,
325
- packageJson: "package.json" /* PackageJson */,
326
- sourceCode: "source code bundle"
327
- };
328
- async function validateNpmSnap(snapFiles, errorPrefix) {
329
- EXPECTED_SNAP_FILES.forEach((key) => {
330
- if (!snapFiles[key]) {
331
- throw new Error(
332
- `${errorPrefix ?? ""}Missing file "${SnapFileNameFromKey[key]}".`
333
- );
334
- }
335
- });
336
- const {
337
- manifest,
338
- packageJson,
339
- sourceCode,
340
- svgIcon,
341
- auxiliaryFiles,
342
- localizationFiles
343
- } = snapFiles;
344
- try {
345
- assertIsSnapManifest(manifest.result);
346
- } catch (error) {
347
- throw new Error(`${errorPrefix ?? ""}${error.message}`);
348
- }
349
- const validatedManifest = manifest;
350
- const { iconPath } = validatedManifest.result.source.location.npm;
351
- if (iconPath && !svgIcon) {
352
- throw new Error(`Missing file "${iconPath}".`);
353
- }
354
- try {
355
- assertIsNpmSnapPackageJson(packageJson.result);
356
- } catch (error) {
357
- throw new Error(`${errorPrefix ?? ""}${error.message}`);
358
- }
359
- const validatedPackageJson = packageJson;
360
- await validateNpmSnapManifest({
361
- manifest: validatedManifest,
362
- packageJson: validatedPackageJson,
363
- sourceCode,
364
- svgIcon,
365
- auxiliaryFiles,
366
- localizationFiles
367
- });
368
- if (svgIcon) {
369
- try {
370
- assertIsSnapIcon(svgIcon);
371
- } catch (error) {
372
- throw new Error(`${errorPrefix ?? ""}${error.message}`);
373
- }
374
- }
375
- if (localizationFiles) {
376
- try {
377
- getValidatedLocalizationFiles(localizationFiles);
378
- validateSnapManifestLocalizations(
379
- manifest.result,
380
- localizationFiles.map((file) => file.result)
381
- );
382
- } catch (error) {
383
- throw new Error(`${errorPrefix ?? ""}${error.message}`);
384
- }
385
- }
386
- return {
387
- manifest: validatedManifest,
388
- packageJson: validatedPackageJson,
389
- sourceCode,
390
- svgIcon,
391
- auxiliaryFiles,
392
- localizationFiles
393
- };
394
- }
395
-
396
- export {
397
- EXPECTED_SNAP_FILES,
398
- SnapFileNameFromKey,
399
- validateNpmSnap,
400
- checkManifest,
401
- fixManifest,
402
- getSnapSourceCode,
403
- getSnapIcon,
404
- getSnapFilePaths,
405
- getSnapFiles,
406
- getWritableManifest,
407
- validateNpmSnapManifest
408
- };
409
- //# sourceMappingURL=chunk-KCECQM3L.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/manifest/manifest.ts","../src/npm.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { getSvgDimensions } from '../icon';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file/node';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialConnections: 7,\n initialPermissions: 8,\n manifestVersion: 9,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n // Intentionally pass null as the encoding here since the files may be binary\n auxiliaryFiles:\n (await getSnapFiles(basePath, auxiliaryFilePaths, null)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (!snapFiles.svgIcon) {\n warnings.push(\n 'No icon found in the Snap manifest. It is recommended to include an icon for the Snap. See https://docs.metamask.io/snaps/how-to/design-a-snap/#guidelines-at-a-glance for more information.',\n );\n }\n\n const iconDimensions =\n snapFiles.svgIcon && getSvgDimensions(snapFiles.svgIcon.toString());\n if (iconDimensions && iconDimensions.height !== iconDimensions.width) {\n warnings.push(\n 'The icon in the Snap manifest is not square. It is recommended to use a square icon for the Snap.',\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @param encoding - An optional encoding to pass down to readVirtualFile.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n encoding: BufferEncoding | null = 'utf8',\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), encoding),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n","import { assertIsSnapIcon } from './icon';\nimport {\n getValidatedLocalizationFiles,\n validateSnapManifestLocalizations,\n} from './localization';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport async function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): Promise<SnapFiles> {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const {\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n } = snapFiles as SnapFiles;\n\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n\n const validatedPackageJson = packageJson;\n await validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n if (localizationFiles) {\n try {\n // This function validates and returns the localization files. We don't\n // use the return value here, but we do want to validate the files.\n getValidatedLocalizationFiles(localizationFiles);\n\n validateSnapManifestLocalizations(\n manifest.result,\n localizationFiles.map((file) => file.result),\n );\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,uBAAuB;AAEhC,SAAS,kBAAkB,QAAQ,qBAAqB;AACxD,OAAO,eAAe;AACtB,SAAS,YAAY,UAAU;AAC/B,OAAO,eAAe;AAgBtB,IAAM,sBAA0D;AAAA,EAC9D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,aAAa;AAAA,EACb,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB,iBAAiB;AACnB;AAqCA,eAAsB,cACpB,UACA,gBAAgB,MAChB,YACA,cAAiC,GAAG,WACN;AAC9B,QAAM,WAAqB,CAAC;AAC5B,QAAM,SAAmB,CAAC;AAE1B,MAAI,UAAU;AAEd,QAAM,eAAe,UAAU,KAAK,6CAAmC;AACvE,QAAM,eAAe,MAAM,aAAa,YAAY;AACpD,QAAM,sBAAsB,aAAa;AAEzC,QAAM,cAAc,MAAM;AAAA,IACxB,UAAU,KAAK,0CAAs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AAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,SAAS,IAAI;AAAA,IACzB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,SAAS,OAAO;AAAA,IAC5B,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACF;AASO,SAAS,0BACd,MACA,OACe;AACf,QAAM,eAAe,uBAAuB;AAAA,IAC1C,CAAC,mBACC,eAAe,UAAU,SAAS,QAAQ,eAAe,MAAM,IAAI;AAAA,EACvE;AAEA,MAAI,cAAc;AAChB,WAAO,aAAa;AAAA,EACtB;AAIA,MACE,UAAU,eACV,KAAK,CAAC,MAAM,OACZ,KAAK,CAAC,MAAM,SACZ,KAAK,CAAC,EAAE,SAAS,GAAG,GACpB;AACA,UAAM,WAAW,KAAK,CAAC,EAAE,MAAM,GAAG,EAAE;AACpC,WAAO,sBAAsB,QAAQ,KAAK;AAAA,EAC5C;AAEA,SAAO;AACT;AAUO,SAAS,sBAAsB,UAA2B;AAC/D,MAAI,OAAO,QAAQ,MAAM,KAAK;AAC5B,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,QAA+B,GAAG,QAAQ;AAC1D","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport slip44 from '@metamask/slip44';\n\nimport { isEqual } from './array';\n\nexport type SnapsDerivationPath = {\n path: ['m', ...string[]];\n curve: SupportedCurve;\n name: string;\n};\n\nexport const SNAPS_DERIVATION_PATHS: SnapsDerivationPath[] = [\n {\n path: ['m', `44'`, `0'`],\n curve: 'ed25519',\n name: 'Test BIP-32 Path (ed25519)',\n },\n {\n path: ['m', `44'`, `1'`],\n curve: 'secp256k1',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Legacy',\n },\n {\n path: ['m', `49'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Nested SegWit',\n },\n {\n path: ['m', `49'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Nested SegWit',\n },\n {\n path: ['m', `84'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Native SegWit',\n },\n {\n path: ['m', `84'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Native SegWit',\n },\n {\n path: ['m', `44'`, `501'`],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `501'`, \"0'\", \"0'\"],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `2'`],\n curve: 'secp256k1',\n name: 'Litecoin',\n },\n {\n path: ['m', `44'`, `3'`],\n curve: 'secp256k1',\n name: 'Dogecoin',\n },\n {\n path: ['m', `44'`, `60'`],\n curve: 'secp256k1',\n name: 'Ethereum',\n },\n {\n path: ['m', `44'`, `118'`],\n curve: 'secp256k1',\n name: 'Atom',\n },\n {\n path: ['m', `44'`, `145'`],\n curve: 'secp256k1',\n name: 'Bitcoin Cash',\n },\n {\n path: ['m', `44'`, `637'`],\n curve: 'ed25519',\n name: 'Aptos',\n },\n {\n path: ['m', `44'`, `714'`],\n curve: 'secp256k1',\n name: 'Binance (BNB)',\n },\n {\n path: ['m', `44'`, `784'`],\n curve: 'ed25519',\n name: 'Sui',\n },\n {\n path: ['m', `44'`, `931'`],\n curve: 'secp256k1',\n name: 'THORChain (RUNE)',\n },\n {\n path: ['m', `44'`, `330'`],\n curve: 'secp256k1',\n name: 'Terra (LUNA)',\n },\n {\n path: ['m', `44'`, `459'`],\n curve: 'secp256k1',\n name: 'Kava',\n },\n {\n path: ['m', `44'`, `529'`],\n curve: 'secp256k1',\n name: 'Secret Network',\n },\n {\n path: ['m', `44'`, `397'`, `0'`],\n curve: 'ed25519',\n name: 'NEAR Protocol',\n },\n {\n path: ['m', `44'`, `1'`, `0'`],\n curve: 'ed25519',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `472'`],\n curve: 'ed25519',\n name: 'Arweave',\n },\n {\n path: ['m', `44'`, `12586'`],\n curve: 'secp256k1',\n name: 'Mina',\n },\n {\n path: ['m', `44'`, `242'`],\n curve: 'ed25519',\n name: 'Nimiq',\n },\n {\n path: ['m', `44'`, `1729'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'Tezos',\n },\n {\n path: ['m', `1789'`, `0'`],\n curve: 'ed25519',\n name: 'Vega',\n },\n {\n path: ['m', `1852'`, `1815'`],\n curve: 'ed25519Bip32',\n name: 'Cardano',\n },\n];\n\n/**\n * Gets the name of a derivation path supported by snaps.\n *\n * @param path - The derivation path.\n * @param curve - The curve used to derive the keys.\n * @returns The name of the derivation path, otherwise null.\n */\nexport function getSnapDerivationPathName(\n path: SnapsDerivationPath['path'],\n curve: SupportedCurve,\n): string | null {\n const pathMetadata = SNAPS_DERIVATION_PATHS.find(\n (derivationPath) =>\n derivationPath.curve === curve && isEqual(derivationPath.path, path),\n );\n\n if (pathMetadata) {\n return pathMetadata.name;\n }\n\n // If the curve is secp256k1 and the path is a valid BIP44 path\n // we try looking for the network/protocol name in SLIP44\n if (\n curve === 'secp256k1' &&\n path[0] === 'm' &&\n path[1] === `44'` &&\n path[2].endsWith(`'`)\n ) {\n const coinType = path[2].slice(0, -1);\n return getSlip44ProtocolName(coinType) ?? null;\n }\n\n return null;\n}\n\n/**\n * Gets the name of the SLIP-44 protocol corresponding to the specified\n * `coin_type`.\n *\n * @param coinType - The SLIP-44 `coin_type` value whose name\n * to retrieve.\n * @returns The name of the protocol, otherwise null.\n */\nexport function getSlip44ProtocolName(coinType: number | string) {\n if (String(coinType) === '1') {\n return 'Test Networks';\n }\n\n return slip44[coinType as keyof typeof slip44]?.name ?? null;\n}\n"]}
@@ -1 +0,0 @@
1
- //# sourceMappingURL=chunk-OYZPBNHS.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/types.ts"],"names":["NpmSnapFileNames","SnapIdPrefixes","SnapValidationFailureReason","SNAP_STREAM_NAMES"],"mappings":";AACA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AAM,MAAM,CAAC,OAAwB,CAAC,MAC3C,OAAO,MAAM,CAAC,OAAO,GAAG,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,UAAU;AACzD,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,KAAK;AAEzB,UAAM,YAAY,KAAK,IAAI;AAC3B,sBAAkB,KAAK,SAAS;AAChC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,sBAAsB,MAAM,SAAS,CAAC;AAAA,EAC/C;AACF,CAAC;AASI,SAAS,WACd,KACA,OAAwB,CAAC,GACJ;AACrB,SAAO,GAAG,KAAK,IAAI,IAAI,CAAC;AAC1B;AAGO,IAAM,6BAA6B","sourcesContent":["import type { Infer, Struct } from '@metamask/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 '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/snaps.ts"],"names":["SnapStatus","SnapStatusEvents"],"mappings":";;;;;;;;;AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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AACH,CAAC;AAEM,IAAM,eAAe,MAAM,CAAC,iBAAiB,iBAAiB,CAAC;AAQ/D,SAAS,cAAc,QAAgC;AAC5D,QAAM,SAAS,OAAO,OAAO,cAAc,EAAE;AAAA,IAAK,CAAC,mBACjD,OAAO,WAAW,cAAc;AAAA,EAClC;AACA,MAAI,WAAW,QAAW;AACxB,WAAO;AAAA,EACT;AACA,QAAM,IAAI,MAAM,mCAAmC,MAAM,GAAG;AAC9D;AAQO,SAAS,gBAAgB,QAAwB;AACtD,SAAO,OAAO,QAAQ,cAAc,MAAM,GAAG,EAAE;AACjD;AAQO,SAAS,oBAAoB,OAAyC;AAC3E,eAAa,OAAO,cAAc,iBAAiB;AACrD;AAQO,SAAS,cAAc,SAAqC;AACjE,SACE,OAAO,YAAY,YACnB,mEAAmE;AAAA,IACjE;AAAA,EACF;AAEJ;AASO,SAAS,gBACd,aACA,QACA;AACA,SAAO;AAAA,KAGA,aAAa,aAAa,SAAS;AAAA,MAClC,CAAC,WAAW,OAAO;AAAA,IACrB,KAAK,CAAC,GACN,QACA,MAAM;AAAA,EACZ;AACF;AASO,SAAS,+BACd,sBACwD;AACxD;AAAA,IACE,SAAS,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,QAAM,EAAE,aAAa,qBAAqB,IAAI;AAE9C;AAAA,IACE,SAAS,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,QAAM,EAAE,QAAQ,IAAI;AAEpB;AAAA,IACE,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AAAA,IAC7C;AAAA,EACF;AAEA,QAAM,CAAC,MAAM,IAAI;AAEjB;AAAA,IACE,SAAS,MAAM,KACb,OAAO,oCACP,SAAS,OAAO,KAAK;AAAA,IACvB,wEAAuE;AAAA,EACzE;AACF","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 { Struct } from '@metamask/superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\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 validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} 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 connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\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 /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: 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"]}
@@ -1 +0,0 @@
1
- {"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KAAK;AACnB,iBAAW,UAAU,SAAS;AAC5B,eAAO,OAAO,QAAQ,OAAO,GAAG;AAAA,MAClC;AAAA,IACF;AAAA,EACF,CAAC;AACH","sourcesContent":["import { union } from '@metamask/snaps-sdk';\nimport type {\n AnyStruct,\n Assign,\n Failure,\n ObjectSchema,\n ObjectType,\n} from '@metamask/superstruct';\nimport {\n assign,\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n} from '@metamask/superstruct';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\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 * 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\n// These types are copied from Superstruct, to mirror `assign`.\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n): Struct<ObjectType<Assign<ObjectA, ObjectB>>, Assign<ObjectA, ObjectB>>;\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n ObjectC extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n C: Struct<ObjectType<ObjectC>, ObjectC>,\n): Struct<\n ObjectType<Assign<Assign<ObjectA, ObjectB>, ObjectC>>,\n Assign<Assign<ObjectA, ObjectB>, ObjectC>\n>;\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n ObjectC extends ObjectSchema,\n ObjectD extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n C: Struct<ObjectType<ObjectC>, ObjectC>,\n D: Struct<ObjectType<ObjectD>, ObjectD>,\n): Struct<\n ObjectType<Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>>,\n Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>\n>;\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n ObjectC extends ObjectSchema,\n ObjectD extends ObjectSchema,\n ObjectE extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n C: Struct<ObjectType<ObjectC>, ObjectC>,\n D: Struct<ObjectType<ObjectD>, ObjectD>,\n E: Struct<ObjectType<ObjectE>, ObjectE>,\n): Struct<\n ObjectType<\n Assign<Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>, ObjectE>\n >,\n Assign<Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>, ObjectE>\n>;\n\n/**\n * Merge multiple structs into one, using superstruct `assign`.\n *\n * Differently from plain `assign`, this function also copies over refinements from each struct.\n *\n * @param structs - The `superstruct` structs to merge.\n * @returns The merged struct.\n */\nexport function mergeStructs(...structs: Struct<any>[]): Struct<any> {\n const mergedStruct = (assign as (...structs: Struct<any>[]) => Struct)(\n ...structs,\n );\n return new Struct({\n ...mergedStruct,\n *refiner(value, ctx) {\n for (const struct of structs) {\n yield* struct.refiner(value, ctx);\n }\n },\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/derivation-paths.ts"],"sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport slip44 from '@metamask/slip44';\n\nimport { isEqual } from './array';\n\nexport type SnapsDerivationPath = {\n path: ['m', ...string[]];\n curve: SupportedCurve;\n name: string;\n};\n\nexport const SNAPS_DERIVATION_PATHS: SnapsDerivationPath[] = [\n {\n path: ['m', `44'`, `0'`],\n curve: 'ed25519',\n name: 'Test BIP-32 Path (ed25519)',\n },\n {\n path: ['m', `44'`, `1'`],\n curve: 'secp256k1',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Legacy',\n },\n {\n path: ['m', `49'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Nested SegWit',\n },\n {\n path: ['m', `49'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Nested SegWit',\n },\n {\n path: ['m', `84'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Native SegWit',\n },\n {\n path: ['m', `84'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Native SegWit',\n },\n {\n path: ['m', `44'`, `501'`],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `501'`, \"0'\", \"0'\"],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `2'`],\n curve: 'secp256k1',\n name: 'Litecoin',\n },\n {\n path: ['m', `44'`, `3'`],\n curve: 'secp256k1',\n name: 'Dogecoin',\n },\n {\n path: ['m', `44'`, `60'`],\n curve: 'secp256k1',\n name: 'Ethereum',\n },\n {\n path: ['m', `44'`, `118'`],\n curve: 'secp256k1',\n name: 'Atom',\n },\n {\n path: ['m', `44'`, `145'`],\n curve: 'secp256k1',\n name: 'Bitcoin Cash',\n },\n {\n path: ['m', `44'`, `637'`],\n curve: 'ed25519',\n name: 'Aptos',\n },\n {\n path: ['m', `44'`, `714'`],\n curve: 'secp256k1',\n name: 'Binance (BNB)',\n },\n {\n path: ['m', `44'`, `784'`],\n curve: 'ed25519',\n name: 'Sui',\n },\n {\n path: ['m', `44'`, `931'`],\n curve: 'secp256k1',\n name: 'THORChain (RUNE)',\n },\n {\n path: ['m', `44'`, `330'`],\n curve: 'secp256k1',\n name: 'Terra (LUNA)',\n },\n {\n path: ['m', `44'`, `459'`],\n curve: 'secp256k1',\n name: 'Kava',\n },\n {\n path: ['m', `44'`, `529'`],\n curve: 'secp256k1',\n name: 'Secret Network',\n },\n {\n path: ['m', `44'`, `397'`, `0'`],\n curve: 'ed25519',\n name: 'NEAR Protocol',\n },\n {\n path: ['m', `44'`, `1'`, `0'`],\n curve: 'ed25519',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `472'`],\n curve: 'ed25519',\n name: 'Arweave',\n },\n {\n path: ['m', `44'`, `12586'`],\n curve: 'secp256k1',\n name: 'Mina',\n },\n {\n path: ['m', `44'`, `242'`],\n curve: 'ed25519',\n name: 'Nimiq',\n },\n {\n path: ['m', `44'`, `1729'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'Tezos',\n },\n {\n path: ['m', `1789'`, `0'`],\n curve: 'ed25519',\n name: 'Vega',\n },\n {\n path: ['m', `1852'`, `1815'`],\n curve: 'ed25519Bip32',\n name: 'Cardano',\n },\n];\n\n/**\n * Gets the name of a derivation path supported by snaps.\n *\n * @param path - The derivation path.\n * @param curve - The curve used to derive the keys.\n * @returns The name of the derivation path, otherwise null.\n */\nexport function getSnapDerivationPathName(\n path: SnapsDerivationPath['path'],\n curve: SupportedCurve,\n): string | null {\n const pathMetadata = SNAPS_DERIVATION_PATHS.find(\n (derivationPath) =>\n derivationPath.curve === curve && isEqual(derivationPath.path, path),\n );\n\n if (pathMetadata) {\n return pathMetadata.name;\n }\n\n // If the curve is secp256k1 and the path is a valid BIP44 path\n // we try looking for the network/protocol name in SLIP44\n if (\n curve === 'secp256k1' &&\n path[0] === 'm' &&\n path[1] === `44'` &&\n path[2].endsWith(`'`)\n ) {\n const coinType = path[2].slice(0, -1);\n return getSlip44ProtocolName(coinType) ?? null;\n }\n\n return null;\n}\n\n/**\n * Gets the name of the SLIP-44 protocol corresponding to the specified\n * `coin_type`.\n *\n * @param coinType - The SLIP-44 `coin_type` value whose name\n * to retrieve.\n * @returns The name of the protocol, otherwise null.\n */\nexport function getSlip44ProtocolName(coinType: number | string) {\n if (String(coinType) === '1') {\n return 'Test Networks';\n }\n\n return slip44[coinType as keyof typeof slip44]?.name ?? null;\n}\n"],"mappings":";;;;;AACA,OAAO,YAAY;AAUZ,IAAM,yBAAgD;AAAA,EAC3D;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,MAAM;AAAA,IACzB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,QAAQ,MAAM,IAAI;AAAA,IACrC,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,O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