@metamask/snaps-controllers 0.34.1-flask.1 → 0.35.0-flask.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (314) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/dist/cjs/cronjob/CronjobController.js +290 -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 +404 -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 +1708 -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/{snaps → cjs/snaps}/endowments/cronjob.js.map +1 -1
  48. package/dist/cjs/snaps/endowments/enum.js +22 -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 +78 -0
  53. package/dist/cjs/snaps/endowments/index.js.map +1 -0
  54. package/dist/cjs/snaps/endowments/long-running.js +38 -0
  55. package/dist/cjs/snaps/endowments/long-running.js.map +1 -0
  56. package/dist/cjs/snaps/endowments/network-access.js +44 -0
  57. package/dist/cjs/snaps/endowments/network-access.js.map +1 -0
  58. package/dist/cjs/snaps/endowments/rpc.js +99 -0
  59. package/dist/cjs/snaps/endowments/rpc.js.map +1 -0
  60. package/dist/cjs/snaps/endowments/transaction-insight.js +106 -0
  61. package/dist/cjs/snaps/endowments/transaction-insight.js.map +1 -0
  62. package/dist/cjs/snaps/endowments/web-assembly.js +42 -0
  63. package/dist/cjs/snaps/endowments/web-assembly.js.map +1 -0
  64. package/dist/cjs/snaps/index.js +25 -0
  65. package/dist/cjs/snaps/index.js.map +1 -0
  66. package/dist/cjs/snaps/location/http.js +106 -0
  67. package/dist/cjs/snaps/location/http.js.map +1 -0
  68. package/dist/cjs/snaps/location/index.js +23 -0
  69. package/dist/cjs/snaps/location/index.js.map +1 -0
  70. package/dist/cjs/snaps/location/local.js +93 -0
  71. package/dist/cjs/snaps/location/local.js.map +1 -0
  72. package/dist/cjs/snaps/location/location.js +34 -0
  73. package/dist/cjs/snaps/location/location.js.map +1 -0
  74. package/dist/cjs/snaps/location/npm.js +291 -0
  75. package/dist/cjs/snaps/location/npm.js.map +1 -0
  76. package/dist/cjs/snaps/permissions.js +61 -0
  77. package/dist/cjs/snaps/permissions.js.map +1 -0
  78. package/dist/cjs/snaps/registry/index.js +21 -0
  79. package/dist/cjs/snaps/registry/index.js.map +1 -0
  80. package/dist/cjs/snaps/registry/json.js +249 -0
  81. package/dist/cjs/snaps/registry/json.js.map +1 -0
  82. package/dist/cjs/snaps/registry/registry.js +18 -0
  83. package/dist/cjs/snaps/registry/registry.js.map +1 -0
  84. package/dist/cjs/snaps/selectors.js +13 -0
  85. package/dist/cjs/snaps/selectors.js.map +1 -0
  86. package/dist/cjs/utils.js +70 -0
  87. package/dist/cjs/utils.js.map +1 -0
  88. package/dist/esm/cronjob/CronjobController.js +275 -0
  89. package/dist/esm/cronjob/CronjobController.js.map +1 -0
  90. package/dist/esm/cronjob/index.js +3 -0
  91. package/dist/esm/cronjob/index.js.map +1 -0
  92. package/dist/esm/fsm.js +70 -0
  93. package/dist/esm/fsm.js.map +1 -0
  94. package/dist/esm/index.js +6 -0
  95. package/dist/esm/index.js.map +1 -0
  96. package/dist/esm/logging.js +10 -0
  97. package/dist/esm/logging.js.map +1 -0
  98. package/dist/esm/services/AbstractExecutionService.js +387 -0
  99. package/dist/esm/services/AbstractExecutionService.js.map +1 -0
  100. package/dist/esm/services/ExecutionService.js +4 -0
  101. package/dist/esm/services/ExecutionService.js.map +1 -0
  102. package/dist/esm/services/ProxyPostMessageStream.js +109 -0
  103. package/dist/esm/services/ProxyPostMessageStream.js.map +1 -0
  104. package/dist/esm/services/browser.js +9 -0
  105. package/dist/esm/services/browser.js.map +1 -0
  106. package/dist/esm/services/iframe/IframeExecutionService.js +44 -0
  107. package/dist/esm/services/iframe/IframeExecutionService.js.map +1 -0
  108. package/dist/esm/services/iframe/index.js +3 -0
  109. package/dist/esm/services/iframe/index.js.map +1 -0
  110. package/dist/esm/services/index.js +9 -0
  111. package/dist/esm/services/index.js.map +1 -0
  112. package/dist/esm/services/node/NodeProcessExecutionService.js +20 -0
  113. package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -0
  114. package/dist/esm/services/node/NodeThreadExecutionService.js +21 -0
  115. package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -0
  116. package/dist/esm/services/node/index.js +4 -0
  117. package/dist/esm/services/node/index.js.map +1 -0
  118. package/dist/esm/services/offscreen/OffscreenExecutionService.js +149 -0
  119. package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -0
  120. package/dist/esm/services/offscreen/index.js +3 -0
  121. package/dist/esm/services/offscreen/index.js.map +1 -0
  122. package/dist/esm/services/webworker/WebWorkerExecutionService.js +130 -0
  123. package/dist/esm/services/webworker/WebWorkerExecutionService.js.map +1 -0
  124. package/dist/esm/services/webworker/index.js +3 -0
  125. package/dist/esm/services/webworker/index.js.map +1 -0
  126. package/dist/esm/snaps/RequestQueue.js +53 -0
  127. package/dist/esm/snaps/RequestQueue.js.map +1 -0
  128. package/dist/esm/snaps/SnapController.js +1687 -0
  129. package/dist/esm/snaps/SnapController.js.map +1 -0
  130. package/dist/esm/snaps/Timer.js +107 -0
  131. package/dist/esm/snaps/Timer.js.map +1 -0
  132. package/dist/esm/snaps/endowments/cronjob.js +99 -0
  133. package/dist/esm/snaps/endowments/cronjob.js.map +1 -0
  134. package/dist/esm/snaps/endowments/enum.js +12 -0
  135. package/dist/esm/snaps/endowments/enum.js.map +1 -0
  136. package/dist/esm/snaps/endowments/ethereum-provider.js +33 -0
  137. package/dist/esm/snaps/endowments/ethereum-provider.js.map +1 -0
  138. package/dist/esm/snaps/endowments/index.js +37 -0
  139. package/dist/esm/snaps/endowments/index.js.map +1 -0
  140. package/dist/esm/snaps/endowments/long-running.js +28 -0
  141. package/dist/esm/snaps/endowments/long-running.js.map +1 -0
  142. package/dist/esm/snaps/endowments/network-access.js +34 -0
  143. package/dist/esm/snaps/endowments/network-access.js.map +1 -0
  144. package/dist/esm/snaps/endowments/rpc.js +88 -0
  145. package/dist/esm/snaps/endowments/rpc.js.map +1 -0
  146. package/dist/esm/snaps/endowments/transaction-insight.js +99 -0
  147. package/dist/esm/snaps/endowments/transaction-insight.js.map +1 -0
  148. package/dist/esm/snaps/endowments/web-assembly.js +32 -0
  149. package/dist/esm/snaps/endowments/web-assembly.js.map +1 -0
  150. package/dist/esm/snaps/index.js +8 -0
  151. package/dist/esm/snaps/index.js.map +1 -0
  152. package/dist/{snaps → esm/snaps}/location/http.js +52 -31
  153. package/dist/esm/snaps/location/http.js.map +1 -0
  154. package/dist/esm/snaps/location/index.js +6 -0
  155. package/dist/esm/snaps/location/index.js.map +1 -0
  156. package/dist/esm/snaps/location/local.js +83 -0
  157. package/dist/esm/snaps/location/local.js.map +1 -0
  158. package/dist/esm/snaps/location/location.js +30 -0
  159. package/dist/esm/snaps/location/location.js.map +1 -0
  160. package/dist/{snaps → esm/snaps}/location/npm.js +118 -110
  161. package/dist/esm/snaps/location/npm.js.map +1 -0
  162. package/dist/esm/snaps/permissions.js +50 -0
  163. package/dist/esm/snaps/permissions.js.map +1 -0
  164. package/dist/esm/snaps/registry/index.js +4 -0
  165. package/dist/esm/snaps/registry/index.js.map +1 -0
  166. package/dist/esm/snaps/registry/json.js +239 -0
  167. package/dist/esm/snaps/registry/json.js.map +1 -0
  168. package/dist/esm/snaps/registry/registry.js +8 -0
  169. package/dist/esm/snaps/registry/registry.js.map +1 -0
  170. package/dist/esm/snaps/selectors.js +3 -0
  171. package/dist/esm/snaps/selectors.js.map +1 -0
  172. package/dist/{utils.js → esm/utils.js} +19 -28
  173. package/dist/esm/utils.js.map +1 -0
  174. package/dist/{index.d.ts → types/index.d.ts} +0 -1
  175. package/dist/{snaps → types/snaps}/endowments/enum.d.ts +0 -1
  176. package/dist/{snaps → types/snaps}/endowments/index.d.ts +1 -12
  177. package/package.json +60 -14
  178. package/dist/cronjob/CronjobController.js +0 -248
  179. package/dist/cronjob/CronjobController.js.map +0 -1
  180. package/dist/cronjob/index.js +0 -18
  181. package/dist/cronjob/index.js.map +0 -1
  182. package/dist/fsm.js +0 -75
  183. package/dist/fsm.js.map +0 -1
  184. package/dist/index.js +0 -22
  185. package/dist/index.js.map +0 -1
  186. package/dist/logging.js +0 -13
  187. package/dist/logging.js.map +0 -1
  188. package/dist/multichain/MultiChainController.d.ts +0 -137
  189. package/dist/multichain/MultiChainController.js +0 -339
  190. package/dist/multichain/MultiChainController.js.map +0 -1
  191. package/dist/multichain/index.d.ts +0 -3
  192. package/dist/multichain/index.js +0 -20
  193. package/dist/multichain/index.js.map +0 -1
  194. package/dist/multichain/matching.d.ts +0 -9
  195. package/dist/multichain/matching.js +0 -57
  196. package/dist/multichain/matching.js.map +0 -1
  197. package/dist/multichain/middleware.d.ts +0 -14
  198. package/dist/multichain/middleware.js +0 -42
  199. package/dist/multichain/middleware.js.map +0 -1
  200. package/dist/services/AbstractExecutionService.js +0 -318
  201. package/dist/services/AbstractExecutionService.js.map +0 -1
  202. package/dist/services/ExecutionService.js +0 -4
  203. package/dist/services/ExecutionService.js.map +0 -1
  204. package/dist/services/ProxyPostMessageStream.js +0 -62
  205. package/dist/services/ProxyPostMessageStream.js.map +0 -1
  206. package/dist/services/browser.js +0 -26
  207. package/dist/services/browser.js.map +0 -1
  208. package/dist/services/iframe/IframeExecutionService.js +0 -30
  209. package/dist/services/iframe/IframeExecutionService.js.map +0 -1
  210. package/dist/services/iframe/index.js +0 -18
  211. package/dist/services/iframe/index.js.map +0 -1
  212. package/dist/services/index.js +0 -26
  213. package/dist/services/index.js.map +0 -1
  214. package/dist/services/node/NodeProcessExecutionService.js +0 -18
  215. package/dist/services/node/NodeProcessExecutionService.js.map +0 -1
  216. package/dist/services/node/NodeThreadExecutionService.js +0 -19
  217. package/dist/services/node/NodeThreadExecutionService.js.map +0 -1
  218. package/dist/services/node/index.js +0 -19
  219. package/dist/services/node/index.js.map +0 -1
  220. package/dist/services/offscreen/OffscreenExecutionService.js +0 -105
  221. package/dist/services/offscreen/OffscreenExecutionService.js.map +0 -1
  222. package/dist/services/offscreen/index.js +0 -18
  223. package/dist/services/offscreen/index.js.map +0 -1
  224. package/dist/services/webworker/WebWorkerExecutionService.js +0 -100
  225. package/dist/services/webworker/WebWorkerExecutionService.js.map +0 -1
  226. package/dist/services/webworker/index.js +0 -18
  227. package/dist/services/webworker/index.js.map +0 -1
  228. package/dist/snaps/RequestQueue.js +0 -44
  229. package/dist/snaps/RequestQueue.js.map +0 -1
  230. package/dist/snaps/SnapController.js +0 -1495
  231. package/dist/snaps/SnapController.js.map +0 -1
  232. package/dist/snaps/Timer.js +0 -86
  233. package/dist/snaps/Timer.js.map +0 -1
  234. package/dist/snaps/endowments/cronjob.js +0 -105
  235. package/dist/snaps/endowments/enum.js +0 -15
  236. package/dist/snaps/endowments/enum.js.map +0 -1
  237. package/dist/snaps/endowments/ethereum-provider.js +0 -32
  238. package/dist/snaps/endowments/ethereum-provider.js.map +0 -1
  239. package/dist/snaps/endowments/index.js +0 -58
  240. package/dist/snaps/endowments/index.js.map +0 -1
  241. package/dist/snaps/endowments/keyring.d.ts +0 -40
  242. package/dist/snaps/endowments/keyring.js +0 -104
  243. package/dist/snaps/endowments/keyring.js.map +0 -1
  244. package/dist/snaps/endowments/long-running.js +0 -29
  245. package/dist/snaps/endowments/long-running.js.map +0 -1
  246. package/dist/snaps/endowments/network-access.js +0 -30
  247. package/dist/snaps/endowments/network-access.js.map +0 -1
  248. package/dist/snaps/endowments/rpc.js +0 -93
  249. package/dist/snaps/endowments/rpc.js.map +0 -1
  250. package/dist/snaps/endowments/transaction-insight.js +0 -106
  251. package/dist/snaps/endowments/transaction-insight.js.map +0 -1
  252. package/dist/snaps/endowments/web-assembly.js +0 -31
  253. package/dist/snaps/endowments/web-assembly.js.map +0 -1
  254. package/dist/snaps/index.js +0 -23
  255. package/dist/snaps/index.js.map +0 -1
  256. package/dist/snaps/location/http.js.map +0 -1
  257. package/dist/snaps/location/index.js +0 -21
  258. package/dist/snaps/location/index.js.map +0 -1
  259. package/dist/snaps/location/local.js +0 -51
  260. package/dist/snaps/location/local.js.map +0 -1
  261. package/dist/snaps/location/location.js +0 -34
  262. package/dist/snaps/location/location.js.map +0 -1
  263. package/dist/snaps/location/npm.js.map +0 -1
  264. package/dist/snaps/permissions.js +0 -54
  265. package/dist/snaps/permissions.js.map +0 -1
  266. package/dist/snaps/registry/index.js +0 -19
  267. package/dist/snaps/registry/index.js.map +0 -1
  268. package/dist/snaps/registry/json.js +0 -170
  269. package/dist/snaps/registry/json.js.map +0 -1
  270. package/dist/snaps/registry/registry.js +0 -11
  271. package/dist/snaps/registry/registry.js.map +0 -1
  272. package/dist/snaps/selectors.js +0 -6
  273. package/dist/snaps/selectors.js.map +0 -1
  274. package/dist/utils.js.map +0 -1
  275. /package/dist/{cronjob → types/cronjob}/CronjobController.d.ts +0 -0
  276. /package/dist/{cronjob → types/cronjob}/index.d.ts +0 -0
  277. /package/dist/{fsm.d.ts → types/fsm.d.ts} +0 -0
  278. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  279. /package/dist/{services → types/services}/AbstractExecutionService.d.ts +0 -0
  280. /package/dist/{services → types/services}/ExecutionService.d.ts +0 -0
  281. /package/dist/{services → types/services}/ProxyPostMessageStream.d.ts +0 -0
  282. /package/dist/{services → types/services}/browser.d.ts +0 -0
  283. /package/dist/{services → types/services}/iframe/IframeExecutionService.d.ts +0 -0
  284. /package/dist/{services → types/services}/iframe/index.d.ts +0 -0
  285. /package/dist/{services → types/services}/index.d.ts +0 -0
  286. /package/dist/{services → types/services}/node/NodeProcessExecutionService.d.ts +0 -0
  287. /package/dist/{services → types/services}/node/NodeThreadExecutionService.d.ts +0 -0
  288. /package/dist/{services → types/services}/node/index.d.ts +0 -0
  289. /package/dist/{services → types/services}/offscreen/OffscreenExecutionService.d.ts +0 -0
  290. /package/dist/{services → types/services}/offscreen/index.d.ts +0 -0
  291. /package/dist/{services → types/services}/webworker/WebWorkerExecutionService.d.ts +0 -0
  292. /package/dist/{services → types/services}/webworker/index.d.ts +0 -0
  293. /package/dist/{snaps → types/snaps}/RequestQueue.d.ts +0 -0
  294. /package/dist/{snaps → types/snaps}/SnapController.d.ts +0 -0
  295. /package/dist/{snaps → types/snaps}/Timer.d.ts +0 -0
  296. /package/dist/{snaps → types/snaps}/endowments/cronjob.d.ts +0 -0
  297. /package/dist/{snaps → types/snaps}/endowments/ethereum-provider.d.ts +0 -0
  298. /package/dist/{snaps → types/snaps}/endowments/long-running.d.ts +0 -0
  299. /package/dist/{snaps → types/snaps}/endowments/network-access.d.ts +0 -0
  300. /package/dist/{snaps → types/snaps}/endowments/rpc.d.ts +0 -0
  301. /package/dist/{snaps → types/snaps}/endowments/transaction-insight.d.ts +0 -0
  302. /package/dist/{snaps → types/snaps}/endowments/web-assembly.d.ts +0 -0
  303. /package/dist/{snaps → types/snaps}/index.d.ts +0 -0
  304. /package/dist/{snaps → types/snaps}/location/http.d.ts +0 -0
  305. /package/dist/{snaps → types/snaps}/location/index.d.ts +0 -0
  306. /package/dist/{snaps → types/snaps}/location/local.d.ts +0 -0
  307. /package/dist/{snaps → types/snaps}/location/location.d.ts +0 -0
  308. /package/dist/{snaps → types/snaps}/location/npm.d.ts +0 -0
  309. /package/dist/{snaps → types/snaps}/permissions.d.ts +0 -0
  310. /package/dist/{snaps → types/snaps}/registry/index.d.ts +0 -0
  311. /package/dist/{snaps → types/snaps}/registry/json.d.ts +0 -0
  312. /package/dist/{snaps → types/snaps}/registry/registry.d.ts +0 -0
  313. /package/dist/{snaps → types/snaps}/selectors.d.ts +0 -0
  314. /package/dist/{utils.d.ts → types/utils.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/location/local.ts"],"sourcesContent":["import {\n LocalSnapIdStruct,\n SnapIdPrefixes,\n SnapManifest,\n VirtualFile,\n} from '@metamask/snaps-utils';\nimport { assert, assertStruct } from '@metamask/utils';\n\nimport { HttpLocation, HttpOptions } from './http';\nimport { SnapLocation } from './location';\n\nexport class LocalLocation implements SnapLocation {\n readonly #http: HttpLocation;\n\n constructor(url: URL, opts: HttpOptions = {}) {\n assertStruct(url.toString(), LocalSnapIdStruct, 'Invalid Snap Id');\n // TODO(ritave): Write deepMerge() which merges fetchOptions.\n assert(\n opts.fetchOptions === undefined,\n 'Currently adding fetch options to local: is unsupported.',\n );\n\n this.#http = new HttpLocation(\n new URL(url.toString().slice(SnapIdPrefixes.local.length)),\n { ...opts, fetchOptions: { cache: 'no-cache' } },\n );\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n const vfile = await this.#http.manifest();\n\n return convertCanonical(vfile);\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n return convertCanonical(await this.#http.fetch(path));\n }\n\n get shouldAlwaysReload() {\n return true;\n }\n}\n\n/**\n * Converts vfiles with canonical `http:` paths into `local:` paths.\n *\n * @param vfile - The {@link VirtualFile} to convert.\n * @returns The same object with updated `.data.canonicalPath`.\n */\nfunction convertCanonical<Result>(\n vfile: VirtualFile<Result>,\n): VirtualFile<Result> {\n assert(vfile.data.canonicalPath !== undefined);\n vfile.data.canonicalPath = `local:${vfile.data.canonicalPath}`;\n return vfile;\n}\n"],"names":["LocalSnapIdStruct","SnapIdPrefixes","assert","assertStruct","HttpLocation","LocalLocation","manifest","vfile","http","convertCanonical","fetch","path","shouldAlwaysReload","constructor","url","opts","toString","fetchOptions","undefined","URL","slice","local","length","cache","data","canonicalPath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SACEA,iBAAiB,EACjBC,cAAc,QAGT,wBAAwB;AAC/B,SAASC,MAAM,EAAEC,YAAY,QAAQ,kBAAkB;AAEvD,SAASC,YAAY,QAAqB,SAAS;IAIxC;AADX,OAAO,MAAMC;IAiBX,MAAMC,WAA+C;QACnD,MAAMC,QAAQ,MAAM,yBAAA,IAAI,EAAEC,OAAKF,QAAQ;QAEvC,OAAOG,iBAAiBF;IAC1B;IAEA,MAAMG,MAAMC,IAAY,EAAwB;QAC9C,OAAOF,iBAAiB,MAAM,yBAAA,IAAI,EAAED,OAAKE,KAAK,CAACC;IACjD;IAEA,IAAIC,qBAAqB;QACvB,OAAO;IACT;IA1BAC,YAAYC,GAAQ,EAAEC,OAAoB,CAAC,CAAC,CAAE;QAF9C,gCAAS;;mBAAT,KAAA;;QAGEZ,aAAaW,IAAIE,QAAQ,IAAIhB,mBAAmB;QAChD,6DAA6D;QAC7DE,OACEa,KAAKE,YAAY,KAAKC,WACtB;uCAGIV,OAAO,IAAIJ,aACf,IAAIe,IAAIL,IAAIE,QAAQ,GAAGI,KAAK,CAACnB,eAAeoB,KAAK,CAACC,MAAM,IACxD;YAAE,GAAGP,IAAI;YAAEE,cAAc;gBAAEM,OAAO;YAAW;QAAE;IAEnD;AAeF;AAEA;;;;;CAKC,GACD,SAASd,iBACPF,KAA0B;IAE1BL,OAAOK,MAAMiB,IAAI,CAACC,aAAa,KAAKP;IACpCX,MAAMiB,IAAI,CAACC,aAAa,GAAG,CAAC,MAAM,EAAElB,MAAMiB,IAAI,CAACC,aAAa,CAAC,CAAC;IAC9D,OAAOlB;AACT"}
@@ -0,0 +1,30 @@
1
+ import { assert } from '@metamask/utils';
2
+ import { HttpLocation } from './http';
3
+ import { LocalLocation } from './local';
4
+ import { NpmLocation } from './npm';
5
+ /**
6
+ * Auto-magically detects which SnapLocation object to create based on the provided {@link location}.
7
+ *
8
+ * @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.
9
+ * @param opts - NPM options and feature flags.
10
+ * @returns SnapLocation based on url.
11
+ */ export function detectSnapLocation(location, opts) {
12
+ const allowHttp = opts?.allowHttp ?? false;
13
+ const allowLocal = opts?.allowLocal ?? false;
14
+ const root = new URL(location);
15
+ switch(root.protocol){
16
+ case 'npm:':
17
+ return new NpmLocation(root, opts);
18
+ case 'local:':
19
+ assert(allowLocal, new TypeError('Fetching local snaps is disabled.'));
20
+ return new LocalLocation(root, opts);
21
+ case 'http:':
22
+ case 'https:':
23
+ assert(allowHttp, new TypeError('Fetching snaps through http/https is disabled.'));
24
+ return new HttpLocation(root, opts);
25
+ default:
26
+ throw new TypeError(`Unrecognized "${root.protocol}" snap location protocol.`);
27
+ }
28
+ }
29
+
30
+ //# sourceMappingURL=location.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/location/location.ts"],"sourcesContent":["import { SnapManifest, VirtualFile } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { HttpLocation } from './http';\nimport { LocalLocation } from './local';\nimport { NpmLocation, NpmOptions } from './npm';\n\ndeclare module '@metamask/snaps-utils' {\n interface DataMap {\n /**\n * Fully qualified, canonical path for the file in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8 } URI format.\n */\n canonicalPath: string;\n }\n}\n\nexport interface SnapLocation {\n /**\n * All files are relative to the manifest, except the manifest itself.\n */\n manifest(): Promise<VirtualFile<SnapManifest>>;\n fetch(path: string): Promise<VirtualFile>;\n\n readonly shouldAlwaysReload?: boolean;\n}\n\nexport type DetectSnapLocationOptions = NpmOptions & {\n /**\n * The function used to fetch data.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * @default false\n */\n allowHttp?: boolean;\n /**\n * @default false\n */\n allowLocal?: boolean;\n};\n\n/**\n * Auto-magically detects which SnapLocation object to create based on the provided {@link location}.\n *\n * @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.\n * @param opts - NPM options and feature flags.\n * @returns SnapLocation based on url.\n */\nexport function detectSnapLocation(\n location: string | URL,\n opts?: DetectSnapLocationOptions,\n): SnapLocation {\n const allowHttp = opts?.allowHttp ?? false;\n const allowLocal = opts?.allowLocal ?? false;\n const root = new URL(location);\n switch (root.protocol) {\n case 'npm:':\n return new NpmLocation(root, opts);\n case 'local:':\n assert(allowLocal, new TypeError('Fetching local snaps is disabled.'));\n return new LocalLocation(root, opts);\n case 'http:':\n case 'https:':\n assert(\n allowHttp,\n new TypeError('Fetching snaps through http/https is disabled.'),\n );\n return new HttpLocation(root, opts);\n default:\n throw new TypeError(\n `Unrecognized \"${root.protocol}\" snap location protocol.`,\n );\n }\n}\n"],"names":["assert","HttpLocation","LocalLocation","NpmLocation","detectSnapLocation","location","opts","allowHttp","allowLocal","root","URL","protocol","TypeError"],"mappings":"AACA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,YAAY,QAAQ,SAAS;AACtC,SAASC,aAAa,QAAQ,UAAU;AACxC,SAASC,WAAW,QAAoB,QAAQ;AAsChD;;;;;;CAMC,GACD,OAAO,SAASC,mBACdC,QAAsB,EACtBC,IAAgC;IAEhC,MAAMC,YAAYD,MAAMC,aAAa;IACrC,MAAMC,aAAaF,MAAME,cAAc;IACvC,MAAMC,OAAO,IAAIC,IAAIL;IACrB,OAAQI,KAAKE,QAAQ;QACnB,KAAK;YACH,OAAO,IAAIR,YAAYM,MAAMH;QAC/B,KAAK;YACHN,OAAOQ,YAAY,IAAII,UAAU;YACjC,OAAO,IAAIV,cAAcO,MAAMH;QACjC,KAAK;QACL,KAAK;YACHN,OACEO,WACA,IAAIK,UAAU;YAEhB,OAAO,IAAIX,aAAaQ,MAAMH;QAChC;YACE,MAAM,IAAIM,UACR,CAAC,cAAc,EAAEH,KAAKE,QAAQ,CAAC,yBAAyB,CAAC;IAE/D;AACF"}
@@ -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.fetchNpmMetadata = exports.NpmLocation = exports.DEFAULT_NPM_REGISTRY = 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
- exports.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(exports.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");
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");
62
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 pump from 'pump';
34
+ import { ReadableWebToNodeStream } from 'readable-web-to-node-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 = JSON.parse(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,17 +123,16 @@ _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
+ pump(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
  /**
@@ -133,19 +145,17 @@ const TARBALL_SIZE_SAFETY_LIMIT = 262144000;
133
145
  * {@link fetch}. Useful for Node.js compatibility.
134
146
  * @returns The NPM metadata object.
135
147
  * @throws If fetching the metadata fails.
136
- */
137
- async function fetchNpmMetadata(packageName, registryUrl, fetchFunction) {
148
+ */ export async function fetchNpmMetadata(packageName, registryUrl, fetchFunction) {
138
149
  const packageResponse = await fetchFunction(new URL(packageName, registryUrl).toString());
139
150
  if (!packageResponse.ok) {
140
151
  throw new Error(`Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`);
141
152
  }
142
153
  const packageMetadata = await packageResponse.json();
143
- if (!(0, utils_1.isObject)(packageMetadata)) {
154
+ if (!isObject(packageMetadata)) {
144
155
  throw new Error(`Failed to fetch package "${packageName}" metadata from npm.`);
145
156
  }
146
157
  return packageMetadata;
147
158
  }
148
- exports.fetchNpmMetadata = fetchNpmMetadata;
149
159
  /**
150
160
  * Fetches the tarball (`.tgz` file) of the specified package and version from
151
161
  * the public npm registry.
@@ -159,20 +169,18 @@ exports.fetchNpmMetadata = fetchNpmMetadata;
159
169
  * @returns A tuple of the {@link Response} for the package tarball and the
160
170
  * actual version of the package.
161
171
  * @throws If fetching the tarball fails.
162
- */
163
- async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction) {
172
+ */ async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction) {
164
173
  const packageMetadata = await fetchNpmMetadata(packageName, registryUrl, fetchFunction);
165
- const versions = Object.keys(packageMetadata?.versions ?? {}).map((version) => {
166
- (0, utils_1.assertIsSemVerVersion)(version);
174
+ const versions = Object.keys(packageMetadata?.versions ?? {}).map((version)=>{
175
+ assertIsSemVerVersion(version);
167
176
  return version;
168
177
  });
169
- const targetVersion = (0, snaps_utils_1.getTargetVersion)(versions, versionRange);
178
+ const targetVersion = getTargetVersion(versions, versionRange);
170
179
  if (targetVersion === null) {
171
180
  throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}".`);
172
181
  }
173
182
  const tarballUrlString = packageMetadata?.versions?.[targetVersion]?.dist?.tarball;
174
- if (!(0, snaps_utils_1.isValidUrl)(tarballUrlString) ||
175
- !tarballUrlString.toString().endsWith('.tgz')) {
183
+ if (!isValidUrl(tarballUrlString) || !tarballUrlString.toString().endsWith('.tgz')) {
176
184
  throw new Error(`Failed to find valid tarball URL in NPM metadata for package "${packageName}".`);
177
185
  }
178
186
  // Override the tarball hostname/protocol with registryUrl hostname/protocol
@@ -187,16 +195,18 @@ async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunc
187
195
  }
188
196
  // We assume that NPM is a good actor and provides us with a valid `content-length` header.
189
197
  const tarballSizeString = tarballResponse.headers.get('content-length');
190
- (0, utils_1.assert)(tarballSizeString, 'Snap tarball has invalid content-length');
198
+ assert(tarballSizeString, 'Snap tarball has invalid content-length');
191
199
  const tarballSize = parseInt(tarballSizeString, 10);
192
- (0, utils_1.assert)(tarballSize <= TARBALL_SIZE_SAFETY_LIMIT, 'Snap tarball exceeds size limit');
193
- return [tarballResponse.body, targetVersion];
200
+ assert(tarballSize <= TARBALL_SIZE_SAFETY_LIMIT, 'Snap tarball exceeds size limit');
201
+ return [
202
+ tarballResponse.body,
203
+ targetVersion
204
+ ];
194
205
  }
195
206
  /**
196
207
  * The paths of files within npm tarballs appear to always be prefixed with
197
208
  * "package/".
198
- */
199
- const NPM_TARBALL_PATH_PREFIX = /^package\//u;
209
+ */ const NPM_TARBALL_PATH_PREFIX = /^package\//u;
200
210
  /**
201
211
  * Converts a {@link ReadableStream} to a Node.js {@link Readable}
202
212
  * stream. Returns the stream directly if it is already a Node.js stream.
@@ -205,12 +215,11 @@ const NPM_TARBALL_PATH_PREFIX = /^package\//u;
205
215
  *
206
216
  * @param stream - The stream to convert.
207
217
  * @returns The given stream as a Node.js Readable stream.
208
- */
209
- function getNodeStream(stream) {
218
+ */ function getNodeStream(stream) {
210
219
  if (typeof stream.getReader !== 'function') {
211
220
  return stream;
212
221
  }
213
- return new readable_web_to_node_stream_1.ReadableWebToNodeStream(stream);
222
+ return new ReadableWebToNodeStream(stream);
214
223
  }
215
224
  /**
216
225
  * Creates a `tar-stream` that will get the necessary files from an npm Snap
@@ -219,39 +228,37 @@ function getNodeStream(stream) {
219
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.
220
229
  * @param files - An object to write target file contents to.
221
230
  * @returns The {@link Writable} tarball extraction stream.
222
- */
223
- function createTarballStream(canonicalBase, files) {
224
- (0, utils_1.assert)(canonicalBase.endsWith('/'), "Base needs to end with '/' for relative paths to be added as children instead of siblings.");
225
- (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:".');
226
234
  // `tar-stream` is pretty old-school, so we create it first and then
227
235
  // instrument it by adding event listeners.
228
- const extractStream = (0, tar_stream_1.extract)();
236
+ const extractStream = tarExtract();
229
237
  let totalSize = 0;
230
238
  // "entry" is fired for every discreet entity in the tarball. This includes
231
239
  // files and folders.
232
- extractStream.on('entry', (header, entryStream, next) => {
240
+ extractStream.on('entry', (header, entryStream, next)=>{
233
241
  const { name: headerName, type: headerType } = header;
234
242
  if (headerType === 'file') {
235
243
  // The name is a path if the header type is "file".
236
244
  const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');
237
- return entryStream.pipe((0, concat_stream_1.default)((data) => {
245
+ return entryStream.pipe(concat((data)=>{
238
246
  try {
239
247
  totalSize += data.byteLength;
240
248
  // To prevent zip bombs, we set a safety limit for the total size of tarballs.
241
- (0, utils_1.assert)(totalSize < TARBALL_SIZE_SAFETY_LIMIT, `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`);
242
- const vfile = new snaps_utils_1.VirtualFile({
249
+ assert(totalSize < TARBALL_SIZE_SAFETY_LIMIT, `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`);
250
+ const vfile = new VirtualFile({
243
251
  value: data,
244
252
  path,
245
253
  data: {
246
- canonicalPath: new URL(path, canonicalBase).toString(),
247
- },
254
+ canonicalPath: new URL(path, canonicalBase).toString()
255
+ }
248
256
  });
249
257
  // We disallow files having identical paths as it may confuse our checksum calculations.
250
- (0, utils_1.assert)(!files.has(path), 'Malformed tarball, multiple files with the same path.');
258
+ assert(!files.has(path), 'Malformed tarball, multiple files with the same path.');
251
259
  files.set(path, vfile);
252
260
  return next();
253
- }
254
- catch (error) {
261
+ } catch (error) {
255
262
  return extractStream.destroy(error);
256
263
  }
257
264
  }));
@@ -259,9 +266,10 @@ function createTarballStream(canonicalBase, files) {
259
266
  // If we get here, the entry is not a file, and we want to ignore. The entry
260
267
  // stream must be drained, or the extractStream will stop reading. This is
261
268
  // effectively a no-op for the current entry.
262
- entryStream.on('end', () => next());
269
+ entryStream.on('end', ()=>next());
263
270
  return entryStream.resume();
264
271
  });
265
272
  return extractStream;
266
273
  }
274
+
267
275
  //# sourceMappingURL=npm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/location/npm.ts"],"sourcesContent":["import {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n SnapManifest,\n VirtualFile,\n normalizeRelative,\n parseJson,\n} from '@metamask/snaps-utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n SemVerRange,\n SemVerVersion,\n} from '@metamask/utils';\nimport concat from 'concat-stream';\nimport createGunzipStream from 'gunzip-maybe';\nimport pump from 'pump';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport { 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 pump(\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((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","pump","ReadableWebToNodeStream","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","data","byteLength","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,EAChBC,UAAU,EACVC,eAAe,EAEfC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,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YAAYO,IAAI,CACrBjG,OAAO,CAACkG;gBACN,IAAI;oBACFX,aAAaW,KAAKC,UAAU;oBAC5B,8EAA8E;oBAC9EvG,OACE2F,YAAY/B,2BACZ,CAAC,8BAA8B,EAAEA,0BAA0B,OAAO,CAAC;oBAErE,MAAM7C,QAAQ,IAAIlB,YAAY;wBAC5B2G,OAAOF;wBACPnF;wBACAmF,MAAM;4BACJG,eAAe,IAAI9D,IAAIxB,MAAMiC,eAAelC,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFlB,OACE,CAACqB,MAAMqF,GAAG,CAACvF,OACX;oBAEFE,MAAMsF,GAAG,CAACxF,MAAMJ;oBAChB,OAAOgF;gBACT,EAAE,OAAOpC,OAAO;oBACd,OAAO+B,cAAckB,OAAO,CAACjD;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CmC,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYe,MAAM;IAC3B;IACA,OAAOnB;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 {\n PermissionConstraint,\n PermissionSpecificationConstraint,\n} from '@metamask/permission-controller';\nimport {\n caveatMappers,\n restrictedMethodPermissionBuilders,\n selectHooks,\n} from '@metamask/rpc-methods';\nimport { 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"}