@metamask/snaps-utils 0.35.1-flask.1 → 1.0.0-prerelease.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/CHANGELOG.md +5 -46
  2. package/dist/{esm/array.js → array.js} +7 -3
  3. package/dist/array.js.map +1 -0
  4. package/dist/{types/caveats.d.ts → caveats.d.ts} +4 -0
  5. package/dist/caveats.js +35 -0
  6. package/dist/caveats.js.map +1 -0
  7. package/dist/checksum.js +42 -0
  8. package/dist/checksum.js.map +1 -0
  9. package/dist/cronjob.js +71 -0
  10. package/dist/cronjob.js.map +1 -0
  11. package/dist/deep-clone.js +9 -0
  12. package/dist/deep-clone.js.map +1 -0
  13. package/dist/{esm/default-endowments.js → default-endowments.js} +6 -3
  14. package/dist/default-endowments.js.map +1 -0
  15. package/dist/entropy.js +8 -0
  16. package/dist/entropy.js.map +1 -0
  17. package/dist/{cjs/eval-worker.js → eval-worker.js} +21 -22
  18. package/dist/eval-worker.js.map +1 -0
  19. package/dist/eval.js +27 -0
  20. package/dist/eval.js.map +1 -0
  21. package/dist/{esm/fs.js → fs.js} +56 -33
  22. package/dist/fs.js.map +1 -0
  23. package/dist/{types/handlers.d.ts → handlers.d.ts} +42 -5
  24. package/dist/handlers.js +3 -0
  25. package/dist/handlers.js.map +1 -0
  26. package/dist/{types/iframe.d.ts → iframe.d.ts} +2 -3
  27. package/dist/{esm/iframe.js → iframe.js} +18 -16
  28. package/dist/iframe.js.map +1 -0
  29. package/dist/iframe.test.browser.js +15 -0
  30. package/dist/iframe.test.browser.js.map +1 -0
  31. package/dist/{types/index.browser.d.ts → index.browser.d.ts} +1 -2
  32. package/dist/index.browser.js +37 -0
  33. package/dist/index.browser.js.map +1 -0
  34. package/dist/{types/index.d.ts → index.d.ts} +1 -2
  35. package/dist/index.executionenv.js +22 -0
  36. package/dist/index.executionenv.js.map +1 -0
  37. package/dist/index.js +42 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/json-rpc.js +46 -0
  40. package/dist/json-rpc.js.map +1 -0
  41. package/dist/json.d.ts +9 -0
  42. package/dist/json.js +18 -0
  43. package/dist/json.js.map +1 -0
  44. package/dist/{esm/logging.js → logging.js} +14 -6
  45. package/dist/logging.js.map +1 -0
  46. package/dist/manifest/index.browser.js +18 -0
  47. package/dist/manifest/index.browser.js.map +1 -0
  48. package/dist/manifest/index.js +19 -0
  49. package/dist/manifest/index.js.map +1 -0
  50. package/dist/{esm/manifest → manifest}/manifest.js +113 -98
  51. package/dist/manifest/manifest.js.map +1 -0
  52. package/dist/{types/manifest → manifest}/validation.d.ts +73 -31
  53. package/dist/manifest/validation.js +141 -0
  54. package/dist/manifest/validation.js.map +1 -0
  55. package/dist/{esm/mock.js → mock.js} +40 -42
  56. package/dist/mock.js.map +1 -0
  57. package/dist/namespace.d.ts +275 -0
  58. package/dist/namespace.js +225 -0
  59. package/dist/namespace.js.map +1 -0
  60. package/dist/notification.d.ts +66 -0
  61. package/dist/notification.js +58 -0
  62. package/dist/notification.js.map +1 -0
  63. package/dist/{types/npm.d.ts → npm.d.ts} +2 -0
  64. package/dist/npm.js +74 -0
  65. package/dist/npm.js.map +1 -0
  66. package/dist/path.js +21 -0
  67. package/dist/path.js.map +1 -0
  68. package/dist/{esm/post-process.js → post-process.js} +99 -110
  69. package/dist/post-process.js.map +1 -0
  70. package/dist/{types/snaps.d.ts → snaps.d.ts} +2 -9
  71. package/dist/snaps.js +202 -0
  72. package/dist/snaps.js.map +1 -0
  73. package/dist/{types/types.d.ts → types.d.ts} +5 -2
  74. package/dist/types.js +103 -0
  75. package/dist/types.js.map +1 -0
  76. package/dist/{esm/versions.js → versions.js} +18 -15
  77. package/dist/versions.js.map +1 -0
  78. package/dist/{esm/virtual-file → virtual-file}/VirtualFile.js +33 -47
  79. package/dist/virtual-file/VirtualFile.js.map +1 -0
  80. package/dist/virtual-file/index.browser.js +18 -0
  81. package/dist/virtual-file/index.browser.js.map +1 -0
  82. package/dist/virtual-file/index.js +19 -0
  83. package/dist/virtual-file/index.js.map +1 -0
  84. package/dist/virtual-file/toVirtualFile.js +30 -0
  85. package/dist/virtual-file/toVirtualFile.js.map +1 -0
  86. package/package.json +32 -61
  87. package/dist/cjs/array.js +0 -23
  88. package/dist/cjs/array.js.map +0 -1
  89. package/dist/cjs/caveats.js +0 -33
  90. package/dist/cjs/caveats.js.map +0 -1
  91. package/dist/cjs/checksum.js +0 -38
  92. package/dist/cjs/checksum.js.map +0 -1
  93. package/dist/cjs/cronjob.js +0 -84
  94. package/dist/cjs/cronjob.js.map +0 -1
  95. package/dist/cjs/deep-clone.js +0 -22
  96. package/dist/cjs/deep-clone.js.map +0 -1
  97. package/dist/cjs/default-endowments.js +0 -49
  98. package/dist/cjs/default-endowments.js.map +0 -1
  99. package/dist/cjs/entropy.js +0 -23
  100. package/dist/cjs/entropy.js.map +0 -1
  101. package/dist/cjs/enum.js +0 -16
  102. package/dist/cjs/enum.js.map +0 -1
  103. package/dist/cjs/eval-worker.js.map +0 -1
  104. package/dist/cjs/eval.js +0 -29
  105. package/dist/cjs/eval.js.map +0 -1
  106. package/dist/cjs/fs.js +0 -126
  107. package/dist/cjs/fs.js.map +0 -1
  108. package/dist/cjs/handlers.js +0 -6
  109. package/dist/cjs/handlers.js.map +0 -1
  110. package/dist/cjs/icon.js +0 -37
  111. package/dist/cjs/icon.js.map +0 -1
  112. package/dist/cjs/iframe.js +0 -59
  113. package/dist/cjs/iframe.js.map +0 -1
  114. package/dist/cjs/index.browser.js +0 -40
  115. package/dist/cjs/index.browser.js.map +0 -1
  116. package/dist/cjs/index.executionenv.js +0 -24
  117. package/dist/cjs/index.executionenv.js.map +0 -1
  118. package/dist/cjs/index.js +0 -45
  119. package/dist/cjs/index.js.map +0 -1
  120. package/dist/cjs/json-rpc.js +0 -46
  121. package/dist/cjs/json-rpc.js.map +0 -1
  122. package/dist/cjs/json.js +0 -16
  123. package/dist/cjs/json.js.map +0 -1
  124. package/dist/cjs/logging.js +0 -40
  125. package/dist/cjs/logging.js.map +0 -1
  126. package/dist/cjs/manifest/index.browser.js +0 -20
  127. package/dist/cjs/manifest/index.browser.js.map +0 -1
  128. package/dist/cjs/manifest/index.js +0 -21
  129. package/dist/cjs/manifest/index.js.map +0 -1
  130. package/dist/cjs/manifest/manifest.js +0 -239
  131. package/dist/cjs/manifest/manifest.js.map +0 -1
  132. package/dist/cjs/manifest/validation.js +0 -183
  133. package/dist/cjs/manifest/validation.js.map +0 -1
  134. package/dist/cjs/mock.js +0 -128
  135. package/dist/cjs/mock.js.map +0 -1
  136. package/dist/cjs/namespace.js +0 -124
  137. package/dist/cjs/namespace.js.map +0 -1
  138. package/dist/cjs/npm.js +0 -81
  139. package/dist/cjs/npm.js.map +0 -1
  140. package/dist/cjs/path.js +0 -21
  141. package/dist/cjs/path.js.map +0 -1
  142. package/dist/cjs/post-process.js +0 -328
  143. package/dist/cjs/post-process.js.map +0 -1
  144. package/dist/cjs/snaps.js +0 -230
  145. package/dist/cjs/snaps.js.map +0 -1
  146. package/dist/cjs/types.js +0 -117
  147. package/dist/cjs/types.js.map +0 -1
  148. package/dist/cjs/validation.js +0 -22
  149. package/dist/cjs/validation.js.map +0 -1
  150. package/dist/cjs/versions.js +0 -47
  151. package/dist/cjs/versions.js.map +0 -1
  152. package/dist/cjs/virtual-file/VirtualFile.js +0 -85
  153. package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
  154. package/dist/cjs/virtual-file/index.browser.js +0 -20
  155. package/dist/cjs/virtual-file/index.browser.js.map +0 -1
  156. package/dist/cjs/virtual-file/index.js +0 -21
  157. package/dist/cjs/virtual-file/index.js.map +0 -1
  158. package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
  159. package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
  160. package/dist/esm/array.js.map +0 -1
  161. package/dist/esm/caveats.js +0 -23
  162. package/dist/esm/caveats.js.map +0 -1
  163. package/dist/esm/checksum.js +0 -36
  164. package/dist/esm/checksum.js.map +0 -1
  165. package/dist/esm/cronjob.js +0 -66
  166. package/dist/esm/cronjob.js.map +0 -1
  167. package/dist/esm/deep-clone.js +0 -7
  168. package/dist/esm/deep-clone.js.map +0 -1
  169. package/dist/esm/default-endowments.js.map +0 -1
  170. package/dist/esm/entropy.js +0 -6
  171. package/dist/esm/entropy.js.map +0 -1
  172. package/dist/esm/enum.js +0 -12
  173. package/dist/esm/enum.js.map +0 -1
  174. package/dist/esm/eval-worker.js +0 -47
  175. package/dist/esm/eval-worker.js.map +0 -1
  176. package/dist/esm/eval.js +0 -25
  177. package/dist/esm/eval.js.map +0 -1
  178. package/dist/esm/fs.js.map +0 -1
  179. package/dist/esm/handlers.js +0 -3
  180. package/dist/esm/handlers.js.map +0 -1
  181. package/dist/esm/icon.js +0 -11
  182. package/dist/esm/icon.js.map +0 -1
  183. package/dist/esm/iframe.js.map +0 -1
  184. package/dist/esm/index.browser.js +0 -23
  185. package/dist/esm/index.browser.js.map +0 -1
  186. package/dist/esm/index.executionenv.js +0 -7
  187. package/dist/esm/index.executionenv.js.map +0 -1
  188. package/dist/esm/index.js +0 -28
  189. package/dist/esm/index.js.map +0 -1
  190. package/dist/esm/json-rpc.js +0 -39
  191. package/dist/esm/json-rpc.js.map +0 -1
  192. package/dist/esm/json.js +0 -17
  193. package/dist/esm/json.js.map +0 -1
  194. package/dist/esm/logging.js.map +0 -1
  195. package/dist/esm/manifest/index.browser.js +0 -3
  196. package/dist/esm/manifest/index.browser.js.map +0 -1
  197. package/dist/esm/manifest/index.js +0 -4
  198. package/dist/esm/manifest/index.js.map +0 -1
  199. package/dist/esm/manifest/manifest.js.map +0 -1
  200. package/dist/esm/manifest/validation.js +0 -152
  201. package/dist/esm/manifest/validation.js.map +0 -1
  202. package/dist/esm/mock.js.map +0 -1
  203. package/dist/esm/namespace.js +0 -110
  204. package/dist/esm/namespace.js.map +0 -1
  205. package/dist/esm/npm.js +0 -70
  206. package/dist/esm/npm.js.map +0 -1
  207. package/dist/esm/path.js +0 -17
  208. package/dist/esm/path.js.map +0 -1
  209. package/dist/esm/post-process.js.map +0 -1
  210. package/dist/esm/snaps.js +0 -215
  211. package/dist/esm/snaps.js.map +0 -1
  212. package/dist/esm/types.js +0 -85
  213. package/dist/esm/types.js.map +0 -1
  214. package/dist/esm/validation.js +0 -17
  215. package/dist/esm/validation.js.map +0 -1
  216. package/dist/esm/versions.js.map +0 -1
  217. package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
  218. package/dist/esm/virtual-file/index.browser.js +0 -3
  219. package/dist/esm/virtual-file/index.browser.js.map +0 -1
  220. package/dist/esm/virtual-file/index.js +0 -4
  221. package/dist/esm/virtual-file/index.js.map +0 -1
  222. package/dist/esm/virtual-file/toVirtualFile.js +0 -26
  223. package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
  224. package/dist/types/enum.d.ts +0 -30
  225. package/dist/types/icon.d.ts +0 -4
  226. package/dist/types/json.d.ts +0 -13
  227. package/dist/types/namespace.d.ts +0 -124
  228. package/dist/types/validation.d.ts +0 -8
  229. /package/dist/{types/array.d.ts → array.d.ts} +0 -0
  230. /package/dist/{types/checksum.d.ts → checksum.d.ts} +0 -0
  231. /package/dist/{types/cronjob.d.ts → cronjob.d.ts} +0 -0
  232. /package/dist/{types/deep-clone.d.ts → deep-clone.d.ts} +0 -0
  233. /package/dist/{types/default-endowments.d.ts → default-endowments.d.ts} +0 -0
  234. /package/dist/{types/entropy.d.ts → entropy.d.ts} +0 -0
  235. /package/dist/{types/eval-worker.d.ts → eval-worker.d.ts} +0 -0
  236. /package/dist/{types/eval.d.ts → eval.d.ts} +0 -0
  237. /package/dist/{types/fs.d.ts → fs.d.ts} +0 -0
  238. /package/dist/{types/iframe.test.browser.d.ts → iframe.test.browser.d.ts} +0 -0
  239. /package/dist/{types/index.executionenv.d.ts → index.executionenv.d.ts} +0 -0
  240. /package/dist/{types/json-rpc.d.ts → json-rpc.d.ts} +0 -0
  241. /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
  242. /package/dist/{types/manifest → manifest}/index.browser.d.ts +0 -0
  243. /package/dist/{types/manifest → manifest}/index.d.ts +0 -0
  244. /package/dist/{types/manifest → manifest}/manifest.d.ts +0 -0
  245. /package/dist/{types/mock.d.ts → mock.d.ts} +0 -0
  246. /package/dist/{types/path.d.ts → path.d.ts} +0 -0
  247. /package/dist/{types/post-process.d.ts → post-process.d.ts} +0 -0
  248. /package/dist/{types/versions.d.ts → versions.d.ts} +0 -0
  249. /package/dist/{types/virtual-file → virtual-file}/VirtualFile.d.ts +0 -0
  250. /package/dist/{types/virtual-file → virtual-file}/index.browser.d.ts +0 -0
  251. /package/dist/{types/virtual-file → virtual-file}/index.d.ts +0 -0
  252. /package/dist/{types/virtual-file → virtual-file}/toVirtualFile.d.ts +0 -0
