@metamask/snaps-utils 0.38.0-flask.1 → 1.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 (268) hide show
  1. package/CHANGELOG.md +222 -11
  2. package/dist/{esm/array.js → array.js} +7 -3
  3. package/dist/array.js.map +1 -0
  4. package/dist/{types/caveats.d.ts → caveats.d.ts} +4 -0
  5. package/dist/caveats.js +35 -0
  6. package/dist/caveats.js.map +1 -0
  7. package/dist/checksum.js +42 -0
  8. package/dist/checksum.js.map +1 -0
  9. package/dist/{types/cronjob.d.ts → cronjob.d.ts} +1 -1
  10. package/dist/cronjob.js +71 -0
  11. package/dist/cronjob.js.map +1 -0
  12. package/dist/deep-clone.js +9 -0
  13. package/dist/deep-clone.js.map +1 -0
  14. package/dist/{esm/default-endowments.js → default-endowments.js} +6 -3
  15. package/dist/default-endowments.js.map +1 -0
  16. package/dist/entropy.js +8 -0
  17. package/dist/entropy.js.map +1 -0
  18. package/dist/{cjs/eval-worker.js → eval-worker.js} +21 -22
  19. package/dist/eval-worker.js.map +1 -0
  20. package/dist/{types/eval.d.ts → eval.d.ts} +1 -9
  21. package/dist/eval.js +27 -0
  22. package/dist/eval.js.map +1 -0
  23. package/dist/{types/fs.d.ts → fs.d.ts} +2 -2
  24. package/dist/{esm/fs.js → fs.js} +56 -33
  25. package/dist/fs.js.map +1 -0
  26. package/dist/handlers.d.ts +105 -0
  27. package/dist/handlers.js +3 -0
  28. package/dist/handlers.js.map +1 -0
  29. package/dist/{types/iframe.d.ts → iframe.d.ts} +2 -3
  30. package/dist/{esm/iframe.js → iframe.js} +18 -16
  31. package/dist/iframe.js.map +1 -0
  32. package/dist/iframe.test.browser.js +15 -0
  33. package/dist/iframe.test.browser.js.map +1 -0
  34. package/dist/{types/index.browser.d.ts → index.browser.d.ts} +1 -5
  35. package/dist/index.browser.js +37 -0
  36. package/dist/index.browser.js.map +1 -0
  37. package/dist/{types/index.d.ts → index.d.ts} +1 -5
  38. package/dist/index.executionenv.js +22 -0
  39. package/dist/index.executionenv.js.map +1 -0
  40. package/dist/index.js +42 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/{types/json-rpc.d.ts → json-rpc.d.ts} +2 -2
  43. package/dist/json-rpc.js +46 -0
  44. package/dist/json-rpc.js.map +1 -0
  45. package/dist/json.d.ts +9 -0
  46. package/dist/json.js +18 -0
  47. package/dist/json.js.map +1 -0
  48. package/dist/{esm/logging.js → logging.js} +14 -6
  49. package/dist/logging.js.map +1 -0
  50. package/dist/manifest/index.browser.js +18 -0
  51. package/dist/manifest/index.browser.js.map +1 -0
  52. package/dist/manifest/index.js +19 -0
  53. package/dist/manifest/index.js.map +1 -0
  54. package/dist/{types/manifest → manifest}/manifest.d.ts +4 -6
  55. package/dist/{esm/manifest → manifest}/manifest.js +115 -101
  56. package/dist/manifest/manifest.js.map +1 -0
  57. package/dist/{types/manifest → manifest}/validation.d.ts +76 -34
  58. package/dist/manifest/validation.js +141 -0
  59. package/dist/manifest/validation.js.map +1 -0
  60. package/dist/{esm/mock.js → mock.js} +40 -42
  61. package/dist/mock.js.map +1 -0
  62. package/dist/namespace.d.ts +275 -0
  63. package/dist/namespace.js +225 -0
  64. package/dist/namespace.js.map +1 -0
  65. package/dist/notification.d.ts +66 -0
  66. package/dist/notification.js +58 -0
  67. package/dist/notification.js.map +1 -0
  68. package/dist/{types/npm.d.ts → npm.d.ts} +3 -2
  69. package/dist/npm.js +74 -0
  70. package/dist/npm.js.map +1 -0
  71. package/dist/path.js +21 -0
  72. package/dist/path.js.map +1 -0
  73. package/dist/{esm/post-process.js → post-process.js} +99 -110
  74. package/dist/post-process.js.map +1 -0
  75. package/dist/{types/snaps.d.ts → snaps.d.ts} +9 -17
  76. package/dist/snaps.js +202 -0
  77. package/dist/snaps.js.map +1 -0
  78. package/dist/{types/types.d.ts → types.d.ts} +22 -15
  79. package/dist/types.js +103 -0
  80. package/dist/types.js.map +1 -0
  81. package/dist/{types/versions.d.ts → versions.d.ts} +1 -1
  82. package/dist/{esm/versions.js → versions.js} +18 -15
  83. package/dist/versions.js.map +1 -0
  84. package/dist/{esm/virtual-file → virtual-file}/VirtualFile.js +33 -47
  85. package/dist/virtual-file/VirtualFile.js.map +1 -0
  86. package/dist/virtual-file/index.browser.js +18 -0
  87. package/dist/virtual-file/index.browser.js.map +1 -0
  88. package/dist/virtual-file/index.js +19 -0
  89. package/dist/virtual-file/index.js.map +1 -0
  90. package/dist/virtual-file/toVirtualFile.js +30 -0
  91. package/dist/virtual-file/toVirtualFile.js.map +1 -0
  92. package/package.json +40 -59
  93. package/dist/cjs/array.js +0 -23
  94. package/dist/cjs/array.js.map +0 -1
  95. package/dist/cjs/caveats.js +0 -33
  96. package/dist/cjs/caveats.js.map +0 -1
  97. package/dist/cjs/checksum.js +0 -38
  98. package/dist/cjs/checksum.js.map +0 -1
  99. package/dist/cjs/cronjob.js +0 -84
  100. package/dist/cjs/cronjob.js.map +0 -1
  101. package/dist/cjs/deep-clone.js +0 -22
  102. package/dist/cjs/deep-clone.js.map +0 -1
  103. package/dist/cjs/default-endowments.js +0 -49
  104. package/dist/cjs/default-endowments.js.map +0 -1
  105. package/dist/cjs/entropy.js +0 -23
  106. package/dist/cjs/entropy.js.map +0 -1
  107. package/dist/cjs/enum.js +0 -16
  108. package/dist/cjs/enum.js.map +0 -1
  109. package/dist/cjs/errors.js +0 -19
  110. package/dist/cjs/errors.js.map +0 -1
  111. package/dist/cjs/eval-worker.js.map +0 -1
  112. package/dist/cjs/eval.js +0 -77
  113. package/dist/cjs/eval.js.map +0 -1
  114. package/dist/cjs/fs.js +0 -126
  115. package/dist/cjs/fs.js.map +0 -1
  116. package/dist/cjs/handlers.js +0 -65
  117. package/dist/cjs/handlers.js.map +0 -1
  118. package/dist/cjs/icon.js +0 -37
  119. package/dist/cjs/icon.js.map +0 -1
  120. package/dist/cjs/iframe.js +0 -59
  121. package/dist/cjs/iframe.js.map +0 -1
  122. package/dist/cjs/index.browser.js +0 -43
  123. package/dist/cjs/index.browser.js.map +0 -1
  124. package/dist/cjs/index.executionenv.js +0 -24
  125. package/dist/cjs/index.executionenv.js.map +0 -1
  126. package/dist/cjs/index.js +0 -48
  127. package/dist/cjs/index.js.map +0 -1
  128. package/dist/cjs/json-rpc.js +0 -46
  129. package/dist/cjs/json-rpc.js.map +0 -1
  130. package/dist/cjs/json.js +0 -16
  131. package/dist/cjs/json.js.map +0 -1
  132. package/dist/cjs/logging.js +0 -40
  133. package/dist/cjs/logging.js.map +0 -1
  134. package/dist/cjs/manifest/index.browser.js +0 -20
  135. package/dist/cjs/manifest/index.browser.js.map +0 -1
  136. package/dist/cjs/manifest/index.js +0 -21
  137. package/dist/cjs/manifest/index.js.map +0 -1
  138. package/dist/cjs/manifest/manifest.js +0 -239
  139. package/dist/cjs/manifest/manifest.js.map +0 -1
  140. package/dist/cjs/manifest/validation.js +0 -183
  141. package/dist/cjs/manifest/validation.js.map +0 -1
  142. package/dist/cjs/mock.js +0 -128
  143. package/dist/cjs/mock.js.map +0 -1
  144. package/dist/cjs/namespace.js +0 -124
  145. package/dist/cjs/namespace.js.map +0 -1
  146. package/dist/cjs/npm.js +0 -81
  147. package/dist/cjs/npm.js.map +0 -1
  148. package/dist/cjs/path.js +0 -21
  149. package/dist/cjs/path.js.map +0 -1
  150. package/dist/cjs/post-process.js +0 -328
  151. package/dist/cjs/post-process.js.map +0 -1
  152. package/dist/cjs/snaps.js +0 -230
  153. package/dist/cjs/snaps.js.map +0 -1
  154. package/dist/cjs/strings.js +0 -21
  155. package/dist/cjs/strings.js.map +0 -1
  156. package/dist/cjs/structs.js +0 -163
  157. package/dist/cjs/structs.js.map +0 -1
  158. package/dist/cjs/types.js +0 -109
  159. package/dist/cjs/types.js.map +0 -1
  160. package/dist/cjs/validation.js +0 -22
  161. package/dist/cjs/validation.js.map +0 -1
  162. package/dist/cjs/versions.js +0 -47
  163. package/dist/cjs/versions.js.map +0 -1
  164. package/dist/cjs/virtual-file/VirtualFile.js +0 -85
  165. package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
  166. package/dist/cjs/virtual-file/index.browser.js +0 -20
  167. package/dist/cjs/virtual-file/index.browser.js.map +0 -1
  168. package/dist/cjs/virtual-file/index.js +0 -21
  169. package/dist/cjs/virtual-file/index.js.map +0 -1
  170. package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
  171. package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
  172. package/dist/esm/array.js.map +0 -1
  173. package/dist/esm/caveats.js +0 -23
  174. package/dist/esm/caveats.js.map +0 -1
  175. package/dist/esm/checksum.js +0 -36
  176. package/dist/esm/checksum.js.map +0 -1
  177. package/dist/esm/cronjob.js +0 -66
  178. package/dist/esm/cronjob.js.map +0 -1
  179. package/dist/esm/deep-clone.js +0 -7
  180. package/dist/esm/deep-clone.js.map +0 -1
  181. package/dist/esm/default-endowments.js.map +0 -1
  182. package/dist/esm/entropy.js +0 -6
  183. package/dist/esm/entropy.js.map +0 -1
  184. package/dist/esm/enum.js +0 -12
  185. package/dist/esm/enum.js.map +0 -1
  186. package/dist/esm/errors.js +0 -17
  187. package/dist/esm/errors.js.map +0 -1
  188. package/dist/esm/eval-worker.js +0 -47
  189. package/dist/esm/eval-worker.js.map +0 -1
  190. package/dist/esm/eval.js +0 -65
  191. package/dist/esm/eval.js.map +0 -1
  192. package/dist/esm/fs.js.map +0 -1
  193. package/dist/esm/handlers.js +0 -47
  194. package/dist/esm/handlers.js.map +0 -1
  195. package/dist/esm/icon.js +0 -11
  196. package/dist/esm/icon.js.map +0 -1
  197. package/dist/esm/iframe.js.map +0 -1
  198. package/dist/esm/index.browser.js +0 -26
  199. package/dist/esm/index.browser.js.map +0 -1
  200. package/dist/esm/index.executionenv.js +0 -7
  201. package/dist/esm/index.executionenv.js.map +0 -1
  202. package/dist/esm/index.js +0 -31
  203. package/dist/esm/index.js.map +0 -1
  204. package/dist/esm/json-rpc.js +0 -39
  205. package/dist/esm/json-rpc.js.map +0 -1
  206. package/dist/esm/json.js +0 -17
  207. package/dist/esm/json.js.map +0 -1
  208. package/dist/esm/logging.js.map +0 -1
  209. package/dist/esm/manifest/index.browser.js +0 -3
  210. package/dist/esm/manifest/index.browser.js.map +0 -1
  211. package/dist/esm/manifest/index.js +0 -4
  212. package/dist/esm/manifest/index.js.map +0 -1
  213. package/dist/esm/manifest/manifest.js.map +0 -1
  214. package/dist/esm/manifest/validation.js +0 -152
  215. package/dist/esm/manifest/validation.js.map +0 -1
  216. package/dist/esm/mock.js.map +0 -1
  217. package/dist/esm/namespace.js +0 -110
  218. package/dist/esm/namespace.js.map +0 -1
  219. package/dist/esm/npm.js +0 -70
  220. package/dist/esm/npm.js.map +0 -1
  221. package/dist/esm/path.js +0 -17
  222. package/dist/esm/path.js.map +0 -1
  223. package/dist/esm/post-process.js.map +0 -1
  224. package/dist/esm/snaps.js +0 -215
  225. package/dist/esm/snaps.js.map +0 -1
  226. package/dist/esm/strings.js +0 -11
  227. package/dist/esm/strings.js.map +0 -1
  228. package/dist/esm/structs.js +0 -230
  229. package/dist/esm/structs.js.map +0 -1
  230. package/dist/esm/types.js +0 -80
  231. package/dist/esm/types.js.map +0 -1
  232. package/dist/esm/validation.js +0 -17
  233. package/dist/esm/validation.js.map +0 -1
  234. package/dist/esm/versions.js.map +0 -1
  235. package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
  236. package/dist/esm/virtual-file/index.browser.js +0 -3
  237. package/dist/esm/virtual-file/index.browser.js.map +0 -1
  238. package/dist/esm/virtual-file/index.js +0 -4
  239. package/dist/esm/virtual-file/index.js.map +0 -1
  240. package/dist/esm/virtual-file/toVirtualFile.js +0 -26
  241. package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
  242. package/dist/types/enum.d.ts +0 -30
  243. package/dist/types/errors.d.ts +0 -10
  244. package/dist/types/handlers.d.ts +0 -144
  245. package/dist/types/icon.d.ts +0 -4
  246. package/dist/types/json.d.ts +0 -13
  247. package/dist/types/namespace.d.ts +0 -124
  248. package/dist/types/strings.d.ts +0 -8
  249. package/dist/types/structs.d.ts +0 -158
  250. package/dist/types/validation.d.ts +0 -8
  251. /package/dist/{types/array.d.ts → array.d.ts} +0 -0
  252. /package/dist/{types/checksum.d.ts → checksum.d.ts} +0 -0
  253. /package/dist/{types/deep-clone.d.ts → deep-clone.d.ts} +0 -0
  254. /package/dist/{types/default-endowments.d.ts → default-endowments.d.ts} +0 -0
  255. /package/dist/{types/entropy.d.ts → entropy.d.ts} +0 -0
  256. /package/dist/{types/eval-worker.d.ts → eval-worker.d.ts} +0 -0
  257. /package/dist/{types/iframe.test.browser.d.ts → iframe.test.browser.d.ts} +0 -0
  258. /package/dist/{types/index.executionenv.d.ts → index.executionenv.d.ts} +0 -0
  259. /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
  260. /package/dist/{types/manifest → manifest}/index.browser.d.ts +0 -0
  261. /package/dist/{types/manifest → manifest}/index.d.ts +0 -0
  262. /package/dist/{types/mock.d.ts → mock.d.ts} +0 -0
  263. /package/dist/{types/path.d.ts → path.d.ts} +0 -0
  264. /package/dist/{types/post-process.d.ts → post-process.d.ts} +0 -0
  265. /package/dist/{types/virtual-file → virtual-file}/VirtualFile.d.ts +0 -0
  266. /package/dist/{types/virtual-file → virtual-file}/index.browser.d.ts +0 -0
  267. /package/dist/{types/virtual-file → virtual-file}/index.d.ts +0 -0
  268. /package/dist/{types/virtual-file → virtual-file}/toVirtualFile.d.ts +0 -0
