@metamask/snaps-utils 7.7.0 → 7.8.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 (210) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/auxiliary-files.js +8 -5
  3. package/dist/auxiliary-files.mjs +9 -6
  4. package/dist/base64.js +4 -4
  5. package/dist/base64.mjs +3 -3
  6. package/dist/bytes.js +3 -3
  7. package/dist/bytes.mjs +2 -2
  8. package/dist/checksum.js +4 -4
  9. package/dist/checksum.mjs +3 -3
  10. package/dist/{chunk-7LOVOG6X.js → chunk-25ESL4NL.js} +27 -27
  11. package/dist/{chunk-6YRUDGNL.mjs → chunk-3S4INAGA.mjs} +2 -2
  12. package/dist/{chunk-I4TRH6VO.mjs → chunk-4AA3TKRJ.mjs} +2 -2
  13. package/dist/chunk-4AA3TKRJ.mjs.map +1 -0
  14. package/dist/{chunk-2LBN5T56.js → chunk-4ZJOU3LR.js} +9 -2
  15. package/dist/chunk-4ZJOU3LR.js.map +1 -0
  16. package/dist/{chunk-ZJKG5Q2C.js → chunk-5I5WPAVD.js} +20 -20
  17. package/dist/chunk-5I5WPAVD.js.map +1 -0
  18. package/dist/chunk-5WKQI22S.js +7 -0
  19. package/dist/chunk-5WKQI22S.js.map +1 -0
  20. package/dist/{chunk-J5B5YRG5.js → chunk-6ATNGN44.js} +35 -2
  21. package/dist/chunk-6ATNGN44.js.map +1 -0
  22. package/dist/{chunk-G6BVXNNZ.js → chunk-6HXIPMBN.js} +3 -3
  23. package/dist/{chunk-5ZIWKLVB.mjs → chunk-7HLSXEHK.mjs} +35 -2
  24. package/dist/chunk-7HLSXEHK.mjs.map +1 -0
  25. package/dist/{chunk-T6FWIDA6.mjs → chunk-AJNKQYKP.mjs} +3 -3
  26. package/dist/chunk-AJNKQYKP.mjs.map +1 -0
  27. package/dist/{chunk-MLOQHUOY.js → chunk-AMW2VJ3N.js} +3 -3
  28. package/dist/{chunk-K2OTEZZZ.mjs → chunk-ANYNWSCA.mjs} +11 -4
  29. package/dist/chunk-ANYNWSCA.mjs.map +1 -0
  30. package/dist/{chunk-R5DO7T2D.js → chunk-B5GNTDE2.js} +2 -2
  31. package/dist/chunk-B5GNTDE2.js.map +1 -0
  32. package/dist/{chunk-WZ457PEQ.mjs → chunk-CJK7DDV2.mjs} +2 -2
  33. package/dist/chunk-CJK7DDV2.mjs.map +1 -0
  34. package/dist/{chunk-ZJRWU4AJ.mjs → chunk-DE22V5AO.mjs} +4 -1
  35. package/dist/{chunk-ZJRWU4AJ.mjs.map → chunk-DE22V5AO.mjs.map} +1 -1
  36. package/dist/{chunk-HJYRGKCX.js → chunk-DEQUNIME.js} +4 -1
  37. package/dist/chunk-DEQUNIME.js.map +1 -0
  38. package/dist/chunk-F6G67XQ4.js +1 -0
  39. package/dist/{chunk-KSRDEGBC.js → chunk-FBZ5SU7X.js} +11 -1
  40. package/dist/chunk-FBZ5SU7X.js.map +1 -0
  41. package/dist/{chunk-NHGIT2SZ.mjs → chunk-FLSK6ISS.mjs} +6 -6
  42. package/dist/chunk-FLSK6ISS.mjs.map +1 -0
  43. package/dist/{chunk-YCIPY3UP.mjs → chunk-H35ZUVQT.mjs} +7 -7
  44. package/dist/chunk-H35ZUVQT.mjs.map +1 -0
  45. package/dist/{chunk-IPOE62V4.js → chunk-I2SWLZ34.js} +2 -2
  46. package/dist/chunk-I2SWLZ34.js.map +1 -0
  47. package/dist/{chunk-X3XJN63W.mjs → chunk-IELPPZJP.mjs} +11 -1
  48. package/dist/chunk-IELPPZJP.mjs.map +1 -0
  49. package/dist/{chunk-FOWIC2SO.mjs → chunk-JJTIVHFX.mjs} +2 -2
  50. package/dist/{chunk-NN2HXPZN.mjs → chunk-KCECQM3L.mjs} +11 -11
  51. package/dist/{chunk-EXUEHPZ4.mjs → chunk-LHQP7CUJ.mjs} +2 -2
  52. package/dist/chunk-LHQP7CUJ.mjs.map +1 -0
  53. package/dist/{chunk-6LOYTBS3.js → chunk-LOJA2ZS4.js} +2 -2
  54. package/dist/chunk-LOJA2ZS4.js.map +1 -0
  55. package/dist/{chunk-QSCKTRRU.js → chunk-MKFQAXRF.js} +3 -3
  56. package/dist/{chunk-UMZNVWEM.mjs → chunk-N5HVDE3P.mjs} +2 -2
  57. package/dist/chunk-N5HVDE3P.mjs.map +1 -0
  58. package/dist/{chunk-IHQPAJ2B.js → chunk-OBN2WDFU.js} +3 -3
  59. package/dist/chunk-OYZPBNHS.mjs +1 -0
  60. package/dist/chunk-PLNIERDY.js +34 -0
  61. package/dist/chunk-PLNIERDY.js.map +1 -0
  62. package/dist/{chunk-CMOSYNZR.js → chunk-PZNIU23I.js} +3 -3
  63. package/dist/chunk-PZNIU23I.js.map +1 -0
  64. package/dist/{chunk-K4B37F3L.js → chunk-RD6BN2TQ.js} +12 -12
  65. package/dist/chunk-RD6BN2TQ.js.map +1 -0
  66. package/dist/{chunk-F72OSQD6.js → chunk-SB43G2RI.js} +8 -8
  67. package/dist/chunk-SPCIIRSB.mjs +7 -0
  68. package/dist/chunk-SPCIIRSB.mjs.map +1 -0
  69. package/dist/{chunk-37VHIRUJ.js → chunk-T2VA4YJE.js} +11 -4
  70. package/dist/chunk-T2VA4YJE.js.map +1 -0
  71. package/dist/{chunk-473MIETW.js → chunk-UAINMOUU.js} +3 -3
  72. package/dist/chunk-VIAHMNTA.mjs +34 -0
  73. package/dist/chunk-VIAHMNTA.mjs.map +1 -0
  74. package/dist/{chunk-HEXZ4DFV.js → chunk-VOPTAKVG.js} +4 -4
  75. package/dist/chunk-VOPTAKVG.js.map +1 -0
  76. package/dist/{chunk-OJM2SKJZ.js → chunk-X2GGUOMY.js} +2 -2
  77. package/dist/chunk-X2GGUOMY.js.map +1 -0
  78. package/dist/{chunk-LBCPJOAV.mjs → chunk-X3UZCGO5.mjs} +2 -2
  79. package/dist/{chunk-HJRCBSNA.mjs → chunk-XF2AZMWG.mjs} +2 -2
  80. package/dist/{chunk-VDJTPG6F.js → chunk-XWYJQWHG.js} +3 -3
  81. package/dist/{chunk-PWLXPALG.mjs → chunk-XZ7362GQ.mjs} +2 -2
  82. package/dist/{chunk-IGMAXVPP.mjs → chunk-XZNJFDBF.mjs} +2 -2
  83. package/dist/{chunk-EA2FOAEG.mjs → chunk-YJHQZFR4.mjs} +9 -2
  84. package/dist/chunk-YJHQZFR4.mjs.map +1 -0
  85. package/dist/{chunk-BT2AEFEP.mjs → chunk-YNOZU43P.mjs} +6 -6
  86. package/dist/{chunk-EXEEDJ6N.mjs → chunk-ZXHR322P.mjs} +19 -19
  87. package/dist/chunk-ZXHR322P.mjs.map +1 -0
  88. package/dist/constants.js +8 -0
  89. package/dist/constants.js.map +1 -0
  90. package/dist/constants.mjs +8 -0
  91. package/dist/constants.mjs.map +1 -0
  92. package/dist/cronjob.js +2 -2
  93. package/dist/cronjob.mjs +1 -1
  94. package/dist/derivation-paths.js +2 -2
  95. package/dist/derivation-paths.mjs +1 -1
  96. package/dist/eval-worker.js +1 -1
  97. package/dist/eval-worker.mjs +1 -1
  98. package/dist/eval.js +5 -5
  99. package/dist/eval.mjs +4 -4
  100. package/dist/fs.js +4 -4
  101. package/dist/fs.mjs +3 -3
  102. package/dist/handlers.js +2 -2
  103. package/dist/handlers.mjs +1 -1
  104. package/dist/index.executionenv.js +4 -4
  105. package/dist/index.executionenv.mjs +15 -15
  106. package/dist/index.js +38 -30
  107. package/dist/index.mjs +75 -67
  108. package/dist/json-rpc.js +2 -2
  109. package/dist/json-rpc.mjs +1 -1
  110. package/dist/localization.js +2 -2
  111. package/dist/localization.mjs +1 -1
  112. package/dist/manifest/index.js +11 -11
  113. package/dist/manifest/index.mjs +10 -10
  114. package/dist/manifest/manifest.js +15 -15
  115. package/dist/manifest/manifest.mjs +14 -14
  116. package/dist/manifest/node.js +15 -15
  117. package/dist/manifest/node.mjs +14 -14
  118. package/dist/manifest/validation.js +11 -11
  119. package/dist/manifest/validation.mjs +10 -10
  120. package/dist/namespace.js +2 -2
  121. package/dist/namespace.mjs +1 -1
  122. package/dist/node.js +42 -34
  123. package/dist/node.mjs +79 -71
  124. package/dist/npm.js +15 -15
  125. package/dist/npm.mjs +14 -14
  126. package/dist/snaps.js +6 -6
  127. package/dist/snaps.mjs +5 -5
  128. package/dist/structs.js +2 -2
  129. package/dist/structs.mjs +1 -1
  130. package/dist/tsconfig.build.tsbuildinfo +1 -1
  131. package/dist/types/auxiliary-files.d.ts +7 -0
  132. package/dist/types/constants.d.ts +1 -0
  133. package/dist/types/cronjob.d.ts +22 -22
  134. package/dist/types/handlers.d.ts +39 -39
  135. package/dist/types/index.d.ts +1 -0
  136. package/dist/types/json-rpc.d.ts +7 -7
  137. package/dist/types/localization.d.ts +4 -4
  138. package/dist/types/manifest/validation.d.ts +1 -1
  139. package/dist/types/namespace.d.ts +18 -18
  140. package/dist/types/snaps.d.ts +1 -1
  141. package/dist/types/structs.d.ts +2 -3
  142. package/dist/types/types.d.ts +1 -1
  143. package/dist/types/ui.d.ts +10 -1
  144. package/dist/types/virtual-file/VirtualFile.d.ts +1 -0
  145. package/dist/types.js +2 -2
  146. package/dist/types.mjs +1 -1
  147. package/dist/ui.js +4 -2
  148. package/dist/ui.mjs +3 -1
  149. package/dist/validation.js +13 -13
  150. package/dist/validation.mjs +12 -12
  151. package/dist/versions.js +2 -2
  152. package/dist/versions.mjs +1 -1
  153. package/dist/virtual-file/VirtualFile.js +2 -2
  154. package/dist/virtual-file/VirtualFile.mjs +1 -1
  155. package/dist/virtual-file/index.js +2 -2
  156. package/dist/virtual-file/index.mjs +1 -1
  157. package/dist/virtual-file/node.js +3 -3
  158. package/dist/virtual-file/node.mjs +2 -2
  159. package/dist/virtual-file/toVirtualFile.js +3 -3
  160. package/dist/virtual-file/toVirtualFile.mjs +2 -2
  161. package/package.json +9 -9
  162. package/dist/chunk-2LBN5T56.js.map +0 -1
  163. package/dist/chunk-37VHIRUJ.js.map +0 -1
  164. package/dist/chunk-5ZIWKLVB.mjs.map +0 -1
  165. package/dist/chunk-6LOYTBS3.js.map +0 -1
  166. package/dist/chunk-7LOABHVW.js +0 -1
  167. package/dist/chunk-7MTAHOWC.mjs +0 -1
  168. package/dist/chunk-CMOSYNZR.js.map +0 -1
  169. package/dist/chunk-EA2FOAEG.mjs.map +0 -1
  170. package/dist/chunk-EXEEDJ6N.mjs.map +0 -1
  171. package/dist/chunk-EXUEHPZ4.mjs.map +0 -1
  172. package/dist/chunk-HEXZ4DFV.js.map +0 -1
  173. package/dist/chunk-HJYRGKCX.js.map +0 -1
  174. package/dist/chunk-I4TRH6VO.mjs.map +0 -1
  175. package/dist/chunk-IPOE62V4.js.map +0 -1
  176. package/dist/chunk-IXBJNVHK.js +0 -22
  177. package/dist/chunk-IXBJNVHK.js.map +0 -1
  178. package/dist/chunk-J5B5YRG5.js.map +0 -1
  179. package/dist/chunk-K2OTEZZZ.mjs.map +0 -1
  180. package/dist/chunk-K4B37F3L.js.map +0 -1
  181. package/dist/chunk-KMLVVVK3.mjs +0 -22
  182. package/dist/chunk-KMLVVVK3.mjs.map +0 -1
  183. package/dist/chunk-KSRDEGBC.js.map +0 -1
  184. package/dist/chunk-NHGIT2SZ.mjs.map +0 -1
  185. package/dist/chunk-OJM2SKJZ.js.map +0 -1
  186. package/dist/chunk-R5DO7T2D.js.map +0 -1
  187. package/dist/chunk-T6FWIDA6.mjs.map +0 -1
  188. package/dist/chunk-UMZNVWEM.mjs.map +0 -1
  189. package/dist/chunk-WZ457PEQ.mjs.map +0 -1
  190. package/dist/chunk-X3XJN63W.mjs.map +0 -1
  191. package/dist/chunk-YCIPY3UP.mjs.map +0 -1
  192. package/dist/chunk-ZJKG5Q2C.js.map +0 -1
  193. /package/dist/{chunk-7LOVOG6X.js.map → chunk-25ESL4NL.js.map} +0 -0
  194. /package/dist/{chunk-6YRUDGNL.mjs.map → chunk-3S4INAGA.mjs.map} +0 -0
  195. /package/dist/{chunk-G6BVXNNZ.js.map → chunk-6HXIPMBN.js.map} +0 -0
  196. /package/dist/{chunk-MLOQHUOY.js.map → chunk-AMW2VJ3N.js.map} +0 -0
  197. /package/dist/{chunk-7LOABHVW.js.map → chunk-F6G67XQ4.js.map} +0 -0
  198. /package/dist/{chunk-FOWIC2SO.mjs.map → chunk-JJTIVHFX.mjs.map} +0 -0
  199. /package/dist/{chunk-NN2HXPZN.mjs.map → chunk-KCECQM3L.mjs.map} +0 -0
  200. /package/dist/{chunk-QSCKTRRU.js.map → chunk-MKFQAXRF.js.map} +0 -0
  201. /package/dist/{chunk-IHQPAJ2B.js.map → chunk-OBN2WDFU.js.map} +0 -0
  202. /package/dist/{chunk-7MTAHOWC.mjs.map → chunk-OYZPBNHS.mjs.map} +0 -0
  203. /package/dist/{chunk-F72OSQD6.js.map → chunk-SB43G2RI.js.map} +0 -0
  204. /package/dist/{chunk-473MIETW.js.map → chunk-UAINMOUU.js.map} +0 -0
  205. /package/dist/{chunk-LBCPJOAV.mjs.map → chunk-X3UZCGO5.mjs.map} +0 -0
  206. /package/dist/{chunk-HJRCBSNA.mjs.map → chunk-XF2AZMWG.mjs.map} +0 -0
  207. /package/dist/{chunk-PWLXPALG.mjs.map → chunk-XWYJQWHG.js.map} +0 -0
  208. /package/dist/{chunk-VDJTPG6F.js.map → chunk-XZ7362GQ.mjs.map} +0 -0
  209. /package/dist/{chunk-IGMAXVPP.mjs.map → chunk-XZNJFDBF.mjs.map} +0 -0
  210. /package/dist/{chunk-BT2AEFEP.mjs.map → chunk-YNOZU43P.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/structs.ts"],"sourcesContent":["import { union } from '@metamask/snaps-sdk';\nimport type {\n AnyStruct,\n Assign,\n Failure,\n ObjectSchema,\n ObjectType,\n} from '@metamask/superstruct';\nimport {\n assign,\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n} from '@metamask/superstruct';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * Colorize a value with a color function. This is useful for colorizing values\n * in error messages. If colorization is disabled, the original value is\n * returned.\n *\n * @param value - The value to colorize.\n * @param colorFunction - The color function to use.\n * @param enabled - Whether to colorize the value.\n * @returns The colorized value, or the original value if colorization is\n * disabled.\n */\nfunction color(\n value: string,\n colorFunction: (value: string) => string,\n enabled: boolean,\n) {\n if (enabled) {\n return colorFunction(value);\n }\n\n return value;\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 colorize = true,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(\n struct,\n [...failures()],\n colorize,\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 colorize?: boolean;\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 * @param options.colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n colorize,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(\n struct,\n prefix,\n suffix,\n error,\n () => arrayToGenerator(error.failures()),\n colorize,\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 * @param colorize - Whether to colorize the value. Defaults to `true`.\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 colorize = true,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => color(type, green, colorize));\n }\n\n return null;\n}\n\n/**\n * Get an 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 * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure, colorize = true) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;\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 * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n colorize = true,\n) {\n const received = color(JSON.stringify(failure.value), red, colorize);\n const prefix = getStructErrorPrefix(failure, colorize);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct, colorize);\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(\n /the literal `(.+)`,/u,\n `the value to be \\`${color('$1', green, colorize)}\\`,`,\n )\n .replace(\n /, but received: (.+)/u,\n `, but received: ${color('$1', red, colorize)}`,\n );\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${color(\n failure.path.join('.'),\n bold,\n colorize,\n )}, received: ${received}.`;\n }\n\n if (failure.refinement === 'size') {\n const message = failure.message\n .replace(\n /length between `(\\d+)` and `(\\d+)`/u,\n `length between ${color('$1', green, colorize)} and ${color(\n '$2',\n green,\n colorize,\n )},`,\n )\n .replace(/length of `(\\d+)`/u, `length of ${color('$1', red, colorize)}`)\n .replace(/a array/u, 'an array');\n\n return `${prefix}${message}.`;\n }\n\n return `${prefix}Expected a value of type ${color(\n failure.type,\n green,\n colorize,\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 * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n colorize = true,\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure, colorize)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n\n/**\n * Validate a union struct, and throw readable errors if the value does not\n * satisfy the struct. This is useful for improving the error messages returned\n * by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @param coerce - Whether to coerce the value to satisfy the struct. Defaults\n * to `false`.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @example\n * const struct = union([\n * object({ type: literal('a'), value: string() }),\n * object({ type: literal('b'), value: number() }),\n * object({ type: literal('c'), value: boolean() }),\n * // ...\n * ]);\n *\n * // At path: type — Expected the value to be one of: \"a\", \"b\", \"c\", but received: \"d\".\n * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');\n *\n * // At path: value — Expected a value of type string, but received: 42.\n * validateUnion({ type: 'a', value: 42 }, struct, 'value');\n */\nexport function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n coerce = false,\n) {\n assert(\n struct.schema,\n 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.',\n );\n assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');\n\n const keyUnion = struct.schema.map(\n (innerStruct) => innerStruct.schema[structKey],\n // This is guaranteed to be a non-empty array by the assertion above. We\n // need to cast it since `superstruct` requires a non-empty array of structs\n // for the `union` struct.\n ) as NonEmptyArray<Struct>;\n\n const key = superstructType({\n [structKey]: union(keyUnion),\n });\n\n const [keyError] = validate(value, key, { coerce });\n if (keyError) {\n throw new Error(\n getStructFailureMessage(key, keyError.failures()[0], false),\n );\n }\n\n // At this point it's guaranteed that the value is an object, so we can safely\n // cast it to a Record.\n const objectValue = value as Record<PropertyKey, unknown>;\n const objectStructs = struct.schema.filter((innerStruct) =>\n is(objectValue[structKey], innerStruct.schema[structKey]),\n );\n\n assert(objectStructs.length > 0, 'Expected a struct to match the value.');\n\n // We need to validate the value against all the object structs that match the\n // struct key, and return the first validated value.\n const validationResults = objectStructs.map((objectStruct) =>\n validate(objectValue, objectStruct, { coerce }),\n );\n\n const validatedValue = validationResults.find(([error]) => !error);\n if (validatedValue) {\n return validatedValue[1];\n }\n\n assert(validationResults[0][0], 'Expected at least one error.');\n\n // If there is no validated value, we need to find the error with the least\n // number of failures (with the assumption that it's the most specific error).\n const validationError = validationResults.reduce((error, [innerError]) => {\n assert(innerError, 'Expected an error.');\n if (innerError.failures().length < error.failures().length) {\n return innerError;\n }\n\n return error;\n }, validationResults[0][0]);\n\n throw new Error(\n getStructFailureMessage(struct, validationError.failures()[0], false),\n );\n}\n\n/**\n * Create a value with the coercion logic of a union struct, and throw readable\n * errors if the value does not satisfy the struct. 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` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @see validateUnion\n */\nexport function createUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n) {\n return validateUnion(value, struct, structKey, true);\n}\n\n// These types are copied from Superstruct, to mirror `assign`.\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n): Struct<ObjectType<Assign<ObjectA, ObjectB>>, Assign<ObjectA, ObjectB>>;\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n ObjectC extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n C: Struct<ObjectType<ObjectC>, ObjectC>,\n): Struct<\n ObjectType<Assign<Assign<ObjectA, ObjectB>, ObjectC>>,\n Assign<Assign<ObjectA, ObjectB>, ObjectC>\n>;\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n ObjectC extends ObjectSchema,\n ObjectD extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n C: Struct<ObjectType<ObjectC>, ObjectC>,\n D: Struct<ObjectType<ObjectD>, ObjectD>,\n): Struct<\n ObjectType<Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>>,\n Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>\n>;\nexport function mergeStructs<\n ObjectA extends ObjectSchema,\n ObjectB extends ObjectSchema,\n ObjectC extends ObjectSchema,\n ObjectD extends ObjectSchema,\n ObjectE extends ObjectSchema,\n>(\n A: Struct<ObjectType<ObjectA>, ObjectA>,\n B: Struct<ObjectType<ObjectB>, ObjectB>,\n C: Struct<ObjectType<ObjectC>, ObjectC>,\n D: Struct<ObjectType<ObjectD>, ObjectD>,\n E: Struct<ObjectType<ObjectE>, ObjectE>,\n): Struct<\n ObjectType<\n Assign<Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>, ObjectE>\n >,\n Assign<Assign<Assign<Assign<ObjectA, ObjectB>, ObjectC>, ObjectD>, ObjectE>\n>;\n\n/**\n * Merge multiple structs into one, using superstruct `assign`.\n *\n * Differently from plain `assign`, this function also copies over refinements from each struct.\n *\n * @param structs - The `superstruct` structs to merge.\n * @returns The merged struct.\n */\nexport function mergeStructs(...structs: Struct<any>[]): Struct<any> {\n const mergedStruct = (assign as (...structs: Struct<any>[]) => Struct)(\n ...structs,\n );\n return new Struct({\n ...mergedStruct,\n *refiner(value, ctx) {\n for (const struct of structs) {\n yield* struct.refiner(value, ctx);\n }\n },\n });\n}\n"],"mappings":";;;;;AAAA,SAAS,aAAa;AAQtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,QAAQ,gBAAgB;AACjC,SAAS,MAAM,OAAO,WAAW;AA0CjC,SAAS,MACP,OACA,eACA,SACA;AACA,MAAI,SAAS;AACX,WAAO,cAAc,KAAK;AAAA,EAC5B;AAEA,SAAO;AACT;AAWO,SAAS,MACd,MACA,QACA;AACA,SAAO,IAAI,OAAO;AAAA,IAChB,GAAG;AAAA,IACH,MAAM;AAAA,EACR,CAAC;AACH;AAEO,IAAM,mBAAN,cAA6C,YAAY;AAAA,EAC9D,YACE,QACA,QACA,QACA,SACA,UACA,WAAW,MACX;AACA,UAAM,SAAS,QAAQ;AAEvB,SAAK,OAAO;AACZ,SAAK,UAAU,GAAG,MAAM;AAAA;AAAA,EAAQ;AAAA,MAC9B;AAAA,MACA,CAAC,GAAG,SAAS,CAAC;AAAA,MACd;AAAA,IACF,CAAC,GAAG,SAAS;AAAA;AAAA,EAA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O,CAAC,UAAU,MAAM;AACxE,WAAO,YAAY,oBAAoB;AACvC,QAAI,WAAW,SAAS,EAAE,SAAS,MAAM,SAAS,EAAE,QAAQ;AAC1D,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,GAAG,kBAAkB,CAAC,EAAE,CAAC,CAAC;AAE1B,QAAM,IAAI;AAAA,IACR,wBAAwB,QAAQ,gBAAgB,SAAS,EAAE,CAAC,GAAG,KAAK;AAAA,EACtE;AACF;AAkBO,SAAS,YACd,OACA,QACA,WACA;AACA,SAAO,cAAc,OAAO,QAAQ,WAAW,IAAI;AACrD;AA+DO,SAAS,gBAAgB,SAAqC;AACnE,QAAM,eAAgB;AAAA,IACpB,GAAG;AAAA,EACL;AACA,SAAO,IAAI,OAAO;AAAA,IAChB,GAAG;AAAA,IACH,CAAC,QAAQ,OAAO,KAAK;AACnB,iBAAW,UAAU,SAAS;AAC5B,eAAO,OAAO,QAAQ,OAAO,GAAG;AAAA,MAClC;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -1,15 +1,12 @@
1
1
  import {
2
2
  SnapIdPrefixes,
3
3
  uri
4
- } from "./chunk-T6FWIDA6.mjs";
4
+ } from "./chunk-AJNKQYKP.mjs";
5
5
  import {
6
6
  checksumFiles
7
- } from "./chunk-HJRCBSNA.mjs";
7
+ } from "./chunk-XF2AZMWG.mjs";
8
8
 
