@metamask/snaps-utils 0.38.0-flask.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/CHANGELOG.md +222 -11
  2. package/dist/{esm/array.js → array.js} +7 -3
  3. package/dist/array.js.map +1 -0
  4. package/dist/{types/caveats.d.ts → caveats.d.ts} +4 -0
  5. package/dist/caveats.js +35 -0
  6. package/dist/caveats.js.map +1 -0
  7. package/dist/checksum.js +42 -0
  8. package/dist/checksum.js.map +1 -0
  9. package/dist/{types/cronjob.d.ts → cronjob.d.ts} +1 -1
  10. package/dist/cronjob.js +71 -0
  11. package/dist/cronjob.js.map +1 -0
  12. package/dist/deep-clone.js +9 -0
  13. package/dist/deep-clone.js.map +1 -0
  14. package/dist/{esm/default-endowments.js → default-endowments.js} +6 -3
  15. package/dist/default-endowments.js.map +1 -0
  16. package/dist/entropy.js +8 -0
  17. package/dist/entropy.js.map +1 -0
  18. package/dist/{cjs/eval-worker.js → eval-worker.js} +21 -22
  19. package/dist/eval-worker.js.map +1 -0
  20. package/dist/{types/eval.d.ts → eval.d.ts} +1 -9
  21. package/dist/eval.js +27 -0
  22. package/dist/eval.js.map +1 -0
  23. package/dist/{types/fs.d.ts → fs.d.ts} +2 -2
  24. package/dist/{esm/fs.js → fs.js} +56 -33
  25. package/dist/fs.js.map +1 -0
  26. package/dist/handlers.d.ts +105 -0
  27. package/dist/handlers.js +3 -0
  28. package/dist/handlers.js.map +1 -0
  29. package/dist/{types/iframe.d.ts → iframe.d.ts} +2 -3
  30. package/dist/{esm/iframe.js → iframe.js} +18 -16
  31. package/dist/iframe.js.map +1 -0
  32. package/dist/iframe.test.browser.js +15 -0
  33. package/dist/iframe.test.browser.js.map +1 -0
  34. package/dist/{types/index.browser.d.ts → index.browser.d.ts} +1 -5
  35. package/dist/index.browser.js +37 -0
  36. package/dist/index.browser.js.map +1 -0
  37. package/dist/{types/index.d.ts → index.d.ts} +1 -5
  38. package/dist/index.executionenv.js +22 -0
  39. package/dist/index.executionenv.js.map +1 -0
  40. package/dist/index.js +42 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/{types/json-rpc.d.ts → json-rpc.d.ts} +2 -2
  43. package/dist/json-rpc.js +46 -0
  44. package/dist/json-rpc.js.map +1 -0
  45. package/dist/json.d.ts +9 -0
  46. package/dist/json.js +18 -0
  47. package/dist/json.js.map +1 -0
  48. package/dist/{esm/logging.js → logging.js} +14 -6
  49. package/dist/logging.js.map +1 -0
  50. package/dist/manifest/index.browser.js +18 -0
  51. package/dist/manifest/index.browser.js.map +1 -0
  52. package/dist/manifest/index.js +19 -0
  53. package/dist/manifest/index.js.map +1 -0
  54. package/dist/{types/manifest → manifest}/manifest.d.ts +4 -6
  55. package/dist/{esm/manifest → manifest}/manifest.js +115 -101
  56. package/dist/manifest/manifest.js.map +1 -0
  57. package/dist/{types/manifest → manifest}/validation.d.ts +76 -34
  58. package/dist/manifest/validation.js +141 -0
  59. package/dist/manifest/validation.js.map +1 -0
  60. package/dist/{esm/mock.js → mock.js} +40 -42
  61. package/dist/mock.js.map +1 -0
  62. package/dist/namespace.d.ts +275 -0
  63. package/dist/namespace.js +225 -0
  64. package/dist/namespace.js.map +1 -0
  65. package/dist/notification.d.ts +66 -0
  66. package/dist/notification.js +58 -0
  67. package/dist/notification.js.map +1 -0
  68. package/dist/{types/npm.d.ts → npm.d.ts} +3 -2
  69. package/dist/npm.js +74 -0
  70. package/dist/npm.js.map +1 -0
  71. package/dist/path.js +21 -0
  72. package/dist/path.js.map +1 -0
  73. package/dist/{esm/post-process.js → post-process.js} +99 -110
  74. package/dist/post-process.js.map +1 -0
  75. package/dist/{types/snaps.d.ts → snaps.d.ts} +9 -17
  76. package/dist/snaps.js +202 -0
  77. package/dist/snaps.js.map +1 -0
  78. package/dist/{types/types.d.ts → types.d.ts} +22 -15
  79. package/dist/types.js +103 -0
  80. package/dist/types.js.map +1 -0
  81. package/dist/{types/versions.d.ts → versions.d.ts} +1 -1
  82. package/dist/{esm/versions.js → versions.js} +18 -15
  83. package/dist/versions.js.map +1 -0
  84. package/dist/{esm/virtual-file → virtual-file}/VirtualFile.js +33 -47
  85. package/dist/virtual-file/VirtualFile.js.map +1 -0
  86. package/dist/virtual-file/index.browser.js +18 -0
  87. package/dist/virtual-file/index.browser.js.map +1 -0
  88. package/dist/virtual-file/index.js +19 -0
  89. package/dist/virtual-file/index.js.map +1 -0
  90. package/dist/virtual-file/toVirtualFile.js +30 -0
  91. package/dist/virtual-file/toVirtualFile.js.map +1 -0
  92. package/package.json +40 -59
  93. package/dist/cjs/array.js +0 -23
  94. package/dist/cjs/array.js.map +0 -1
  95. package/dist/cjs/caveats.js +0 -33
  96. package/dist/cjs/caveats.js.map +0 -1
  97. package/dist/cjs/checksum.js +0 -38
  98. package/dist/cjs/checksum.js.map +0 -1
  99. package/dist/cjs/cronjob.js +0 -84
  100. package/dist/cjs/cronjob.js.map +0 -1
  101. package/dist/cjs/deep-clone.js +0 -22
  102. package/dist/cjs/deep-clone.js.map +0 -1
  103. package/dist/cjs/default-endowments.js +0 -49
  104. package/dist/cjs/default-endowments.js.map +0 -1
  105. package/dist/cjs/entropy.js +0 -23
  106. package/dist/cjs/entropy.js.map +0 -1
  107. package/dist/cjs/enum.js +0 -16
  108. package/dist/cjs/enum.js.map +0 -1
  109. package/dist/cjs/errors.js +0 -19
  110. package/dist/cjs/errors.js.map +0 -1
  111. package/dist/cjs/eval-worker.js.map +0 -1
  112. package/dist/cjs/eval.js +0 -77
  113. package/dist/cjs/eval.js.map +0 -1
  114. package/dist/cjs/fs.js +0 -126
  115. package/dist/cjs/fs.js.map +0 -1
  116. package/dist/cjs/handlers.js +0 -65
  117. package/dist/cjs/handlers.js.map +0 -1
  118. package/dist/cjs/icon.js +0 -37
  119. package/dist/cjs/icon.js.map +0 -1
  120. package/dist/cjs/iframe.js +0 -59
  121. package/dist/cjs/iframe.js.map +0 -1
  122. package/dist/cjs/index.browser.js +0 -43
  123. package/dist/cjs/index.browser.js.map +0 -1
  124. package/dist/cjs/index.executionenv.js +0 -24
  125. package/dist/cjs/index.executionenv.js.map +0 -1
  126. package/dist/cjs/index.js +0 -48
  127. package/dist/cjs/index.js.map +0 -1
  128. package/dist/cjs/json-rpc.js +0 -46
  129. package/dist/cjs/json-rpc.js.map +0 -1
  130. package/dist/cjs/json.js +0 -16
  131. package/dist/cjs/json.js.map +0 -1
  132. package/dist/cjs/logging.js +0 -40
  133. package/dist/cjs/logging.js.map +0 -1
  134. package/dist/cjs/manifest/index.browser.js +0 -20
  135. package/dist/cjs/manifest/index.browser.js.map +0 -1
  136. package/dist/cjs/manifest/index.js +0 -21
  137. package/dist/cjs/manifest/index.js.map +0 -1
  138. package/dist/cjs/manifest/manifest.js +0 -239
  139. package/dist/cjs/manifest/manifest.js.map +0 -1
  140. package/dist/cjs/manifest/validation.js +0 -183
  141. package/dist/cjs/manifest/validation.js.map +0 -1
  142. package/dist/cjs/mock.js +0 -128
  143. package/dist/cjs/mock.js.map +0 -1
  144. package/dist/cjs/namespace.js +0 -124
  145. package/dist/cjs/namespace.js.map +0 -1
  146. package/dist/cjs/npm.js +0 -81
  147. package/dist/cjs/npm.js.map +0 -1
  148. package/dist/cjs/path.js +0 -21
  149. package/dist/cjs/path.js.map +0 -1
  150. package/dist/cjs/post-process.js +0 -328
  151. package/dist/cjs/post-process.js.map +0 -1
  152. package/dist/cjs/snaps.js +0 -230
  153. package/dist/cjs/snaps.js.map +0 -1
  154. package/dist/cjs/strings.js +0 -21
  155. package/dist/cjs/strings.js.map +0 -1
  156. package/dist/cjs/structs.js +0 -163
  157. package/dist/cjs/structs.js.map +0 -1
  158. package/dist/cjs/types.js +0 -109
  159. package/dist/cjs/types.js.map +0 -1
  160. package/dist/cjs/validation.js +0 -22
  161. package/dist/cjs/validation.js.map +0 -1
  162. package/dist/cjs/versions.js +0 -47
  163. package/dist/cjs/versions.js.map +0 -1
  164. package/dist/cjs/virtual-file/VirtualFile.js +0 -85
  165. package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
  166. package/dist/cjs/virtual-file/index.browser.js +0 -20
  167. package/dist/cjs/virtual-file/index.browser.js.map +0 -1
  168. package/dist/cjs/virtual-file/index.js +0 -21
  169. package/dist/cjs/virtual-file/index.js.map +0 -1
  170. package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
  171. package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
  172. package/dist/esm/array.js.map +0 -1
  173. package/dist/esm/caveats.js +0 -23
  174. package/dist/esm/caveats.js.map +0 -1
  175. package/dist/esm/checksum.js +0 -36
  176. package/dist/esm/checksum.js.map +0 -1
  177. package/dist/esm/cronjob.js +0 -66
  178. package/dist/esm/cronjob.js.map +0 -1
  179. package/dist/esm/deep-clone.js +0 -7
  180. package/dist/esm/deep-clone.js.map +0 -1
  181. package/dist/esm/default-endowments.js.map +0 -1
  182. package/dist/esm/entropy.js +0 -6
  183. package/dist/esm/entropy.js.map +0 -1
  184. package/dist/esm/enum.js +0 -12
  185. package/dist/esm/enum.js.map +0 -1
  186. package/dist/esm/errors.js +0 -17
  187. package/dist/esm/errors.js.map +0 -1
  188. package/dist/esm/eval-worker.js +0 -47
  189. package/dist/esm/eval-worker.js.map +0 -1
  190. package/dist/esm/eval.js +0 -65
  191. package/dist/esm/eval.js.map +0 -1
  192. package/dist/esm/fs.js.map +0 -1
  193. package/dist/esm/handlers.js +0 -47
  194. package/dist/esm/handlers.js.map +0 -1
  195. package/dist/esm/icon.js +0 -11
  196. package/dist/esm/icon.js.map +0 -1
  197. package/dist/esm/iframe.js.map +0 -1
  198. package/dist/esm/index.browser.js +0 -26
  199. package/dist/esm/index.browser.js.map +0 -1
  200. package/dist/esm/index.executionenv.js +0 -7
  201. package/dist/esm/index.executionenv.js.map +0 -1
  202. package/dist/esm/index.js +0 -31
  203. package/dist/esm/index.js.map +0 -1
  204. package/dist/esm/json-rpc.js +0 -39
  205. package/dist/esm/json-rpc.js.map +0 -1
  206. package/dist/esm/json.js +0 -17
  207. package/dist/esm/json.js.map +0 -1
  208. package/dist/esm/logging.js.map +0 -1
  209. package/dist/esm/manifest/index.browser.js +0 -3
  210. package/dist/esm/manifest/index.browser.js.map +0 -1
  211. package/dist/esm/manifest/index.js +0 -4
  212. package/dist/esm/manifest/index.js.map +0 -1
  213. package/dist/esm/manifest/manifest.js.map +0 -1
  214. package/dist/esm/manifest/validation.js +0 -152
  215. package/dist/esm/manifest/validation.js.map +0 -1
  216. package/dist/esm/mock.js.map +0 -1
  217. package/dist/esm/namespace.js +0 -110
  218. package/dist/esm/namespace.js.map +0 -1
  219. package/dist/esm/npm.js +0 -70
  220. package/dist/esm/npm.js.map +0 -1
  221. package/dist/esm/path.js +0 -17
  222. package/dist/esm/path.js.map +0 -1
  223. package/dist/esm/post-process.js.map +0 -1
  224. package/dist/esm/snaps.js +0 -215
  225. package/dist/esm/snaps.js.map +0 -1
  226. package/dist/esm/strings.js +0 -11
  227. package/dist/esm/strings.js.map +0 -1
  228. package/dist/esm/structs.js +0 -230
  229. package/dist/esm/structs.js.map +0 -1
  230. package/dist/esm/types.js +0 -80
  231. package/dist/esm/types.js.map +0 -1
  232. package/dist/esm/validation.js +0 -17
  233. package/dist/esm/validation.js.map +0 -1
  234. package/dist/esm/versions.js.map +0 -1
  235. package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
  236. package/dist/esm/virtual-file/index.browser.js +0 -3
  237. package/dist/esm/virtual-file/index.browser.js.map +0 -1
  238. package/dist/esm/virtual-file/index.js +0 -4
  239. package/dist/esm/virtual-file/index.js.map +0 -1
  240. package/dist/esm/virtual-file/toVirtualFile.js +0 -26
  241. package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
  242. package/dist/types/enum.d.ts +0 -30
  243. package/dist/types/errors.d.ts +0 -10
  244. package/dist/types/handlers.d.ts +0 -144
  245. package/dist/types/icon.d.ts +0 -4
  246. package/dist/types/json.d.ts +0 -13
  247. package/dist/types/namespace.d.ts +0 -124
  248. package/dist/types/strings.d.ts +0 -8
  249. package/dist/types/structs.d.ts +0 -158
  250. package/dist/types/validation.d.ts +0 -8
  251. /package/dist/{types/array.d.ts → array.d.ts} +0 -0
  252. /package/dist/{types/checksum.d.ts → checksum.d.ts} +0 -0
  253. /package/dist/{types/deep-clone.d.ts → deep-clone.d.ts} +0 -0
  254. /package/dist/{types/default-endowments.d.ts → default-endowments.d.ts} +0 -0
  255. /package/dist/{types/entropy.d.ts → entropy.d.ts} +0 -0
  256. /package/dist/{types/eval-worker.d.ts → eval-worker.d.ts} +0 -0
  257. /package/dist/{types/iframe.test.browser.d.ts → iframe.test.browser.d.ts} +0 -0
  258. /package/dist/{types/index.executionenv.d.ts → index.executionenv.d.ts} +0 -0
  259. /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
  260. /package/dist/{types/manifest → manifest}/index.browser.d.ts +0 -0
  261. /package/dist/{types/manifest → manifest}/index.d.ts +0 -0
  262. /package/dist/{types/mock.d.ts → mock.d.ts} +0 -0
  263. /package/dist/{types/path.d.ts → path.d.ts} +0 -0
  264. /package/dist/{types/post-process.d.ts → post-process.d.ts} +0 -0
  265. /package/dist/{types/virtual-file → virtual-file}/VirtualFile.d.ts +0 -0
  266. /package/dist/{types/virtual-file → virtual-file}/index.browser.d.ts +0 -0
  267. /package/dist/{types/virtual-file → virtual-file}/index.d.ts +0 -0
  268. /package/dist/{types/virtual-file → virtual-file}/toVirtualFile.d.ts +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["transformSync","template","binaryExpression","isUnaryExpression","isUpdateExpression","stringLiteral","templateElement","templateLiteral","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","raw","cooked","evalWrapper","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","lastMatch","suffix","replace","postProcessBundle","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","expression","setData","StringLiteral","replacement","acc","skip","BinaryExpression","errorMessage","operator","right","argument","left","end","start","includes","Error","file","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;AAExD,SAASA,aAAa,EAAEC,QAAQ,QAAQ,cAAc;AAEtD,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,kBAAkB,EAClBC,aAAa,EACbC,eAAe,EACfC,eAAe,QACV,eAAe;WAgDf;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBL,gBAAgB;IAAEM,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcb,SAASc,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBf,SAASc,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BhB,SAASc,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AAK,OAClBnG,mBAAmB2D,KAAK2C,IAAI,KAC5B3C,KAAK2C,IAAI,CAACH,QAAQ,KAAK,QACvBxC,KAAK2C,IAAI,CAACD,QAAQ,CAACE,GAAG,IACtB5C,KAAKyC,KAAK,CAACI,KAAK,EAChB;gBACA,MAAMb,aAAahD,KAAKN,KAAK,CAACsB,KAAK2C,IAAI,CAACD,QAAQ,CAACE,GAAG,EAAE5C,KAAKyC,KAAK,CAACI,KAAK;gBAEtE,IAAIb,WAAWc,QAAQ,CAAC,QAAQ;oBAC9B,MAAM,IAAIC,MAAMR;gBAClB;YACF;QACF;IACF;IAEA,IAAI;QACF,MAAMS,OAAO/G,cAAc+C,MAAM;YAC/B,kDAAkD;YAClDiE,YAAY;YAEZC,YAAY;gBACV,sEAAsE;gBACtEC,YAAY;gBAEZ,sEAAsE;gBACtE,wEAAwE;gBACxEC,eAAe,CAACnE;YAClB;YAEA,mEAAmE;YACnE,yEAAyE;YACzEoE,SAAS;YAET,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnEjE;YACAD;YAEAmE,SAAS;gBACP,IAAO,CAAA;wBACL/D;wBACAM;oBACF,CAAA;aACD;QACH;QAEA,IAAI,CAACmD,MAAMhE,MAAM;YACf,MAAM,IAAI+D,MAAM;QAClB;QAEA,OAAO;YACL/D,MAAMgE,KAAKhE,IAAI;YACfE,WAAW8D,KAAKO,GAAG;YACnBlE,UAAUzB,MAAMC,IAAI,CAACwB;QACvB;IACF,EAAE,OAAOmE,OAAO;QACd,MAAM,IAAIT,MAAM,CAAC,8BAA8B,EAAES,MAAMC,OAAO,CAAC,CAAC;IAClE;AACF"}
