@metamask/snaps-controllers 1.0.2 → 2.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 (322) hide show
  1. package/CHANGELOG.md +31 -562
  2. package/dist/cjs/cronjob/CronjobController.js +294 -0
  3. package/dist/cjs/cronjob/CronjobController.js.map +1 -0
  4. package/dist/cjs/cronjob/index.js +20 -0
  5. package/dist/cjs/cronjob/index.js.map +1 -0
  6. package/dist/cjs/fsm.js +69 -0
  7. package/dist/cjs/fsm.js.map +1 -0
  8. package/dist/cjs/index.js +23 -0
  9. package/dist/cjs/index.js.map +1 -0
  10. package/dist/cjs/logging.js +15 -0
  11. package/dist/cjs/logging.js.map +1 -0
  12. package/dist/cjs/services/AbstractExecutionService.js +390 -0
  13. package/dist/cjs/services/AbstractExecutionService.js.map +1 -0
  14. package/dist/cjs/services/ExecutionService.js +7 -0
  15. package/dist/cjs/services/ExecutionService.js.map +1 -0
  16. package/dist/cjs/services/ProxyPostMessageStream.js +116 -0
  17. package/dist/cjs/services/ProxyPostMessageStream.js.map +1 -0
  18. package/dist/cjs/services/browser.js +32 -0
  19. package/dist/cjs/services/browser.js.map +1 -0
  20. package/dist/cjs/services/iframe/IframeExecutionService.js +54 -0
  21. package/dist/cjs/services/iframe/IframeExecutionService.js.map +1 -0
  22. package/dist/cjs/services/iframe/index.js +20 -0
  23. package/dist/cjs/services/iframe/index.js.map +1 -0
  24. package/dist/cjs/services/index.js +32 -0
  25. package/dist/cjs/services/index.js.map +1 -0
  26. package/dist/cjs/services/node/NodeProcessExecutionService.js +30 -0
  27. package/dist/cjs/services/node/NodeProcessExecutionService.js.map +1 -0
  28. package/dist/cjs/services/node/NodeThreadExecutionService.js +30 -0
  29. package/dist/cjs/services/node/NodeThreadExecutionService.js.map +1 -0
  30. package/dist/cjs/services/node/index.js +21 -0
  31. package/dist/cjs/services/node/index.js.map +1 -0
  32. package/dist/cjs/services/offscreen/OffscreenExecutionService.js +159 -0
  33. package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +1 -0
  34. package/dist/cjs/services/offscreen/index.js +20 -0
  35. package/dist/cjs/services/offscreen/index.js.map +1 -0
  36. package/dist/cjs/services/webworker/WebWorkerExecutionService.js +148 -0
  37. package/dist/cjs/services/webworker/WebWorkerExecutionService.js.map +1 -0
  38. package/dist/cjs/services/webworker/index.js +20 -0
  39. package/dist/cjs/services/webworker/index.js.map +1 -0
  40. package/dist/cjs/snaps/RequestQueue.js +63 -0
  41. package/dist/cjs/snaps/RequestQueue.js.map +1 -0
  42. package/dist/cjs/snaps/SnapController.js +1736 -0
  43. package/dist/cjs/snaps/SnapController.js.map +1 -0
  44. package/dist/cjs/snaps/Timer.js +117 -0
  45. package/dist/cjs/snaps/Timer.js.map +1 -0
  46. package/dist/cjs/snaps/endowments/cronjob.js +100 -0
  47. package/dist/cjs/snaps/endowments/cronjob.js.map +1 -0
  48. package/dist/cjs/snaps/endowments/enum.js +24 -0
  49. package/dist/cjs/snaps/endowments/enum.js.map +1 -0
  50. package/dist/cjs/snaps/endowments/ethereum-provider.js +43 -0
  51. package/dist/cjs/snaps/endowments/ethereum-provider.js.map +1 -0
  52. package/dist/cjs/snaps/endowments/index.js +90 -0
  53. package/dist/cjs/snaps/endowments/index.js.map +1 -0
  54. package/dist/cjs/snaps/endowments/lifecycle-hooks.js +37 -0
  55. package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +1 -0
  56. package/dist/cjs/snaps/endowments/long-running.js +38 -0
  57. package/dist/cjs/snaps/endowments/long-running.js.map +1 -0
  58. package/dist/cjs/snaps/endowments/name-lookup.js +106 -0
  59. package/dist/cjs/snaps/endowments/name-lookup.js.map +1 -0
  60. package/dist/cjs/snaps/endowments/network-access.js +44 -0
  61. package/dist/cjs/snaps/endowments/network-access.js.map +1 -0
  62. package/dist/cjs/snaps/endowments/rpc.js +99 -0
  63. package/dist/cjs/snaps/endowments/rpc.js.map +1 -0
  64. package/dist/cjs/snaps/endowments/transaction-insight.js +106 -0
  65. package/dist/cjs/snaps/endowments/transaction-insight.js.map +1 -0
  66. package/dist/cjs/snaps/endowments/web-assembly.js +42 -0
  67. package/dist/cjs/snaps/endowments/web-assembly.js.map +1 -0
  68. package/dist/cjs/snaps/index.js +25 -0
  69. package/dist/cjs/snaps/index.js.map +1 -0
  70. package/dist/cjs/snaps/location/http.js +106 -0
  71. package/dist/cjs/snaps/location/http.js.map +1 -0
  72. package/dist/cjs/snaps/location/index.js +23 -0
  73. package/dist/cjs/snaps/location/index.js.map +1 -0
  74. package/dist/cjs/snaps/location/local.js +93 -0
  75. package/dist/cjs/snaps/location/local.js.map +1 -0
  76. package/dist/cjs/snaps/location/location.js +34 -0
  77. package/dist/cjs/snaps/location/location.js.map +1 -0
  78. package/dist/cjs/snaps/location/npm.js +293 -0
  79. package/dist/cjs/snaps/location/npm.js.map +1 -0
  80. package/dist/cjs/snaps/permissions.js +61 -0
  81. package/dist/cjs/snaps/permissions.js.map +1 -0
  82. package/dist/cjs/snaps/registry/index.js +21 -0
  83. package/dist/cjs/snaps/registry/index.js.map +1 -0
  84. package/dist/cjs/snaps/registry/json.js +277 -0
  85. package/dist/cjs/snaps/registry/json.js.map +1 -0
  86. package/dist/cjs/snaps/registry/registry.js +18 -0
  87. package/dist/cjs/snaps/registry/registry.js.map +1 -0
  88. package/dist/cjs/snaps/selectors.js +13 -0
  89. package/dist/cjs/snaps/selectors.js.map +1 -0
  90. package/dist/cjs/utils.js +70 -0
  91. package/dist/cjs/utils.js.map +1 -0
  92. package/dist/esm/cronjob/CronjobController.js +279 -0
  93. package/dist/esm/cronjob/CronjobController.js.map +1 -0
  94. package/dist/esm/cronjob/index.js +3 -0
  95. package/dist/esm/cronjob/index.js.map +1 -0
  96. package/dist/esm/fsm.js +70 -0
  97. package/dist/esm/fsm.js.map +1 -0
  98. package/dist/esm/index.js +6 -0
  99. package/dist/esm/index.js.map +1 -0
  100. package/dist/esm/logging.js +10 -0
  101. package/dist/esm/logging.js.map +1 -0
  102. package/dist/esm/services/AbstractExecutionService.js +373 -0
  103. package/dist/esm/services/AbstractExecutionService.js.map +1 -0
  104. package/dist/esm/services/ExecutionService.js +4 -0
  105. package/dist/esm/services/ExecutionService.js.map +1 -0
  106. package/dist/esm/services/ProxyPostMessageStream.js +109 -0
  107. package/dist/esm/services/ProxyPostMessageStream.js.map +1 -0
  108. package/dist/esm/services/browser.js +9 -0
  109. package/dist/esm/services/browser.js.map +1 -0
  110. package/dist/esm/services/iframe/IframeExecutionService.js +44 -0
  111. package/dist/esm/services/iframe/IframeExecutionService.js.map +1 -0
  112. package/dist/esm/services/iframe/index.js +3 -0
  113. package/dist/esm/services/iframe/index.js.map +1 -0
  114. package/dist/esm/services/index.js +9 -0
  115. package/dist/esm/services/index.js.map +1 -0
  116. package/dist/esm/services/node/NodeProcessExecutionService.js +20 -0
  117. package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -0
  118. package/dist/esm/services/node/NodeThreadExecutionService.js +21 -0
  119. package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -0
  120. package/dist/esm/services/node/index.js +4 -0
  121. package/dist/esm/services/node/index.js.map +1 -0
  122. package/dist/esm/services/offscreen/OffscreenExecutionService.js +149 -0
  123. package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -0
  124. package/dist/esm/services/offscreen/index.js +3 -0
  125. package/dist/esm/services/offscreen/index.js.map +1 -0
  126. package/dist/esm/services/webworker/WebWorkerExecutionService.js +130 -0
  127. package/dist/esm/services/webworker/WebWorkerExecutionService.js.map +1 -0
  128. package/dist/esm/services/webworker/index.js +3 -0
  129. package/dist/esm/services/webworker/index.js.map +1 -0
  130. package/dist/esm/snaps/RequestQueue.js +53 -0
  131. package/dist/esm/snaps/RequestQueue.js.map +1 -0
  132. package/dist/esm/snaps/SnapController.js +1715 -0
  133. package/dist/esm/snaps/SnapController.js.map +1 -0
  134. package/dist/esm/snaps/Timer.js +107 -0
  135. package/dist/esm/snaps/Timer.js.map +1 -0
  136. package/dist/esm/snaps/endowments/cronjob.js +99 -0
  137. package/dist/esm/snaps/endowments/cronjob.js.map +1 -0
  138. package/dist/esm/snaps/endowments/enum.js +14 -0
  139. package/dist/esm/snaps/endowments/enum.js.map +1 -0
  140. package/dist/esm/snaps/endowments/ethereum-provider.js +33 -0
  141. package/dist/esm/snaps/endowments/ethereum-provider.js.map +1 -0
  142. package/dist/esm/snaps/endowments/index.js +47 -0
  143. package/dist/esm/snaps/endowments/index.js.map +1 -0
  144. package/dist/esm/snaps/endowments/lifecycle-hooks.js +27 -0
  145. package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +1 -0
  146. package/dist/esm/snaps/endowments/long-running.js +28 -0
  147. package/dist/esm/snaps/endowments/long-running.js.map +1 -0
  148. package/dist/esm/snaps/endowments/name-lookup.js +98 -0
  149. package/dist/esm/snaps/endowments/name-lookup.js.map +1 -0
  150. package/dist/esm/snaps/endowments/network-access.js +34 -0
  151. package/dist/esm/snaps/endowments/network-access.js.map +1 -0
  152. package/dist/esm/snaps/endowments/rpc.js +88 -0
  153. package/dist/esm/snaps/endowments/rpc.js.map +1 -0
  154. package/dist/esm/snaps/endowments/transaction-insight.js +99 -0
  155. package/dist/esm/snaps/endowments/transaction-insight.js.map +1 -0
  156. package/dist/esm/snaps/endowments/web-assembly.js +32 -0
  157. package/dist/esm/snaps/endowments/web-assembly.js.map +1 -0
  158. package/dist/esm/snaps/index.js +8 -0
  159. package/dist/esm/snaps/index.js.map +1 -0
  160. package/dist/{snaps → esm/snaps}/location/http.js +52 -31
  161. package/dist/esm/snaps/location/http.js.map +1 -0
  162. package/dist/esm/snaps/location/index.js +6 -0
  163. package/dist/esm/snaps/location/index.js.map +1 -0
  164. package/dist/esm/snaps/location/local.js +83 -0
  165. package/dist/esm/snaps/location/local.js.map +1 -0
  166. package/dist/esm/snaps/location/location.js +30 -0
  167. package/dist/esm/snaps/location/location.js.map +1 -0
  168. package/dist/{snaps → esm/snaps}/location/npm.js +143 -117
  169. package/dist/esm/snaps/location/npm.js.map +1 -0
  170. package/dist/esm/snaps/permissions.js +50 -0
  171. package/dist/esm/snaps/permissions.js.map +1 -0
  172. package/dist/esm/snaps/registry/index.js +4 -0
  173. package/dist/esm/snaps/registry/index.js.map +1 -0
  174. package/dist/esm/snaps/registry/json.js +267 -0
  175. package/dist/esm/snaps/registry/json.js.map +1 -0
  176. package/dist/esm/snaps/registry/registry.js +8 -0
  177. package/dist/esm/snaps/registry/registry.js.map +1 -0
  178. package/dist/esm/snaps/selectors.js +3 -0
  179. package/dist/esm/snaps/selectors.js.map +1 -0
  180. package/dist/{utils.js → esm/utils.js} +21 -30
  181. package/dist/esm/utils.js.map +1 -0
  182. package/dist/{cronjob → types/cronjob}/CronjobController.d.ts +12 -11
  183. package/dist/{fsm.d.ts → types/fsm.d.ts} +1 -1
  184. package/dist/{index.d.ts → types/index.d.ts} +0 -1
  185. package/dist/{services → types/services}/AbstractExecutionService.d.ts +4 -4
  186. package/dist/{services → types/services}/ExecutionService.d.ts +3 -3
  187. package/dist/{services/offscreen/OffscreenPostMessageStream.d.ts → types/services/ProxyPostMessageStream.d.ts} +10 -10
  188. package/dist/{services → types/services}/browser.d.ts +2 -0
  189. package/dist/{services → types/services}/iframe/IframeExecutionService.d.ts +3 -2
  190. package/dist/{services → types/services}/index.d.ts +2 -0
  191. package/dist/{services → types/services}/node/NodeProcessExecutionService.d.ts +4 -3
  192. package/dist/{services → types/services}/node/NodeThreadExecutionService.d.ts +3 -2
  193. package/dist/{services → types/services}/offscreen/OffscreenExecutionService.d.ts +4 -3
  194. package/dist/types/services/offscreen/index.d.ts +1 -0
  195. package/dist/types/services/webworker/WebWorkerExecutionService.d.ts +45 -0
  196. package/dist/types/services/webworker/index.d.ts +1 -0
  197. package/dist/{snaps → types/snaps}/SnapController.d.ts +78 -39
  198. package/dist/{snaps → types/snaps}/endowments/cronjob.d.ts +5 -3
  199. package/dist/{snaps → types/snaps}/endowments/enum.d.ts +3 -2
  200. package/dist/{snaps → types/snaps}/endowments/ethereum-provider.d.ts +2 -1
  201. package/dist/{snaps → types/snaps}/endowments/index.d.ts +23 -14
  202. package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +15 -0
  203. package/dist/{snaps → types/snaps}/endowments/long-running.d.ts +2 -1
  204. package/dist/types/snaps/endowments/name-lookup.d.ts +38 -0
  205. package/dist/{snaps → types/snaps}/endowments/network-access.d.ts +2 -1
  206. package/dist/{snaps → types/snaps}/endowments/rpc.d.ts +5 -3
  207. package/dist/{snaps → types/snaps}/endowments/transaction-insight.d.ts +3 -2
  208. package/dist/{snaps → types/snaps}/endowments/web-assembly.d.ts +2 -1
  209. package/dist/{snaps → types/snaps}/index.d.ts +2 -0
  210. package/dist/{snaps → types/snaps}/location/http.d.ts +3 -2
  211. package/dist/{snaps → types/snaps}/location/local.d.ts +3 -3
  212. package/dist/{snaps → types/snaps}/location/location.d.ts +2 -2
  213. package/dist/types/snaps/location/npm.d.ts +49 -0
  214. package/dist/types/snaps/permissions.d.ts +16 -0
  215. package/dist/{snaps → types/snaps}/registry/json.d.ts +5 -4
  216. package/dist/{snaps → types/snaps}/registry/registry.d.ts +5 -5
  217. package/dist/types/snaps/selectors.d.ts +2 -0
  218. package/dist/{utils.d.ts → types/utils.d.ts} +14 -14
  219. package/package.json +55 -45
  220. package/dist/cronjob/CronjobController.js +0 -248
  221. package/dist/cronjob/CronjobController.js.map +0 -1
  222. package/dist/cronjob/index.js +0 -18
  223. package/dist/cronjob/index.js.map +0 -1
  224. package/dist/fsm.js +0 -75
  225. package/dist/fsm.js.map +0 -1
  226. package/dist/index.js +0 -22
  227. package/dist/index.js.map +0 -1
  228. package/dist/logging.js +0 -13
  229. package/dist/logging.js.map +0 -1
  230. package/dist/multichain/MultiChainController.d.ts +0 -137
  231. package/dist/multichain/MultiChainController.js +0 -339
  232. package/dist/multichain/MultiChainController.js.map +0 -1
  233. package/dist/multichain/index.d.ts +0 -3
  234. package/dist/multichain/index.js +0 -20
  235. package/dist/multichain/index.js.map +0 -1
  236. package/dist/multichain/matching.d.ts +0 -9
  237. package/dist/multichain/matching.js +0 -57
  238. package/dist/multichain/matching.js.map +0 -1
  239. package/dist/multichain/middleware.d.ts +0 -14
  240. package/dist/multichain/middleware.js +0 -42
  241. package/dist/multichain/middleware.js.map +0 -1
  242. package/dist/services/AbstractExecutionService.js +0 -318
  243. package/dist/services/AbstractExecutionService.js.map +0 -1
  244. package/dist/services/ExecutionService.js +0 -4
  245. package/dist/services/ExecutionService.js.map +0 -1
  246. package/dist/services/browser.js +0 -22
  247. package/dist/services/browser.js.map +0 -1
  248. package/dist/services/iframe/IframeExecutionService.js +0 -30
  249. package/dist/services/iframe/IframeExecutionService.js.map +0 -1
  250. package/dist/services/iframe/index.js +0 -18
  251. package/dist/services/iframe/index.js.map +0 -1
  252. package/dist/services/index.js +0 -22
  253. package/dist/services/index.js.map +0 -1
  254. package/dist/services/node/NodeProcessExecutionService.js +0 -18
  255. package/dist/services/node/NodeProcessExecutionService.js.map +0 -1
  256. package/dist/services/node/NodeThreadExecutionService.js +0 -19
  257. package/dist/services/node/NodeThreadExecutionService.js.map +0 -1
  258. package/dist/services/node/index.js +0 -19
  259. package/dist/services/node/index.js.map +0 -1
  260. package/dist/services/offscreen/OffscreenExecutionService.js +0 -100
  261. package/dist/services/offscreen/OffscreenExecutionService.js.map +0 -1
  262. package/dist/services/offscreen/OffscreenPostMessageStream.js +0 -66
  263. package/dist/services/offscreen/OffscreenPostMessageStream.js.map +0 -1
  264. package/dist/services/offscreen/index.d.ts +0 -2
  265. package/dist/services/offscreen/index.js +0 -19
  266. package/dist/services/offscreen/index.js.map +0 -1
  267. package/dist/snaps/RequestQueue.js +0 -44
  268. package/dist/snaps/RequestQueue.js.map +0 -1
  269. package/dist/snaps/SnapController.js +0 -1478
  270. package/dist/snaps/SnapController.js.map +0 -1
  271. package/dist/snaps/Timer.js +0 -86
  272. package/dist/snaps/Timer.js.map +0 -1
  273. package/dist/snaps/endowments/cronjob.js +0 -105
  274. package/dist/snaps/endowments/cronjob.js.map +0 -1
  275. package/dist/snaps/endowments/enum.js +0 -15
  276. package/dist/snaps/endowments/enum.js.map +0 -1
  277. package/dist/snaps/endowments/ethereum-provider.js +0 -32
  278. package/dist/snaps/endowments/ethereum-provider.js.map +0 -1
  279. package/dist/snaps/endowments/index.js +0 -60
  280. package/dist/snaps/endowments/index.js.map +0 -1
  281. package/dist/snaps/endowments/keyring.d.ts +0 -40
  282. package/dist/snaps/endowments/keyring.js +0 -103
  283. package/dist/snaps/endowments/keyring.js.map +0 -1
  284. package/dist/snaps/endowments/long-running.js +0 -29
  285. package/dist/snaps/endowments/long-running.js.map +0 -1
  286. package/dist/snaps/endowments/network-access.js +0 -30
  287. package/dist/snaps/endowments/network-access.js.map +0 -1
  288. package/dist/snaps/endowments/rpc.js +0 -92
  289. package/dist/snaps/endowments/rpc.js.map +0 -1
  290. package/dist/snaps/endowments/transaction-insight.js +0 -106
  291. package/dist/snaps/endowments/transaction-insight.js.map +0 -1
  292. package/dist/snaps/endowments/web-assembly.js +0 -31
  293. package/dist/snaps/endowments/web-assembly.js.map +0 -1
  294. package/dist/snaps/index.js +0 -21
  295. package/dist/snaps/index.js.map +0 -1
  296. package/dist/snaps/location/http.js.map +0 -1
  297. package/dist/snaps/location/index.js +0 -21
  298. package/dist/snaps/location/index.js.map +0 -1
  299. package/dist/snaps/location/local.js +0 -51
  300. package/dist/snaps/location/local.js.map +0 -1
  301. package/dist/snaps/location/location.js +0 -34
  302. package/dist/snaps/location/location.js.map +0 -1
  303. package/dist/snaps/location/npm.d.ts +0 -28
  304. package/dist/snaps/location/npm.js.map +0 -1
  305. package/dist/snaps/registry/index.js +0 -19
  306. package/dist/snaps/registry/index.js.map +0 -1
  307. package/dist/snaps/registry/json.js +0 -197
  308. package/dist/snaps/registry/json.js.map +0 -1
  309. package/dist/snaps/registry/registry.js +0 -11
  310. package/dist/snaps/registry/registry.js.map +0 -1
  311. package/dist/snaps/selectors.d.ts +0 -2
  312. package/dist/snaps/selectors.js +0 -6
  313. package/dist/snaps/selectors.js.map +0 -1
  314. package/dist/utils.js.map +0 -1
  315. /package/dist/{cronjob → types/cronjob}/index.d.ts +0 -0
  316. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  317. /package/dist/{services → types/services}/iframe/index.d.ts +0 -0
  318. /package/dist/{services → types/services}/node/index.d.ts +0 -0
  319. /package/dist/{snaps → types/snaps}/RequestQueue.d.ts +0 -0
  320. /package/dist/{snaps → types/snaps}/Timer.d.ts +0 -0
  321. /package/dist/{snaps → types/snaps}/location/index.d.ts +0 -0
  322. /package/dist/{snaps → types/snaps}/registry/index.d.ts +0 -0