9
9
  // src/snaps.ts
10
- import { assert, isObject, assertStruct } from "@metamask/utils";
11
- import { base64 } from "@scure/base";
12
- import stableStringify from "fast-json-stable-stringify";
13
10
  import {
14
11
  empty,
15
12
  enums,
@@ -20,7 +17,10 @@ import {
20
17
  string,
21
18
  union,
22
19
  validate
23
- } from "superstruct";
20
+ } from "@metamask/superstruct";
21
+ import { assert, isObject, assertStruct } from "@metamask/utils";
22
+ import { base64 } from "@scure/base";
23
+ import stableStringify from "fast-json-stable-stringify";
24
24
  import validateNPMPackage from "validate-npm-package-name";
25
25
  var 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;
26
26
  var SnapStatus = /* @__PURE__ */ ((SnapStatus2) => {
@@ -190,4 +190,4 @@ export {
190
190
  isSnapPermitted,
191
191
  verifyRequestedSnapPermissions
192
192
  };
193
- //# sourceMappingURL=chunk-YCIPY3UP.mjs.map
193
+ //# sourceMappingURL=chunk-H35ZUVQT.mjs.map
@@ -0,0 +1 @@
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 { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, 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\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: SnapId };\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 SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\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 * 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 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 /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\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 async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await 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 async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await 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});\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\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(value: unknown): asserts value is SnapId {\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\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"],"mappings":";;;;;;;;;AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,QAAQ,UAAU,oBAAoB;AAC/C,SAAS,cAAc;AACvB,OAAO,qBAAqB;AAC5B,OAAO,wBAAwB;AAuBxB,IAAM,sBACX;AAEK,IAAK,aAAL,kBAAKA,gBAAL;AACL,EAAAA,YAAA,gBAAa;AACb,EAAAA,YAAA,cAAW;AACX,EAAAA,YAAA,aAAU;AACV,EAAAA,YAAA,aAAU;AACV,EAAAA,YAAA,aAAU;AALA,SAAAA;AAAA,GAAA;AAQL,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,WAAQ;AACR,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,WAAQ;AACR,EAAAA,kBAAA,YAAS;AAJC,SAAAA;AAAA,GAAA;AA+GL,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAG1D,YAAY,SAAiB,QAAqC;AAChE,UAAM,OAAO;AACb,SAAK,SAAS;AAAA,EAChB;AACF;AAQA,SAAS,yBACP,UACa;AACb,QAAM,eAAe,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AAO;AAAA,IACrB,KAAK,CAAC,GACN,QACA,MAAM;AAAA,EACZ;AACF;AASO,SAAS,+BACd,sBACwD;AACxD;AAAA,IACE,SAAS,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,QAAM,EAAE,aAAa,qBAAqB,IAAI;AAE9C;AAAA,IACE,SAAS,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,QAAM,EAAE,QAAQ,IAAI;AAEpB;AAAA,IACE,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AAAA,IAC7C;AAAA,EACF;AAEA,QAAM,CAAC,MAAM,IAAI;AAEjB;AAAA,IACE,SAAS,MAAM,KACb,OAAO,oCACP,SAAS,OAAO,KAAK;AAAA,IACvB,wEAAuE;AAAA,EACzE;AACF;","names":["SnapStatus","SnapStatusEvents"]}
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/versions.ts
2
+ var _superstruct = require('@metamask/superstruct');
2
3
  var _utils = require('@metamask/utils');
3
4
  var _semver = require('semver');
4
- var _superstruct = require('superstruct');
5
5
  var DEFAULT_REQUESTED_SNAP_VERSION = "*";
6
6
  function getTargetVersion(versions, versionRange) {
7
7
  const maxSatisfyingNonPreRelease = _semver.maxSatisfying.call(void 0,
@@ -27,4 +27,4 @@ function resolveVersionRange(version) {
27
27
 
28
28
 
29
29
  exports.DEFAULT_REQUESTED_SNAP_VERSION = DEFAULT_REQUESTED_SNAP_VERSION; exports.getTargetVersion = getTargetVersion; exports.resolveVersionRange = resolveVersionRange;
30
- //# sourceMappingURL=chunk-IPOE62V4.js.map
30
+ //# sourceMappingURL=chunk-I2SWLZ34.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/versions.ts"],"names":[],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,0BAA0B;AACnC,SAAS,iBAAiB,2BAA2B;AAE9C,IAAM,iCAAiC;AAYvC,SAAS,iBACd,UACA,cACsB;AACtB,QAAM,6BAA6B;AAAA,IACjC;AAAA,IACA;AAAA,EACF;AAGA,MAAI,4BAA4B;AAC9B,WAAO;AAAA,EACT;AAGA,SAAO,oBAAoB,UAAU,cAAc;AAAA,IACjD,mBAAmB;AAAA,EACrB,CAAC;AACH;AASO,SAAS,oBACd,SAC2E;AAC3E,MAAI,YAAY,UAAa,YAAY,UAAU;AACjD,WAAO,CAAC,QAAW,8BAA8B;AAAA,EACnD;AACA,SAAO,SAAS,SAAS,kBAAkB;AAC7C","sourcesContent":["import { validate } from '@metamask/superstruct';\nimport type { Json, SemVerVersion, SemVerRange } from '@metamask/utils';\nimport { VersionRangeStruct } from '@metamask/utils';\nimport { maxSatisfying as maxSatisfyingSemver } from 'semver';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"]}
@@ -149,6 +149,16 @@ var SNAPS_DERIVATION_PATHS = [
149
149
  path: ["m", `1852'`, `1815'`],
150
150
  curve: "ed25519Bip32",
151
151
  name: "Cardano"
152
+ },
153
+ {
154
+ path: ["m", `44'`, `508'`, `0'`, `0'`, `0'`],
155
+ curve: "ed25519",
156
+ name: "MultiversX"
157
+ },
158
+ {
159
+ path: ["m", `44'`, `709'`],
160
+ curve: "secp256k1",
161
+ name: "Avail"
152
162
  }
153
163
  ];
154
164
  function getSnapDerivationPathName(path, curve) {
@@ -176,4 +186,4 @@ export {
176
186
  getSnapDerivationPathName,
177
187
  getSlip44ProtocolName
178
188
  };
179
- //# sourceMappingURL=chunk-X3XJN63W.mjs.map
189
+ //# sourceMappingURL=chunk-IELPPZJP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/derivation-paths.ts"],"sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport slip44 from '@metamask/slip44';\n\nimport { isEqual } from './array';\n\nexport type SnapsDerivationPath = {\n path: ['m', ...string[]];\n curve: SupportedCurve;\n name: string;\n};\n\nexport const SNAPS_DERIVATION_PATHS: SnapsDerivationPath[] = [\n {\n path: ['m', `44'`, `0'`],\n curve: 'ed25519',\n name: 'Test BIP-32 Path (ed25519)',\n },\n {\n path: ['m', `44'`, `1'`],\n curve: 'secp256k1',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Legacy',\n },\n {\n path: ['m', `49'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Nested SegWit',\n },\n {\n path: ['m', `49'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Nested SegWit',\n },\n {\n path: ['m', `84'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Native SegWit',\n },\n {\n path: ['m', `84'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Native SegWit',\n },\n {\n path: ['m', `44'`, `501'`],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `501'`, \"0'\", \"0'\"],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `2'`],\n curve: 'secp256k1',\n name: 'Litecoin',\n },\n {\n path: ['m', `44'`, `3'`],\n curve: 'secp256k1',\n name: 'Dogecoin',\n },\n {\n path: ['m', `44'`, `60'`],\n curve: 'secp256k1',\n name: 'Ethereum',\n },\n {\n path: ['m', `44'`, `118'`],\n curve: 'secp256k1',\n name: 'Atom',\n },\n {\n path: ['m', `44'`, `145'`],\n curve: 'secp256k1',\n name: 'Bitcoin Cash',\n },\n {\n path: ['m', `44'`, `637'`],\n curve: 'ed25519',\n name: 'Aptos',\n },\n {\n path: ['m', `44'`, `714'`],\n curve: 'secp256k1',\n name: 'Binance (BNB)',\n },\n {\n path: ['m', `44'`, `784'`],\n curve: 'ed25519',\n name: 'Sui',\n },\n {\n path: ['m', `44'`, `931'`],\n curve: 'secp256k1',\n name: 'THORChain (RUNE)',\n },\n {\n path: ['m', `44'`, `330'`],\n curve: 'secp256k1',\n name: 'Terra (LUNA)',\n },\n {\n path: ['m', `44'`, `459'`],\n curve: 'secp256k1',\n name: 'Kava',\n },\n {\n path: ['m', `44'`, `529'`],\n curve: 'secp256k1',\n name: 'Secret Network',\n },\n {\n path: ['m', `44'`, `397'`, `0'`],\n curve: 'ed25519',\n name: 'NEAR Protocol',\n },\n {\n path: ['m', `44'`, `1'`, `0'`],\n curve: 'ed25519',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `472'`],\n curve: 'ed25519',\n name: 'Arweave',\n },\n {\n path: ['m', `44'`, `12586'`],\n curve: 'secp256k1',\n name: 'Mina',\n },\n {\n path: ['m', `44'`, `242'`],\n curve: 'ed25519',\n name: 'Nimiq',\n },\n {\n path: ['m', `44'`, `1729'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'Tezos',\n },\n {\n path: ['m', `1789'`, `0'`],\n curve: 'ed25519',\n name: 'Vega',\n },\n {\n path: ['m', `1852'`, `1815'`],\n curve: 'ed25519Bip32',\n name: 'Cardano',\n },\n {\n path: ['m', `44'`, `508'`, `0'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'MultiversX',\n },\n {\n path: ['m', `44'`, `709'`],\n curve: 'secp256k1',\n name: 'Avail',\n },\n];\n\n/**\n * Gets the name of a derivation path supported by snaps.\n *\n * @param path - The derivation path.\n * @param curve - The curve used to derive the keys.\n * @returns The name of the derivation path, otherwise null.\n */\nexport function getSnapDerivationPathName(\n path: SnapsDerivationPath['path'],\n curve: SupportedCurve,\n): string | null {\n const pathMetadata = SNAPS_DERIVATION_PATHS.find(\n (derivationPath) =>\n derivationPath.curve === curve && isEqual(derivationPath.path, path),\n );\n\n if (pathMetadata) {\n return pathMetadata.name;\n }\n\n // If the curve is secp256k1 and the path is a valid BIP44 path\n // we try looking for the network/protocol name in SLIP44\n if (\n curve === 'secp256k1' &&\n path[0] === 'm' &&\n path[1] === `44'` &&\n path[2].endsWith(`'`)\n ) {\n const coinType = path[2].slice(0, -1);\n return getSlip44ProtocolName(coinType) ?? null;\n }\n\n return null;\n}\n\n/**\n * Gets the name of the SLIP-44 protocol corresponding to the specified\n * `coin_type`.\n *\n * @param coinType - The SLIP-44 `coin_type` value whose name\n * to retrieve.\n * @returns The name of the protocol, otherwise null.\n */\nexport function getSlip44ProtocolName(coinType: number | string) {\n if (String(coinType) === '1') {\n return 'Test Networks';\n }\n\n return slip44[coinType as keyof typeof slip44]?.name ?? null;\n}\n"],"mappings":";;;;;AACA,OAAO,YAAY;AAUZ,IAAM,yBAAgD;AAAA,EAC3D;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,IACvB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,IAAI;AAAA,I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S,IAAI;AAAA,IACzB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,SAAS,OAAO;AAAA,IAC5B,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,QAAQ,MAAM,MAAM,IAAI;AAAA,IAC3C,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM,CAAC,KAAK,OAAO,MAAM;AAAA,IACzB,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACF;AASO,SAAS,0BACd,MACA,OACe;AACf,QAAM,eAAe,uBAAuB;AAAA,IAC1C,CAAC,mBACC,eAAe,UAAU,SAAS,QAAQ,eAAe,MAAM,IAAI;AAAA,EACvE;AAEA,MAAI,cAAc;AAChB,WAAO,aAAa;AAAA,EACtB;AAIA,MACE,UAAU,eACV,KAAK,CAAC,MAAM,OACZ,KAAK,CAAC,MAAM,SACZ,KAAK,CAAC,EAAE,SAAS,GAAG,GACpB;AACA,UAAM,WAAW,KAAK,CAAC,EAAE,MAAM,GAAG,EAAE;AACpC,WAAO,sBAAsB,QAAQ,KAAK;AAAA,EAC5C;AAEA,SAAO;AACT;AAUO,SAAS,sBAAsB,UAA2B;AAC/D,MAAI,OAAO,QAAQ,MAAM,KAAK;AAC5B,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,QAA+B,GAAG,QAAQ;AAC1D;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getBytes
3
- } from "./chunk-6YRUDGNL.mjs";
3
+ } from "./chunk-3S4INAGA.mjs";
4
4
 
5
5
  // src/base64.ts
6
6
  import { bytesToBase64 } from "@metamask/utils";
@@ -35,4 +35,4 @@ export {
35
35
  encodeBase64,
36
36
  decodeBase64
37
37
  };
38
- //# sourceMappingURL=chunk-FOWIC2SO.mjs.map
38
+ //# sourceMappingURL=chunk-JJTIVHFX.mjs.map
@@ -1,11 +1,15 @@
1
1
  import {
2
2
  assertIsSnapManifest
3
- } from "./chunk-EXEEDJ6N.mjs";
3
+ } from "./chunk-ZXHR322P.mjs";
4
4
  import {
5
5
  ProgrammaticallyFixableSnapError,
6
6
  getSnapChecksum,
7
7
  validateSnapShasum
8
- } from "./chunk-YCIPY3UP.mjs";
8
+ } from "./chunk-H35ZUVQT.mjs";
9
+ import {
10
+ getValidatedLocalizationFiles,
11
+ validateSnapManifestLocalizations
12
+ } from "./chunk-CJK7DDV2.mjs";
9
13
  import {
10
14
  assertIsSnapIcon,
11
15
  getSvgDimensions
@@ -13,20 +17,16 @@ import {
13
17
  import {
14
18
  SnapValidationFailureReason,
15
19
  assertIsNpmSnapPackageJson
16
- } from "./chunk-T6FWIDA6.mjs";
17
- import {
18
- getValidatedLocalizationFiles,
19
- validateSnapManifestLocalizations
20
- } from "./chunk-WZ457PEQ.mjs";
20
+ } from "./chunk-AJNKQYKP.mjs";
21
21
  import {
22
22
  readJsonFile
23
- } from "./chunk-LBCPJOAV.mjs";
23
+ } from "./chunk-X3UZCGO5.mjs";
24
24
  import {
25
25
  readVirtualFile
26
- } from "./chunk-IGMAXVPP.mjs";
26
+ } from "./chunk-XZNJFDBF.mjs";
27
27
  import {
28
28
  VirtualFile
29
- } from "./chunk-ZJRWU4AJ.mjs";
29
+ } from "./chunk-DE22V5AO.mjs";
30
30
  import {
31
31
  deepClone
32
32
  } from "./chunk-Z2JQNSVL.mjs";
