@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
@@ -1,27 +1,22 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.validateNpmSnapManifest = exports.getWritableManifest = exports.getSnapIcon = exports.getSnapSourceCode = exports.fixManifest = exports.checkManifest = void 0;
7
- const utils_1 = require("@metamask/utils");
8
- const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
9
- const fs_1 = require("fs");
10
- const path_1 = __importDefault(require("path"));
11
- const deep_clone_1 = require("../deep-clone");
12
- const fs_2 = require("../fs");
13
- const npm_1 = require("../npm");
14
- const snaps_1 = require("../snaps");
15
- const types_1 = require("../types");
16
- const virtual_file_1 = require("../virtual-file");
1
+ import { assertExhaustive, assert, isPlainObject } from '@metamask/utils';
2
+ import deepEqual from 'fast-deep-equal';
3
+ import { promises as fs } from 'fs';
4
+ import pathUtils from 'path';
5
+ import { deepClone } from '../deep-clone';
6
+ import { readJsonFile } from '../fs';
7
+ import { validateNpmSnap } from '../npm';
8
+ import { getSnapChecksum, ProgrammaticallyFixableSnapError, validateSnapShasum } from '../snaps';
9
+ import { NpmSnapFileNames, SnapValidationFailureReason } from '../types';
10
+ import { readVirtualFile, VirtualFile } from '../virtual-file';
17
11
  const MANIFEST_SORT_ORDER = {
18
- version: 1,
19
- description: 2,
20
- proposedName: 3,
21
- repository: 4,
22
- source: 5,
23
- initialPermissions: 6,
24
- manifestVersion: 7,
12
+ $schema: 1,
13
+ version: 2,
14
+ description: 3,
15
+ proposedName: 4,
16
+ repository: 5,
17
+ source: 6,
18
+ initialPermissions: 7,
19
+ manifestVersion: 8
25
20
  };