@@ -1,39 +0,0 @@
1
- import { isJsonRpcFailure, isJsonRpcSuccess, assertStruct } from '@metamask/utils';
2
- import { boolean, object, optional, refine } from 'superstruct';
3
- export const RpcOriginsStruct = refine(object({
4
- dapps: optional(boolean()),
5
- snaps: optional(boolean())
6
- }), 'RPC origins', (value)=>{
7
- if (!Object.values(value).some(Boolean)) {
8
- throw new Error('Must specify at least one JSON-RPC origin');
9
- }
10
- return true;
11
- });
12
- /**
13
- * Asserts that the given value is a valid {@link RpcOrigins} object.
14
- *
15
- * @param value - The value to assert.
16
- * @param ErrorWrapper - An optional error wrapper to use. Defaults to
17
- * {@link AssertionError}.
18
- * @throws If the value is not a valid {@link RpcOrigins} object.
19
- */ export function assertIsRpcOrigins(value, // eslint-disable-next-line @typescript-eslint/naming-convention
20
- ErrorWrapper) {
21
- assertStruct(value, RpcOriginsStruct, 'Invalid JSON-RPC origins', ErrorWrapper);
22
- }
23
- /**
24
- * Assert that the given value is a successful JSON-RPC response. If the value
25
- * is not a success response, an error is thrown. If the value is an JSON-RPC
26
- * error, the error message is included in the thrown error.
27
- *
28
- * @param value - The value to check.
29
- * @throws If the value is not a JSON-RPC success response.
30
- */ export function assertIsJsonRpcSuccess(value) {
31
- if (!isJsonRpcSuccess(value)) {
32
- if (isJsonRpcFailure(value)) {
33
- throw new Error(`JSON-RPC request failed: ${value.error.message}`);
34
- }
35
- throw new Error('Invalid JSON-RPC response.');
36
- }
37
- }
38
-
39
- //# sourceMappingURL=json-rpc.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/json-rpc.ts"],"sourcesContent":["import type {\n Json,\n JsonRpcSuccess,\n AssertionErrorConstructor,\n} from '@metamask/utils';\nimport {\n isJsonRpcFailure,\n isJsonRpcSuccess,\n assertStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { boolean, object, optional, refine } from 'superstruct';\n\nexport const RpcOriginsStruct = refine(\n object({\n dapps: optional(boolean()),\n snaps: optional(boolean()),\n }),\n 'RPC origins',\n (value) => {\n if (!Object.values(value).some(Boolean)) {\n throw new Error('Must specify at least one JSON-RPC origin');\n }\n\n return true;\n },\n);\n\nexport type RpcOrigins = Infer<typeof RpcOriginsStruct>;\n\n/**\n * Asserts that the given value is a valid {@link RpcOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link RpcOrigins} object.\n */\nexport function assertIsRpcOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is RpcOrigins {\n assertStruct(\n value,\n RpcOriginsStruct,\n 'Invalid JSON-RPC origins',\n ErrorWrapper,\n );\n}\n\n/**\n * Assert that the given value is a successful JSON-RPC response. If the value\n * is not a success response, an error is thrown. If the value is an JSON-RPC\n * error, the error message is included in the thrown error.\n *\n * @param value - The value to check.\n * @throws If the value is not a JSON-RPC success response.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n): asserts value is JsonRpcSuccess<Json> {\n if (!isJsonRpcSuccess(value)) {\n if (isJsonRpcFailure(value)) {\n throw new Error(`JSON-RPC request failed: ${value.error.message}`);\n }\n\n throw new Error('Invalid JSON-RPC response.');\n }\n}\n"],"names":["isJsonRpcFailure","isJsonRpcSuccess","assertStruct","boolean","object","optional","refine","RpcOriginsStruct","dapps","snaps","value","Object","values","some","Boolean","Error","assertIsRpcOrigins","ErrorWrapper","assertIsJsonRpcSuccess","error","message"],"mappings":"AAKA,SACEA,gBAAgB,EAChBC,gBAAgB,EAChBC,YAAY,QACP,kBAAkB;AAEzB,SAASC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,QAAQ,cAAc;AAEhE,OAAO,MAAMC,mBAAmBD,OAC9BF,OAAO;IACLI,OAAOH,SAASF;IAChBM,OAAOJ,SAASF;AAClB,IACA,eACA,CAACO;IACC,IAAI,CAACC,OAAOC,MAAM,CAACF,OAAOG,IAAI,CAACC,UAAU;QACvC,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;AACT,GACA;AAIF;;;;;;;CAOC,GACD,OAAO,SAASC,mBACdN,KAAc,EACd,gEAAgE;AAChEO,YAAwC;IAExCf,aACEQ,OACAH,kBACA,4BACAU;AAEJ;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,uBACdR,KAAc;IAEd,IAAI,CAACT,iBAAiBS,QAAQ;QAC5B,IAAIV,iBAAiBU,QAAQ;YAC3B,MAAM,IAAIK,MAAM,CAAC,yBAAyB,EAAEL,MAAMS,KAAK,CAACC,OAAO,CAAC,CAAC;QACnE;QAEA,MAAM,IAAIL,MAAM;IAClB;AACF"}
package/dist/esm/json.js DELETED
@@ -1,17 +0,0 @@
1
- import { getSafeJson } from '@metamask/utils';
2
- // TODO: Upstream this to @metamask/utils
3
- /**
4
- * Parse JSON safely.
5
- *
6
- * Does multiple kinds of validation and strips unwanted properties like
7
- * `__proto__` and `constructor`.
8
- *
9
- * @param json - A JSON string to be parsed.
10
- * @returns The parsed JSON object.
11
- * @template Type - The type of the JSON object. The type is not actually
12
- * checked, but it is used to infer the return type.
13
- */ export function parseJson(json) {
14
- return getSafeJson(JSON.parse(json));
15
- }
16
-
17
- //# sourceMappingURL=json.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/json.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { getSafeJson } from '@metamask/utils';\n\n// TODO: Upstream this to @metamask/utils\n\n/**\n * Parse JSON safely.\n *\n * Does multiple kinds of validation and strips unwanted properties like\n * `__proto__` and `constructor`.\n *\n * @param json - A JSON string to be parsed.\n * @returns The parsed JSON object.\n * @template Type - The type of the JSON object. The type is not actually\n * checked, but it is used to infer the return type.\n */\nexport function parseJson<Type extends Json = Json>(json: string) {\n return getSafeJson<Type>(JSON.parse(json));\n}\n"],"names":["getSafeJson","parseJson","json","JSON","parse"],"mappings":"AACA,SAASA,WAAW,QAAQ,kBAAkB;AAE9C,yCAAyC;AAEzC;;;;;;;;;;CAUC,GACD,OAAO,SAASC,UAAoCC,IAAY;IAC9D,OAAOF,YAAkBG,KAAKC,KAAK,CAACF;AACtC"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/logging.ts"],"sourcesContent":["import { createProjectLogger } from '@metamask/utils';\n\n// The global logger used across the monorepo. Other projects should use this\n// to create a module logger.\nexport const snapsLogger = createProjectLogger('snaps');\n\n/**\n * Log a message. Currently, this is just a wrapper around `console.log`, but\n * the implementation may change in the future. These logs will be included in\n * production builds, so they should be used sparingly, and not contain any\n * sensitive information.\n *\n * This function makes it easy to swap out the logging implementation in all\n * files at once.\n *\n * @param message - The message to log.\n * @param optionalParams - Additional parameters to pass to the logging.\n */\nexport function logInfo(message: string, ...optionalParams: unknown[]): void {\n // eslint-disable-next-line no-console\n console.log(message, ...optionalParams);\n}\n\n/**\n * Log an error. Currently, this is just a wrapper around `console.error`, but\n * the implementation may change in the future. These logs will be included in\n * production builds, so they should be used sparingly, and not contain any\n * sensitive information.\n *\n * These logs should always be visible, without requiring the user to enable\n * verbose logging (like setting a `DEBUG` environment variable), as they are\n * important for debugging snaps.\n *\n * This function makes it easy to swap out the logging implementation in all\n * files at once.\n *\n * @param error - The error to log.\n * @param optionalParams - Additional parameters to pass to the logging.\n */\nexport function logError(error: unknown, ...optionalParams: unknown[]): void {\n // eslint-disable-next-line no-console\n console.error(error, ...optionalParams);\n}\n\n/**\n * Log a warning. Currently, this is just a wrapper around `console.warn`, but\n * the implementation may change in the future. These logs will be included in\n * production builds, so they should be used sparingly, and not contain any\n * sensitive information.\n *\n * These logs should always be visible, without requiring the user to enable\n * verbose logging (like setting a `DEBUG` environment variable), as they are\n * important for debugging snaps.\n *\n * This function makes it easy to swap out the logging implementation in all\n * files at once.\n *\n * @param message - The message to log.\n * @param optionalParams - Additional parameters to pass to the logging.\n */\nexport function logWarning(\n message: string,\n ...optionalParams: unknown[]\n): void {\n // eslint-disable-next-line no-console\n console.warn(message, ...optionalParams);\n}\n"],"names":["createProjectLogger","snapsLogger","logInfo","message","optionalParams","console","log","logError","error","logWarning","warn"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,kBAAkB;AAEtD,6EAA6E;AAC7E,6BAA6B;AAC7B,OAAO,MAAMC,cAAcD,oBAAoB,SAAS;AAExD;;;;;;;;;;;CAWC,GACD,OAAO,SAASE,QAAQC,OAAe,EAAE,GAAGC,cAAyB;IACnE,sCAAsC;IACtCC,QAAQC,GAAG,CAACH,YAAYC;AAC1B;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASG,SAASC,KAAc,EAAE,GAAGJ,cAAyB;IACnE,sCAAsC;IACtCC,QAAQG,KAAK,CAACA,UAAUJ;AAC1B;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASK,WACdN,OAAe,EACf,GAAGC,cAAyB;IAE5B,sCAAsC;IACtCC,QAAQK,IAAI,CAACP,YAAYC;AAC3B"}
@@ -1,3 +0,0 @@
1
- export * from './validation';
2
-
3
- //# sourceMappingURL=index.browser.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/manifest/index.browser.ts"],"sourcesContent":["export * from './validation';\n"],"names":[],"mappings":"AAAA,cAAc,eAAe"}
@@ -1,4 +0,0 @@
1
- export * from './manifest';
2
- export * from './validation';
3
-
4
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/manifest/index.ts"],"sourcesContent":["export * from './manifest';\nexport * from './validation';\n"],"names":[],"mappings":"AAAA,cAAc,aAAa;AAC3B,cAAc,eAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","writeFileFn","writeFile","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,MAAM,EAAEC,aAAa,QAAQ,kBAAkB;AAC1E,OAAOC,eAAe,kBAAkB;AACxC,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,eAAe,OAAO;AAE7B,SAASC,SAAS,QAAQ,gBAAgB;AAC1C,SAASC,YAAY,QAAQ,QAAQ;AACrC,SAASC,eAAe,QAAQ,SAAS;AACzC,SACEC,eAAe,EACfC,gCAAgC,EAChCC,kBAAkB,QACb,WAAW;AAElB,SAASC,gBAAgB,EAAEC,2BAA2B,QAAQ,WAAW;AACzE,SAASC,eAAe,EAAEC,WAAW,QAAQ,kBAAkB;AAG/D,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAyBA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeC,cACpBC,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCzB,GAAG0B,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC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BAAyB7D,SAASJ,MAAM,CAACrB,OAAO;IACtD,MAAMuF,qBAAqB9D,SAASJ,MAAM,CAAClB,UAAU;IAErD,IAAI+E,oBAAoBG,qBAAqB;QAC3C,MAAM,IAAI7F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,qBAAqB,EAAEmE,oBAAoB,uBAAuB,EAAE3F,iBAAiB6B,WAAW,CAAC,iBAAiB,EAAE2D,gBAAgB,GAAG,CAAC,EACtKvF,4BAA4BmE,YAAY;IAE5C;IAEA,IAAIqB,uBAAuBG,wBAAwB;QACjD,MAAM,IAAI9F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,wBAAwB,EAAEoE,uBAAuB,uBAAuB,EAAE5F,iBAAiB6B,WAAW,CAAC,oBAAoB,EAAE4D,mBAAmB,GAAG,CAAC,EAClLxF,4BAA4BwE,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACvG,UAAUoG,uBAAuBG,qBAClC;QACA,MAAM,IAAI/F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,yCAAyC,EAAExB,iBAAiB6B,WAAW,CAAC,qBAAqB,CAAC,EAC5H5B,4BAA4ByE,kBAAkB;IAElD;IAEA3E,mBACE;QAAEgC;QAAUf;QAAYkB;IAAQ,GAChC,CAAC,CAAC,EAAElC,iBAAiBwB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
@@ -1,152 +0,0 @@
1
- import { isValidBIP32PathSegment } from '@metamask/key-tree';
2
- import { assertStruct, ChecksumStruct, VersionStruct, isValidSemVerRange } from '@metamask/utils';
3
- import { array, boolean, create, enums, integer, is, literal, object, optional, pattern, refine, record, size, string, type, union } from 'superstruct';
4
- import { isEqual } from '../array';
5
- import { CronjobSpecificationArrayStruct } from '../cronjob';
6
- import { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';
7
- import { RpcOriginsStruct } from '../json-rpc';
8
- import { SnapIdStruct } from '../snaps';
9
- import { NameStruct, NpmSnapFileNames } from '../types';
10
- // BIP-43 purposes that cannot be used for entropy derivation. These are in the
11
- // string form, ending with `'`.
12
- const FORBIDDEN_PURPOSES = [
13
- SIP_6_MAGIC_VALUE,
14
- STATE_ENCRYPTION_MAGIC_VALUE
15
- ];
16
- export const FORBIDDEN_COIN_TYPES = [
17
- 60
18
- ];
19
- const FORBIDDEN_PATHS = FORBIDDEN_COIN_TYPES.map((coinType)=>[
20
- 'm',
21
- "44'",
22
- `${coinType}'`
23
- ]);
24
- export const Bip32PathStruct = refine(array(string()), 'BIP-32 path', (path)=>{
25
- if (path.length === 0) {
26
- return 'Path must be a non-empty BIP-32 derivation path array';
27
- }
28
- if (path[0] !== 'm') {
29
- return 'Path must start with "m".';
30
- }
31
- if (path.length < 3) {
32
- return 'Paths must have a length of at least three.';
33
- }
34
- if (path.slice(1).some((part)=>!isValidBIP32PathSegment(part))) {
35
- return 'Path must be a valid BIP-32 derivation path array.';
36
- }
37
- if (FORBIDDEN_PURPOSES.includes(path[1])) {
38
- return `The purpose "${path[1]}" is not allowed for entropy derivation.`;
39
- }
40
- if (FORBIDDEN_PATHS.some((forbiddenPath)=>isEqual(path.slice(0, forbiddenPath.length), forbiddenPath))) {
41
- return `The path "${path.join('/')}" is not allowed for entropy derivation.`;
42
- }
43
- return true;
44
- });
45
- export const bip32entropy = (struct)=>refine(struct, 'BIP-32 entropy', (value)=>{
46
- if (value.curve === 'ed25519' && value.path.slice(1).some((part)=>!part.endsWith("'"))) {
47
- return 'Ed25519 does not support unhardened paths.';
48
- }
49
- return true;
50
- });
51
- // Used outside @metamask/snap-utils
52
- export const Bip32EntropyStruct = bip32entropy(type({
53
- path: Bip32PathStruct,
54
- curve: enums([
55
- 'ed25519',
56
- 'secp256k1'
57
- ])
58
- }));
59
- export const SnapGetBip32EntropyPermissionsStruct = size(array(Bip32EntropyStruct), 1, Infinity);
60
- export const SemVerRangeStruct = refine(string(), 'SemVer range', (value)=>{
61
- if (isValidSemVerRange(value)) {
62
- return true;
63
- }
64
- return 'Expected a valid SemVer range.';
65
- });
66
- export const SnapIdsStruct = refine(record(SnapIdStruct, object({
67
- version: optional(SemVerRangeStruct)
68
- })), 'SnapIds', (value)=>{
69
- if (Object.keys(value).length === 0) {
70
- return false;
71
- }
72
- return true;
73
- });
74
- /* eslint-disable @typescript-eslint/naming-convention */ export const PermissionsStruct = type({
75
- 'endowment:long-running': optional(object({})),
76
- 'endowment:network-access': optional(object({})),
77
- 'endowment:webassembly': optional(object({})),
78
- 'endowment:transaction-insight': optional(object({
79
- allowTransactionOrigin: optional(boolean())
80
- })),
81
- 'endowment:cronjob': optional(object({
82
- jobs: CronjobSpecificationArrayStruct
83
- })),
84
- 'endowment:rpc': optional(RpcOriginsStruct),
85
- snap_dialog: optional(object({})),
86
- // TODO: Remove
87
- snap_confirm: optional(object({})),
88
- snap_manageState: optional(object({})),
89
- snap_manageAccounts: optional(object({})),
90
- snap_notify: optional(object({})),
91
- snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),
92
- snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),
93
- snap_getBip44Entropy: optional(size(array(object({
94
- coinType: size(integer(), 0, 2 ** 32 - 1)
95
- })), 1, Infinity)),
96
- snap_getEntropy: optional(object({})),
97
- wallet_snap: optional(SnapIdsStruct)
98
- });
99
- export const SnapManifestStruct = object({
100
- version: VersionStruct,
101
- description: size(string(), 1, 280),
102
- proposedName: size(pattern(string(), /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u), 1, 214),
103
- repository: optional(object({
104
- type: size(string(), 1, Infinity),
105
- url: size(string(), 1, Infinity)
106
- })),
107
- source: object({
108
- shasum: ChecksumStruct,
109
- location: object({
110
- npm: object({
111
- filePath: size(string(), 1, Infinity),
112
- iconPath: optional(size(string(), 1, Infinity)),
113
- packageName: NameStruct,
114
- registry: union([
115
- literal('https://registry.npmjs.org'),
116
- literal('https://registry.npmjs.org/')
117
- ])
118
- })
119
- })
120
- }),
121
- initialPermissions: PermissionsStruct,
122
- manifestVersion: literal('0.1'),
123
- $schema: optional(string())
124
- });
125
- /**
126
- * Check if the given value is a valid {@link SnapManifest} object.
127
- *
128
- * @param value - The value to check.
129
- * @returns Whether the value is a valid {@link SnapManifest} object.
130
- */ export function isSnapManifest(value) {
131
- return is(value, SnapManifestStruct);
132
- }
133
- /**
134
- * Assert that the given value is a valid {@link SnapManifest} object.
135
- *
136
- * @param value - The value to check.
137
- * @throws If the value is not a valid {@link SnapManifest} object.
138
- */ export function assertIsSnapManifest(value) {
139
- assertStruct(value, SnapManifestStruct, `"${NpmSnapFileNames.Manifest}" is invalid`);
140
- }
141
- /**
142
- * Creates a {@link SnapManifest} object from JSON.
143
- *
144
- * @param value - The value to check.
145
- * @throws If the value cannot be coerced to a {@link SnapManifest} object.
146
- * @returns The created {@link SnapManifest} object.
147
- */ export function createSnapManifest(value) {
148
- // TODO: Add a utility to prefix these errors similar to assertStruct
149
- return create(value, SnapManifestStruct);
150
- }
151
-
152
- //# sourceMappingURL=validation.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:long-running': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","pattern","refine","record","size","string","type","union","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","RpcOriginsStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","PermissionsStruct","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","wallet_snap","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,qBAAqB;AAC7D,SACEC,YAAY,EACZC,cAAc,EACdC,aAAa,EACbC,kBAAkB,QACb,kBAAkB;AAEzB,SACEC,KAAK,EACLC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,EAAE,EACFC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,QACA,cAAc;AAErB,SAASC,OAAO,QAAQ,WAAW;AACnC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,iBAAiB,EAAEC,4BAA4B,QAAQ,aAAa;AAC7E,SAASC,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,YAAY,QAAQ,WAAW;AACxC,SAASC,UAAU,EAAEC,gBAAgB,QAAQ,WAAW;AAExD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCN;IACAC;CACD;AAED,OAAO,MAAMM,uBAAiC;IAAC;CAAG,CAAC;AACnD,MAAMC,kBAA8BD,qBAAqBE,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KAC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AUhE,OAAO;YACfiE,KAAKjE,OAAO;gBACVkE,UAAU7D,KAAKC,UAAU,GAAGgC;gBAC5B6B,UAAUlE,SAASI,KAAKC,UAAU,GAAGgC;gBACrC8B,aAAarD;gBACbsD,UAAU7D,MAAM;oBACdT,QAAQ;oBACRA,QAAQ;iBACT;YACH;QACF;IACF;IACAuE,oBAAoB1B;IACpB2B,iBAAiBxE,QAAQ;IACzByE,SAASvE,SAASK;AACpB,GAAG;AAIH;;;;;CAKC,GACD,OAAO,SAASmE,eAAexC,KAAc;IAC3C,OAAOnC,GAAGmC,OAAOwB;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASiB,qBACdzC,KAAc;IAEd5C,aACE4C,OACAwB,oBACA,CAAC,CAAC,EAAEzC,iBAAiB2D,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmB3C,KAAc;IAC/C,qEAAqE;IACrE,OAAOtC,OAAOsC,OAAOwB;AACvB"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/mock.ts"],"sourcesContent":["import crypto from 'crypto';\nimport EventEmitter from 'events';\n\nimport { DEFAULT_ENDOWMENTS } from './default-endowments';\n\nconst NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];\n\nexport const ALL_APIS: string[] = [\n ...DEFAULT_ENDOWMENTS,\n ...NETWORK_APIS,\n 'WebAssembly',\n];\n\ntype MockSnapGlobal = {\n request: () => Promise<any>;\n};\n\ntype MockEthereumProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap API, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapGlobal(): MockSnapGlobal {\n // eslint-disable-next-line @typescript-eslint/require-await\n return { request: async () => true };\n}\n\n/**\n * Get a mock Ethereum provider, that always returns `true` for requests.\n *\n * @returns A mocked ethereum provider.\n */\nfunction getMockEthereumProvider(): MockEthereumProvider {\n const mockProvider = new EventEmitter() as Partial<MockEthereumProvider>;\n // eslint-disable-next-line @typescript-eslint/require-await\n mockProvider.request = async () => true;\n return mockProvider as MockEthereumProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we\n// have types for them and can use that to generate mocks if needed.\nconst mockWindow: Record<string, unknown> = {\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? mockWindow[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() },\n );\n};\n"],"names":["crypto","EventEmitter","DEFAULT_ENDOWMENTS","NETWORK_APIS","ALL_APIS","getMockSnapGlobal","request","getMockEthereumProvider","mockProvider","isConstructor","value","Boolean","prototype","constructor","name","mockFunction","MockClass","handler","construct","Target","args","Proxy","get","_target","_prop","generateMockClass","mockWindow","SubtleCrypto","generateMockEndowment","key","globalValue","globalThis","includes","globalOrMocked","type","isFunction","generateMockEndowments","reduce","acc","cur","snap","ethereum"],"mappings":"AAAA,OAAOA,YAAY,SAAS;AAC5B,OAAOC,kBAAkB,SAAS;AAElC,SAASC,kBAAkB,QAAQ,uBAAuB;AAE1D,MAAMC,eAAe;IAAC;IAAS;IAAW;IAAW;CAAW;AAEhE,OAAO,MAAMC,WAAqB;OAC7BF;OACAC;IACH;CACD,CAAC;AAUF;;;;CAIC,GACD,SAASE;IACP,4DAA4D;IAC5D,OAAO;QAAEC,SAAS,UAAY;IAAK;AACrC;AAEA;;;;CAIC,GACD,SAASC;IACP,MAAMC,eAAe,IAAIP;IACzB,4DAA4D;IAC5DO,aAAaF,OAAO,GAAG,UAAY;IACnC,OAAOE;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,gBAAgB,CAACC,QAC5BC,QAAQ,OAAOD,OAAOE,WAAWC,aAAaC,SAAS,UAAU;AAEnE;;;;CAIC,GACD,MAAMC,eAAe,IAAM;AAC3B,MAAMC;AAAW;AAEjB,MAAMC,UAAU;IACd,gEAAgE;IAChEC,WAAUC,MAAW,EAAEC,IAAW;QAChC,OAAO,IAAIC,MAAM,IAAIF,UAAUC,OAAOH;IACxC;IACAK,KAAIC,OAAY,EAAEC,KAAU;QAC1B,OAAOT;IACT;AACF;AAEA;;;;;;CAMC,GACD,MAAMU,oBAAoB,CAACf;IACzB,OAAO,IAAIW,MAAMX,OAAOO;AAC1B;AAEA,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMS,aAAsC;IAC1C1B;IACA2B,cAAcX;AAChB;AAEA;;;;;;;CAOC,GACD,MAAMY,wBAAwB,CAACC;IAC7B,MAAMC,cAAc,AAACC,UAAkB,CAACF,IAAI;IAE5C,+CAA+C;IAC/C,IAAIC,eAAe5B,mBAAmB8B,QAAQ,CAACH,MAAM;QACnD,OAAOC;IACT;IAEA,4EAA4E;IAC5E,MAAMG,iBAAiBH,eAAeJ,UAAU,CAACG,IAAI;IAErD,MAAMK,OAAO,OAAOD;IACpB,MAAME,aAAaD,SAAS;IAC5B,IAAIC,cAAc1B,cAAcwB,iBAAiB;QAC/C,OAAOR,kBAAkBQ;IAC3B,OAAO,IAAIE,cAAc,CAACF,gBAAgB;QACxC,qCAAqC;QACrC,OAAOlB;IACT;IACA,OAAOkB;AACT;AAEA;;;;CAIC,GACD,OAAO,MAAMG,yBAAyB;IACpC,OAAOhC,SAASiC,MAAM,CACpB,CAACC,KAAKC,MAAS,CAAA;YAAE,GAAGD,GAAG;YAAE,CAACC,IAAI,EAAEX,sBAAsBW;QAAK,CAAA,GAC3D;QAAEC,MAAMnC;QAAqBoC,UAAUlC;IAA0B;AAErE,EAAE"}
@@ -1,110 +0,0 @@
1
- import { array, is, object, optional, pattern, size, string } from 'superstruct';
2
- export const CHAIN_ID_REGEX = RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u");
3
- export const ACCOUNT_ID_REGEX = RegExp("^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
4
- /**
5
- * Parse a chain ID string to an object containing the namespace and reference.
6
- * This validates the chain ID before parsing it.
7
- *
8
- * @param chainId - The chain ID to validate and parse.
9
- * @returns The parsed chain ID.
10
- */ export function parseChainId(chainId) {
11
- const match = CHAIN_ID_REGEX.exec(chainId);
12
- if (!match?.groups) {
13
- throw new Error('Invalid chain ID.');
14
- }
15
- return {
16
- namespace: match.groups.namespace,
17
- reference: match.groups.reference
18
- };
19
- }
20
- /**
21
- * Parse an account ID to an object containing the chain, chain ID and address.
22
- * This validates the account ID before parsing it.
23
- *
24
- * @param accountId - The account ID to validate and parse.
25
- * @returns The parsed account ID.
26
- */ export function parseAccountId(accountId) {
27
- const match = ACCOUNT_ID_REGEX.exec(accountId);
28
- if (!match?.groups) {
29
- throw new Error('Invalid account ID.');
30
- }
31
- return {
32
- address: match.groups.accountAddress,
33
- chainId: match.groups.chainId,
34
- chain: {
35
- namespace: match.groups.namespace,
36
- reference: match.groups.reference
37
- }
38
- };
39
- }
40
- /**
41
- * A helper struct for a string with a minimum length of 1 and a maximum length
42
- * of 40.
43
- */ export const LimitedString = size(string(), 1, 40);
44
- /**
45
- * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
46
- */ export const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);
47
- export const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);
48
- export const AccountIdArrayStruct = array(AccountIdStruct);
49
- /**
50
- * A chain descriptor.
51
- */ export const ChainStruct = object({
52
- id: ChainIdStruct,
53
- name: LimitedString
54
- });
55
- export const NamespaceStruct = object({
56
- /**
57
- * A list of supported chains in the namespace.
58
- */ chains: array(ChainStruct),
59
- /**
60
- * A list of supported RPC methods on the namespace, that a DApp can call.
61
- */ methods: optional(array(LimitedString)),
62
- /**
63
- * A list of supported RPC events on the namespace, that a DApp can listen to.
64
- */ events: optional(array(LimitedString))
65
- });
66
- /**
67
- * A CAIP-2 namespace, i.e., the first part of a chain ID.
68
- */ export const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);
69
- /**
70
- * Check if the given value is a CAIP-2 namespace ID.
71
- *
72
- * @param value - The value to check.
73
- * @returns Whether the value is a CAIP-2 namespace ID.
74
- */ export function isNamespaceId(value) {
75
- return is(value, NamespaceIdStruct);
76
- }
77
- /**
78
- * Check if the given value is a CAIP-2 chain ID.
79
- *
80
- * @param value - The value to check.
81
- * @returns Whether the value is a CAIP-2 chain ID.
82
- */ export function isChainId(value) {
83
- return is(value, ChainIdStruct);
84
- }
85
- /**
86
- * Check if the given value is a CAIP-10 account ID.
87
- *
88
- * @param value - The value to check.
89
- * @returns Whether the value is a CAIP-10 account ID.
90
- */ export function isAccountId(value) {
91
- return is(value, AccountIdStruct);
92
- }
93
- /**
94
- * Check if the given value is an array of CAIP-10 account IDs.
95
- *
96
- * @param value - The value to check.
97
- * @returns Whether the value is an array of CAIP-10 account IDs.
98
- */ export function isAccountIdArray(value) {
99
- return is(value, AccountIdArrayStruct);
100
- }
101
- /**
102
- * Check if a value is a {@link Namespace}.
103
- *
104
- * @param value - The value to validate.
105
- * @returns True if the value is a valid {@link Namespace}.
106
- */ export function isNamespace(value) {
107
- return is(value, NamespaceStruct);
108
- }
109
-
110
- //# sourceMappingURL=namespace.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n array,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"names":["array","is","object","optional","pattern","size","string","CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","parseChainId","chainId","match","exec","groups","Error","namespace","reference","parseAccountId","accountId","address","accountAddress","chain","LimitedString","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","ChainStruct","id","name","NamespaceStruct","chains","methods","events","NamespaceIdStruct","isNamespaceId","value","isChainId","isAccountId","isAccountIdArray","isNamespace"],"mappings":"AACA,SACEA,KAAK,EACLC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,IAAI,EACJC,MAAM,QACD,cAAc;AAErB,OAAO,MAAMC,iBACX,+EAAmE;AAErE,OAAO,MAAMC,mBACX,gIAAoH;AAEtH;;;;;;CAMC,GACD,OAAO,SAASC,aAAaC,OAAgB;IAI3C,MAAMC,QAAQJ,eAAeK,IAAI,CAACF;IAClC,IAAI,CAACC,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLC,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kC,OAAOX;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,iBAAiBH,KAAc;IAC7C,OAAOlC,GAAGkC,OAAOV;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,YAAYJ,KAAc;IACxC,OAAOlC,GAAGkC,OAAON;AACnB"}
package/dist/esm/npm.js DELETED
@@ -1,70 +0,0 @@
1
- import { assertIsSnapIcon } from './icon';
2
- import { validateNpmSnapManifest } from './manifest/manifest';
3
- import { assertIsSnapManifest } from './manifest/validation';
4
- import { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';
5
- export const EXPECTED_SNAP_FILES = [
6
- 'manifest',
7
- 'packageJson',
8
- 'sourceCode'
9
- ];
10
- export const SnapFileNameFromKey = {
11
- manifest: NpmSnapFileNames.Manifest,
12
- packageJson: NpmSnapFileNames.PackageJson,
13
- sourceCode: 'source code bundle'
14
- };
15
- // TODO: Refactor this to be more shared with other validation.
16
- /**
17
- * Validates the files extracted from an npm Snap package tarball by ensuring
18
- * that they're non-empty and that the Json files match their respective schemas
19
- * and the Snaps publishing specification.
20
- *
21
- * @param snapFiles - The object containing the expected Snap file contents,
22
- * if any.
23
- * @param errorPrefix - The prefix of the error message.
24
- * @returns A tuple of the Snap manifest object and the Snap source code.
25
- */ export function validateNpmSnap(snapFiles, errorPrefix) {
26
- EXPECTED_SNAP_FILES.forEach((key)=>{
27
- if (!snapFiles[key]) {
28
- throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
29
- }
30
- });
31
- // Typecast: We are assured that the required files exist if we get here.
32
- const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
33
- try {
34
- assertIsSnapManifest(manifest.result);
35
- } catch (error) {
36
- throw new Error(`${errorPrefix ?? ''}${error.message}`);
37
- }
38
- const validatedManifest = manifest;
39
- const { iconPath } = validatedManifest.result.source.location.npm;
40
- if (iconPath && !svgIcon) {
41
- throw new Error(`Missing file "${iconPath}".`);
42
- }
43
- try {
44
- assertIsNpmSnapPackageJson(packageJson.result);
45
- } catch (error) {
46
- throw new Error(`${errorPrefix ?? ''}${error.message}`);
47
- }
48
- const validatedPackageJson = packageJson;
49
- validateNpmSnapManifest({
50
- manifest: validatedManifest,
51
- packageJson: validatedPackageJson,
52
- sourceCode,
53
- svgIcon
54
- });
55
- if (svgIcon) {
56
- try {
57
- assertIsSnapIcon(svgIcon);
58
- } catch (error) {
59
- throw new Error(`${errorPrefix ?? ''}${error.message}`);
60
- }
61
- }
62
- return {
63
- manifest: validatedManifest,
64
- packageJson: validatedPackageJson,
65
- sourceCode,
66
- svgIcon
67
- };
68
- }
69
-
70
- //# sourceMappingURL=npm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"],"names":["assertIsSnapIcon","validateNpmSnapManifest","assertIsSnapManifest","assertIsNpmSnapPackageJson","NpmSnapFileNames","EXPECTED_SNAP_FILES","SnapFileNameFromKey","manifest","Manifest","packageJson","PackageJson","sourceCode","validateNpmSnap","snapFiles","errorPrefix","forEach","key","Error","svgIcon","result","error","message","validatedManifest","iconPath","source","location","npm","validatedPackageJson"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,uBAAuB,QAAQ,sBAAsB;AAC9D,SAASC,oBAAoB,QAAQ,wBAAwB;AAE7D,SAASC,0BAA0B,EAAEC,gBAAgB,QAAQ,UAAU;AAEvE,OAAO,MAAMC,sBAAsB;IACjC;IACA;IACA;CACD,CAAU;AAEX,OAAO,MAAMC,sBAAsB;IACjCC,UAAUH,iBAAiBI,QAAQ;IACnCC,aAAaL,iBAAiBM,WAAW;IACzCC,YAAY;AACd,EAAW;AAEX,+DAA+D;AAE/D;;;;;;;;;CASC,GACD,OAAO,SAASC,gBACdC,SAA+B,EAC/BC,WAA2B;IAE3BT,oBAAoBU,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAER,mBAAmB,CAACU,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;IAEA,yEAAyE;IACzE,MAAM,EAAET,QAAQ,EAAEE,WAAW,EAAEE,UAAU,EAAEO,OAAO,EAAE,GAAGL;IACvD,IAAI;QACFX,qBAAqBK,SAASY,MAAM;IACtC,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMC,oBAAoBf;IAE1B,MAAM,EAAEgB,QAAQ,EAAE,GAAGD,kBAAkBH,MAAM,CAACK,MAAM,CAACC,QAAQ,CAACC,GAAG;IACjE,IAAIH,YAAY,CAACL,SAAS;QACxB,MAAM,IAAID,MAAM,CAAC,cAAc,EAAEM,SAAS,EAAE,CAAC;IAC/C;IAEA,IAAI;QACFpB,2BAA2BM,YAAYU,MAAM;IAC/C,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMM,uBAAuBlB;IAE7BR,wBAAwB;QACtBM,UAAUe;QACVb,aAAakB;QACbhB;QACAO;IACF;IAEA,IAAIA,SAAS;QACX,IAAI;YACFlB,iBAAiBkB;QACnB,EAAE,OAAOE,OAAO;YACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLd,UAAUe;QACVb,aAAakB;QACbhB;QACAO;IACF;AACF"}
package/dist/esm/path.js DELETED
@@ -1,17 +0,0 @@
1
- import { assert } from '@metamask/utils';
2
- /**
3
- * Normalizes relative paths by optionally removing `./` prefix.
4
- *
5
- * @param path - Path to make normalize.
6
- * @returns The same path, with `./` prefix remove.
7
- */ // TODO(ritave): Include NodeJS path polyfill and use path.normalize as well
8
- export function normalizeRelative(path) {
9
- assert(!path.startsWith('/'));
10
- assert(path.search(/:|\/\//u) === -1, `Path "${path}" potentially an URI instead of local relative`);
11
- if (path.startsWith('./')) {
12
- return path.slice(2);
13
- }
14
- return path;
15
- }
16
-
17
- //# sourceMappingURL=path.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/path.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\n/**\n * Normalizes relative paths by optionally removing `./` prefix.\n *\n * @param path - Path to make normalize.\n * @returns The same path, with `./` prefix remove.\n */\n// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well\nexport function normalizeRelative(path: string): string {\n assert(!path.startsWith('/'));\n assert(\n path.search(/:|\\/\\//u) === -1,\n `Path \"${path}\" potentially an URI instead of local relative`,\n );\n\n if (path.startsWith('./')) {\n return path.slice(2);\n }\n return path;\n}\n"],"names":["assert","normalizeRelative","path","startsWith","search","slice"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC;;;;;CAKC,GACD,4EAA4E;AAC5E,OAAO,SAASC,kBAAkBC,IAAY;IAC5CF,OAAO,CAACE,KAAKC,UAAU,CAAC;IACxBH,OACEE,KAAKE,MAAM,CAAC,eAAe,CAAC,GAC5B,CAAC,MAAM,EAAEF,KAAK,8CAA8C,CAAC;IAG/D,IAAIA,KAAKC,UAAU,CAAC,OAAO;QACzB,OAAOD,KAAKG,KAAK,CAAC;IACpB;IACA,OAAOH;AACT"}