@@ -406,4 +406,4 @@ export {
406
406
  getWritableManifest,
407
407
  validateNpmSnapManifest
408
408
  };
409
- //# sourceMappingURL=chunk-NN2HXPZN.mjs.map
409
+ //# sourceMappingURL=chunk-KCECQM3L.mjs.map
@@ -8,7 +8,7 @@ import {
8
8
  pattern,
9
9
  size,
10
10
  string
11
- } from "superstruct";
11
+ } from "@metamask/superstruct";
12
12
  var CHAIN_ID_REGEX = /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;
13
13
  var ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
14
14
  var ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
@@ -104,4 +104,4 @@ export {
104
104
  isAccountIdArray,
105
105
  isNamespace
106
106
  };
107
- //# sourceMappingURL=chunk-EXUEHPZ4.mjs.map
107
+ //# sourceMappingURL=chunk-LHQP7CUJ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespace.ts"],"sourcesContent":["import type { AccountId, ChainId } from '@metamask/snaps-sdk';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n define,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from '@metamask/superstruct';\n\nimport type { InferMatching } from './structs';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\nexport const ChainIdStringStruct = define<ChainId>(\n 'Chain ID',\n string().validator,\n);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern<ChainId, null>(\n ChainIdStringStruct,\n CHAIN_ID_REGEX,\n);\n\nexport type Caip2ChainId = InferMatching<typeof ChainIdStruct, ChainId>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"mappings":";AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIA,IAAM,iBACX;AAEK,IAAM,mBACX;AAEK,IAAM,wBAAwB;AAS9B,SAAS,aAAa,SAG3B;AACA,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,mBAAmB;AAAA,EACrC;AAEA,SAAO;AAAA,IACL,WAAW,MAAM,OAAO;AAAA,IACxB,WAAW,MAAM,OAAO;AAAA,EAC1B;AACF;AASO,SAAS,eAAe,WAI7B;AACA,QAAM,QAAQ,iBAAiB,KAAK,SAAS;AAC7C,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,SAAO;AAAA,IACL,SAAS,MAAM,OAAO;AAAA,IACtB,SAAS,MAAM,OAAO;AAAA,IACtB,OAAO;AAAA,MACL,WAAW,MAAM,OAAO;AAAA,MACxB,WAAW,MAAM,OAAO;AAAA,IAC1B;AAAA,EACF;AACF;AAMO,IAAM,gBAAgB,KAAK,OAAO,GAAG,GAAG,EAAE;AAE1C,IAAM,sBAAsB;AAAA,EACjC;AAAA,EACA,OAAO,EAAE;AACX;AAKO,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AACF;AAIO,IAAM,kBAAkB,QAAQ,OAAO,GAAG,gBAAgB;AAE1D,IAAM,uBAAuB,MAAM,eAAe;AAClD,IAAM,uBAAuB,QAAQ,OAAO,GAAG,qBAAqB;AAMpE,IAAM,cAAc,OAAO;AAAA,EAChC,IAAI;AAAA,EACJ,MAAM;AACR,CAAC;AAGM,IAAM,kBAAkB,OAAO;AAAA;AAAA;AAAA;AAAA,EAIpC,QAAQ,MAAM,WAAW;AAAA;AAAA;AAAA;AAAA,EAKzB,SAAS,SAAS,MAAM,aAAa,CAAC;AAAA;AAAA;AAAA;AAAA,EAKtC,QAAQ,SAAS,MAAM,aAAa,CAAC;AACvC,CAAC;AAMM,IAAM,oBAAoB,QAAQ,OAAO,GAAG,mBAAmB;AAS/D,SAAS,cAAc,OAAsC;AAClE,SAAO,GAAG,OAAO,iBAAiB;AACpC;AAQO,SAAS,UAAU,OAAkC;AAC1D,SAAO,GAAG,OAAO,aAAa;AAChC;AAQO,SAAS,YAAY,OAAoC;AAC9D,SAAO,GAAG,OAAO,eAAe;AAClC;AAQO,SAAS,iBAAiB,OAAsC;AACrE,SAAO,GAAG,OAAO,oBAAoB;AACvC;AAQO,SAAS,YAAY,OAAoC;AAC9D,SAAO,GAAG,OAAO,eAAe;AAClC;","names":[]}
@@ -8,7 +8,7 @@
8
8
 