@@ -1,8 +1,14 @@
1
- import { promises as fs } from 'fs';
2
- import os from 'os';
3
- import pathUtils from 'path';
4
- import { parseJson } from './json';
5
- import { readVirtualFile } from './virtual-file';
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.useTemporaryFile = exports.validateDirPath = exports.validateFilePath = exports.validateOutfileName = exports.getOutfilePath = exports.readJsonFile = exports.isFile = exports.isDirectory = void 0;
7
+ const fs_1 = require("fs");
8
+ const os_1 = __importDefault(require("os"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const json_1 = require("./json");
11
+ const virtual_file_1 = require("./virtual-file");
6
12
  /**
7
13
  * Checks whether the given path string resolves to an existing directory, and
8
14
  * optionally creates the directory if it doesn't exist.
@@ -10,57 +16,64 @@ import { readVirtualFile } from './virtual-file';
10
16
  * @param pathString - The path string to check.
11
17
  * @param createDir - Whether to create the directory if it doesn't exist.
12
18
  * @returns Whether the given path is an existing directory.
13
- */ export async function isDirectory(pathString, createDir) {
19
+ */
20
+ async function isDirectory(pathString, createDir) {
14
21
  try {
15
- const stats = await fs.stat(pathString);
22
+ const stats = await fs_1.promises.stat(pathString);
16
23
  return stats.isDirectory();
17
- } catch (error) {
24
+ }
25
+ catch (error) {
18
26
  if (error.code === 'ENOENT') {
19
27
  if (!createDir) {
20
28
  return false;
21
29
  }
22
- await fs.mkdir(pathString, {
23
- recursive: true
24
- });
30
+ await fs_1.promises.mkdir(pathString, { recursive: true });
25
31
  return true;
26
32
  }
27
33
  return false;
28
34
  }
29
35
  }
36
+ exports.isDirectory = isDirectory;
30
37
  /**
31
38
  * Checks whether the given path string resolves to an existing file.
32
39
  *
33
40
  * @param pathString - The path string to check.
34
41
  * @returns Whether the given path is an existing file.
35
- */ export async function isFile(pathString) {
42
+ */
43
+ async function isFile(pathString) {
36
44
  try {
37
- const stats = await fs.stat(pathString);
45
+ const stats = await fs_1.promises.stat(pathString);
38
46
  return stats.isFile();
39
- } catch (error) {
47
+ }
48
+ catch (error) {
40
49
  return false;
41
50
  }
42
51
  }
52
+ exports.isFile = isFile;
43
53
  /**
44
54
  * Reads a `.json` file, parses its contents, and returns them.
45
55
  *
46
56
  * @param pathString - The path to the JSON file.
47
57
  * @returns The parsed contents of the JSON file.
48
- */ export async function readJsonFile(pathString) {
58
+ */
59
+ async function readJsonFile(pathString) {
49
60
  if (!pathString.endsWith('.json')) {
50
61
  throw new Error('The specified file must be a ".json" file.');
51
62
  }
52
63
  let file;
53
64
  try {
54
- file = await readVirtualFile(pathString, 'utf8');
55
- } catch (error) {
65
+ file = await (0, virtual_file_1.readVirtualFile)(pathString, 'utf8');
66
+ }
67
+ catch (error) {
56
68
  if (error.code === 'ENOENT') {
57
69
  throw new Error(`Could not find '${pathString}'. Please ensure that the file exists.`);
58
70
  }
59
71
  throw error;
60
72
  }
61
- file.result = parseJson(file.toString());
73
+ file.result = (0, json_1.parseJson)(file.toString());
62
74
  return file;
63
75
  }
76
+ exports.readJsonFile = readJsonFile;
64
77
  /**
65
78
  * Gets the complete out file path from an output file name and parent
66
79
  * directory path.
@@ -68,9 +81,11 @@ import { readVirtualFile } from './virtual-file';
68
81
  * @param outDir - The path to the out file's parent directory.
69
82
  * @param outFileName - The out file's name.
70
83
  * @returns The complete path to the out file.
71
- */ export function getOutfilePath(outDir, outFileName) {
72
- return pathUtils.join(outDir, outFileName || 'bundle.js');
84
+ */
85
+ function getOutfilePath(outDir, outFileName) {
86
+ return path_1.default.join(outDir, outFileName || 'bundle.js');
73
87
  }
88
+ exports.getOutfilePath = getOutfilePath;
74
89
  /**
75
90
  * Ensures that the outfile name is just a `.js` file name.
76
91
  * Throws on validation failure.
@@ -78,25 +93,31 @@ import { readVirtualFile } from './virtual-file';
78
93
  * @param filename - The file name to validate.
79
94
  * @returns `true` if validation succeeded.
80
95
  * @throws If the file name is invalid.
81
- */ export function validateOutfileName(filename) {
82
- if (!filename.endsWith('.js') || filename === '.js' || pathUtils.basename(filename) !== filename) {
96
+ */
97
+ function validateOutfileName(filename) {
98
+ if (!filename.endsWith('.js') ||
99
+ filename === '.js' ||
100
+ path_1.default.basename(filename) !== filename) {
83
101
  throw new Error(`Invalid outfile name: ${filename}. Must be a .js file`);
84
102
  }
85
103
  return true;
86
104
  }
105
+ exports.validateOutfileName = validateOutfileName;
87
106
  /**
88
107
  * Validates a file path. Throws on validation failure.
89
108
  *
90
109
  * @param filePath - The file path to validate.
91
110
  * @returns `true` if validation succeeded.
92
111
  * @throws If the path does not resolve to a file.
93
- */ export async function validateFilePath(filePath) {
112
+ */
113
+ async function validateFilePath(filePath) {
94
114
  const exists = await isFile(filePath);
95
115
  if (!exists) {
96
116
  throw new Error(`Invalid params: '${filePath}' is not a file or does not exist.`);
97
117
  }
98
118
  return true;
99
119
  }
120
+ exports.validateFilePath = validateFilePath;
100
121
  /**
101
122
  * Validates a directory path. Throws on validation failure.
102
123
  *
@@ -104,13 +125,15 @@ import { readVirtualFile } from './virtual-file';
104
125
  * @param createDir - Whether to create the directory if it doesn't exist.
105
126
  * @returns `true` if validation succeeded or the directory was created.
106
127
  * @throws If the directory does not exist or could not be created.
107
- */ export async function validateDirPath(dirPath, createDir) {
128
+ */
129
+ async function validateDirPath(dirPath, createDir) {
108
130
  const exists = await isDirectory(dirPath, createDir);
109
131
  if (!exists) {
110
132
  throw new Error(`Invalid params: '${dirPath}' is not a directory or could not be created.`);
111
133
  }
112
134
  return true;
113
135
  }
136
+ exports.validateDirPath = validateDirPath;
114
137
  /**
115
138
  * Creates a temporary file with a given name and content, writes it to disk and calls the provided function.
116
139
  * This function handles deletion of the temporary file after usage.
@@ -118,19 +141,19 @@ import { readVirtualFile } from './virtual-file';
118
141
  * @param fileName - The name of the temporary file.
119
142
  * @param fileContents - The content of the temporary file.
120
143
  * @param fn - The callback function to call when the temporary file has been created.
121
- */ export async function useTemporaryFile(fileName, fileContents, fn) {
122
- const filePath = pathUtils.join(os.tmpdir(), fileName);
123
- await fs.mkdir(pathUtils.dirname(filePath), {
124
- recursive: true
125
- });
126
- await fs.writeFile(filePath, fileContents);
144
+ */
145
+ async function useTemporaryFile(fileName, fileContents, fn) {
146
+ const filePath = path_1.default.join(os_1.default.tmpdir(), fileName);
147
+ await fs_1.promises.mkdir(path_1.default.dirname(filePath), { recursive: true });
148
+ await fs_1.promises.writeFile(filePath, fileContents);
127
149
  try {
128
150
  await fn(filePath);
129
- } finally{
151
+ }
152
+ finally {
130
153
  if (await isFile(filePath)) {
131
- await fs.unlink(filePath);
154
+ await fs_1.promises.unlink(filePath);
132
155
  }
133
156
  }
134
157
  }
135
-
158
+ exports.useTemporaryFile = useTemporaryFile;
136
159
  //# sourceMappingURL=fs.js.map
package/dist/fs.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fs.js","sourceRoot":"","sources":["../src/fs.ts"],"names":[],"mappings":"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","sourcesContent":["import { Json } from '@metamask/utils';\nimport { promises as fs } from 'fs';\nimport os from 'os';\nimport pathUtils from 'path';\n\nimport { parseJson } from './json';\nimport { readVirtualFile, VirtualFile } from './virtual-file';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns Whether the given path is an existing directory.\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n await fs.mkdir(pathString, { recursive: true });\n return true;\n }\n\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check.\n * @returns Whether the given path is an existing file.\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile<Type extends Json = Json>(\n pathString: string,\n): Promise<VirtualFile<Type>> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n let file;\n try {\n file = await readVirtualFile(pathString, 'utf8');\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `Could not find '${pathString}'. Please ensure that the file exists.`,\n );\n }\n\n throw error;\n }\n file.result = parseJson(file.toString());\n return file as VirtualFile<Type>;\n}\n\n/**\n * Gets the complete out file path from an output file name and parent\n * directory path.\n *\n * @param outDir - The path to the out file's parent directory.\n * @param outFileName - The out file's name.\n * @returns The complete path to the out file.\n */\nexport function getOutfilePath(outDir: string, outFileName: string): string {\n return pathUtils.join(outDir, outFileName || 'bundle.js');\n}\n\n/**\n * Ensures that the outfile name is just a `.js` file name.\n * Throws on validation failure.\n *\n * @param filename - The file name to validate.\n * @returns `true` if validation succeeded.\n * @throws If the file name is invalid.\n */\nexport function validateOutfileName(filename: string): boolean {\n if (\n !filename.endsWith('.js') ||\n filename === '.js' ||\n pathUtils.basename(filename) !== filename\n ) {\n throw new Error(`Invalid outfile name: ${filename}. Must be a .js file`);\n }\n return true;\n}\n\n/**\n * Validates a file path. Throws on validation failure.\n *\n * @param filePath - The file path to validate.\n * @returns `true` if validation succeeded.\n * @throws If the path does not resolve to a file.\n */\nexport async function validateFilePath(filePath: string): Promise<boolean> {\n const exists = await isFile(filePath);\n if (!exists) {\n throw new Error(\n `Invalid params: '${filePath}' is not a file or does not exist.`,\n );\n }\n return true;\n}\n\n/**\n * Validates a directory path. Throws on validation failure.\n *\n * @param dirPath - The directory path to validate.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns `true` if validation succeeded or the directory was created.\n * @throws If the directory does not exist or could not be created.\n */\nexport async function validateDirPath(\n dirPath: string,\n createDir: boolean,\n): Promise<boolean> {\n const exists = await isDirectory(dirPath, createDir);\n if (!exists) {\n throw new Error(\n `Invalid params: '${dirPath}' is not a directory or could not be created.`,\n );\n }\n return true;\n}\n\n/**\n * Creates a temporary file with a given name and content, writes it to disk and calls the provided function.\n * This function handles deletion of the temporary file after usage.\n *\n * @param fileName - The name of the temporary file.\n * @param fileContents - The content of the temporary file.\n * @param fn - The callback function to call when the temporary file has been created.\n */\nexport async function useTemporaryFile(\n fileName: string,\n fileContents: string,\n fn: (path: string) => Promise<unknown>,\n): Promise<void> {\n const filePath = pathUtils.join(os.tmpdir(), fileName);\n await fs.mkdir(pathUtils.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, fileContents);\n try {\n await fn(filePath);\n } finally {\n if (await isFile(filePath)) {\n await fs.unlink(filePath);\n }\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { Component } from '@metamask/snaps-ui';
2
2
  import { Json, JsonRpcRequest } from '@metamask/utils';
3
+ import { AccountId, ChainId, RequestArguments } from './namespace';
3
4
  /**
4
5
  * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is
5
6
  * made to the snap.
@@ -10,9 +11,9 @@ import { Json, JsonRpcRequest } from '@metamask/utils';
10
11
  * @param args.request - The JSON-RPC request sent to the snap.
11
12
  * @returns The JSON-RPC response. This must be a JSON-serializable value.
12
13
  */
13
- export declare type OnRpcRequestHandler<Params extends Json[] | Record<string, Json> | undefined = Json[] | Record<string, Json> | undefined> = (args: {
14
+ export declare type OnRpcRequestHandler = (args: {
14
15
  origin: string;
15
- request: JsonRpcRequest<Params>;
16
+ request: JsonRpcRequest<Json[] | Record<string, Json>>;
16
17
  }) => Promise<unknown>;
17
18
  /**
18
19
  * The response from a snap's `onTransaction` handler.
@@ -51,9 +52,43 @@ export declare type OnTransactionHandler = (args: {
51
52
  * @param args - The request arguments.
52
53
  * @param args.request - The JSON-RPC request sent to the snap.
53
54
  */
54
- export declare type OnCronjobHandler<Params extends Json[] | Record<string, Json> | undefined = Json[] | Record<string, Json> | undefined> = (args: {
55
- request: JsonRpcRequest<Params>;
55
+ export declare type OnCronjobHandler = (args: {
56
+ request: JsonRpcRequest<Json[] | Record<string, Json>>;
56
57
  }) => Promise<unknown>;
58
+ /**
59
+ * A request sent to the `handleRequest` handler of a snap keyring.
60
+ *
61
+ * @property chainId - The CAIP-2 chain ID of the network the request is being
62
+ * made to.
63
+ * @property origin - The origin of the request. This can be the ID of another
64
+ * snap, or the URL of a dapp.
65
+ */
66
+ export declare type KeyringRequest = {
67
+ chainId: ChainId;
68
+ origin: string;
69
+ };
70
+ /**
71
+ * A keyring event, which consists of a {@link KeyringRequest}, combined with
72
+ * the name of the event.
73
+ */
74
+ export declare type KeyringEvent = KeyringRequest & {
75
+ eventName: string;
76
+ };
77
+ /**
78
+ * A snap keyring object, which can be exported as `keyring` in a snap.
79
+ */
80
+ export interface SnapKeyring {
81
+ getAccounts(): Promise<AccountId[]>;
82
+ handleRequest(data: KeyringRequest & {
83
+ request: RequestArguments;
84
+ }): Promise<Json>;
85
+ on(data: KeyringEvent, listener: (...args: Json[]) => void): void;
86
+ off(data: KeyringEvent): void;
87
+ addAccount?(chainId: ChainId): Promise<AccountId>;
88
+ removeAccount?(accountId: AccountId): Promise<void>;
89
+ importAccount?(chainId: ChainId, data: Json): Promise<AccountId>;
90
+ exportAccount?(accountId: AccountId): Promise<Json>;
91
+ }
57
92
  /**
58
93
  * All the function-based handlers that a snap can implement.
59
94
  */
@@ -65,4 +100,6 @@ export declare type SnapFunctionExports = {
65
100
  /**
66
101
  * All handlers that a snap can implement.
67
102
  */
68
- export declare type SnapExports = SnapFunctionExports;
103
+ export declare type SnapExports = SnapFunctionExports & {
104
+ keyring?: SnapKeyring;
105
+ };
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=handlers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers.js","sourceRoot":"","sources":["../src/handlers.ts"],"names":[],"mappings":"","sourcesContent":["import { Component } from '@metamask/snaps-ui';\nimport { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport { AccountId, ChainId, RequestArguments } from './namespace';\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler = (args: {\n origin: string;\n request: JsonRpcRequest<Json[] | Record<string, Json>>;\n}) => Promise<unknown>;\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = {\n content: Component | null;\n};\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler = (args: {\n request: JsonRpcRequest<Json[] | Record<string, Json>>;\n}) => Promise<unknown>;\n\n/**\n * A request sent to the `handleRequest` handler of a snap keyring.\n *\n * @property chainId - The CAIP-2 chain ID of the network the request is being\n * made to.\n * @property origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n */\nexport type KeyringRequest = {\n chainId: ChainId;\n origin: string;\n};\n\n/**\n * A keyring event, which consists of a {@link KeyringRequest}, combined with\n * the name of the event.\n */\nexport type KeyringEvent = KeyringRequest & { eventName: string };\n\n/**\n * A snap keyring object, which can be exported as `keyring` in a snap.\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SnapKeyring {\n getAccounts(): Promise<AccountId[]>;\n handleRequest(\n data: KeyringRequest & {\n request: RequestArguments;\n },\n ): Promise<Json>;\n on(data: KeyringEvent, listener: (...args: Json[]) => void): void;\n off(data: KeyringEvent): void;\n\n addAccount?(chainId: ChainId): Promise<AccountId>;\n removeAccount?(accountId: AccountId): Promise<void>;\n\n importAccount?(chainId: ChainId, data: Json): Promise<AccountId>;\n exportAccount?(accountId: AccountId): Promise<Json>;\n}\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n onRpcRequest?: OnRpcRequestHandler;\n onTransaction?: OnTransactionHandler;\n onCronjob?: OnCronjobHandler;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports & {\n keyring?: SnapKeyring;\n};\n"]}
@@ -4,8 +4,7 @@
4
4
  * an initialization timeout in the SnapController.
5
5
  *
6
6
  * @param uri - The iframe URI.
7
- * @param id - The ID to assign to the iframe.
8
- * @param sandbox - Whether to enable the sandbox attribute.
7
+ * @param jobId - The job id.
9
8
  * @returns A promise that resolves to the contentWindow of the iframe.
10
9
  */
11
- export declare function createWindow(uri: string, id: string, sandbox?: boolean): Promise<Window>;
10
+ export declare function createWindow(uri: string, jobId: string): Promise<Window>;
@@ -1,26 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createWindow = void 0;
1
4
  /**
2
5
  * Creates the iframe to be used as the execution environment. This may run
3
6
  * forever if the iframe never loads, but the promise should be wrapped in
4
7
  * an initialization timeout in the SnapController.
5
8
  *
6
9
  * @param uri - The iframe URI.
7
- * @param id - The ID to assign to the iframe.
8
- * @param sandbox - Whether to enable the sandbox attribute.
10
+ * @param jobId - The job id.
9
11
  * @returns A promise that resolves to the contentWindow of the iframe.
10
- */ export async function createWindow(uri, id, sandbox = true) {
11
- return await new Promise((resolve, reject)=>{
12
+ */
13
+ async function createWindow(uri, jobId) {
14
+ return await new Promise((resolve, reject) => {
12
15
  const iframe = document.createElement('iframe');
13
16
  // The order of operations appears to matter for everything except this
14
17
  // attribute. We may as well set it here.
15
- iframe.setAttribute('id', id);
18
+ iframe.setAttribute('id', jobId);
16
19
  iframe.setAttribute('data-testid', 'snaps-iframe');
17
- if (sandbox) {
18
- // For the sandbox property to have any effect it needs to be set before the iframe is appended.
19
- // We apply this property as a principle of least authority (POLA)
20
- // measure.
21
- // Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox
22
- iframe.setAttribute('sandbox', 'allow-scripts');
23
- }
20
+ // For the sandbox property to have any effect it needs to be set before the iframe is appended.
21
+ // We apply this property as a principle of least authority (POLA)
22
+ // measure.
23
+ // Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox
24
+ iframe.setAttribute('sandbox', 'allow-scripts');
24
25
  // In the past, we've had problems that appear to be symptomatic of the
25
26
  // iframe firing the `load` event before its scripts are actually loaded,
26
27
  // which has prevented snaps from executing properly. Therefore, we set
@@ -34,16 +35,17 @@
34
35
  // Re: `load` firing twice: https://stackoverflow.com/questions/10781880/dynamically-created-iframe-triggers-onload-event-twice/15880489#15880489
35
36
  iframe.setAttribute('src', uri);
36
37
  document.body.appendChild(iframe);
37
- iframe.addEventListener('load', ()=>{
38
+ iframe.addEventListener('load', () => {
38
39
  if (iframe.contentWindow) {
39
40
  resolve(iframe.contentWindow);
40
- } else {
41
+ }
42
+ else {
41
43
  // We don't know of a case when this would happen, but better to fail
42
44
  // fast if it does.
43
- reject(new Error(`iframe.contentWindow not present on load for job "${id}".`));
45
+ reject(new Error(`iframe.contentWindow not present on load for job "${jobId}".`));
44
46
  }
45
47
  });
46
48
  });
47
49
  }
48
-
50
+ exports.createWindow = createWindow;
49
51
  //# sourceMappingURL=iframe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iframe.js","sourceRoot":"","sources":["../src/iframe.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;GAQG;AACI,KAAK,UAAU,YAAY,CAChC,GAAW,EACX,KAAa;IAEb,OAAO,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC3C,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAChD,uEAAuE;QACvE,yCAAyC;QACzC,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACjC,MAAM,CAAC,YAAY,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;QAEnD,gGAAgG;QAChG,kEAAkE;QAClE,WAAW;QACX,qFAAqF;QACrF,MAAM,CAAC,YAAY,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;QAEhD,uEAAuE;QACvE,yEAAyE;QACzE,uEAAuE;QACvE,wEAAwE;QACxE,uBAAuB;QACvB,EAAE;QACF,mEAAmE;QACnE,kCAAkC;QAClC,EAAE;QACF,mGAAmG;QACnG,iJAAiJ;QACjJ,MAAM,CAAC,YAAY,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAChC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAElC,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE;YACnC,IAAI,MAAM,CAAC,aAAa,EAAE;gBACxB,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;aAC/B;iBAAM;gBACL,qEAAqE;gBACrE,mBAAmB;gBACnB,MAAM,CACJ,IAAI,KAAK,CACP,qDAAqD,KAAK,IAAI,CAC/D,CACF,CAAC;aACH;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AA7CD,oCA6CC","sourcesContent":["/**\n * Creates the iframe to be used as the execution environment. This may run\n * forever if the iframe never loads, but the promise should be wrapped in\n * an initialization timeout in the SnapController.\n *\n * @param uri - The iframe URI.\n * @param jobId - The job id.\n * @returns A promise that resolves to the contentWindow of the iframe.\n */\nexport async function createWindow(\n uri: string,\n jobId: string,\n): Promise<Window> {\n return await new Promise((resolve, reject) => {\n const iframe = document.createElement('iframe');\n // The order of operations appears to matter for everything except this\n // attribute. We may as well set it here.\n iframe.setAttribute('id', jobId);\n iframe.setAttribute('data-testid', 'snaps-iframe');\n\n // For the sandbox property to have any effect it needs to be set before the iframe is appended.\n // We apply this property as a principle of least authority (POLA)\n // measure.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox\n iframe.setAttribute('sandbox', 'allow-scripts');\n\n // In the past, we've had problems that appear to be symptomatic of the\n // iframe firing the `load` event before its scripts are actually loaded,\n // which has prevented snaps from executing properly. Therefore, we set\n // the `src` attribute and append the iframe to the DOM before attaching\n // the `load` listener.\n //\n // `load` should only fire when \"all dependent resources\" have been\n // loaded, which includes scripts.\n //\n // MDN article for `load` event: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event\n // Re: `load` firing twice: https://stackoverflow.com/questions/10781880/dynamically-created-iframe-triggers-onload-event-twice/15880489#15880489\n iframe.setAttribute('src', uri);\n document.body.appendChild(iframe);\n\n iframe.addEventListener('load', () => {\n if (iframe.contentWindow) {\n resolve(iframe.contentWindow);\n } else {\n // We don't know of a case when this would happen, but better to fail\n // fast if it does.\n reject(\n new Error(\n `iframe.contentWindow not present on load for job \"${jobId}\".`,\n ),\n );\n }\n });\n });\n}\n"]}
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const iframe_1 = require("./iframe");
4
+ const IFRAME_URL = `http://localhost:4569`;
5
+ const MOCK_JOB_ID = 'job-id';
6
+ describe('createWindow', () => {
7
+ it('creates an iframe window with the provided job ID as the iframe ID', async () => {
8
+ const window = await (0, iframe_1.createWindow)(IFRAME_URL, MOCK_JOB_ID);
9
+ const iframe = document.getElementById(MOCK_JOB_ID);
10
+ expect(iframe).toBeDefined();
11
+ expect(iframe.contentWindow).toBe(window);
12
+ expect(iframe.id).toBe(MOCK_JOB_ID);
13
+ });
14
+ });
15
+ //# sourceMappingURL=iframe.test.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iframe.test.browser.js","sourceRoot":"","sources":["../src/iframe.test.browser.ts"],"names":[],"mappings":";;AAAA,qCAAwC;AAExC,MAAM,UAAU,GAAG,uBAAuB,CAAC;AAE3C,MAAM,WAAW,GAAG,QAAQ,CAAC;AAE7B,QAAQ,CAAC,cAAc,EAAE,GAAG,EAAE;IAC5B,EAAE,CAAC,oEAAoE,EAAE,KAAK,IAAI,EAAE;QAClF,MAAM,MAAM,GAAG,MAAM,IAAA,qBAAY,EAAC,UAAU,EAAE,WAAW,CAAC,CAAC;QAC3D,MAAM,MAAM,GAAG,QAAQ,CAAC,cAAc,CAAC,WAAW,CAAsB,CAAC;QAEzE,MAAM,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7B,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC1C,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { createWindow } from './iframe';\n\nconst IFRAME_URL = `http://localhost:4569`;\n\nconst MOCK_JOB_ID = 'job-id';\n\ndescribe('createWindow', () => {\n it('creates an iframe window with the provided job ID as the iframe ID', async () => {\n const window = await createWindow(IFRAME_URL, MOCK_JOB_ID);\n const iframe = document.getElementById(MOCK_JOB_ID) as HTMLIFrameElement;\n\n expect(iframe).toBeDefined();\n expect(iframe.contentWindow).toBe(window);\n expect(iframe.id).toBe(MOCK_JOB_ID);\n });\n});\n"]}
@@ -5,7 +5,6 @@ export * from './cronjob';
5
5
  export * from './deep-clone';
6
6
  export * from './default-endowments';
7
7
  export * from './entropy';
8
- export * from './enum';
9
8
  export * from './handlers';
10
9
  export * from './iframe';
11
10
  export * from './json';
@@ -13,9 +12,9 @@ export * from './json-rpc';
13
12
  export * from './logging';
14
13
  export * from './manifest/index.browser';
15
14
  export * from './namespace';
15
+ export * from './notification';
16
16
  export * from './path';
17
17
  export * from './snaps';
18
18
  export * from './types';
19
- export * from './validation';
20
19
  export * from './versions';
21
20
  export * from './virtual-file/index.browser';
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./array"), exports);
18
+ __exportStar(require("./caveats"), exports);
19
+ __exportStar(require("./checksum"), exports);
20
+ __exportStar(require("./cronjob"), exports);
21
+ __exportStar(require("./deep-clone"), exports);
22
+ __exportStar(require("./default-endowments"), exports);
23
+ __exportStar(require("./entropy"), exports);
24
+ __exportStar(require("./handlers"), exports);
25
+ __exportStar(require("./iframe"), exports);
26
+ __exportStar(require("./json"), exports);
27
+ __exportStar(require("./json-rpc"), exports);
28
+ __exportStar(require("./logging"), exports);
29
+ __exportStar(require("./manifest/index.browser"), exports);
30
+ __exportStar(require("./namespace"), exports);
31
+ __exportStar(require("./notification"), exports);
32
+ __exportStar(require("./path"), exports);
33
+ __exportStar(require("./snaps"), exports);
34
+ __exportStar(require("./types"), exports);
35
+ __exportStar(require("./versions"), exports);
36
+ __exportStar(require("./virtual-file/index.browser"), exports);
37
+ //# sourceMappingURL=index.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../src/index.browser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0CAAwB;AACxB,4CAA0B;AAC1B,6CAA2B;AAC3B,4CAA0B;AAC1B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,6CAA2B;AAC3B,2CAAyB;AACzB,yCAAuB;AACvB,6CAA2B;AAC3B,4CAA0B;AAC1B,2DAAyC;AACzC,8CAA4B;AAC5B,iDAA+B;AAC/B,yCAAuB;AACvB,0CAAwB;AACxB,0CAAwB;AACxB,6CAA2B;AAC3B,+DAA6C","sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './notification';\nexport * from './path';\nexport * from './snaps';\nexport * from './types';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"]}
@@ -5,7 +5,6 @@ export * from './checksum';
5
5
  export * from './deep-clone';
6
6
  export * from './default-endowments';
7
7
  export * from './entropy';
8
- export * from './enum';
9
8
  export * from './eval';
10
9
  export * from './fs';
11
10
  export * from './handlers';
@@ -16,11 +15,11 @@ export * from './logging';
16
15
  export * from './manifest';
17
16
  export * from './mock';
18
17
  export * from './namespace';
18
+ export * from './notification';
19
19
  export * from './npm';
20
20
  export * from './path';
21
21
  export * from './post-process';
22
22
  export * from './snaps';
23
23
  export * from './types';
24
- export * from './validation';
25
24
  export * from './versions';
26
25
  export * from './virtual-file';
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ // Special entrypoint for execution environments for bundle sizing reasons
18
+ __exportStar(require("./handlers"), exports);
19
+ __exportStar(require("./logging"), exports);
20
+ __exportStar(require("./namespace"), exports);
21
+ __exportStar(require("./types"), exports);
22
+ //# sourceMappingURL=index.executionenv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.executionenv.js","sourceRoot":"","sources":["../src/index.executionenv.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0EAA0E;AAC1E,6CAA2B;AAC3B,4CAA0B;AAC1B,8CAA4B;AAC5B,0CAAwB","sourcesContent":["// Special entrypoint for execution environments for bundle sizing reasons\nexport * from './handlers';\nexport * from './logging';\nexport * from './namespace';\nexport * from './types';\n"]}
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./array"), exports);
18
+ __exportStar(require("./caveats"), exports);
19
+ __exportStar(require("./cronjob"), exports);
20
+ __exportStar(require("./checksum"), exports);
21
+ __exportStar(require("./deep-clone"), exports);
22
+ __exportStar(require("./default-endowments"), exports);
23
+ __exportStar(require("./entropy"), exports);
24
+ __exportStar(require("./eval"), exports);
25
+ __exportStar(require("./fs"), exports);
26
+ __exportStar(require("./handlers"), exports);
27
+ __exportStar(require("./iframe"), exports);
28
+ __exportStar(require("./json"), exports);
29
+ __exportStar(require("./json-rpc"), exports);
30
+ __exportStar(require("./logging"), exports);
31
+ __exportStar(require("./manifest"), exports);
32
+ __exportStar(require("./mock"), exports);
33
+ __exportStar(require("./namespace"), exports);
34
+ __exportStar(require("./notification"), exports);
35
+ __exportStar(require("./npm"), exports);
36
+ __exportStar(require("./path"), exports);
37
+ __exportStar(require("./post-process"), exports);
38
+ __exportStar(require("./snaps"), exports);
39
+ __exportStar(require("./types"), exports);
40
+ __exportStar(require("./versions"), exports);
41
+ __exportStar(require("./virtual-file"), exports);
42
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0CAAwB;AACxB,4CAA0B;AAC1B,4CAA0B;AAC1B,6CAA2B;AAC3B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,yCAAuB;AACvB,uCAAqB;AACrB,6CAA2B;AAC3B,2CAAyB;AACzB,yCAAuB;AACvB,6CAA2B;AAC3B,4CAA0B;AAC1B,6CAA2B;AAC3B,yCAAuB;AACvB,8CAA4B;AAC5B,iDAA+B;AAC/B,wCAAsB;AACtB,yCAAuB;AACvB,iDAA+B;AAC/B,0CAAwB;AACxB,0CAAwB;AACxB,6CAA2B;AAC3B,iDAA+B","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 './eval';\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 './notification';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './versions';\nexport * from './virtual-file';\n"]}
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertIsJsonRpcSuccess = exports.assertIsRpcOrigins = exports.RpcOriginsStruct = void 0;
4
+ const utils_1 = require("@metamask/utils");
5
+ const superstruct_1 = require("superstruct");
6
+ exports.RpcOriginsStruct = (0, superstruct_1.refine)((0, superstruct_1.object)({
7
+ dapps: (0, superstruct_1.optional)((0, superstruct_1.boolean)()),
8
+ snaps: (0, superstruct_1.optional)((0, superstruct_1.boolean)()),
9
+ }), 'RPC origins', (value) => {
10
+ if (!Object.values(value).some(Boolean)) {
11
+ throw new Error('Must specify at least one JSON-RPC origin');
12
+ }
13
+ return true;
14
+ });
15
+ /**
16
+ * Asserts that the given value is a valid {@link RpcOrigins} object.
17
+ *
18
+ * @param value - The value to assert.
19
+ * @param ErrorWrapper - An optional error wrapper to use. Defaults to
20
+ * {@link AssertionError}.
21
+ * @throws If the value is not a valid {@link RpcOrigins} object.
22
+ */
23
+ function assertIsRpcOrigins(value,
24
+ // eslint-disable-next-line @typescript-eslint/naming-convention
25
+ ErrorWrapper) {
26
+ (0, utils_1.assertStruct)(value, exports.RpcOriginsStruct, 'Invalid JSON-RPC origins', ErrorWrapper);
27
+ }
28
+ exports.assertIsRpcOrigins = assertIsRpcOrigins;
29
+ /**
30
+ * Assert that the given value is a successful JSON-RPC response. If the value
31
+ * is not a success response, an error is thrown. If the value is an JSON-RPC
32
+ * error, the error message is included in the thrown error.
33
+ *
34
+ * @param value - The value to check.
35
+ * @throws If the value is not a JSON-RPC success response.
36
+ */
37
+ function assertIsJsonRpcSuccess(value) {
38
+ if (!(0, utils_1.isJsonRpcSuccess)(value)) {
39
+ if ((0, utils_1.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
+ exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess;
46
+ //# sourceMappingURL=json-rpc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-rpc.js","sourceRoot":"","sources":["../src/json-rpc.ts"],"names":[],"mappings":";;;AAAA,2CAOyB;AACzB,6CAAuE;AAE1D,QAAA,gBAAgB,GAAG,IAAA,oBAAM,EACpC,IAAA,oBAAM,EAAC;IACL,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,qBAAO,GAAE,CAAC;IAC1B,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,qBAAO,GAAE,CAAC;CAC3B,CAAC,EACF,aAAa,EACb,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;QACvC,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAIF;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAChC,KAAc;AACd,gEAAgE;AAChE,YAAwC;IAExC,IAAA,oBAAY,EACV,KAAK,EACL,wBAAgB,EAChB,0BAA0B,EAC1B,YAAY,CACb,CAAC;AACJ,CAAC;AAXD,gDAWC;AAED;;;;;;;GAOG;AACH,SAAgB,sBAAsB,CACpC,KAAc;IAEd,IAAI,CAAC,IAAA,wBAAgB,EAAC,KAAK,CAAC,EAAE;QAC5B,IAAI,IAAA,wBAAgB,EAAC,KAAK,CAAC,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;SACpE;QAED,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;KAC/C;AACH,CAAC;AAVD,wDAUC","sourcesContent":["import {\n isJsonRpcFailure,\n isJsonRpcSuccess,\n Json,\n JsonRpcSuccess,\n AssertionErrorConstructor,\n assertStruct,\n} from '@metamask/utils';\nimport { boolean, Infer, 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"]}
package/dist/json.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Parses JSON safely.
3
+ *
4
+ * Does multiple kinds of validation and strips unwanted properties like __proto__.
5
+ *
6
+ * @param json - A JSON string to be parsed.
7
+ * @returns The parsed JSON object.
8
+ */
9
+ export declare function parseJson(json: string): import("@metamask/utils").Json;