package/dist/esm/snaps.js DELETED
@@ -1,215 +0,0 @@
1
- function _define_property(obj, key, value) {
2
- if (key in obj) {
3
- Object.defineProperty(obj, key, {
4
- value: value,
5
- enumerable: true,
6
- configurable: true,
7
- writable: true
8
- });
9
- } else {
10
- obj[key] = value;
11
- }
12
- return obj;
13
- }
14
- import { assert, isObject, assertStruct } from '@metamask/utils';
15
- import { base64 } from '@scure/base';
16
- import stableStringify from 'fast-json-stable-stringify';
17
- import { empty, enums, intersection, literal, pattern, refine, string, union, validate } from 'superstruct';
18
- import validateNPMPackage from 'validate-npm-package-name';
19
- import { SnapCaveatType } from './caveats';
20
- import { checksumFiles } from './checksum';
21
- import { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';
22
- // This RegEx matches valid npm package names (with some exceptions) and space-
23
- // separated alphanumerical words, optionally with dashes and underscores.
24
- // The RegEx consists of two parts. The first part matches space-separated
25
- // words. It is based on the following Stackoverflow answer:
26
- // https://stackoverflow.com/a/34974982
27
- // The second part, after the pipe operator, is the same RegEx used for the
28
- // `name` field of the official package.json JSON Schema, except that we allow
29
- // mixed-case letters. It was originally copied from:
30
- // https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138
31
- export const PROPOSED_NAME_REGEX = /^(?:[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;
32
- export var SnapStatus;
33
- (function(SnapStatus) {
34
- SnapStatus["Installing"] = 'installing';
35
- SnapStatus["Updating"] = 'updating';
36
- SnapStatus["Running"] = 'running';
37
- SnapStatus["Stopped"] = 'stopped';
38
- SnapStatus["Crashed"] = 'crashed';
39
- })(SnapStatus || (SnapStatus = {}));
40
- export var SnapStatusEvents;
41
- (function(SnapStatusEvents) {
42
- SnapStatusEvents["Start"] = 'START';
43
- SnapStatusEvents["Stop"] = 'STOP';
44
- SnapStatusEvents["Crash"] = 'CRASH';
45
- SnapStatusEvents["Update"] = 'UPDATE';
46
- })(SnapStatusEvents || (SnapStatusEvents = {}));
47
- /**
48
- * An error indicating that a Snap validation failure is programmatically
49
- * fixable during development.
50
- */ export class ProgrammaticallyFixableSnapError extends Error {
51
- constructor(message, reason){
52
- super(message);
53
- _define_property(this, "reason", void 0);
54
- this.reason = reason;
55
- }
56
- }
57
- /**
58
- * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.
59
- *
60
- * @param manifest - The manifest itself.
61
- * @returns A virtual file containing the checksummable manifest.
62
- */ function getChecksummableManifest(manifest) {
63
- const manifestCopy = manifest.clone();
64
- delete manifestCopy.result.source.shasum;
65
- // We use fast-json-stable-stringify to deterministically serialize the JSON
66
- // This is required before checksumming so we get reproducible checksums across platforms etc
67
- manifestCopy.value = stableStringify(manifestCopy.result);
68
- return manifestCopy;
69
- }
70
- /**
71
- * Calculates the Base64-encoded SHA-256 digest of all required Snap files.
72
- *
73
- * @param files - All required Snap files to be included in the checksum.
74
- * @returns The Base64-encoded SHA-256 digest of the source code.
75
- */ export function getSnapChecksum(files) {
76
- const { manifest, sourceCode, svgIcon } = files;
77
- const all = [
78
- getChecksummableManifest(manifest),
79
- sourceCode,
80
- svgIcon
81
- ].filter((file)=>file !== undefined);
82
- return base64.encode(checksumFiles(all));
83
- }
84
- /**
85
- * Checks whether the `source.shasum` property of a Snap manifest matches the
86
- * shasum of the snap.
87
- *
88
- * @param files - All required Snap files to be included in the checksum.
89
- * @param errorMessage - The error message to throw if validation fails.
90
- */ export function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
91
- if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {
92
- throw new ProgrammaticallyFixableSnapError(errorMessage, SnapValidationFailureReason.ShasumMismatch);
93
- }
94
- }
95
- export const LOCALHOST_HOSTNAMES = [
96
- 'localhost',
97
- '127.0.0.1',
98
- '[::1]'
99
- ];
100
- // Require snap ids to only consist of printable ASCII characters
101
- export const BaseSnapIdStruct = pattern(string(), /^[\x21-\x7E]*$/u);
102
- const LocalSnapIdSubUrlStruct = uri({
103
- protocol: enums([
104
- 'http:',
105
- 'https:'
106
- ]),
107
- hostname: enums(LOCALHOST_HOSTNAMES),
108
- hash: empty(string()),
109
- search: empty(string())
110
- });
111
- export const LocalSnapIdStruct = refine(BaseSnapIdStruct, 'local Snap Id', (value)=>{
112
- if (!value.startsWith(SnapIdPrefixes.local)) {
113
- return `Expected local snap ID, got "${value}".`;
114
- }
115
- const [error] = validate(value.slice(SnapIdPrefixes.local.length), LocalSnapIdSubUrlStruct);
116
- return error ?? true;
117
- });
118
- export const NpmSnapIdStruct = intersection([
119
- BaseSnapIdStruct,
120
- uri({
121
- protocol: literal(SnapIdPrefixes.npm),
122
- pathname: refine(string(), 'package name', function*(value) {
123
- const normalized = value.startsWith('/') ? value.slice(1) : value;
124
- const { errors, validForNewPackages, warnings } = validateNPMPackage(normalized);
125
- if (!validForNewPackages) {
126
- if (errors === undefined) {
127
- assert(warnings !== undefined);
128
- yield* warnings;
129
- } else {
130
- yield* errors;
131
- }
132
- }
133
- return true;
134
- }),
135
- search: empty(string()),
136
- hash: empty(string())
137
- })
138
- ]);
139
- export const HttpSnapIdStruct = intersection([
140
- BaseSnapIdStruct,
141
- uri({
142
- protocol: enums([
143
- 'http:',
144
- 'https:'
145
- ]),
146
- search: empty(string()),
147
- hash: empty(string())
148
- })
149
- ]);
150
- export const SnapIdStruct = union([
151
- NpmSnapIdStruct,
152
- LocalSnapIdStruct
153
- ]);
154
- /**
155
- * Extracts the snap prefix from a snap ID.
156
- *
157
- * @param snapId - The snap ID to extract the prefix from.
158
- * @returns The snap prefix from a snap id, e.g. `npm:`.
159
- */ export function getSnapPrefix(snapId) {
160
- const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix)=>snapId.startsWith(possiblePrefix));
161
- if (prefix !== undefined) {
162
- return prefix;
163
- }
164
- throw new Error(`Invalid or no prefix found for "${snapId}"`);
165
- }
166
- /**
167
- * Strips snap prefix from a full snap ID.
168
- *
169
- * @param snapId - The snap ID to strip.
170
- * @returns The stripped snap ID.
171
- */ export function stripSnapPrefix(snapId) {
172
- return snapId.replace(getSnapPrefix(snapId), '');
173
- }
174
- /**
175
- * Assert that the given value is a valid snap ID.
176
- *
177
- * @param value - The value to check.
178
- * @throws If the value is not a valid snap ID.
179
- */ export function assertIsValidSnapId(value) {
180
- assertStruct(value, SnapIdStruct, 'Invalid snap ID');
181
- }
182
- /**
183
- * Typeguard to ensure a chainId follows the CAIP-2 standard.
184
- *
185
- * @param chainId - The chainId being tested.
186
- * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.
187
- */ export function isCaipChainId(chainId) {
188
- return typeof chainId === 'string' && RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u").test(chainId);
189
- }
190
- /**
191
- * Utility function to check if an origin has permission (and caveat) for a particular snap.
192
- *
193
- * @param permissions - An origin's permissions object.
194
- * @param snapId - The id of the snap.
195
- * @returns A boolean based on if an origin has the specified snap.
196
- */ export function isSnapPermitted(permissions, snapId) {
197
- return Boolean((permissions?.wallet_snap?.caveats?.find((caveat)=>caveat.type === SnapCaveatType.SnapIds) ?? {}).value?.[snapId]);
198
- }
199
- /**
200
- * Checks whether the passed in requestedPermissions is a valid
201
- * permission request for a `wallet_snap` permission.
202
- *
203
- * @param requestedPermissions - The requested permissions.
204
- * @throws If the criteria is not met.
205
- */ export function verifyRequestedSnapPermissions(requestedPermissions) {
206
- assert(isObject(requestedPermissions), 'Requested permissions must be an object.');
207
- const { wallet_snap: walletSnapPermission } = requestedPermissions;
208
- assert(isObject(walletSnapPermission), 'wallet_snap is missing from the requested permissions.');
209
- const { caveats } = walletSnapPermission;
210
- assert(Array.isArray(caveats) && caveats.length === 1, 'wallet_snap must have a caveat property with a single-item array value.');
211
- const [caveat] = caveats;
212
- assert(isObject(caveat) && caveat.type === SnapCaveatType.SnapIds && isObject(caveat.value), `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`);
213
- }
214
-
215
- //# sourceMappingURL=snaps.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\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/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAOA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AAErC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,aAAa,QAAQ,aAAa;AAG3C,SAASC,cAAc,EAAEC,2BAA2B,EAAEC,GAAG,QAAQ,UAAU;AA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MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC4B,OAAO,GAAGD;IAEjBhG,OACEC,SAASgG,WACPA,OAAOC,IAAI,KAAKnF,eAAeoF,OAAO,IACtClG,SAASgG,OAAOrD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAeoF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
@@ -1,11 +0,0 @@
1
- /**
2
- * Indent a message by adding a number of spaces to the beginning of each line.
3
- *
4
- * @param message - The message to indent.
5
- * @param spaces - The number of spaces to indent by. Defaults to 2.
6
- * @returns The indented message.
7
- */ export function indent(message, spaces = 2) {
8
- return message.replace(/^/gmu, ' '.repeat(spaces));
9
- }
10
-
11
- //# sourceMappingURL=strings.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/strings.ts"],"sourcesContent":["/**\n * Indent a message by adding a number of spaces to the beginning of each line.\n *\n * @param message - The message to indent.\n * @param spaces - The number of spaces to indent by. Defaults to 2.\n * @returns The indented message.\n */\nexport function indent(message: string, spaces = 2) {\n return message.replace(/^/gmu, ' '.repeat(spaces));\n}\n"],"names":["indent","message","spaces","replace","repeat"],"mappings":"AAAA;;;;;;CAMC,GACD,OAAO,SAASA,OAAOC,OAAe,EAAEC,SAAS,CAAC;IAChD,OAAOD,QAAQE,OAAO,CAAC,QAAQ,IAAIC,MAAM,CAACF;AAC5C"}
@@ -1,230 +0,0 @@
1
- import { isObject } from '@metamask/utils';
2
- import { bold, green, red } from 'chalk';
3
- import { resolve } from 'path';
4
- import { Struct, StructError, define, literal as superstructLiteral, union as superstructUnion, create, string, coerce } from 'superstruct';
5
- import { indent } from './strings';
6
- /**
7
- * A wrapper of `superstruct`'s `literal` struct that also defines the name of
8
- * the struct as the literal value.
9
- *
10
- * This is useful for improving the error messages returned by `superstruct`.
11
- * For example, instead of returning an error like:
12
- *
13
- * ```
14
- * Expected the value to satisfy a union of `literal | literal`, but received: \"baz\"
15
- * ```
16
- *
17
- * This struct will return an error like:
18
- *
19
- * ```
20
- * Expected the value to satisfy a union of `"foo" | "bar"`, but received: \"baz\"
21
- * ```
22
- *
23
- * @param value - The literal value.
24
- * @returns The `superstruct` struct, which validates that the value is equal
25
- * to the literal value.
26
- */ export function literal(value) {
27
- return define(JSON.stringify(value), superstructLiteral(value).validator);
28
- }
29
- /**
30
- * A wrapper of `superstruct`'s `union` struct that also defines the schema as
31
- * the union of the schemas of the structs.
32
- *
33
- * This is useful for improving the error messages returned by `superstruct`.
34
- *
35
- * @param structs - The structs to union.
36
- * @param structs."0" - The first struct.
37
- * @param structs."1" - The remaining structs.
38
- * @returns The `superstruct` struct, which validates that the value satisfies
39
- * one of the structs.
40
- */ export function union([head, ...tail]) {
41
- const struct = superstructUnion([
42
- head,
43
- ...tail
44
- ]);
45
- return new Struct({
46
- ...struct,
47
- schema: [
48
- head,
49
- ...tail
50
- ]
51
- });
52
- }
53
- /**
54
- * A wrapper of `superstruct`'s `string` struct that coerces a value to a string
55
- * and resolves it relative to the current working directory. This is useful
56
- * for specifying file paths in a configuration file, as it allows the user to
57
- * use both relative and absolute paths.
58
- *
59
- * @returns The `superstruct` struct, which validates that the value is a
60
- * string, and resolves it relative to the current working directory.
61
- * @example
62
- * ```ts
63
- * const config = struct({
64
- * file: file(),
65
- * // ...
66
- * });
67
- *
68
- * const value = create({ file: 'path/to/file' }, config);
69
- * console.log(value.file); // /process/cwd/path/to/file
70
- * ```
71
- */ export function file() {
72
- return coerce(string(), string(), (value)=>{
73
- return resolve(process.cwd(), value);
74
- });
75
- }
76
- /**
77
- * Define a struct, and also define the name of the struct as the given name.
78
- *
79
- * This is useful for improving the error messages returned by `superstruct`.
80
- *
81
- * @param name - The name of the struct.
82
- * @param struct - The struct.
83
- * @returns The struct.
84
- */ export function named(name, struct) {
85
- return new Struct({
86
- ...struct,
87
- type: name
88
- });
89
- }
90
- export class SnapsStructError extends StructError {
91
- constructor(struct, prefix, suffix, failure, failures){
92
- super(failure, failures);
93
- this.name = 'SnapsStructError';
94
- this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
95
- ...failures()
96
- ])}${suffix ? `\n\n${suffix}` : ''}`;
97
- }
98
- }
99
- /**
100
- * Converts an array to a generator function that yields the items in the
101
- * array.
102
- *
103
- * @param array - The array.
104
- * @returns A generator function.
105
- * @yields The items in the array.
106
- */ export function* arrayToGenerator(array) {
107
- for (const item of array){
108
- yield item;
109
- }
110
- }
111
- /**
112
- * Returns a `SnapsStructError` with the given prefix and suffix.
113
- *
114
- * @param options - The options.
115
- * @param options.struct - The struct that caused the error.
116
- * @param options.prefix - The prefix to add to the error message.
117
- * @param options.suffix - The suffix to add to the error message. Defaults to
118
- * an empty string.
119
- * @param options.error - The `superstruct` error to wrap.
120
- * @returns The `SnapsStructError`.
121
- */ export function getError({ struct, prefix, suffix = '', error }) {
122
- return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
123
- }
124
- /**
125
- * A wrapper of `superstruct`'s `create` function that throws a
126
- * `SnapsStructError` instead of a `StructError`. This is useful for improving
127
- * the error messages returned by `superstruct`.
128
- *
129
- * @param value - The value to validate.
130
- * @param struct - The `superstruct` struct to validate the value against.
131
- * @param prefix - The prefix to add to the error message.
132
- * @param suffix - The suffix to add to the error message. Defaults to an empty
133
- * string.
134
- * @returns The validated value.
135
- */ export function createFromStruct(value, struct, prefix, suffix = '') {
136
- try {
137
- return create(value, struct);
138
- } catch (error) {
139
- if (error instanceof StructError) {
140
- throw getError({
141
- struct,
142
- prefix,
143
- suffix,
144
- error
145
- });
146
- }
147
- throw error;
148
- }
149
- }
150
- /**
151
- * Get a struct from a failure path.
152
- *
153
- * @param struct - The struct.
154
- * @param path - The failure path.
155
- * @returns The struct at the failure path.
156
- */ export function getStructFromPath(struct, path) {
157
- return path.reduce((result, key)=>{
158
- if (isObject(struct.schema) && struct.schema[key]) {
159
- return struct.schema[key];
160
- }
161
- return result;
162
- }, struct);
163
- }
164
- /**
165
- * Get the union struct names from a struct.
166
- *
167
- * @param struct - The struct.
168
- * @returns The union struct names, or `null` if the struct is not a union
169
- * struct.
170
- */ export function getUnionStructNames(struct) {
171
- if (Array.isArray(struct.schema)) {
172
- return struct.schema.map(({ type })=>green(type));
173
- }
174
- return null;
175
- }
176
- /**
177
- * Get a error prefix from a `superstruct` failure. This is useful for
178
- * formatting the error message returned by `superstruct`.
179
- *
180
- * @param failure - The `superstruct` failure.
181
- * @returns The error prefix.
182
- */ export function getStructErrorPrefix(failure) {
183
- if (failure.type === 'never' || failure.path.length === 0) {
184
- return '';
185
- }
186
- return `At path: ${bold(failure.path.join('.'))} — `;
187
- }
188
- /**
189
- * Get a string describing the failure. This is similar to the `message`
190
- * property of `superstruct`'s `Failure` type, but formats the value in a more
191
- * readable way.
192
- *
193
- * @param struct - The struct that caused the failure.
194
- * @param failure - The `superstruct` failure.
195
- * @returns A string describing the failure.
196
- */ export function getStructFailureMessage(struct, failure) {
197
- const received = red(JSON.stringify(failure.value));
198
- const prefix = getStructErrorPrefix(failure);
199
- if (failure.type === 'union') {
200
- const childStruct = getStructFromPath(struct, failure.path);
201
- const unionNames = getUnionStructNames(childStruct);
202
- if (unionNames) {
203
- return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
204
- }
205
- return `${prefix}${failure.message}.`;
206
- }
207
- if (failure.type === 'literal') {
208
- // Superstruct's failure does not provide information about which literal
209
- // value was expected, so we need to parse the message to get the literal.
210
- const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${green('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);
211
- return `${prefix}${message}.`;
212
- }
213
- if (failure.type === 'never') {
214
- return `Unknown key: ${bold(failure.path.join('.'))}, received: ${received}.`;
215
- }
216
- return `${prefix}Expected a value of type ${green(failure.type)}, but received: ${received}.`;
217
- }
218
- /**
219
- * Get a string describing the errors. This formats all the errors in a
220
- * human-readable way.
221
- *
222
- * @param struct - The struct that caused the failures.
223
- * @param failures - The `superstruct` failures.
224
- * @returns A string describing the errors.
225
- */ export function getStructErrorMessage(struct, failures) {
226
- const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure)}`));
227
- return formattedFailures.join('\n');
228
- }
229
-
230
- //# sourceMappingURL=structs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["isObject","bold","green","red","resolve","Struct","StructError","define","literal","superstructLiteral","union","superstructUnion","create","string","coerce","indent","value","JSON","stringify","validator","head","tail","struct","schema","file","process","cwd","named","name","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SACEC,MAAM,EACNC,WAAW,EACXC,MAAM,EACNC,WAAWC,kBAAkB,EAC7BC,SAASC,gBAAgB,EACzBC,MAAM,EACNC,MAAM,EACNC,MAAM,QACD,cAAc;AAGrB,SAASC,MAAM,QAAQ,YAAY;AAEnC;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASP,QAAgDQ,KAAW;IACzE,OAAOT,OACLU,KAAKC,SAAS,CAACF,QACfP,mBAAmBO,OAAOG,SAAS;AAEvC;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAAST,MAAwD,CACtEU,MACA,GAAGC,KACyB;IAI5B,MAAMC,SAASX,iBAAiB;QAACS;WAASC;KAAK;IAE/C,OAAO,IAAIhB,OAAO;QAChB,GAAGiB,MAAM;QACTC,QAAQ;YAACH;eAASC;SAAK;IACzB;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASG;IACd,OAAOV,OAAOD,UAAUA,UAAU,CAACG;QACjC,OAAOZ,QAAQqB,QAAQC,GAAG,IAAIV;IAChC;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASW,MACdC,IAAY,EACZN,MAA4B;IAE5B,OAAO,IAAIjB,OAAO;QAChB,GAAGiB,MAAM;QACTO,MAAMD;IACR;AACF;AAEA,OAAO,MAAME,yBAAuCxB;IAClDyB,YACET,MAA4B,EAC5BU,MAAc,EACdC,MAAc,EACdC,OAAoB,EACpBC,QAAkC,CAClC;QACA,KAAK,CAACD,SAASC;QAEf,IAAI,CAACP,IAAI,GAAG;QACZ,IAAI,CAACQ,OAAO,GAAG,CAAC,EAAEJ,OAAO,KAAK,EAAEK,sBAAsBf,QAAQ;eACz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