9
9
 
10
10
 
11
- var _superstruct = require('superstruct');
11
+ var _superstruct = require('@metamask/superstruct');
12
12
  var CHAIN_ID_REGEX = /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;
13
13
  var ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
14
14
  var ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
@@ -104,4 +104,4 @@ function isNamespace(value) {
104
104
 
105
105
 
106
106
  exports.CHAIN_ID_REGEX = CHAIN_ID_REGEX; exports.ACCOUNT_ID_REGEX = ACCOUNT_ID_REGEX; exports.ACCOUNT_ADDRESS_REGEX = ACCOUNT_ADDRESS_REGEX; exports.parseChainId = parseChainId; exports.parseAccountId = parseAccountId; exports.LimitedString = LimitedString; exports.ChainIdStringStruct = ChainIdStringStruct; exports.ChainIdStruct = ChainIdStruct; exports.AccountIdStruct = AccountIdStruct; exports.AccountIdArrayStruct = AccountIdArrayStruct; exports.AccountAddressStruct = AccountAddressStruct; exports.ChainStruct = ChainStruct; exports.NamespaceStruct = NamespaceStruct; exports.NamespaceIdStruct = NamespaceIdStruct; exports.isNamespaceId = isNamespaceId; exports.isChainId = isChainId; exports.isAccountId = isAccountId; exports.isAccountIdArray = isAccountIdArray; exports.isNamespace = isNamespace;
107
- //# sourceMappingURL=chunk-6LOYTBS3.js.map
107
+ //# sourceMappingURL=chunk-LOJA2ZS4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespace.ts"],"names":[],"mappings":";AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIA,IAAM,iBACX;AAEK,IAAM,mBACX;AAEK,IAAM,wBAAwB;AAS9B,SAAS,aAAa,SAG3B;AACA,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,mBAAmB;AAAA,E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AAS,iBAAiB,OAAsC;AACrE,SAAO,GAAG,OAAO,oBAAoB;AACvC;AAQO,SAAS,YAAY,OAAoC;AAC9D,SAAO,GAAG,OAAO,eAAe;AAClC","sourcesContent":["import type { AccountId, ChainId } from '@metamask/snaps-sdk';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n define,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from '@metamask/superstruct';\n\nimport type { InferMatching } from './structs';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\nexport const ChainIdStringStruct = define<ChainId>(\n 'Chain ID',\n string().validator,\n);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern<ChainId, null>(\n ChainIdStringStruct,\n CHAIN_ID_REGEX,\n);\n\nexport type Caip2ChainId = InferMatching<typeof ChainIdStruct, ChainId>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkHJYRGKCXjs = require('./chunk-HJYRGKCX.js');
3
+ var _chunkDEQUNIMEjs = require('./chunk-DEQUNIME.js');
4
4
 
5
5
  // src/virtual-file/toVirtualFile.ts
6
6
  var _fs = require('fs');
7
7
  async function readVirtualFile(path, encoding = null) {
8
- return new (0, _chunkHJYRGKCXjs.VirtualFile)({
8
+ return new (0, _chunkDEQUNIMEjs.VirtualFile)({
9
9
  path,
10
10
  value: await _fs.promises.readFile(path, { encoding })
11
11
  });
@@ -18,4 +18,4 @@ async function writeVirtualFile(vfile, options) {
18
18
 
19
19
 
20
20
  exports.readVirtualFile = readVirtualFile; exports.writeVirtualFile = writeVirtualFile;
21
- //# sourceMappingURL=chunk-QSCKTRRU.js.map
21
+ //# sourceMappingURL=chunk-MKFQAXRF.js.map
@@ -1,7 +1,7 @@
1
1
  // src/versions.ts
2
+ import { validate } from "@metamask/superstruct";
2
3
  import { VersionRangeStruct } from "@metamask/utils";
3
4
  import { maxSatisfying as maxSatisfyingSemver } from "semver";
4
- import { validate } from "superstruct";
5
5
  var DEFAULT_REQUESTED_SNAP_VERSION = "*";
6
6
  function getTargetVersion(versions, versionRange) {
7
7
  const maxSatisfyingNonPreRelease = maxSatisfyingSemver(
@@ -27,4 +27,4 @@ export {
27
27
  getTargetVersion,
28
28
  resolveVersionRange
29
29
  };
30
- //# sourceMappingURL=chunk-UMZNVWEM.mjs.map
30
+ //# sourceMappingURL=chunk-N5HVDE3P.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/versions.ts"],"sourcesContent":["import { validate } from '@metamask/superstruct';\nimport type { Json, SemVerVersion, SemVerRange } from '@metamask/utils';\nimport { VersionRangeStruct } from '@metamask/utils';\nimport { maxSatisfying as maxSatisfyingSemver } from 'semver';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,0BAA0B;AACnC,SAAS,iBAAiB,2BAA2B;AAE9C,IAAM,iCAAiC;AAYvC,SAAS,iBACd,UACA,cACsB;AACtB,QAAM,6BAA6B;AAAA,IACjC;AAAA,IACA;AAAA,EACF;AAGA,MAAI,4BAA4B;AAC9B,WAAO;AAAA,EACT;AAGA,SAAO,oBAAoB,UAAU,cAAc;AAAA,IACjD,mBAAmB;AAAA,EACrB,CAAC;AACH;AASO,SAAS,oBACd,SAC2E;AAC3E,MAAI,YAAY,UAAa,YAAY,UAAU;AACjD,WAAO,CAAC,QAAW,8BAA8B;AAAA,EACnD;AACA,SAAO,SAAS,SAAS,kBAAkB;AAC7C;","names":[]}
@@ -1,11 +1,11 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunk473MIETWjs = require('./chunk-473MIETW.js');
3
+ var _chunkUAINMOUUjs = require('./chunk-UAINMOUU.js');
4
4
 
5
5
  // src/base64.ts
6
6
  var _utils = require('@metamask/utils');
7
7
  async function encodeBase64(input) {
8
- const bytes = _chunk473MIETWjs.getBytes.call(void 0, input);
8
+ const bytes = _chunkUAINMOUUjs.getBytes.call(void 0, input);
9
9
  if ("FileReader" in globalThis) {
10
10
  return await new Promise((resolve, reject) => {
11
11
  const reader = Object.assign(new FileReader(), {
@@ -35,4 +35,4 @@ async function decodeBase64(base64) {
35
35
 
36
36
 
37
37
  exports.encodeBase64 = encodeBase64; exports.decodeBase64 = decodeBase64;
38
- //# sourceMappingURL=chunk-IHQPAJ2B.js.map
38
+ //# sourceMappingURL=chunk-OBN2WDFU.js.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-OYZPBNHS.mjs.map
@@ -0,0 +1,34 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkOBN2WDFUjs = require('./chunk-OBN2WDFU.js');
4
+
5
+
6
+ var _chunk5WKQI22Sjs = require('./chunk-5WKQI22S.js');
7
+
8
+ // src/auxiliary-files.ts
9
+ var _snapssdk = require('@metamask/snaps-sdk');
10
+ var _utils = require('@metamask/utils');
11
+ async function encodeAuxiliaryFile(value, encoding) {
12
+ if (encoding === _snapssdk.AuxiliaryFileEncoding.Base64) {
13
+ return value;
14
+ }
15
+ const decoded = await _chunkOBN2WDFUjs.decodeBase64.call(void 0, value);
16
+ if (encoding === _snapssdk.AuxiliaryFileEncoding.Utf8) {
17
+ return _utils.bytesToString.call(void 0, decoded);
18
+ }
19
+ return _utils.bytesToHex.call(void 0, decoded);
20
+ }
21
+ function validateAuxiliaryFiles(files) {
22
+ for (const file of files) {
23
+ _utils.assert.call(void 0,
24
+ file.size < _chunk5WKQI22Sjs.MAX_FILE_SIZE,
25
+ "Static files required by the Snap must be smaller than 64 MB."
26
+ );
27
+ }
28
+ }
29
+
30
+
31
+
32
+
33
+ exports.encodeAuxiliaryFile = encodeAuxiliaryFile; exports.validateAuxiliaryFiles = validateAuxiliaryFiles;
34
+ //# sourceMappingURL=chunk-PLNIERDY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/auxiliary-files.ts"],"names":[],"mappings":";;;;;;;;AAAA,SAAS,6BAA6B;AACtC,SAAS,QAAQ,YAAY,qBAAqB;AAalD,eAAsB,oBACpB,OACA,UACA;AAEA,MAAI,aAAa,sBAAsB,QAAQ;AAC7C,WAAO;AAAA,EACT;AAGA,QAAM,UAAU,MAAM,aAAa,KAAK;AACxC,MAAI,aAAa,sBAAsB,MAAM;AAC3C,WAAO,cAAc,OAAO;AAAA,EAC9B;AAEA,SAAO,WAAW,OAAO;AAC3B;AAOO,SAAS,uBAAuB,OAAsB;AAC3D,aAAW,QAAQ,OAAO;AACxB;AAAA,MACE,KAAK,OAAO;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport { assert, bytesToHex, bytesToString } from '@metamask/utils';\n\nimport { decodeBase64 } from './base64';\nimport { MAX_FILE_SIZE } from './constants';\nimport type { VirtualFile } from './virtual-file';\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport async function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = await decodeBase64(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n\n/**\n * Validate that auxiliary files used by the Snap are within size limits.\n *\n * @param files - A list of auxiliary files.\n */\nexport function validateAuxiliaryFiles(files: VirtualFile[]) {\n for (const file of files) {\n assert(\n file.size < MAX_FILE_SIZE,\n 'Static files required by the Snap must be smaller than 64 MB.',\n );\n }\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/types.ts
2
- var _utils = require('@metamask/utils');
3
2
 
4
3
 
5
4
 
@@ -12,7 +11,8 @@ var _utils = require('@metamask/utils');
12
11
 
13
12
 
14
13
 
15
- var _superstruct = require('superstruct');
14
+ var _superstruct = require('@metamask/superstruct');
15
+ var _utils = require('@metamask/utils');
16
16
  var NpmSnapFileNames = /* @__PURE__ */ ((NpmSnapFileNames2) => {
17
17
  NpmSnapFileNames2["PackageJson"] = "package.json";
18
18
  NpmSnapFileNames2["Manifest"] = "snap.manifest.json";
@@ -92,4 +92,4 @@ var WALLET_SNAP_PERMISSION_KEY = "wallet_snap";
92
92
 
93
93
 
94
94
  exports.NpmSnapFileNames = NpmSnapFileNames; exports.NameStruct = NameStruct; exports.NpmSnapPackageJsonStruct = NpmSnapPackageJsonStruct; exports.isNpmSnapPackageJson = isNpmSnapPackageJson; exports.assertIsNpmSnapPackageJson = assertIsNpmSnapPackageJson; exports.SnapIdPrefixes = SnapIdPrefixes; exports.SnapValidationFailureReason = SnapValidationFailureReason; exports.SNAP_STREAM_NAMES = SNAP_STREAM_NAMES; exports.uri = uri; exports.isValidUrl = isValidUrl; exports.WALLET_SNAP_PERMISSION_KEY = WALLET_SNAP_PERMISSION_KEY;
95
- //# sourceMappingURL=chunk-CMOSYNZR.js.map
95
+ //# sourceMappingURL=chunk-PZNIU23I.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts"],"names":["NpmSnapFileNames","SnapIdPrefixes","SnapValidationFailureReason","SNAP_STREAM_NAMES"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,OACL;AAEP,SAAS,cAAc,qBAAqB;AAQrC,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,iBAAc;AACd,EAAAA,kBAAA,cAAW;AAFD,SAAAA;AAAA,GAAA;AAKL,IAAM,aAAa;AAAA,EACxB;AAAA,IACE,OAAO;AAAA,IACP;AAAA,EACF;AAAA,EACA;AAAA,EACA;AACF;AAIO,IAAM,2BAA2B,KAAK;AAAA,EAC3C,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM,SAAS,KAAK,OAAO,GAAG,GAAG,QAAQ,CAAC;AAAA,EAC1C,YAAY;AAAA,IACV,OAAO;AAAA,MACL,MAAM,KAAK,OAAO,GAAG,GAAG,QAAQ;AAAA,MAChC,KAAK,KAAK,OAAO,GAAG,GAAG,QAAQ;AAAA,IACjC,CAAC;AAAA,EACH;AACF,CAAC;AAWM,SAAS,qBACd,OAC6B;AAC7B,SAAO,GAAG,OAAO,wBAAwB;AAC3C;AAQO,SAAS,2BACd,OACqC;AACrC;AAAA,IACE;AAAA,IACA;AAAA,IACA,IAAI,gCAA4B;AAAA,EAClC;AACF;AAuCO,IAAK,iBAAL,kBAAKC,oBAAL;AACL,EAAAA,gBAAA,SAAM;AACN,EAAAA,gBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAUL,IAAK,8BAAL,kBAAKC,iCAAL;AACL,EAAAA,6BAAA,kBAAe;AACf,EAAAA,6BAAA,qBAAkB;AAClB,EAAAA,6BAAA,wBAAqB;AACrB,EAAAA,6BAAA,oBAAiB;AAJP,SAAAA;AAAA,GAAA;AAQL,IAAK,oBAAL,kBAAKC,uBAAL;AACL,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,aAAU;AAFA,SAAAA;AAAA,GAAA;AAwBL,IAAM,MAAM,CAAC,OAAwB,CAAC,MAC3C,OAAO,MAAM,CAAC,OAAO,GAAG,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,UAAU;AACzD,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,KAAK;AAEzB,UAAM,YAAY,KAAK,IAAI;AAC3B,sBAAkB,KAAK,SAAS;AAChC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,sBAAsB,MAAM,SAAS,CAAC;AAAA,EAC/C;AACF,CAAC;AASI,SAAS,WACd,KACA,OAAwB,CAAC,GACJ;AACrB,SAAO,GAAG,KAAK,IAAI,IAAI,CAAC;AAC1B;AAGO,IAAM,6BAA6B","sourcesContent":["import type { Infer, Struct } from '@metamask/superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile<LocalizationFile>[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles' | 'localizationFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"]}
@@ -1,15 +1,12 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
3
 
4
- var _chunkCMOSYNZRjs = require('./chunk-CMOSYNZR.js');
4
+ var _chunkPZNIU23Ijs = require('./chunk-PZNIU23I.js');
5
5
 
6
6
 
7
- var _chunkMLOQHUOYjs = require('./chunk-MLOQHUOY.js');
7
+ var _chunkAMW2VJ3Njs = require('./chunk-AMW2VJ3N.js');
8
8
 
9
9
  // src/snaps.ts
10
- var _utils = require('@metamask/utils');
11
- var _base = require('@scure/base');
12
- var _fastjsonstablestringify = require('fast-json-stable-stringify'); var _fastjsonstablestringify2 = _interopRequireDefault(_fastjsonstablestringify);
13
10
 
14
11
 
15
12
 
@@ -20,7 +17,10 @@ var _fastjsonstablestringify = require('fast-json-stable-stringify'); var _fastj
20
17
 
21
18
 
22
19
 
23
- var _superstruct = require('superstruct');
20
+ var _superstruct = require('@metamask/superstruct');
21
+ var _utils = require('@metamask/utils');
22
+ var _base = require('@scure/base');
23
+ var _fastjsonstablestringify = require('fast-json-stable-stringify'); var _fastjsonstablestringify2 = _interopRequireDefault(_fastjsonstablestringify);
24
24
  var _validatenpmpackagename = require('validate-npm-package-name'); var _validatenpmpackagename2 = _interopRequireDefault(_validatenpmpackagename);
25
25
  var 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;
26
26
  var SnapStatus = /* @__PURE__ */ ((SnapStatus2) => {
@@ -59,7 +59,7 @@ async function getSnapChecksum(files) {
59
59
  ...auxiliaryFiles,
60
60
  ...localizationFiles
61
61
  ].filter((file) => file !== void 0);
62
- return _base.base64.encode(await _chunkMLOQHUOYjs.checksumFiles.call(void 0, all));
62
+ return _base.base64.encode(await _chunkAMW2VJ3Njs.checksumFiles.call(void 0, all));
63
63
  }
64
64
  async function validateSnapShasum(files, errorMessage = "Invalid Snap manifest: manifest shasum does not match computed shasum.") {
65
65
  if (files.manifest.result.source.shasum !== await getSnapChecksum(files)) {
@@ -71,7 +71,7 @@ async function validateSnapShasum(files, errorMessage = "Invalid Snap manifest:
71
71
  }
72
72
  var LOCALHOST_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]"];
73
73
  var BaseSnapIdStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^[\x21-\x7E]*$/u);
74
- var LocalSnapIdSubUrlStruct = _chunkCMOSYNZRjs.uri.call(void 0, {
74
+ var LocalSnapIdSubUrlStruct = _chunkPZNIU23Ijs.uri.call(void 0, {
75
75
  protocol: _superstruct.enums.call(void 0, ["http:", "https:"]),
76
76
  hostname: _superstruct.enums.call(void 0, LOCALHOST_HOSTNAMES),
77
77
  hash: _superstruct.empty.call(void 0, _superstruct.string.call(void 0, )),
@@ -93,7 +93,7 @@ var LocalSnapIdStruct = _superstruct.refine.call(void 0,
93
93
  );
94
94
  var NpmSnapIdStruct = _superstruct.intersection.call(void 0, [
95
95
  BaseSnapIdStruct,
96
- _chunkCMOSYNZRjs.uri.call(void 0, {
96
+ _chunkPZNIU23Ijs.uri.call(void 0, {
97
97
  protocol: _superstruct.literal.call(void 0, "npm:" /* npm */),
98
98
  pathname: _superstruct.refine.call(void 0, _superstruct.string.call(void 0, ), "package name", function* (value) {
99
99
  const normalized = value.startsWith("/") ? value.slice(1) : value;
@@ -114,7 +114,7 @@ var NpmSnapIdStruct = _superstruct.intersection.call(void 0, [
114
114
  ]);
115
115
  var HttpSnapIdStruct = _superstruct.intersection.call(void 0, [
116
116
  BaseSnapIdStruct,
117
- _chunkCMOSYNZRjs.uri.call(void 0, {
117
+ _chunkPZNIU23Ijs.uri.call(void 0, {
118
118
  protocol: _superstruct.enums.call(void 0, ["http:", "https:"]),
119
119
  search: _superstruct.empty.call(void 0, _superstruct.string.call(void 0, )),
120
120
  hash: _superstruct.empty.call(void 0, _superstruct.string.call(void 0, ))
@@ -122,7 +122,7 @@ var HttpSnapIdStruct = _superstruct.intersection.call(void 0, [
122
122
  ]);
123
123
  var SnapIdStruct = _superstruct.union.call(void 0, [NpmSnapIdStruct, LocalSnapIdStruct]);
124
124
  function getSnapPrefix(snapId) {
125
- const prefix = Object.values(_chunkCMOSYNZRjs.SnapIdPrefixes).find(
125
+ const prefix = Object.values(_chunkPZNIU23Ijs.SnapIdPrefixes).find(
126
126
  (possiblePrefix) => snapId.startsWith(possiblePrefix)
127
127
  );
128
128
  if (prefix !== void 0) {
@@ -190,4 +190,4 @@ function verifyRequestedSnapPermissions(requestedPermissions) {
190
190
 
191
191
 
192
192
  exports.PROPOSED_NAME_REGEX = PROPOSED_NAME_REGEX; exports.SnapStatus = SnapStatus; exports.SnapStatusEvents = SnapStatusEvents; exports.ProgrammaticallyFixableSnapError = ProgrammaticallyFixableSnapError; exports.getSnapChecksum = getSnapChecksum; exports.validateSnapShasum = validateSnapShasum; exports.LOCALHOST_HOSTNAMES = LOCALHOST_HOSTNAMES; exports.BaseSnapIdStruct = BaseSnapIdStruct; exports.LocalSnapIdStruct = LocalSnapIdStruct; exports.NpmSnapIdStruct = NpmSnapIdStruct; exports.HttpSnapIdStruct = HttpSnapIdStruct; exports.SnapIdStruct = SnapIdStruct; exports.getSnapPrefix = getSnapPrefix; exports.stripSnapPrefix = stripSnapPrefix; exports.assertIsValidSnapId = assertIsValidSnapId; exports.isCaipChainId = isCaipChainId; exports.isSnapPermitted = isSnapPermitted; exports.verifyRequestedSnapPermissions = verifyRequestedSnapPermissions;
193
- //# sourceMappingURL=chunk-K4B37F3L.js.map
193
+ //# sourceMappingURL=chunk-RD6BN2TQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/snaps.ts"],"names":["SnapStatus","SnapStatusEvents"],"mapp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":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, 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\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: SnapId };\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 SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\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 * 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 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 /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\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 async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await 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 async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await 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});\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\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(value: unknown): asserts value is SnapId {\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\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}