26
21
  /**
27
22
  * Validates a snap.manifest.json file. Attempts to fix the manifest and write
@@ -31,72 +26,73 @@ const MANIFEST_SORT_ORDER = {
31
26
  * @param basePath - The path to the folder with the manifest files.
32
27
  * @param writeManifest - Whether to write the fixed manifest to disk.
33
28
  * @param sourceCode - The source code of the Snap.
29
+ * @param writeFileFn - The function to use to write the manifest to disk.
34
30
  * @returns Whether the manifest was updated, and an array of warnings that
35
31
  * were encountered during processing of the manifest files.
36
- */
37
- async function checkManifest(basePath, writeManifest = true, sourceCode) {
32
+ */ export async function checkManifest(basePath, writeManifest = true, sourceCode, writeFileFn = fs.writeFile) {
38
33
  const warnings = [];
39
34
  const errors = [];
40
35
  let updated = false;
41
- const manifestPath = path_1.default.join(basePath, types_1.NpmSnapFileNames.Manifest);
42
- const manifestFile = await (0, fs_2.readJsonFile)(manifestPath);
36
+ const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);
37
+ const manifestFile = await readJsonFile(manifestPath);
43
38
  const unvalidatedManifest = manifestFile.result;
44
- const packageFile = await (0, fs_2.readJsonFile)(path_1.default.join(basePath, types_1.NpmSnapFileNames.PackageJson));
39
+ const packageFile = await readJsonFile(pathUtils.join(basePath, NpmSnapFileNames.PackageJson));
45
40
  const snapFiles = {
46
41
  manifest: manifestFile,
47
42
  packageJson: packageFile,
48
43
  sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
49
- svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
44
+ svgIcon: await getSnapIcon(basePath, unvalidatedManifest)
50
45
  };
51
46
  let manifest;
52
47
  try {
53
- ({ manifest } = (0, npm_1.validateNpmSnap)(snapFiles));
54
- }
55
- catch (error) {
56
- if (error instanceof snaps_1.ProgrammaticallyFixableSnapError) {
48
+ ({ manifest } = validateNpmSnap(snapFiles));
49
+ } catch (error) {
50
+ if (error instanceof ProgrammaticallyFixableSnapError) {
57
51
  errors.push(error.message);
58
52
  // If we get here, the files at least have the correct shape.
59
53
  const partiallyValidatedFiles = snapFiles;
60
54
  let isInvalid = true;
61
55
  let currentError = error;
62
- const maxAttempts = Object.keys(types_1.SnapValidationFailureReason).length;
56
+ const maxAttempts = Object.keys(SnapValidationFailureReason).length;
63
57
  // Attempt to fix all fixable validation failure reasons. All such reasons
64
58
  // are enumerated by the `SnapValidationFailureReason` enum, so we only
65
59
  // attempt to fix the manifest the same amount of times as there are
66
60
  // reasons in the enum.
67
- for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {
68
- manifest = fixManifest(manifest
69
- ? { ...partiallyValidatedFiles, manifest }
70
- : partiallyValidatedFiles, currentError);
61
+ for(let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++){
62
+ manifest = fixManifest(manifest ? {
63
+ ...partiallyValidatedFiles,
64
+ manifest
65
+ } : partiallyValidatedFiles, currentError);
71
66
  try {
72
- validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });
67
+ validateNpmSnapManifest({
68
+ ...partiallyValidatedFiles,
69
+ manifest
70
+ });
73
71
  isInvalid = false;
74
- }
75
- catch (nextValidationError) {
72
+ } catch (nextValidationError) {
76
73
  currentError = nextValidationError;
77
- /* istanbul ignore next: this should be impossible */
78
- if (!(nextValidationError instanceof snaps_1.ProgrammaticallyFixableSnapError) ||
79
- (attempts === maxAttempts && !isInvalid)) {
74
+ /* istanbul ignore next: this should be impossible */ if (!(nextValidationError instanceof ProgrammaticallyFixableSnapError) || attempts === maxAttempts && !isInvalid) {
80
75
  throw new Error(`Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\n${error.message}`);
81
76
  }
82
77
  errors.push(currentError.message);
83
78
  }
84
79
  }
85
80
  updated = true;
86
- }
87
- else {
81
+ } else {
88
82
  throw error;
89
83
  }
90
84
  }
91
85
  // TypeScript assumes `manifest` can still be undefined, that is not the case.
92
86
  // But we assert to keep TypeScript happy.
93
- (0, utils_1.assert)(manifest);
87
+ assert(manifest);
94
88
  const validatedManifest = manifest.result;
95
89
  // Check presence of recommended keys
96
- const recommendedFields = ['repository'];
97
- const missingRecommendedFields = recommendedFields.filter((key) => !validatedManifest[key]);
90
+ const recommendedFields = [
91
+ 'repository'
92
+ ];
93
+ const missingRecommendedFields = recommendedFields.filter((key)=>!validatedManifest[key]);
98
94
  if (missingRecommendedFields.length > 0) {
99
- warnings.push(`Missing recommended package.json properties:\n${missingRecommendedFields.reduce((allMissing, currentField) => {
95
+ warnings.push(`Missing recommended package.json properties:\n${missingRecommendedFields.reduce((allMissing, currentField)=>{
100
96
  return `${allMissing}\t${currentField}\n`;
101
97
  }, '')}`);
102
98
  }
@@ -104,18 +100,21 @@ async function checkManifest(basePath, writeManifest = true, sourceCode) {
104
100
  try {
105
101
  const newManifest = `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\n`;
106
102
  if (updated || newManifest !== manifestFile.value) {
107
- await fs_1.promises.writeFile(path_1.default.join(basePath, types_1.NpmSnapFileNames.Manifest), newManifest);
103
+ await writeFileFn(pathUtils.join(basePath, NpmSnapFileNames.Manifest), newManifest);
108
104
  }
109
- }
110
- catch (error) {
105
+ } catch (error) {
111
106
  // Note: This error isn't pushed to the errors array, because it's not an
112
107
  // error in the manifest itself.
113
108
  throw new Error(`Failed to update snap.manifest.json: ${error.message}`);
114
109
  }
115
110
  }
116
- return { manifest: validatedManifest, updated, warnings, errors };
111
+ return {
112
+ manifest: validatedManifest,
113
+ updated,
114
+ warnings,
115
+ errors
116
+ };
117
117
  }
118
- exports.checkManifest = checkManifest;
119
118
  /**
120
119
  * Given the relevant Snap files (manifest, `package.json`, and bundle) and a
121
120
  * Snap manifest validation error, fixes the fault in the manifest that caused
@@ -124,35 +123,30 @@ exports.checkManifest = checkManifest;
124
123
  * @param snapFiles - The contents of all Snap files.
125
124
  * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.
126
125
  * @returns A copy of the manifest file where the cause of the error is fixed.
127
- */
128
- function fixManifest(snapFiles, error) {
126
+ */ export function fixManifest(snapFiles, error) {
129
127
  const { manifest, packageJson } = snapFiles;
130
128
  const clonedFile = manifest.clone();
131
129
  const manifestCopy = clonedFile.result;
132
- switch (error.reason) {
133
- case types_1.SnapValidationFailureReason.NameMismatch:
130
+ switch(error.reason){
131
+ case SnapValidationFailureReason.NameMismatch:
134
132
  manifestCopy.source.location.npm.packageName = packageJson.result.name;
135
133
  break;
136
- case types_1.SnapValidationFailureReason.VersionMismatch:
134
+ case SnapValidationFailureReason.VersionMismatch:
137
135
  manifestCopy.version = packageJson.result.version;
138
136
  break;
139
- case types_1.SnapValidationFailureReason.RepositoryMismatch:
140
- manifestCopy.repository = packageJson.result.repository
141
- ? (0, deep_clone_1.deepClone)(packageJson.result.repository)
142
- : undefined;
137
+ case SnapValidationFailureReason.RepositoryMismatch:
138
+ manifestCopy.repository = packageJson.result.repository ? deepClone(packageJson.result.repository) : undefined;
143
139
  break;
144
- case types_1.SnapValidationFailureReason.ShasumMismatch:
145
- manifestCopy.source.shasum = (0, snaps_1.getSnapChecksum)(snapFiles);
140
+ case SnapValidationFailureReason.ShasumMismatch:
141
+ manifestCopy.source.shasum = getSnapChecksum(snapFiles);
146
142
  break;
147
- /* istanbul ignore next */
148
- default:
149
- (0, utils_1.assertExhaustive)(error.reason);
143
+ /* istanbul ignore next */ default:
144
+ assertExhaustive(error.reason);
150
145
  }
151
146
  clonedFile.result = manifestCopy;
152
147
  clonedFile.value = JSON.stringify(manifestCopy);
153
148
  return clonedFile;
154
149
  }
155
- exports.fixManifest = fixManifest;
156
150
  /**
157
151
  * Given an unvalidated Snap manifest, attempts to extract the location of the
158
152
  * bundle source file location and read the file.
@@ -161,31 +155,27 @@ exports.fixManifest = fixManifest;
161
155
  * @param manifest - The unvalidated Snap manifest file contents.
162
156
  * @param sourceCode - Override source code for plugins.
163
157
  * @returns The contents of the bundle file, if any.
164
- */
165
- async function getSnapSourceCode(basePath, manifest, sourceCode) {
166
- if (!(0, utils_1.isPlainObject)(manifest)) {
158
+ */ export async function getSnapSourceCode(basePath, manifest, sourceCode) {
159
+ if (!isPlainObject(manifest)) {
167
160
  return undefined;
168
161
  }
169
- const sourceFilePath = manifest.source?.location
170
- ?.npm?.filePath;
162
+ const sourceFilePath = manifest.source?.location?.npm?.filePath;
171
163
  if (!sourceFilePath) {
172
164
  return undefined;
173
165
  }
174
166
  if (sourceCode) {
175
- return new virtual_file_1.VirtualFile({
176
- path: path_1.default.join(basePath, sourceFilePath),
177
- value: sourceCode,
167
+ return new VirtualFile({
168
+ path: pathUtils.join(basePath, sourceFilePath),
169
+ value: sourceCode
178
170
  });
179
171
  }
180
172
  try {
181
- const virtualFile = await (0, virtual_file_1.readVirtualFile)(path_1.default.join(basePath, sourceFilePath), 'utf8');
173
+ const virtualFile = await readVirtualFile(pathUtils.join(basePath, sourceFilePath), 'utf8');
182
174
  return virtualFile;
183
- }
184
- catch (error) {
185
- throw new Error(`Failed to read Snap bundle file: ${error.message}`);
175
+ } catch (error) {
176
+ throw new Error(`Failed to read snap bundle file: ${error.message}`);
186
177
  }
187
178
  }
188
- exports.getSnapSourceCode = getSnapSourceCode;
189
179
  /**
190
180
  * Given an unvalidated Snap manifest, attempts to extract the location of the
191
181
  * icon and read the file.
@@ -193,44 +183,39 @@ exports.getSnapSourceCode = getSnapSourceCode;
193
183
  * @param basePath - The path to the folder with the manifest files.
194
184
  * @param manifest - The unvalidated Snap manifest file contents.
195
185
  * @returns The contents of the icon, if any.
196
- */
197
- async function getSnapIcon(basePath, manifest) {
198
- if (!(0, utils_1.isPlainObject)(manifest)) {
186
+ */ export async function getSnapIcon(basePath, manifest) {
187
+ if (!isPlainObject(manifest)) {
199
188
  return undefined;
200
189
  }
201
- const iconPath = manifest.source?.location?.npm
202
- ?.iconPath;
190
+ const iconPath = manifest.source?.location?.npm?.iconPath;
203
191
  if (!iconPath) {
204
192
  return undefined;
205
193
  }
206
194
  try {
207
- const virtualFile = await (0, virtual_file_1.readVirtualFile)(path_1.default.join(basePath, iconPath), 'utf8');
195
+ const virtualFile = await readVirtualFile(pathUtils.join(basePath, iconPath), 'utf8');
208
196
  return virtualFile;
209
- }
210
- catch (error) {
211
- throw new Error(`Failed to read Snap icon file: ${error.message}`);
197
+ } catch (error) {
198
+ throw new Error(`Failed to read snap icon file: ${error.message}`);
212
199
  }
213
200
  }
214
- exports.getSnapIcon = getSnapIcon;
215
201
  /**
216
202
  * Sorts the given manifest in our preferred sort order and removes the
217
203
  * `repository` field if it is falsy (it may be `null`).
218
204
  *
219
205
  * @param manifest - The manifest to sort and modify.
220
206
  * @returns The disk-ready manifest.
221
- */
222
- function getWritableManifest(manifest) {
207
+ */ export function getWritableManifest(manifest) {
223
208
  const { repository, ...remaining } = manifest;
224
- const keys = Object.keys(repository ? { ...remaining, repository } : remaining);
225
- const writableManifest = keys
226
- .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])
227
- .reduce((result, key) => ({
228
- ...result,
229
- [key]: manifest[key],
230
- }), {});
209
+ const keys = Object.keys(repository ? {
210
+ ...remaining,
211
+ repository
212
+ } : remaining);
213
+ const writableManifest = keys.sort((a, b)=>MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b]).reduce((result, key)=>({
214
+ ...result,
215
+ [key]: manifest[key]
216
+ }), {});
231
217
  return writableManifest;
232
218
  }
233
- exports.getWritableManifest = getWritableManifest;
234
219
  /**
235
220
  * Validates the fields of an npm Snap manifest that has already passed JSON
236
221
  * Schema validation.
@@ -240,8 +225,7 @@ exports.getWritableManifest = getWritableManifest;
240
225
  * @param snapFiles.packageJson - The npm Snap's `package.json`.
241
226
  * @param snapFiles.sourceCode - The Snap's source code.
242
227
  * @param snapFiles.svgIcon - The Snap's optional icon.
243
- */
244
- function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, }) {
228
+ */ export function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon }) {
245
229
  const packageJsonName = packageJson.result.name;
246
230
  const packageJsonVersion = packageJson.result.version;
247
231
  const packageJsonRepository = packageJson.result.repository;
@@ -249,19 +233,21 @@ function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, }
249
233
  const manifestPackageVersion = manifest.result.version;
250
234
  const manifestRepository = manifest.result.repository;
251
235
  if (packageJsonName !== manifestPackageName) {
252
- throw new snaps_1.ProgrammaticallyFixableSnapError(`"${types_1.NpmSnapFileNames.Manifest}" npm package name ("${manifestPackageName}") does not match the "${types_1.NpmSnapFileNames.PackageJson}" "name" field ("${packageJsonName}").`, types_1.SnapValidationFailureReason.NameMismatch);
236
+ throw new ProgrammaticallyFixableSnapError(`"${NpmSnapFileNames.Manifest}" npm package name ("${manifestPackageName}") does not match the "${NpmSnapFileNames.PackageJson}" "name" field ("${packageJsonName}").`, SnapValidationFailureReason.NameMismatch);
253
237
  }
254
238
  if (packageJsonVersion !== manifestPackageVersion) {
255
- throw new snaps_1.ProgrammaticallyFixableSnapError(`"${types_1.NpmSnapFileNames.Manifest}" npm package version ("${manifestPackageVersion}") does not match the "${types_1.NpmSnapFileNames.PackageJson}" "version" field ("${packageJsonVersion}").`, types_1.SnapValidationFailureReason.VersionMismatch);
239
+ throw new ProgrammaticallyFixableSnapError(`"${NpmSnapFileNames.Manifest}" npm package version ("${manifestPackageVersion}") does not match the "${NpmSnapFileNames.PackageJson}" "version" field ("${packageJsonVersion}").`, SnapValidationFailureReason.VersionMismatch);
256
240
  }
257
- if (
258
- // The repository may be `undefined` in package.json but can only be defined
241
+ if (// The repository may be `undefined` in package.json but can only be defined
259
242
  // or `null` in the Snap manifest due to TS@<4.4 issues.
260
- (packageJsonRepository || manifestRepository) &&
261
- !(0, fast_deep_equal_1.default)(packageJsonRepository, manifestRepository)) {
262
- throw new snaps_1.ProgrammaticallyFixableSnapError(`"${types_1.NpmSnapFileNames.Manifest}" "repository" field does not match the "${types_1.NpmSnapFileNames.PackageJson}" "repository" field.`, types_1.SnapValidationFailureReason.RepositoryMismatch);
263
- }
264
- (0, snaps_1.validateSnapShasum)({ manifest, sourceCode, svgIcon }, `"${types_1.NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
243
+ (packageJsonRepository || manifestRepository) && !deepEqual(packageJsonRepository, manifestRepository)) {
244
+ throw new ProgrammaticallyFixableSnapError(`"${NpmSnapFileNames.Manifest}" "repository" field does not match the "${NpmSnapFileNames.PackageJson}" "repository" field.`, SnapValidationFailureReason.RepositoryMismatch);
245
+ }
246
+ validateSnapShasum({
247
+ manifest,
248
+ sourceCode,
249
+ svgIcon
250
+ }, `"${NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
265
251
  }
266
- exports.validateNpmSnapManifest = validateNpmSnapManifest;
252
+
267
253
  //# 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":["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,QAA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AW,CAAC,qBAAqB,CAAC,EAC5H5B,4BAA4ByE,kBAAkB;IAElD;IAEA3E,mBACE;QAAEgC;QAAUf;QAAYkB;IAAQ,GAChC,CAAC,CAAC,EAAElC,iBAAiBwB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
@@ -0,0 +1,155 @@
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 { ChainIdStruct } from '../namespace';
9
+ import { SnapIdStruct } from '../snaps';
10
+ import { NameStruct, NpmSnapFileNames } from '../types';
11
+ // BIP-43 purposes that cannot be used for entropy derivation. These are in the
12
+ // string form, ending with `'`.
13
+ const FORBIDDEN_PURPOSES = [
14
+ SIP_6_MAGIC_VALUE,
15
+ STATE_ENCRYPTION_MAGIC_VALUE
16
+ ];
17
+ export const FORBIDDEN_COIN_TYPES = [
18
+ 60
19
+ ];
20
+ const FORBIDDEN_PATHS = FORBIDDEN_COIN_TYPES.map((coinType)=>[
21
+ 'm',
22
+ "44'",
23
+ `${coinType}'`
24
+ ]);
25
+ export const Bip32PathStruct = refine(array(string()), 'BIP-32 path', (path)=>{
26
+ if (path.length === 0) {
27
+ return 'Path must be a non-empty BIP-32 derivation path array';
28
+ }
29
+ if (path[0] !== 'm') {
30
+ return 'Path must start with "m".';
31
+ }
32
+ if (path.length < 3) {
33
+ return 'Paths must have a length of at least three.';
34
+ }
35
+ if (path.slice(1).some((part)=>!isValidBIP32PathSegment(part))) {
36
+ return 'Path must be a valid BIP-32 derivation path array.';
37
+ }
38
+ if (FORBIDDEN_PURPOSES.includes(path[1])) {
39
+ return `The purpose "${path[1]}" is not allowed for entropy derivation.`;
40
+ }
41
+ if (FORBIDDEN_PATHS.some((forbiddenPath)=>isEqual(path.slice(0, forbiddenPath.length), forbiddenPath))) {
42
+ return `The path "${path.join('/')}" is not allowed for entropy derivation.`;
43
+ }
44
+ return true;
45
+ });
46
+ export const bip32entropy = (struct)=>refine(struct, 'BIP-32 entropy', (value)=>{
47
+ if (value.curve === 'ed25519' && value.path.slice(1).some((part)=>!part.endsWith("'"))) {
48
+ return 'Ed25519 does not support unhardened paths.';
49
+ }
50
+ return true;
51
+ });
52
+ // Used outside @metamask/snap-utils
53
+ export const Bip32EntropyStruct = bip32entropy(type({
54
+ path: Bip32PathStruct,
55
+ curve: enums([
56
+ 'ed25519',
57
+ 'secp256k1'
58
+ ])
59
+ }));
60
+ export const SnapGetBip32EntropyPermissionsStruct = size(array(Bip32EntropyStruct), 1, Infinity);
61
+ export const SemVerRangeStruct = refine(string(), 'SemVer range', (value)=>{
62
+ if (isValidSemVerRange(value)) {
63
+ return true;
64
+ }
65
+ return 'Expected a valid SemVer range.';
66
+ });
67
+ export const SnapIdsStruct = refine(record(SnapIdStruct, object({
68
+ version: optional(SemVerRangeStruct)
69
+ })), 'SnapIds', (value)=>{
70
+ if (Object.keys(value).length === 0) {
71
+ return false;
72
+ }
73
+ return true;
74
+ });
75
+ export const ChainIdsStruct = array(ChainIdStruct);
76
+ /* eslint-disable @typescript-eslint/naming-convention */ export const PermissionsStruct = type({
77
+ 'endowment:long-running': optional(object({})),
78
+ 'endowment:network-access': optional(object({})),
79
+ 'endowment:webassembly': optional(object({})),
80
+ 'endowment:transaction-insight': optional(object({
81
+ allowTransactionOrigin: optional(boolean())
82
+ })),
83
+ 'endowment:cronjob': optional(object({
84
+ jobs: CronjobSpecificationArrayStruct
85
+ })),
86
+ 'endowment:rpc': optional(RpcOriginsStruct),
87
+ 'endowment:name-lookup': optional(ChainIdsStruct),
88
+ snap_dialog: optional(object({})),
89
+ // TODO: Remove
90
+ snap_confirm: optional(object({})),
91
+ snap_manageState: optional(object({})),
92
+ snap_manageAccounts: optional(object({})),
93
+ snap_notify: optional(object({})),
94
+ snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),
95
+ snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),
96
+ snap_getBip44Entropy: optional(size(array(object({
97
+ coinType: size(integer(), 0, 2 ** 32 - 1)
98
+ })), 1, Infinity)),
99
+ snap_getEntropy: optional(object({})),
100
+ wallet_snap: optional(SnapIdsStruct)
101
+ });
102
+ export const SnapManifestStruct = object({
103
+ version: VersionStruct,
104
+ description: size(string(), 1, 280),
105
+ 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),
106
+ repository: optional(object({
107
+ type: size(string(), 1, Infinity),
108
+ url: size(string(), 1, Infinity)
109
+ })),
110
+ source: object({
111
+ shasum: ChecksumStruct,
112
+ location: object({
113
+ npm: object({
114
+ filePath: size(string(), 1, Infinity),
115
+ iconPath: optional(size(string(), 1, Infinity)),
116
+ packageName: NameStruct,
117
+ registry: union([
118
+ literal('https://registry.npmjs.org'),
119
+ literal('https://registry.npmjs.org/')
120
+ ])
121
+ })
122
+ })
123
+ }),
124
+ initialPermissions: PermissionsStruct,
125
+ manifestVersion: literal('0.1'),
126
+ $schema: optional(string())
127
+ });
128
+ /**
129
+ * Check if the given value is a valid {@link SnapManifest} object.
130
+ *
131
+ * @param value - The value to check.
132
+ * @returns Whether the value is a valid {@link SnapManifest} object.
133
+ */ export function isSnapManifest(value) {
134
+ return is(value, SnapManifestStruct);
135
+ }
136
+ /**
137
+ * Assert that the given value is a valid {@link SnapManifest} object.
138
+ *
139
+ * @param value - The value to check.
140
+ * @throws If the value is not a valid {@link SnapManifest} object.
141
+ */ export function assertIsSnapManifest(value) {
142
+ assertStruct(value, SnapManifestStruct, `"${NpmSnapFileNames.Manifest}" is invalid`);
143
+ }
144
+ /**
145
+ * Creates a {@link SnapManifest} object from JSON.
146
+ *
147
+ * @param value - The value to check.
148
+ * @throws If the value cannot be coerced to a {@link SnapManifest} object.
149
+ * @returns The created {@link SnapManifest} object.
150
+ */ export function createSnapManifest(value) {
151
+ // TODO: Add a utility to prefix these errors similar to assertStruct
152
+ return create(value, SnapManifestStruct);
153
+ }
154
+
155
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
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 { ChainIdStruct } from '../namespace';\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\nexport const ChainIdsStruct = array(ChainIdStruct);\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 'endowment:name-lookup': optional(ChainIdsStruct),\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","ChainIdStruct","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","ChainIdsStruct","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,aAAa,QAAQ,eAAe;AAC7C,SAASC,YAAY,QAAQ,WAAW;AACxC,SAASC,UAAU,EAAEC,gBAAgB,QAAQ,WAAW;AAExD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCP;IACAC;CACD;AAED,OAAO,MAAMO,uBAAiC;IAAC;CAAG,CAAC;AACnD,MAAMC,kBAA8BD,qBAAqBE,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAED,OAAO,MAAMC,kBAAkBpB,OAC7BV,MAAMa,WACN,eACA,CAACkB;IACC,IAAIA,KAAKC,MAAM,KAAK,GAAG;QACrB,OAAO;IACT;IAEA,IAAID,IAAI,CAAC,EAAE,KAAK,KAAK;QACnB,OAAO;IACT;IAEA,IAAIA,KAAKC,MAAM,GAAG,GAAG;QACnB,OAAO;IACT;IAEA,IAAID,KAAKE,KAAK,CAAC,GAAGC,IAAI,CAAC,CAACC,OAAS,CAACxC,wBAAwBwC,QAAQ;QAChE,OAAO;IACT;IAEA,IAAIV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