@metamask/snaps-utils 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/CHANGELOG.md +33 -223
  2. package/dist/cjs/array.js +23 -0
  3. package/dist/cjs/array.js.map +1 -0
  4. package/dist/cjs/caveats.js +36 -0
  5. package/dist/cjs/caveats.js.map +1 -0
  6. package/dist/cjs/checksum.js +38 -0
  7. package/dist/cjs/checksum.js.map +1 -0
  8. package/dist/cjs/cronjob.js +84 -0
  9. package/dist/cjs/cronjob.js.map +1 -0
  10. package/dist/cjs/deep-clone.js +22 -0
  11. package/dist/cjs/deep-clone.js.map +1 -0
  12. package/dist/cjs/default-endowments.js +49 -0
  13. package/dist/cjs/default-endowments.js.map +1 -0
  14. package/dist/cjs/entropy.js +23 -0
  15. package/dist/cjs/entropy.js.map +1 -0
  16. package/dist/cjs/enum.js +16 -0
  17. package/dist/cjs/enum.js.map +1 -0
  18. package/dist/cjs/errors.js +19 -0
  19. package/dist/cjs/errors.js.map +1 -0
  20. package/dist/{eval-worker.js → cjs/eval-worker.js} +22 -21
  21. package/dist/cjs/eval-worker.js.map +1 -0
  22. package/dist/cjs/eval.js +77 -0
  23. package/dist/cjs/eval.js.map +1 -0
  24. package/dist/cjs/fs.js +126 -0
  25. package/dist/cjs/fs.js.map +1 -0
  26. package/dist/cjs/handlers.js +80 -0
  27. package/dist/cjs/handlers.js.map +1 -0
  28. package/dist/cjs/icon.js +37 -0
  29. package/dist/cjs/icon.js.map +1 -0
  30. package/dist/cjs/iframe.js +59 -0
  31. package/dist/cjs/iframe.js.map +1 -0
  32. package/dist/cjs/index.browser.js +43 -0
  33. package/dist/cjs/index.browser.js.map +1 -0
  34. package/dist/cjs/index.executionenv.js +24 -0
  35. package/dist/cjs/index.executionenv.js.map +1 -0
  36. package/dist/cjs/index.js +48 -0
  37. package/dist/cjs/index.js.map +1 -0
  38. package/dist/cjs/json-rpc.js +46 -0
  39. package/dist/cjs/json-rpc.js.map +1 -0
  40. package/dist/cjs/json.js +16 -0
  41. package/dist/cjs/json.js.map +1 -0
  42. package/dist/cjs/logging.js +40 -0
  43. package/dist/cjs/logging.js.map +1 -0
  44. package/dist/cjs/manifest/index.browser.js +20 -0
  45. package/dist/cjs/manifest/index.browser.js.map +1 -0
  46. package/dist/cjs/manifest/index.js +21 -0
  47. package/dist/cjs/manifest/index.js.map +1 -0
  48. package/dist/cjs/manifest/manifest.js +239 -0
  49. package/dist/cjs/manifest/manifest.js.map +1 -0
  50. package/dist/cjs/manifest/validation.js +189 -0
  51. package/dist/cjs/manifest/validation.js.map +1 -0
  52. package/dist/cjs/mock.js +128 -0
  53. package/dist/cjs/mock.js.map +1 -0
  54. package/dist/cjs/namespace.js +132 -0
  55. package/dist/cjs/namespace.js.map +1 -0
  56. package/dist/cjs/npm.js +81 -0
  57. package/dist/cjs/npm.js.map +1 -0
  58. package/dist/cjs/path.js +21 -0
  59. package/dist/cjs/path.js.map +1 -0
  60. package/dist/cjs/post-process.js +328 -0
  61. package/dist/cjs/post-process.js.map +1 -0
  62. package/dist/cjs/snaps.js +230 -0
  63. package/dist/cjs/snaps.js.map +1 -0
  64. package/dist/cjs/strings.js +21 -0
  65. package/dist/cjs/strings.js.map +1 -0
  66. package/dist/cjs/structs.js +163 -0
  67. package/dist/cjs/structs.js.map +1 -0
  68. package/dist/cjs/types.js +109 -0
  69. package/dist/cjs/types.js.map +1 -0
  70. package/dist/cjs/validation.js +22 -0
  71. package/dist/cjs/validation.js.map +1 -0
  72. package/dist/cjs/versions.js +47 -0
  73. package/dist/cjs/versions.js.map +1 -0
  74. package/dist/cjs/virtual-file/VirtualFile.js +85 -0
  75. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -0
  76. package/dist/cjs/virtual-file/index.browser.js +20 -0
  77. package/dist/cjs/virtual-file/index.browser.js.map +1 -0
  78. package/dist/cjs/virtual-file/index.js +21 -0
  79. package/dist/cjs/virtual-file/index.js.map +1 -0
  80. package/dist/cjs/virtual-file/toVirtualFile.js +33 -0
  81. package/dist/cjs/virtual-file/toVirtualFile.js.map +1 -0
  82. package/dist/{array.js → esm/array.js} +3 -7
  83. package/dist/esm/array.js.map +1 -0
  84. package/dist/esm/caveats.js +26 -0
  85. package/dist/esm/caveats.js.map +1 -0
  86. package/dist/esm/checksum.js +36 -0
  87. package/dist/esm/checksum.js.map +1 -0
  88. package/dist/esm/cronjob.js +66 -0
  89. package/dist/esm/cronjob.js.map +1 -0
  90. package/dist/esm/deep-clone.js +7 -0
  91. package/dist/esm/deep-clone.js.map +1 -0
  92. package/dist/{default-endowments.js → esm/default-endowments.js} +3 -6
  93. package/dist/esm/default-endowments.js.map +1 -0
  94. package/dist/esm/entropy.js +6 -0
  95. package/dist/esm/entropy.js.map +1 -0
  96. package/dist/esm/enum.js +12 -0
  97. package/dist/esm/enum.js.map +1 -0
  98. package/dist/esm/errors.js +17 -0
  99. package/dist/esm/errors.js.map +1 -0
  100. package/dist/esm/eval-worker.js +47 -0
  101. package/dist/esm/eval-worker.js.map +1 -0
  102. package/dist/esm/eval.js +65 -0
  103. package/dist/esm/eval.js.map +1 -0
  104. package/dist/{fs.js → esm/fs.js} +33 -56
  105. package/dist/esm/fs.js.map +1 -0
  106. package/dist/esm/handlers.js +59 -0
  107. package/dist/esm/handlers.js.map +1 -0
  108. package/dist/esm/icon.js +11 -0
  109. package/dist/esm/icon.js.map +1 -0
  110. package/dist/{iframe.js → esm/iframe.js} +16 -18
  111. package/dist/esm/iframe.js.map +1 -0
  112. package/dist/esm/index.browser.js +26 -0
  113. package/dist/esm/index.browser.js.map +1 -0
  114. package/dist/esm/index.executionenv.js +7 -0
  115. package/dist/esm/index.executionenv.js.map +1 -0
  116. package/dist/esm/index.js +31 -0
  117. package/dist/esm/index.js.map +1 -0
  118. package/dist/esm/json-rpc.js +39 -0
  119. package/dist/esm/json-rpc.js.map +1 -0
  120. package/dist/esm/json.js +17 -0
  121. package/dist/esm/json.js.map +1 -0
  122. package/dist/{logging.js → esm/logging.js} +6 -14
  123. package/dist/esm/logging.js.map +1 -0
  124. package/dist/esm/manifest/index.browser.js +3 -0
  125. package/dist/esm/manifest/index.browser.js.map +1 -0
  126. package/dist/esm/manifest/index.js +4 -0
  127. package/dist/esm/manifest/index.js.map +1 -0
  128. package/dist/{manifest → esm/manifest}/manifest.js +101 -115
  129. package/dist/esm/manifest/manifest.js.map +1 -0
  130. package/dist/esm/manifest/validation.js +155 -0
  131. package/dist/esm/manifest/validation.js.map +1 -0
  132. package/dist/{mock.js → esm/mock.js} +42 -40
  133. package/dist/esm/mock.js.map +1 -0
  134. package/dist/esm/namespace.js +112 -0
  135. package/dist/esm/namespace.js.map +1 -0
  136. package/dist/esm/npm.js +70 -0
  137. package/dist/esm/npm.js.map +1 -0
  138. package/dist/esm/path.js +17 -0
  139. package/dist/esm/path.js.map +1 -0
  140. package/dist/{post-process.js → esm/post-process.js} +110 -99
  141. package/dist/esm/post-process.js.map +1 -0
  142. package/dist/esm/snaps.js +215 -0
  143. package/dist/esm/snaps.js.map +1 -0
  144. package/dist/esm/strings.js +11 -0
  145. package/dist/esm/strings.js.map +1 -0
  146. package/dist/esm/structs.js +230 -0
  147. package/dist/esm/structs.js.map +1 -0
  148. package/dist/esm/types.js +80 -0
  149. package/dist/esm/types.js.map +1 -0
  150. package/dist/esm/validation.js +17 -0
  151. package/dist/esm/validation.js.map +1 -0
  152. package/dist/{versions.js → esm/versions.js} +15 -18
  153. package/dist/esm/versions.js.map +1 -0
  154. package/dist/{virtual-file → esm/virtual-file}/VirtualFile.js +47 -33
  155. package/dist/esm/virtual-file/VirtualFile.js.map +1 -0
  156. package/dist/esm/virtual-file/index.browser.js +3 -0
  157. package/dist/esm/virtual-file/index.browser.js.map +1 -0
  158. package/dist/esm/virtual-file/index.js +4 -0
  159. package/dist/esm/virtual-file/index.js.map +1 -0
  160. package/dist/esm/virtual-file/toVirtualFile.js +26 -0
  161. package/dist/esm/virtual-file/toVirtualFile.js.map +1 -0
  162. package/dist/{caveats.d.ts → types/caveats.d.ts} +5 -5
  163. package/dist/{cronjob.d.ts → types/cronjob.d.ts} +1 -1
  164. package/dist/types/enum.d.ts +30 -0
  165. package/dist/types/errors.d.ts +10 -0
  166. package/dist/{eval.d.ts → types/eval.d.ts} +9 -1
  167. package/dist/{fs.d.ts → types/fs.d.ts} +2 -2
  168. package/dist/types/handlers.d.ts +196 -0
  169. package/dist/types/icon.d.ts +4 -0
  170. package/dist/{iframe.d.ts → types/iframe.d.ts} +3 -2
  171. package/dist/{index.browser.d.ts → types/index.browser.d.ts} +5 -1
  172. package/dist/{index.d.ts → types/index.d.ts} +5 -1
  173. package/dist/{json-rpc.d.ts → types/json-rpc.d.ts} +2 -2
  174. package/dist/types/json.d.ts +13 -0
  175. package/dist/{manifest → types/manifest}/manifest.d.ts +6 -4
  176. package/dist/{manifest → types/manifest}/validation.d.ts +40 -76
  177. package/dist/types/namespace.d.ts +128 -0
  178. package/dist/{npm.d.ts → types/npm.d.ts} +2 -3
  179. package/dist/{snaps.d.ts → types/snaps.d.ts} +17 -9
  180. package/dist/types/strings.d.ts +8 -0
  181. package/dist/types/structs.d.ts +158 -0
  182. package/dist/{types.d.ts → types/types.d.ts} +15 -22
  183. package/dist/types/validation.d.ts +8 -0
  184. package/dist/{versions.d.ts → types/versions.d.ts} +1 -1
  185. package/package.json +66 -46
  186. package/dist/array.js.map +0 -1
  187. package/dist/caveats.js +0 -35
  188. package/dist/caveats.js.map +0 -1
  189. package/dist/checksum.js +0 -42
  190. package/dist/checksum.js.map +0 -1
  191. package/dist/cronjob.js +0 -71
  192. package/dist/cronjob.js.map +0 -1
  193. package/dist/deep-clone.js +0 -9
  194. package/dist/deep-clone.js.map +0 -1
  195. package/dist/default-endowments.js.map +0 -1
  196. package/dist/entropy.js +0 -8
  197. package/dist/entropy.js.map +0 -1
  198. package/dist/eval-worker.js.map +0 -1
  199. package/dist/eval.js +0 -27
  200. package/dist/eval.js.map +0 -1
  201. package/dist/fs.js.map +0 -1
  202. package/dist/handlers.d.ts +0 -105
  203. package/dist/handlers.js +0 -3
  204. package/dist/handlers.js.map +0 -1
  205. package/dist/iframe.js.map +0 -1
  206. package/dist/iframe.test.browser.js +0 -15
  207. package/dist/iframe.test.browser.js.map +0 -1
  208. package/dist/index.browser.js +0 -37
  209. package/dist/index.browser.js.map +0 -1
  210. package/dist/index.executionenv.js +0 -22
  211. package/dist/index.executionenv.js.map +0 -1
  212. package/dist/index.js +0 -42
  213. package/dist/index.js.map +0 -1
  214. package/dist/json-rpc.js +0 -46
  215. package/dist/json-rpc.js.map +0 -1
  216. package/dist/json.d.ts +0 -9
  217. package/dist/json.js +0 -18
  218. package/dist/json.js.map +0 -1
  219. package/dist/logging.js.map +0 -1
  220. package/dist/manifest/index.browser.js +0 -18
  221. package/dist/manifest/index.browser.js.map +0 -1
  222. package/dist/manifest/index.js +0 -19
  223. package/dist/manifest/index.js.map +0 -1
  224. package/dist/manifest/manifest.js.map +0 -1
  225. package/dist/manifest/validation.js +0 -141
  226. package/dist/manifest/validation.js.map +0 -1
  227. package/dist/mock.js.map +0 -1
  228. package/dist/namespace.d.ts +0 -275
  229. package/dist/namespace.js +0 -225
  230. package/dist/namespace.js.map +0 -1
  231. package/dist/notification.d.ts +0 -66
  232. package/dist/notification.js +0 -58
  233. package/dist/notification.js.map +0 -1
  234. package/dist/npm.js +0 -74
  235. package/dist/npm.js.map +0 -1
  236. package/dist/path.js +0 -21
  237. package/dist/path.js.map +0 -1
  238. package/dist/post-process.js.map +0 -1
  239. package/dist/snaps.js +0 -202
  240. package/dist/snaps.js.map +0 -1
  241. package/dist/types.js +0 -103
  242. package/dist/types.js.map +0 -1
  243. package/dist/versions.js.map +0 -1
  244. package/dist/virtual-file/VirtualFile.js.map +0 -1
  245. package/dist/virtual-file/index.browser.js +0 -18
  246. package/dist/virtual-file/index.browser.js.map +0 -1
  247. package/dist/virtual-file/index.js +0 -19
  248. package/dist/virtual-file/index.js.map +0 -1
  249. package/dist/virtual-file/toVirtualFile.js +0 -30
  250. package/dist/virtual-file/toVirtualFile.js.map +0 -1
  251. /package/dist/{array.d.ts → types/array.d.ts} +0 -0
  252. /package/dist/{checksum.d.ts → types/checksum.d.ts} +0 -0
  253. /package/dist/{deep-clone.d.ts → types/deep-clone.d.ts} +0 -0
  254. /package/dist/{default-endowments.d.ts → types/default-endowments.d.ts} +0 -0
  255. /package/dist/{entropy.d.ts → types/entropy.d.ts} +0 -0
  256. /package/dist/{eval-worker.d.ts → types/eval-worker.d.ts} +0 -0
  257. /package/dist/{iframe.test.browser.d.ts → types/iframe.test.browser.d.ts} +0 -0
  258. /package/dist/{index.executionenv.d.ts → types/index.executionenv.d.ts} +0 -0
  259. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  260. /package/dist/{manifest → types/manifest}/index.browser.d.ts +0 -0
  261. /package/dist/{manifest → types/manifest}/index.d.ts +0 -0
  262. /package/dist/{mock.d.ts → types/mock.d.ts} +0 -0
  263. /package/dist/{path.d.ts → types/path.d.ts} +0 -0
  264. /package/dist/{post-process.d.ts → types/post-process.d.ts} +0 -0
  265. /package/dist/{virtual-file → types/virtual-file}/VirtualFile.d.ts +0 -0
  266. /package/dist/{virtual-file → types/virtual-file}/index.browser.d.ts +0 -0
  267. /package/dist/{virtual-file → types/virtual-file}/index.d.ts +0 -0
  268. /package/dist/{virtual-file → types/virtual-file}/toVirtualFile.d.ts +0 -0
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ _export_star(require("./array"), exports);
6
+ _export_star(require("./caveats"), exports);
7
+ _export_star(require("./cronjob"), exports);
8
+ _export_star(require("./checksum"), exports);
9
+ _export_star(require("./deep-clone"), exports);
10
+ _export_star(require("./default-endowments"), exports);
11
+ _export_star(require("./entropy"), exports);
12
+ _export_star(require("./enum"), exports);
13
+ _export_star(require("./eval"), exports);
14
+ _export_star(require("./errors"), exports);
15
+ _export_star(require("./fs"), exports);
16
+ _export_star(require("./handlers"), exports);
17
+ _export_star(require("./iframe"), exports);
18
+ _export_star(require("./json"), exports);
19
+ _export_star(require("./json-rpc"), exports);
20
+ _export_star(require("./logging"), exports);
21
+ _export_star(require("./manifest"), exports);
22
+ _export_star(require("./mock"), exports);
23
+ _export_star(require("./namespace"), exports);
24
+ _export_star(require("./npm"), exports);
25
+ _export_star(require("./path"), exports);
26
+ _export_star(require("./post-process"), exports);
27
+ _export_star(require("./snaps"), exports);
28
+ _export_star(require("./strings"), exports);
29
+ _export_star(require("./structs"), exports);
30
+ _export_star(require("./types"), exports);
31
+ _export_star(require("./validation"), exports);
32
+ _export_star(require("./versions"), exports);
33
+ _export_star(require("./virtual-file"), exports);
34
+ function _export_star(from, to) {
35
+ Object.keys(from).forEach(function(k) {
36
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
37
+ Object.defineProperty(to, k, {
38
+ enumerable: true,
39
+ get: function() {
40
+ return from[k];
41
+ }
42
+ });
43
+ }
44
+ });
45
+ return from;
46
+ }
47
+
48
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ RpcOriginsStruct: function() {
13
+ return RpcOriginsStruct;
14
+ },
15
+ assertIsRpcOrigins: function() {
16
+ return assertIsRpcOrigins;
17
+ },
18
+ assertIsJsonRpcSuccess: function() {
19
+ return assertIsJsonRpcSuccess;
20
+ }
21
+ });
22
+ const _utils = require("@metamask/utils");
23
+ const _superstruct = require("superstruct");
24
+ const RpcOriginsStruct = (0, _superstruct.refine)((0, _superstruct.object)({
25
+ dapps: (0, _superstruct.optional)((0, _superstruct.boolean)()),
26
+ snaps: (0, _superstruct.optional)((0, _superstruct.boolean)())
27
+ }), 'RPC origins', (value)=>{
28
+ if (!Object.values(value).some(Boolean)) {
29
+ throw new Error('Must specify at least one JSON-RPC origin');
30
+ }
31
+ return true;
32
+ });
33
+ function assertIsRpcOrigins(value, // eslint-disable-next-line @typescript-eslint/naming-convention
34
+ ErrorWrapper) {
35
+ (0, _utils.assertStruct)(value, RpcOriginsStruct, 'Invalid JSON-RPC origins', ErrorWrapper);
36
+ }
37
+ function assertIsJsonRpcSuccess(value) {
38
+ if (!(0, _utils.isJsonRpcSuccess)(value)) {
39
+ if ((0, _utils.isJsonRpcFailure)(value)) {
40
+ throw new Error(`JSON-RPC request failed: ${value.error.message}`);
41
+ }
42
+ throw new Error('Invalid JSON-RPC response.');
43
+ }
44
+ }
45
+
46
+ //# sourceMappingURL=json-rpc.js.map
@@ -0,0 +1 @@
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":["RpcOriginsStruct","assertIsRpcOrigins","assertIsJsonRpcSuccess","refine","object","dapps","optional","boolean","snaps","value","Object","values","some","Boolean","Error","ErrorWrapper","assertStruct","isJsonRpcSuccess","isJsonRpcFailure","error","message"],"mappings":";;;;;;;;;;;IAaaA,gBAAgB;eAAhBA;;IAyBGC,kBAAkB;eAAlBA;;IAqBAC,sBAAsB;eAAtBA;;;uBAlDT;6BAE2C;AAE3C,MAAMF,mBAAmBG,IAAAA,mBAAM,EACpCC,IAAAA,mBAAM,EAAC;IACLC,OAAOC,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO;IACvBC,OAAOF,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO;AACzB,IACA,eACA,CAACE;IACC,IAAI,CAACC,OAAOC,MAAM,CAACF,OAAOG,IAAI,CAACC,UAAU;QACvC,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;AACT;AAaK,SAASb,mBACdQ,KAAc,EACd,gEAAgE;AAChEM,YAAwC;IAExCC,IAAAA,mBAAY,EACVP,OACAT,kBACA,4BACAe;AAEJ;AAUO,SAASb,uBACdO,KAAc;IAEd,IAAI,CAACQ,IAAAA,uBAAgB,EAACR,QAAQ;QAC5B,IAAIS,IAAAA,uBAAgB,EAACT,QAAQ;YAC3B,MAAM,IAAIK,MAAM,CAAC,yBAAyB,EAAEL,MAAMU,KAAK,CAACC,OAAO,CAAC,CAAC;QACnE;QAEA,MAAM,IAAIN,MAAM;IAClB;AACF"}
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "parseJson", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return parseJson;
9
+ }
10
+ });
11
+ const _utils = require("@metamask/utils");
12
+ function parseJson(json) {
13
+ return (0, _utils.getSafeJson)(JSON.parse(json));
14
+ }
15
+
16
+ //# sourceMappingURL=json.js.map
@@ -0,0 +1 @@
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":["parseJson","json","getSafeJson","JSON","parse"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;uBAfY;AAerB,SAASA,UAAoCC,IAAY;IAC9D,OAAOC,IAAAA,kBAAW,EAAOC,KAAKC,KAAK,CAACH;AACtC"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ snapsLogger: function() {
13
+ return snapsLogger;
14
+ },
15
+ logInfo: function() {
16
+ return logInfo;
17
+ },
18
+ logError: function() {
19
+ return logError;
20
+ },
21
+ logWarning: function() {
22
+ return logWarning;
23
+ }
24
+ });
25
+ const _utils = require("@metamask/utils");
26
+ const snapsLogger = (0, _utils.createProjectLogger)('snaps');
27
+ function logInfo(message, ...optionalParams) {
28
+ // eslint-disable-next-line no-console
29
+ console.log(message, ...optionalParams);
30
+ }
31
+ function logError(error, ...optionalParams) {
32
+ // eslint-disable-next-line no-console
33
+ console.error(error, ...optionalParams);
34
+ }
35
+ function logWarning(message, ...optionalParams) {
36
+ // eslint-disable-next-line no-console
37
+ console.warn(message, ...optionalParams);
38
+ }
39
+
40
+ //# sourceMappingURL=logging.js.map
@@ -0,0 +1 @@
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":["snapsLogger","logInfo","logError","logWarning","createProjectLogger","message","optionalParams","console","log","error","warn"],"mappings":";;;;;;;;;;;IAIaA,WAAW;eAAXA;;IAcGC,OAAO;eAAPA;;IAqBAC,QAAQ;eAARA;;IAqBAC,UAAU;eAAVA;;;uBA5DoB;AAI7B,MAAMH,cAAcI,IAAAA,0BAAmB,EAAC;AAcxC,SAASH,QAAQI,OAAe,EAAE,GAAGC,cAAyB;IACnE,sCAAsC;IACtCC,QAAQC,GAAG,CAACH,YAAYC;AAC1B;AAkBO,SAASJ,SAASO,KAAc,EAAE,GAAGH,cAAyB;IACnE,sCAAsC;IACtCC,QAAQE,KAAK,CAACA,UAAUH;AAC1B;AAkBO,SAASH,WACdE,OAAe,EACf,GAAGC,cAAyB;IAE5B,sCAAsC;IACtCC,QAAQG,IAAI,CAACL,YAAYC;AAC3B"}
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ _export_star(require("./validation"), exports);
6
+ function _export_star(from, to) {
7
+ Object.keys(from).forEach(function(k) {
8
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
9
+ Object.defineProperty(to, k, {
10
+ enumerable: true,
11
+ get: function() {
12
+ return from[k];
13
+ }
14
+ });
15
+ }
16
+ });
17
+ return from;
18
+ }
19
+
20
+ //# sourceMappingURL=index.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/manifest/index.browser.ts"],"sourcesContent":["export * from './validation';\n"],"names":[],"mappings":";;;;qBAAc"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ _export_star(require("./manifest"), exports);
6
+ _export_star(require("./validation"), exports);
7
+ function _export_star(from, to) {
8
+ Object.keys(from).forEach(function(k) {
9
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
10
+ Object.defineProperty(to, k, {
11
+ enumerable: true,
12
+ get: function() {
13
+ return from[k];
14
+ }
15
+ });
16
+ }
17
+ });
18
+ return from;
19
+ }
20
+
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/manifest/index.ts"],"sourcesContent":["export * from './manifest';\nexport * from './validation';\n"],"names":[],"mappings":";;;;qBAAc;qBACA"}
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ checkManifest: function() {
13
+ return checkManifest;
14
+ },
15
+ fixManifest: function() {
16
+ return fixManifest;
17
+ },
18
+ getSnapSourceCode: function() {
19
+ return getSnapSourceCode;
20
+ },
21
+ getSnapIcon: function() {
22
+ return getSnapIcon;
23
+ },
24
+ getWritableManifest: function() {
25
+ return getWritableManifest;
26
+ },
27
+ validateNpmSnapManifest: function() {
28
+ return validateNpmSnapManifest;
29
+ }
30
+ });
31
+ const _utils = require("@metamask/utils");
32
+ const _fastdeepequal = /*#__PURE__*/ _interop_require_default(require("fast-deep-equal"));
33
+ const _fs = require("fs");
34
+ const _path = /*#__PURE__*/ _interop_require_default(require("path"));
35
+ const _deepclone = require("../deep-clone");
36
+ const _fs1 = require("../fs");
37
+ const _npm = require("../npm");
38
+ const _snaps = require("../snaps");
39
+ const _types = require("../types");
40
+ const _virtualfile = require("../virtual-file");
41
+ function _interop_require_default(obj) {
42
+ return obj && obj.__esModule ? obj : {
43
+ default: obj
44
+ };
45
+ }
46
+ const MANIFEST_SORT_ORDER = {
47
+ $schema: 1,
48
+ version: 2,
49
+ description: 3,
50
+ proposedName: 4,
51
+ repository: 5,
52
+ source: 6,
53
+ initialPermissions: 7,
54
+ manifestVersion: 8
55
+ };
56
+ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFileFn = _fs.promises.writeFile) {
57
+ const warnings = [];
58
+ const errors = [];
59
+ let updated = false;
60
+ const manifestPath = _path.default.join(basePath, _types.NpmSnapFileNames.Manifest);
61
+ const manifestFile = await (0, _fs1.readJsonFile)(manifestPath);
62
+ const unvalidatedManifest = manifestFile.result;
63
+ const packageFile = await (0, _fs1.readJsonFile)(_path.default.join(basePath, _types.NpmSnapFileNames.PackageJson));
64
+ const snapFiles = {
65
+ manifest: manifestFile,
66
+ packageJson: packageFile,
67
+ sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
68
+ svgIcon: await getSnapIcon(basePath, unvalidatedManifest)
69
+ };
70
+ let manifest;
71
+ try {
72
+ ({ manifest } = (0, _npm.validateNpmSnap)(snapFiles));
73
+ } catch (error) {
74
+ if (error instanceof _snaps.ProgrammaticallyFixableSnapError) {
75
+ errors.push(error.message);
76
+ // If we get here, the files at least have the correct shape.
77
+ const partiallyValidatedFiles = snapFiles;
78
+ let isInvalid = true;
79
+ let currentError = error;
80
+ const maxAttempts = Object.keys(_types.SnapValidationFailureReason).length;
81
+ // Attempt to fix all fixable validation failure reasons. All such reasons
82
+ // are enumerated by the `SnapValidationFailureReason` enum, so we only
83
+ // attempt to fix the manifest the same amount of times as there are
84
+ // reasons in the enum.
85
+ for(let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++){
86
+ manifest = fixManifest(manifest ? {
87
+ ...partiallyValidatedFiles,
88
+ manifest
89
+ } : partiallyValidatedFiles, currentError);
90
+ try {
91
+ validateNpmSnapManifest({
92
+ ...partiallyValidatedFiles,
93
+ manifest
94
+ });
95
+ isInvalid = false;
96
+ } catch (nextValidationError) {
97
+ currentError = nextValidationError;
98
+ /* istanbul ignore next: this should be impossible */ if (!(nextValidationError instanceof _snaps.ProgrammaticallyFixableSnapError) || attempts === maxAttempts && !isInvalid) {
99
+ throw new Error(`Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\n${error.message}`);
100
+ }
101
+ errors.push(currentError.message);
102
+ }
103
+ }
104
+ updated = true;
105
+ } else {
106
+ throw error;
107
+ }
108
+ }
109
+ // TypeScript assumes `manifest` can still be undefined, that is not the case.
110
+ // But we assert to keep TypeScript happy.
111
+ (0, _utils.assert)(manifest);
112
+ const validatedManifest = manifest.result;
113
+ // Check presence of recommended keys
114
+ const recommendedFields = [
115
+ 'repository'
116
+ ];
117
+ const missingRecommendedFields = recommendedFields.filter((key)=>!validatedManifest[key]);
118
+ if (missingRecommendedFields.length > 0) {
119
+ warnings.push(`Missing recommended package.json properties:\n${missingRecommendedFields.reduce((allMissing, currentField)=>{
120
+ return `${allMissing}\t${currentField}\n`;
121
+ }, '')}`);
122
+ }
123
+ if (writeManifest) {
124
+ try {
125
+ const newManifest = `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\n`;
126
+ if (updated || newManifest !== manifestFile.value) {
127
+ await writeFileFn(_path.default.join(basePath, _types.NpmSnapFileNames.Manifest), newManifest);
128
+ }
129
+ } catch (error) {
130
+ // Note: This error isn't pushed to the errors array, because it's not an
131
+ // error in the manifest itself.
132
+ throw new Error(`Failed to update snap.manifest.json: ${error.message}`);
133
+ }
134
+ }
135
+ return {
136
+ manifest: validatedManifest,
137
+ updated,
138
+ warnings,
139
+ errors
140
+ };
141
+ }
142
+ function fixManifest(snapFiles, error) {
143
+ const { manifest, packageJson } = snapFiles;
144
+ const clonedFile = manifest.clone();
145
+ const manifestCopy = clonedFile.result;
146
+ switch(error.reason){
147
+ case _types.SnapValidationFailureReason.NameMismatch:
148
+ manifestCopy.source.location.npm.packageName = packageJson.result.name;
149
+ break;
150
+ case _types.SnapValidationFailureReason.VersionMismatch:
151
+ manifestCopy.version = packageJson.result.version;
152
+ break;
153
+ case _types.SnapValidationFailureReason.RepositoryMismatch:
154
+ manifestCopy.repository = packageJson.result.repository ? (0, _deepclone.deepClone)(packageJson.result.repository) : undefined;
155
+ break;
156
+ case _types.SnapValidationFailureReason.ShasumMismatch:
157
+ manifestCopy.source.shasum = (0, _snaps.getSnapChecksum)(snapFiles);
158
+ break;
159
+ /* istanbul ignore next */ default:
160
+ (0, _utils.assertExhaustive)(error.reason);
161
+ }
162
+ clonedFile.result = manifestCopy;
163
+ clonedFile.value = JSON.stringify(manifestCopy);
164
+ return clonedFile;
165
+ }
166
+ async function getSnapSourceCode(basePath, manifest, sourceCode) {
167
+ if (!(0, _utils.isPlainObject)(manifest)) {
168
+ return undefined;
169
+ }
170
+ const sourceFilePath = manifest.source?.location?.npm?.filePath;
171
+ if (!sourceFilePath) {
172
+ return undefined;
173
+ }
174
+ if (sourceCode) {
175
+ return new _virtualfile.VirtualFile({
176
+ path: _path.default.join(basePath, sourceFilePath),
177
+ value: sourceCode
178
+ });
179
+ }
180
+ try {
181
+ const virtualFile = await (0, _virtualfile.readVirtualFile)(_path.default.join(basePath, sourceFilePath), 'utf8');
182
+ return virtualFile;
183
+ } catch (error) {
184
+ throw new Error(`Failed to read snap bundle file: ${error.message}`);
185
+ }
186
+ }
187
+ async function getSnapIcon(basePath, manifest) {
188
+ if (!(0, _utils.isPlainObject)(manifest)) {
189
+ return undefined;
190
+ }
191
+ const iconPath = manifest.source?.location?.npm?.iconPath;
192
+ if (!iconPath) {
193
+ return undefined;
194
+ }
195
+ try {
196
+ const virtualFile = await (0, _virtualfile.readVirtualFile)(_path.default.join(basePath, iconPath), 'utf8');
197
+ return virtualFile;
198
+ } catch (error) {
199
+ throw new Error(`Failed to read snap icon file: ${error.message}`);
200
+ }
201
+ }
202
+ function getWritableManifest(manifest) {
203
+ const { repository, ...remaining } = manifest;
204
+ const keys = Object.keys(repository ? {
205
+ ...remaining,
206
+ repository
207
+ } : remaining);
208
+ const writableManifest = keys.sort((a, b)=>MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b]).reduce((result, key)=>({
209
+ ...result,
210
+ [key]: manifest[key]
211
+ }), {});
212
+ return writableManifest;
213
+ }
214
+ function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon }) {
215
+ const packageJsonName = packageJson.result.name;
216
+ const packageJsonVersion = packageJson.result.version;
217
+ const packageJsonRepository = packageJson.result.repository;
218
+ const manifestPackageName = manifest.result.source.location.npm.packageName;
219
+ const manifestPackageVersion = manifest.result.version;
220
+ const manifestRepository = manifest.result.repository;
221
+ if (packageJsonName !== manifestPackageName) {
222
+ throw new _snaps.ProgrammaticallyFixableSnapError(`"${_types.NpmSnapFileNames.Manifest}" npm package name ("${manifestPackageName}") does not match the "${_types.NpmSnapFileNames.PackageJson}" "name" field ("${packageJsonName}").`, _types.SnapValidationFailureReason.NameMismatch);
223
+ }
224
+ if (packageJsonVersion !== manifestPackageVersion) {
225
+ throw new _snaps.ProgrammaticallyFixableSnapError(`"${_types.NpmSnapFileNames.Manifest}" npm package version ("${manifestPackageVersion}") does not match the "${_types.NpmSnapFileNames.PackageJson}" "version" field ("${packageJsonVersion}").`, _types.SnapValidationFailureReason.VersionMismatch);
226
+ }
227
+ if (// The repository may be `undefined` in package.json but can only be defined
228
+ // or `null` in the Snap manifest due to TS@<4.4 issues.
229
+ (packageJsonRepository || manifestRepository) && !(0, _fastdeepequal.default)(packageJsonRepository, manifestRepository)) {
230
+ throw new _snaps.ProgrammaticallyFixableSnapError(`"${_types.NpmSnapFileNames.Manifest}" "repository" field does not match the "${_types.NpmSnapFileNames.PackageJson}" "repository" field.`, _types.SnapValidationFailureReason.RepositoryMismatch);
231
+ }
232
+ (0, _snaps.validateSnapShasum)({
233
+ manifest,
234
+ sourceCode,
235
+ svgIcon
236
+ }, `"${_types.NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
237
+ }
238
+
239
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
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":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","svgIcon","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAiEsBA,aAAa;eAAbA;;IA6INC,WAAW;eAAXA;;IA8CMC,iBAAiB;eAAjBA;;IA0CAC,WAAW;eAAXA;;IAiCNC,mBAAmB;eAAnBA;;IA8BAC,uBAAuB;eAAvBA;;;uBApWwC;sEAClC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAqCO,eAAed,cACpBe,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCC,YAAE,CAACC,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAeC,aAAS,CAACC,IAAI,CAACX,UAAUY,uBAAgB,CAACC,QAAQ;IACvE,MAAMC,eAAe,MAAMC,IAAAA,iBAAY,EAACN;IACxC,MAAMO,sBAAsBF,aAAaG,MAAM;IAE/C,MAAMC,cAAc,MAAMH,IAAAA,iBAAY,EACpCL,aAAS,CAACC,IAAI,CAACX,UAAUY,uBAAgB,CAACO,WAAW;I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