@@ -1,90 +1,66 @@
1
- "use strict";
2
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
- };
7
- var __importDefault = (this && this.__importDefault) || function (mod) {
8
- return (mod && mod.__esModule) ? mod : { "default": mod };
9
- };
10
- var _NpmLocation_instances, _NpmLocation_lazyInit;
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.NpmLocation = void 0;
13
- const snaps_utils_1 = require("@metamask/snaps-utils");
14
- const utils_1 = require("@metamask/utils");
15
- const concat_stream_1 = __importDefault(require("concat-stream"));
16
- const gunzip_maybe_1 = __importDefault(require("gunzip-maybe"));
17
- const pump_1 = __importDefault(require("pump"));
18
- const readable_web_to_node_stream_1 = require("readable-web-to-node-stream");
19
- const tar_stream_1 = require("tar-stream");
20
- const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
21
- class NpmLocation {
22
- constructor(url, opts = {}) {
23
- _NpmLocation_instances.add(this);
24
- const allowCustomRegistries = opts.allowCustomRegistries ?? false;
25
- const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);
26
- const requestedRange = opts.versionRange ?? snaps_utils_1.DEFAULT_REQUESTED_SNAP_VERSION;
27
- (0, utils_1.assertStruct)(url.toString(), snaps_utils_1.NpmSnapIdStruct, 'Invalid Snap Id: ');
28
- let registry;
29
- if (url.host === '' &&
30
- url.port === '' &&
31
- url.username === '' &&
32
- url.password === '') {
33
- registry = new URL(DEFAULT_NPM_REGISTRY);
34
- }
35
- else {
36
- registry = 'https://';
37
- if (url.username) {
38
- registry += url.username;
39
- if (url.password) {
40
- registry += `:${url.password}`;
41
- }
42
- registry += '@';
43
- }
44
- registry += url.host;
45
- registry = new URL(registry);
46
- (0, utils_1.assert)(allowCustomRegistries, new TypeError(`Custom NPM registries are disabled, tried to use "${registry.toString()}".`));
47
- }
48
- (0, utils_1.assert)(registry.pathname === '/' &&
49
- registry.search === '' &&
50
- registry.hash === '');
51
- (0, utils_1.assert)(url.pathname !== '' && url.pathname !== '/', new TypeError('The package name in NPM location is empty.'));
52
- let packageName = url.pathname;
53
- if (packageName.startsWith('/')) {
54
- packageName = packageName.slice(1);
55
- }
56
- this.meta = {
57
- requestedRange,
58
- registry,
59
- packageName,
60
- fetch: fetchFunction,
61
- };
1
+ function _check_private_redeclaration(obj, privateCollection) {
2
+ if (privateCollection.has(obj)) {
3
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
62
4
  }
5
+ }
6
+ function _class_private_method_get(receiver, privateSet, fn) {
7
+ if (!privateSet.has(receiver)) {
8
+ throw new TypeError("attempted to get private field on non-instance");
9
+ }
10
+ return fn;
11
+ }
12
+ function _class_private_method_init(obj, privateSet) {
13
+ _check_private_redeclaration(obj, privateSet);
14
+ privateSet.add(obj);
15
+ }
16
+ function _define_property(obj, key, value) {
17
+ if (key in obj) {
18
+ Object.defineProperty(obj, key, {
19
+ value: value,
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true
23
+ });
24
+ } else {
25
+ obj[key] = value;
26
+ }
27
+ return obj;
28
+ }
29
+ import { createSnapManifest, DEFAULT_REQUESTED_SNAP_VERSION, getTargetVersion, isValidUrl, NpmSnapIdStruct, VirtualFile, normalizeRelative, parseJson } from '@metamask/snaps-utils';
30
+ import { assert, assertIsSemVerVersion, assertStruct, isObject } from '@metamask/utils';
31
+ import concat from 'concat-stream';
32
+ import createGunzipStream from 'gunzip-maybe';
33
+ import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
34
+ import { pipeline } from 'stream';
35
+ import { extract as tarExtract } from 'tar-stream';
36
+ export const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
37
+ var _lazyInit = /*#__PURE__*/ new WeakSet();
38
+ export class NpmLocation {
63
39
  async manifest() {
64
40
  if (this.validatedManifest) {
65
41
  return this.validatedManifest.clone();
66
42
  }
67
43
  const vfile = await this.fetch('snap.manifest.json');
68
- const result = (0, snaps_utils_1.parseJson)(vfile.toString());
69
- vfile.result = (0, snaps_utils_1.createSnapManifest)(result);
44
+ const result = parseJson(vfile.toString());
45
+ vfile.result = createSnapManifest(result);
70
46
  this.validatedManifest = vfile;
71
47
  return this.manifest();
72
48
  }
73
49
  async fetch(path) {
74
- const relativePath = (0, snaps_utils_1.normalizeRelative)(path);
50
+ const relativePath = normalizeRelative(path);
75
51
  if (!this.files) {
76
- await __classPrivateFieldGet(this, _NpmLocation_instances, "m", _NpmLocation_lazyInit).call(this);
77
- (0, utils_1.assert)(this.files !== undefined);
52
+ await _class_private_method_get(this, _lazyInit, lazyInit).call(this);
53
+ assert(this.files !== undefined);
78
54
  }
79
55
  const vfile = this.files.get(relativePath);
80
- (0, utils_1.assert)(vfile !== undefined, new TypeError(`File "${path}" not found in package.`));
56
+ assert(vfile !== undefined, new TypeError(`File "${path}" not found in package.`));
81
57
  return vfile.clone();
82
58
  }
83
59
  get packageName() {
84
60
  return this.meta.packageName;
85
61
  }
86
62
  get version() {
87
- (0, utils_1.assert)(this.meta.version !== undefined, 'Tried to access version without first fetching NPM package.');
63
+ assert(this.meta.version !== undefined, 'Tried to access version without first fetching NPM package.');
88
64
  return this.meta.version;
89
65
  }
90
66
  get registry() {
@@ -93,10 +69,47 @@ class NpmLocation {
93
69
  get versionRange() {
94
70
  return this.meta.requestedRange;
95
71
  }
72
+ constructor(url, opts = {}){
73
+ _class_private_method_init(this, _lazyInit);
74
+ _define_property(this, "meta", void 0);
75
+ _define_property(this, "validatedManifest", void 0);
76
+ _define_property(this, "files", void 0);
77
+ const allowCustomRegistries = opts.allowCustomRegistries ?? false;
78
+ const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);
79
+ const requestedRange = opts.versionRange ?? DEFAULT_REQUESTED_SNAP_VERSION;
80
+ assertStruct(url.toString(), NpmSnapIdStruct, 'Invalid Snap Id: ');
81
+ let registry;
82
+ if (url.host === '' && url.port === '' && url.username === '' && url.password === '') {
83
+ registry = new URL(DEFAULT_NPM_REGISTRY);
84
+ } else {
85
+ registry = 'https://';
86
+ if (url.username) {
87
+ registry += url.username;
88
+ if (url.password) {
89
+ registry += `:${url.password}`;
90
+ }
91
+ registry += '@';
92
+ }
93
+ registry += url.host;
94
+ registry = new URL(registry);
95
+ assert(allowCustomRegistries, new TypeError(`Custom NPM registries are disabled, tried to use "${registry.toString()}".`));
96
+ }
97
+ assert(registry.pathname === '/' && registry.search === '' && registry.hash === '');
98
+ assert(url.pathname !== '' && url.pathname !== '/', new TypeError('The package name in NPM location is empty.'));
99
+ let packageName = url.pathname;
100
+ if (packageName.startsWith('/')) {
101
+ packageName = packageName.slice(1);
102
+ }
103
+ this.meta = {
104
+ requestedRange,
105
+ registry,
106
+ packageName,
107
+ fetch: fetchFunction
108
+ };
109
+ }
96
110
  }
97
- exports.NpmLocation = NpmLocation;
98
- _NpmLocation_instances = new WeakSet(), _NpmLocation_lazyInit = async function _NpmLocation_lazyInit() {
99
- (0, utils_1.assert)(this.files === undefined);
111
+ async function lazyInit() {
112
+ assert(this.files === undefined);
100
113
  const [tarballResponse, actualVersion] = await fetchNpmTarball(this.meta.packageName, this.meta.requestedRange, this.meta.registry, this.meta.fetch);
101
114
  this.meta.version = actualVersion;
102
115
  let canonicalBase = 'npm://';
@@ -110,53 +123,64 @@ _NpmLocation_instances = new WeakSet(), _NpmLocation_lazyInit = async function _
110
123
  canonicalBase += this.meta.registry.host;
111
124
  // TODO(ritave): Lazily extract files instead of up-front extracting all of them
112
125
  // We would need to replace tar-stream package because it requires immediate consumption of streams.
113
- await new Promise((resolve, reject) => {
126
+ await new Promise((resolve, reject)=>{
114
127
  this.files = new Map();
115
- (0, pump_1.default)(getNodeStream(tarballResponse),
116
- // The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
128
+ pipeline(getNodeStream(tarballResponse), // The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
117
129
  // before we can actually grab any files from it.
118
130
  // To prevent recursion-based zip bombs, we set a maximum recursion depth of 1.
119
- (0, gunzip_maybe_1.default)(1), createTarballStream(`${canonicalBase}/${this.meta.packageName}/`, this.files), (error) => {
131
+ createGunzipStream(1), createTarballStream(`${canonicalBase}/${this.meta.packageName}/`, this.files), (error)=>{
120
132
  error ? reject(error) : resolve();
121
133
  });
122
134
  });
123
- };
135
+ }
124
136
  // Safety limit for tarballs, 250 MB in bytes
125
137
  const TARBALL_SIZE_SAFETY_LIMIT = 262144000;
126
138
  /**
127
- * Fetches the tarball (`.tgz` file) of the specified package and version from
128
- * the public npm registry. Throws an error if fetching fails.
139
+ * Fetches the NPM metadata of the specified package from
140
+ * the public npm registry.
129
141
  *
130
- * @param packageName - The name of the package whose tarball to fetch.
131
- * @param versionRange - The SemVer range of the package to fetch. The highest
132
- * version satisfying the range will be fetched.
133
- * @param registryUrl - The URL of the npm registry to fetch the tarball from.
142
+ * @param packageName - The name of the package whose metadata to fetch.
143
+ * @param registryUrl - The URL of the npm registry to fetch the metadata from.
134
144
  * @param fetchFunction - The fetch function to use. Defaults to the global
135
145
  * {@link fetch}. Useful for Node.js compatibility.
136
- * @returns A tuple of the {@link Response} for the package tarball and the
137
- * actual version of the package.
138
- */
139
- async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction) {
146
+ * @returns The NPM metadata object.
147
+ * @throws If fetching the metadata fails.
148
+ */ export async function fetchNpmMetadata(packageName, registryUrl, fetchFunction) {
140
149
  const packageResponse = await fetchFunction(new URL(packageName, registryUrl).toString());
141
150
  if (!packageResponse.ok) {
142
151
  throw new Error(`Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`);
143
152
  }
144
153
  const packageMetadata = await packageResponse.json();
145
- if (!(0, utils_1.isObject)(packageMetadata)) {
154
+ if (!isObject(packageMetadata)) {
146
155
  throw new Error(`Failed to fetch package "${packageName}" metadata from npm.`);
147
156
  }
148
- const versions = Object.keys(packageMetadata?.versions ?? {}).map((version) => {
149
- (0, utils_1.assertIsSemVerVersion)(version);
157
+ return packageMetadata;
158
+ }
159
+ /**
160
+ * Fetches the tarball (`.tgz` file) of the specified package and version from
161
+ * the public npm registry.
162
+ *
163
+ * @param packageName - The name of the package whose tarball to fetch.
164
+ * @param versionRange - The SemVer range of the package to fetch. The highest
165
+ * version satisfying the range will be fetched.
166
+ * @param registryUrl - The URL of the npm registry to fetch the tarball from.
167
+ * @param fetchFunction - The fetch function to use. Defaults to the global
168
+ * {@link fetch}. Useful for Node.js compatibility.
169
+ * @returns A tuple of the {@link Response} for the package tarball and the
170
+ * actual version of the package.
171
+ * @throws If fetching the tarball fails.
172
+ */ async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction) {
173
+ const packageMetadata = await fetchNpmMetadata(packageName, registryUrl, fetchFunction);
174
+ const versions = Object.keys(packageMetadata?.versions ?? {}).map((version)=>{
175
+ assertIsSemVerVersion(version);
150
176
  return version;
151
177
  });
152
- const targetVersion = (0, snaps_utils_1.getTargetVersion)(versions, versionRange);
178
+ const targetVersion = getTargetVersion(versions, versionRange);
153
179
  if (targetVersion === null) {
154
180
  throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}".`);
155
181
  }
156
- const tarballUrlString = packageMetadata?.versions?.[targetVersion]
157
- ?.dist?.tarball;
158
- if (!(0, snaps_utils_1.isValidUrl)(tarballUrlString) ||
159
- !tarballUrlString.toString().endsWith('.tgz')) {
182
+ const tarballUrlString = packageMetadata?.versions?.[targetVersion]?.dist?.tarball;
183
+ if (!isValidUrl(tarballUrlString) || !tarballUrlString.toString().endsWith('.tgz')) {
160
184
  throw new Error(`Failed to find valid tarball URL in NPM metadata for package "${packageName}".`);
161
185
  }
162
186
  // Override the tarball hostname/protocol with registryUrl hostname/protocol
@@ -171,16 +195,18 @@ async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunc
171
195
  }
172
196
  // We assume that NPM is a good actor and provides us with a valid `content-length` header.
173
197
  const tarballSizeString = tarballResponse.headers.get('content-length');
174
- (0, utils_1.assert)(tarballSizeString, 'Snap tarball has invalid content-length');
198
+ assert(tarballSizeString, 'Snap tarball has invalid content-length');
175
199
  const tarballSize = parseInt(tarballSizeString, 10);
176
- (0, utils_1.assert)(tarballSize <= TARBALL_SIZE_SAFETY_LIMIT, 'Snap tarball exceeds size limit');
177
- return [tarballResponse.body, targetVersion];
200
+ assert(tarballSize <= TARBALL_SIZE_SAFETY_LIMIT, 'Snap tarball exceeds size limit');
201
+ return [
202
+ tarballResponse.body,
203
+ targetVersion
204
+ ];
178
205
  }
179
206
  /**
180
207
  * The paths of files within npm tarballs appear to always be prefixed with
181
208
  * "package/".
182
- */
183
- const NPM_TARBALL_PATH_PREFIX = /^package\//u;
209
+ */ const NPM_TARBALL_PATH_PREFIX = /^package\//u;
184
210
  /**
185
211
  * Converts a {@link ReadableStream} to a Node.js {@link Readable}
186
212
  * stream. Returns the stream directly if it is already a Node.js stream.
@@ -189,12 +215,11 @@ const NPM_TARBALL_PATH_PREFIX = /^package\//u;
189
215
  *
190
216
  * @param stream - The stream to convert.
191
217
  * @returns The given stream as a Node.js Readable stream.
192
- */
193
- function getNodeStream(stream) {
218
+ */ function getNodeStream(stream) {
194
219
  if (typeof stream.getReader !== 'function') {
195
220
  return stream;
196
221
  }
197
- return new readable_web_to_node_stream_1.ReadableWebToNodeStream(stream);
222
+ return new ReadableWebToNodeStream(stream);
198
223
  }
199
224
  /**
200
225
  * Creates a `tar-stream` that will get the necessary files from an npm Snap
@@ -203,39 +228,39 @@ function getNodeStream(stream) {
203
228
  * @param canonicalBase - A base URI as specified in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8}. Starting with 'npm:'. Will be used for canonicalPath vfile argument.
204
229
  * @param files - An object to write target file contents to.
205
230
  * @returns The {@link Writable} tarball extraction stream.
206
- */
207
- function createTarballStream(canonicalBase, files) {
208
- (0, utils_1.assert)(canonicalBase.endsWith('/'), "Base needs to end with '/' for relative paths to be added as children instead of siblings.");
209
- (0, utils_1.assert)(canonicalBase.startsWith('npm:'), 'Protocol mismatch, expected "npm:".');
231
+ */ function createTarballStream(canonicalBase, files) {
232
+ assert(canonicalBase.endsWith('/'), "Base needs to end with '/' for relative paths to be added as children instead of siblings.");
233
+ assert(canonicalBase.startsWith('npm:'), 'Protocol mismatch, expected "npm:".');
210
234
  // `tar-stream` is pretty old-school, so we create it first and then
211
235
  // instrument it by adding event listeners.
212
- const extractStream = (0, tar_stream_1.extract)();
236
+ const extractStream = tarExtract();
213
237
  let totalSize = 0;
214
238
  // "entry" is fired for every discreet entity in the tarball. This includes
215
239
  // files and folders.
216
- extractStream.on('entry', (header, entryStream, next) => {
240
+ extractStream.on('entry', (header, entryStream, next)=>{
217
241
  const { name: headerName, type: headerType } = header;
218
242
  if (headerType === 'file') {
219
243
  // The name is a path if the header type is "file".
220
244
  const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');
221
- return entryStream.pipe((0, concat_stream_1.default)((data) => {
245
+ return entryStream.pipe(concat({
246
+ encoding: 'uint8array'
247
+ }, (data)=>{
222
248
  try {
223
249
  totalSize += data.byteLength;
224
250
  // To prevent zip bombs, we set a safety limit for the total size of tarballs.
225
- (0, utils_1.assert)(totalSize < TARBALL_SIZE_SAFETY_LIMIT, `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`);
226
- const vfile = new snaps_utils_1.VirtualFile({
251
+ assert(totalSize < TARBALL_SIZE_SAFETY_LIMIT, `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`);
252
+ const vfile = new VirtualFile({
227
253
  value: data,
228
254
  path,
229
255
  data: {
230
- canonicalPath: new URL(path, canonicalBase).toString(),
231
- },
256
+ canonicalPath: new URL(path, canonicalBase).toString()
257
+ }
232
258
  });
233
259
  // We disallow files having identical paths as it may confuse our checksum calculations.
234
- (0, utils_1.assert)(!files.has(path), 'Malformed tarball, multiple files with the same path.');
260
+ assert(!files.has(path), 'Malformed tarball, multiple files with the same path.');
235
261
  files.set(path, vfile);
236
262
  return next();
237
- }
238
- catch (error) {
263
+ } catch (error) {
239
264
  return extractStream.destroy(error);
240
265
  }
241
266
  }));
@@ -243,9 +268,10 @@ function createTarballStream(canonicalBase, files) {
243
268
  // If we get here, the entry is not a file, and we want to ignore. The entry
244
269
  // stream must be drained, or the extractStream will stop reading. This is
245
270
  // effectively a no-op for the current entry.
246
- entryStream.on('end', () => next());
271
+ entryStream.on('end', ()=>next());
247
272
  return entryStream.resume();
248
273
  });
249
274
  return extractStream;
250
275
  }
276
+
251
277
  //# sourceMappingURL=npm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/location/npm.ts"],"sourcesContent":["import type { SnapManifest } from '@metamask/snaps-utils';\nimport {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n VirtualFile,\n normalizeRelative,\n parseJson,\n} from '@metamask/snaps-utils';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n} from '@metamask/utils';\nimport concat from 'concat-stream';\nimport createGunzipStream from 'gunzip-maybe';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { pipeline } from 'stream';\nimport type { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport type { DetectSnapLocationOptions, SnapLocation } from './location';\n\nexport const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n}\nexport interface NpmOptions {\n /**\n * @default DEFAULT_REQUESTED_SNAP_VERSION\n */\n versionRange?: SemVerRange;\n /**\n * Whether to allow custom NPM registries outside of {@link DEFAULT_NPM_REGISTRY}.\n *\n * @default false\n */\n allowCustomRegistries?: boolean;\n}\n\nexport class NpmLocation implements SnapLocation {\n private readonly meta: NpmMeta;\n\n private validatedManifest?: VirtualFile<SnapManifest>;\n\n private files?: Map<string, VirtualFile>;\n\n constructor(url: URL, opts: DetectSnapLocationOptions = {}) {\n const allowCustomRegistries = opts.allowCustomRegistries ?? false;\n const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);\n const requestedRange = opts.versionRange ?? DEFAULT_REQUESTED_SNAP_VERSION;\n\n assertStruct(url.toString(), NpmSnapIdStruct, 'Invalid Snap Id: ');\n\n let registry: string | URL;\n if (\n url.host === '' &&\n url.port === '' &&\n url.username === '' &&\n url.password === ''\n ) {\n registry = new URL(DEFAULT_NPM_REGISTRY);\n } else {\n registry = 'https://';\n if (url.username) {\n registry += url.username;\n if (url.password) {\n registry += `:${url.password}`;\n }\n registry += '@';\n }\n registry += url.host;\n registry = new URL(registry);\n assert(\n allowCustomRegistries,\n new TypeError(\n `Custom NPM registries are disabled, tried to use \"${registry.toString()}\".`,\n ),\n );\n }\n\n assert(\n registry.pathname === '/' &&\n registry.search === '' &&\n registry.hash === '',\n );\n\n assert(\n url.pathname !== '' && url.pathname !== '/',\n new TypeError('The package name in NPM location is empty.'),\n );\n let packageName = url.pathname;\n if (packageName.startsWith('/')) {\n packageName = packageName.slice(1);\n }\n\n this.meta = {\n requestedRange,\n registry,\n packageName,\n fetch: fetchFunction,\n };\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n if (this.validatedManifest) {\n return this.validatedManifest.clone();\n }\n\n const vfile = await this.fetch('snap.manifest.json');\n const result = parseJson(vfile.toString());\n vfile.result = createSnapManifest(result);\n this.validatedManifest = vfile as VirtualFile<SnapManifest>;\n\n return this.manifest();\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n const relativePath = normalizeRelative(path);\n if (!this.files) {\n await this.#lazyInit();\n assert(this.files !== undefined);\n }\n const vfile = this.files.get(relativePath);\n assert(\n vfile !== undefined,\n new TypeError(`File \"${path}\" not found in package.`),\n );\n return vfile.clone();\n }\n\n get packageName(): string {\n return this.meta.packageName;\n }\n\n get version(): string {\n assert(\n this.meta.version !== undefined,\n 'Tried to access version without first fetching NPM package.',\n );\n return this.meta.version;\n }\n\n get registry(): URL {\n return this.meta.registry;\n }\n\n get versionRange(): SemVerRange {\n return this.meta.requestedRange;\n }\n\n async #lazyInit() {\n assert(this.files === undefined);\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n this.meta.packageName,\n this.meta.requestedRange,\n this.meta.registry,\n this.meta.fetch,\n );\n this.meta.version = actualVersion;\n\n let canonicalBase = 'npm://';\n if (this.meta.registry.username !== '') {\n canonicalBase += this.meta.registry.username;\n if (this.meta.registry.password !== '') {\n canonicalBase += `:${this.meta.registry.password}`;\n }\n canonicalBase += '@';\n }\n canonicalBase += this.meta.registry.host;\n\n // TODO(ritave): Lazily extract files instead of up-front extracting all of them\n // We would need to replace tar-stream package because it requires immediate consumption of streams.\n await new Promise<void>((resolve, reject) => {\n this.files = new Map();\n pipeline(\n getNodeStream(tarballResponse),\n // The \"gz\" in \"tgz\" stands for \"gzip\". The tarball needs to be decompressed\n // before we can actually grab any files from it.\n // To prevent recursion-based zip bombs, we set a maximum recursion depth of 1.\n createGunzipStream(1),\n createTarballStream(\n `${canonicalBase}/${this.meta.packageName}/`,\n this.files,\n ),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\n }\n}\n\n// Safety limit for tarballs, 250 MB in bytes\nconst TARBALL_SIZE_SAFETY_LIMIT = 262144000;\n\n// Incomplete type\nexport type PartialNpmMetadata = {\n versions: Record<string, { dist: { tarball: string } }>;\n};\n\n/**\n * Fetches the NPM metadata of the specified package from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns The NPM metadata object.\n * @throws If fetching the metadata fails.\n */\nexport async function fetchNpmMetadata(\n packageName: string,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<PartialNpmMetadata> {\n const packageResponse = await fetchFunction(\n new URL(packageName, registryUrl).toString(),\n );\n if (!packageResponse.ok) {\n throw new Error(\n `Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`,\n );\n }\n const packageMetadata = await packageResponse.json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n return packageMetadata as PartialNpmMetadata;\n}\n\n/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch the tarball from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the {@link Response} for the package tarball and the\n * actual version of the package.\n * @throws If fetching the tarball fails.\n */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const packageMetadata = await fetchNpmMetadata(\n packageName,\n registryUrl,\n fetchFunction,\n );\n\n const versions = Object.keys(packageMetadata?.versions ?? {}).map(\n (version) => {\n assertIsSemVerVersion(version);\n return version;\n },\n );\n\n const targetVersion = getTargetVersion(versions, versionRange);\n\n if (targetVersion === null) {\n throw new Error(\n `Failed to find a matching version in npm metadata for package \"${packageName}\" and requested semver range \"${versionRange}\".`,\n );\n }\n\n const tarballUrlString =\n packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n if (\n !isValidUrl(tarballUrlString) ||\n !tarballUrlString.toString().endsWith('.tgz')\n ) {\n throw new Error(\n `Failed to find valid tarball URL in NPM metadata for package \"${packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newRegistryUrl = new URL(registryUrl);\n const newTarballUrl = new URL(tarballUrlString);\n newTarballUrl.hostname = newRegistryUrl.hostname;\n newTarballUrl.protocol = newRegistryUrl.protocol;\n\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await fetchFunction(newTarballUrl.toString());\n if (!tarballResponse.ok || !tarballResponse.body) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n // We assume that NPM is a good actor and provides us with a valid `content-length` header.\n const tarballSizeString = tarballResponse.headers.get('content-length');\n assert(tarballSizeString, 'Snap tarball has invalid content-length');\n const tarballSize = parseInt(tarballSizeString, 10);\n assert(\n tarballSize <= TARBALL_SIZE_SAFETY_LIMIT,\n 'Snap tarball exceeds size limit',\n );\n return [tarballResponse.body, targetVersion];\n}\n\n/**\n * The paths of files within npm tarballs appear to always be prefixed with\n * \"package/\".\n */\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\n\n/**\n * Converts a {@link ReadableStream} to a Node.js {@link Readable}\n * stream. Returns the stream directly if it is already a Node.js stream.\n * We can't use the native Web {@link ReadableStream} directly because the\n * other stream libraries we use expect Node.js streams.\n *\n * @param stream - The stream to convert.\n * @returns The given stream as a Node.js Readable stream.\n */\nfunction getNodeStream(stream: ReadableStream): Readable {\n if (typeof stream.getReader !== 'function') {\n return stream as unknown as Readable;\n }\n\n return new ReadableWebToNodeStream(stream);\n}\n\n/**\n * Creates a `tar-stream` that will get the necessary files from an npm Snap\n * package tarball (`.tgz` file).\n *\n * @param canonicalBase - A base URI as specified in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8}. Starting with 'npm:'. Will be used for canonicalPath vfile argument.\n * @param files - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nfunction createTarballStream(\n canonicalBase: string,\n files: Map<string, VirtualFile>,\n): Writable {\n assert(\n canonicalBase.endsWith('/'),\n \"Base needs to end with '/' for relative paths to be added as children instead of siblings.\",\n );\n\n assert(\n canonicalBase.startsWith('npm:'),\n 'Protocol mismatch, expected \"npm:\".',\n );\n // `tar-stream` is pretty old-school, so we create it first and then\n // instrument it by adding event listeners.\n const extractStream = tarExtract();\n\n let totalSize = 0;\n\n // \"entry\" is fired for every discreet entity in the tarball. This includes\n // files and folders.\n extractStream.on('entry', (header, entryStream, next) => {\n const { name: headerName, type: headerType } = header;\n if (headerType === 'file') {\n // The name is a path if the header type is \"file\".\n const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');\n return entryStream.pipe(\n concat({ encoding: 'uint8array' }, (data) => {\n try {\n totalSize += data.byteLength;\n // To prevent zip bombs, we set a safety limit for the total size of tarballs.\n assert(\n totalSize < TARBALL_SIZE_SAFETY_LIMIT,\n `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`,\n );\n const vfile = new VirtualFile({\n value: data,\n path,\n data: {\n canonicalPath: new URL(path, canonicalBase).toString(),\n },\n });\n // We disallow files having identical paths as it may confuse our checksum calculations.\n assert(\n !files.has(path),\n 'Malformed tarball, multiple files with the same path.',\n );\n files.set(path, vfile);\n return next();\n } catch (error) {\n return extractStream.destroy(error);\n }\n }),\n );\n }\n\n // If we get here, the entry is not a file, and we want to ignore. The entry\n // stream must be drained, or the extractStream will stop reading. This is\n // effectively a no-op for the current entry.\n entryStream.on('end', () => next());\n return entryStream.resume();\n });\n return extractStream;\n}\n"],"names":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","concat","createGunzipStream","ReadableWebToNodeStream","pipeline","extract","tarExtract","DEFAULT_NPM_REGISTRY","NpmLocation","manifest","validatedManifest","clone","vfile","fetch","result","toString","path","relativePath","files","lazyInit","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","host","port","username","password","URL","pathname","search","hash","startsWith","slice","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","getNodeStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","fetchNpmMetadata","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","versions","Object","keys","map","targetVersion","tarballUrlString","dist","tarball","endsWith","newRegistryUrl","newTarballUrl","hostname","protocol","body","tarballSizeString","headers","tarballSize","parseInt","NPM_TARBALL_PATH_PREFIX","stream","getReader","extractStream","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe","encoding","data","byteLength","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,EAChBC,UAAU,EACVC,eAAe,EACfC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,QACJ,wBAAwB;AAE/B,SACEC,MAAM,EACNC,qBAAqB,EACrBC,YAAY,EACZC,QAAQ,QACH,kBAAkB;AACzB,OAAOC,YAAY,gBAAgB;AACnC,OAAOC,wBAAwB,eAAe;AAC9C,SAASC,uBAAuB,QAAQ,8BAA8B;AACtE,SAASC,QAAQ,QAAQ,SAAS;AAElC,SAASC,WAAWC,UAAU,QAAQ,aAAa;AAInD,OAAO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F;wBACAoF,MAAM;4BACJG,eAAe,IAAI/D,IAAIxB,MAAMiC,eAAelC,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFlB,OACE,CAACqB,MAAMsF,GAAG,CAACxF,OACX;oBAEFE,MAAMuF,GAAG,CAACzF,MAAMJ;oBAChB,OAAOgF;gBACT,EAAE,OAAOpC,OAAO;oBACd,OAAO+B,cAAcmB,OAAO,CAAClD;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CmC,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYgB,MAAM;IAC3B;IACA,OAAOpB;AACT"}
@@ -0,0 +1,50 @@
1
+ import { caveatMappers, restrictedMethodPermissionBuilders, selectHooks } from '@metamask/rpc-methods';
2
+ import { hasProperty } from '@metamask/utils';
3
+ import { endowmentCaveatMappers, endowmentPermissionBuilders } from './endowments';
4
+ /**
5
+ * Map initial permissions as defined in a Snap manifest to something that can
6
+ * be processed by the PermissionsController. Each caveat mapping function
7
+ * should return a valid permission caveat value.
8
+ *
9
+ * This function does not validate the caveat values, since that is done by
10
+ * the PermissionsController itself, upon requesting the permissions.
11
+ *
12
+ * @param initialPermissions - The initial permissions to process.
13
+ * @returns The processed permissions.
14
+ */ export function processSnapPermissions(initialPermissions) {
15
+ return Object.fromEntries(Object.entries(initialPermissions).map(([initialPermission, value])=>{
16
+ if (hasProperty(caveatMappers, initialPermission)) {
17
+ return [
18
+ initialPermission,
19
+ caveatMappers[initialPermission](value)
20
+ ];
21
+ } else if (hasProperty(endowmentCaveatMappers, initialPermission)) {
22
+ return [
23
+ initialPermission,
24
+ endowmentCaveatMappers[initialPermission](value)
25
+ ];
26
+ }
27
+ // If we have no mapping, this may be a non-snap permission, return as-is
28
+ return [
29
+ initialPermission,
30
+ value
31
+ ];
32
+ }));
33
+ }
34
+ export const buildSnapEndowmentSpecifications = (excludedEndowments)=>Object.values(endowmentPermissionBuilders).reduce((allSpecifications, { targetName, specificationBuilder })=>{
35
+ if (!excludedEndowments.includes(targetName)) {
36
+ allSpecifications[targetName] = specificationBuilder({});
37
+ }
38
+ return allSpecifications;
39
+ }, {});
40
+ export const buildSnapRestrictedMethodSpecifications = (excludedPermissions, hooks)=>Object.values(restrictedMethodPermissionBuilders).reduce((specifications, { targetName, specificationBuilder, methodHooks })=>{
41
+ if (!excludedPermissions.includes(targetName)) {
42
+ specifications[targetName] = specificationBuilder({
43
+ // @ts-expect-error The selectHooks type is wonky
44
+ methodHooks: selectHooks(hooks, methodHooks)
45
+ });
46
+ }
47
+ return specifications;
48
+ }, {});
49
+
50
+ //# sourceMappingURL=permissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/snaps/permissions.ts"],"sourcesContent":["import type {\n PermissionConstraint,\n PermissionSpecificationConstraint,\n} from '@metamask/permission-controller';\nimport {\n caveatMappers,\n restrictedMethodPermissionBuilders,\n selectHooks,\n} from '@metamask/rpc-methods';\nimport type { SnapPermissions } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n endowmentCaveatMappers,\n endowmentPermissionBuilders,\n} from './endowments';\n\n/**\n * Map initial permissions as defined in a Snap manifest to something that can\n * be processed by the PermissionsController. Each caveat mapping function\n * should return a valid permission caveat value.\n *\n * This function does not validate the caveat values, since that is done by\n * the PermissionsController itself, upon requesting the permissions.\n *\n * @param initialPermissions - The initial permissions to process.\n * @returns The processed permissions.\n */\nexport function processSnapPermissions(\n initialPermissions: SnapPermissions,\n): Record<string, Pick<PermissionConstraint, 'caveats'>> {\n return Object.fromEntries(\n Object.entries(initialPermissions).map(([initialPermission, value]) => {\n if (hasProperty(caveatMappers, initialPermission)) {\n return [initialPermission, caveatMappers[initialPermission](value)];\n } else if (hasProperty(endowmentCaveatMappers, initialPermission)) {\n return [\n initialPermission,\n endowmentCaveatMappers[initialPermission](value),\n ];\n }\n\n // If we have no mapping, this may be a non-snap permission, return as-is\n return [\n initialPermission,\n value as Pick<PermissionConstraint, 'caveats'>,\n ];\n }),\n );\n}\n\nexport const buildSnapEndowmentSpecifications = (\n excludedEndowments: string[],\n) =>\n Object.values(endowmentPermissionBuilders).reduce<\n Record<string, PermissionSpecificationConstraint>\n >((allSpecifications, { targetName, specificationBuilder }) => {\n if (!excludedEndowments.includes(targetName)) {\n allSpecifications[targetName] = specificationBuilder({});\n }\n return allSpecifications;\n }, {});\n\nexport const buildSnapRestrictedMethodSpecifications = (\n excludedPermissions: string[],\n hooks: Record<string, unknown>,\n) =>\n Object.values(restrictedMethodPermissionBuilders).reduce<\n Record<string, PermissionSpecificationConstraint>\n >((specifications, { targetName, specificationBuilder, methodHooks }) => {\n if (!excludedPermissions.includes(targetName)) {\n specifications[targetName] = specificationBuilder({\n // @ts-expect-error The selectHooks type is wonky\n methodHooks: selectHooks<typeof hooks, keyof typeof methodHooks>(\n hooks,\n methodHooks,\n ) as Pick<typeof hooks, keyof typeof methodHooks>,\n });\n }\n return specifications;\n }, {});\n"],"names":["caveatMappers","restrictedMethodPermissionBuilders","selectHooks","hasProperty","endowmentCaveatMappers","endowmentPermissionBuilders","processSnapPermissions","initialPermissions","Object","fromEntries","entries","map","initialPermission","value","buildSnapEndowmentSpecifications","excludedEndowments","values","reduce","allSpecifications","targetName","specificationBuilder","includes","buildSnapRestrictedMethodSpecifications","excludedPermissions","hooks","specifications","methodHooks"],"mappings":"AAIA,SACEA,aAAa,EACbC,kCAAkC,EAClCC,WAAW,QACN,wBAAwB;AAE/B,SAASC,WAAW,QAAQ,kBAAkB;AAE9C,SACEC,sBAAsB,EACtBC,2BAA2B,QACtB,eAAe;AAEtB;;;;;;;;;;CAUC,GACD,OAAO,SAASC,uBACdC,kBAAmC;IAEnC,OAAOC,OAAOC,WAAW,CACvBD,OAAOE,OAAO,CAACH,oBAAoBI,GAAG,CAAC,CAAC,CAACC,mBAAmBC,MAAM;QAChE,IAAIV,YAAYH,eAAeY,oBAAoB;YACjD,OAAO;gBAACA;gBAAmBZ,aAAa,CAACY,kBAAkB,CAACC;aAAO;QACrE,OAAO,IAAIV,YAAYC,wBAAwBQ,oBAAoB;YACjE,OAAO;gBACLA;gBACAR,sBAAsB,CAACQ,kBAAkB,CAACC;aAC3C;QACH;QAEA,yEAAyE;QACzE,OAAO;YACLD;YACAC;SACD;IACH;AAEJ;AAEA,OAAO,MAAMC,mCAAmC,CAC9CC,qBAEAP,OAAOQ,MAAM,CAACX,6BAA6BY,MAAM,CAE/C,CAACC,mBAAmB,EAAEC,UAAU,EAAEC,oBAAoB,EAAE;QACxD,IAAI,CAACL,mBAAmBM,QAAQ,CAACF,aAAa;YAC5CD,iBAAiB,CAACC,WAAW,GAAGC,qBAAqB,CAAC;QACxD;QACA,OAAOF;IACT,GAAG,CAAC,GAAG;AAET,OAAO,MAAMI,0CAA0C,CACrDC,qBACAC,QAEAhB,OAAOQ,MAAM,CAACf,oCAAoCgB,MAAM,CAEtD,CAACQ,gBAAgB,EAAEN,UAAU,EAAEC,oBAAoB,EAAEM,WAAW,EAAE;QAClE,IAAI,CAACH,oBAAoBF,QAAQ,CAACF,aAAa;YAC7CM,cAAc,CAACN,WAAW,GAAGC,qBAAqB;gBAChD,iDAAiD;gBACjDM,aAAaxB,YACXsB,OACAE;YAEJ;QACF;QACA,OAAOD;IACT,GAAG,CAAC,GAAG"}
@@ -0,0 +1,4 @@
1
+ export * from './registry';
2
+ export * from './json';
3
+
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/registry/index.ts"],"sourcesContent":["export * from './registry';\nexport * from './json';\n"],"names":[],"mappings":"AAAA,cAAc,aAAa;AAC3B,cAAc,SAAS"}