@metamask/snaps-utils 0.34.1-flask.1 → 0.35.1-flask.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 (249) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/cjs/array.js +23 -0
  3. package/dist/cjs/array.js.map +1 -0
  4. package/dist/cjs/caveats.js +33 -0
  5. package/dist/cjs/caveats.js.map +1 -0
  6. package/dist/cjs/checksum.js +38 -0
  7. package/dist/cjs/checksum.js.map +1 -0
  8. package/dist/cjs/cronjob.js +84 -0
  9. package/dist/cjs/cronjob.js.map +1 -0
  10. package/dist/cjs/deep-clone.js +22 -0
  11. package/dist/cjs/deep-clone.js.map +1 -0
  12. package/dist/cjs/default-endowments.js +49 -0
  13. package/dist/cjs/default-endowments.js.map +1 -0
  14. package/dist/cjs/entropy.js +23 -0
  15. package/dist/cjs/entropy.js.map +1 -0
  16. package/dist/cjs/enum.js +16 -0
  17. package/dist/cjs/enum.js.map +1 -0
  18. package/dist/{eval-worker.js → cjs/eval-worker.js} +22 -21
  19. package/dist/cjs/eval-worker.js.map +1 -0
  20. package/dist/cjs/eval.js +29 -0
  21. package/dist/cjs/eval.js.map +1 -0
  22. package/dist/cjs/fs.js +126 -0
  23. package/dist/cjs/fs.js.map +1 -0
  24. package/dist/cjs/handlers.js +6 -0
  25. package/dist/cjs/handlers.js.map +1 -0
  26. package/dist/cjs/icon.js +37 -0
  27. package/dist/cjs/icon.js.map +1 -0
  28. package/dist/{iframe.js → cjs/iframe.js} +14 -9
  29. package/dist/cjs/iframe.js.map +1 -0
  30. package/dist/cjs/index.browser.js +40 -0
  31. package/dist/cjs/index.browser.js.map +1 -0
  32. package/dist/cjs/index.executionenv.js +24 -0
  33. package/dist/cjs/index.executionenv.js.map +1 -0
  34. package/dist/cjs/index.js +45 -0
  35. package/dist/cjs/index.js.map +1 -0
  36. package/dist/cjs/json-rpc.js +46 -0
  37. package/dist/cjs/json-rpc.js.map +1 -0
  38. package/dist/cjs/json.js +16 -0
  39. package/dist/cjs/json.js.map +1 -0
  40. package/dist/cjs/logging.js +40 -0
  41. package/dist/cjs/logging.js.map +1 -0
  42. package/dist/cjs/manifest/index.browser.js +20 -0
  43. package/dist/cjs/manifest/index.browser.js.map +1 -0
  44. package/dist/cjs/manifest/index.js +21 -0
  45. package/dist/cjs/manifest/index.js.map +1 -0
  46. package/dist/cjs/manifest/manifest.js +239 -0
  47. package/dist/cjs/manifest/manifest.js.map +1 -0
  48. package/dist/cjs/manifest/validation.js +183 -0
  49. package/dist/cjs/manifest/validation.js.map +1 -0
  50. package/dist/cjs/mock.js +128 -0
  51. package/dist/cjs/mock.js.map +1 -0
  52. package/dist/cjs/namespace.js +124 -0
  53. package/dist/cjs/namespace.js.map +1 -0
  54. package/dist/cjs/npm.js +81 -0
  55. package/dist/cjs/npm.js.map +1 -0
  56. package/dist/cjs/path.js +21 -0
  57. package/dist/cjs/path.js.map +1 -0
  58. package/dist/cjs/post-process.js +328 -0
  59. package/dist/cjs/post-process.js.map +1 -0
  60. package/dist/cjs/snaps.js +230 -0
  61. package/dist/cjs/snaps.js.map +1 -0
  62. package/dist/cjs/types.js +117 -0
  63. package/dist/cjs/types.js.map +1 -0
  64. package/dist/cjs/validation.js +22 -0
  65. package/dist/cjs/validation.js.map +1 -0
  66. package/dist/cjs/versions.js +47 -0
  67. package/dist/cjs/versions.js.map +1 -0
  68. package/dist/cjs/virtual-file/VirtualFile.js +85 -0
  69. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -0
  70. package/dist/cjs/virtual-file/index.browser.js +20 -0
  71. package/dist/cjs/virtual-file/index.browser.js.map +1 -0
  72. package/dist/cjs/virtual-file/index.js +21 -0
  73. package/dist/cjs/virtual-file/index.js.map +1 -0
  74. package/dist/cjs/virtual-file/toVirtualFile.js +33 -0
  75. package/dist/cjs/virtual-file/toVirtualFile.js.map +1 -0
  76. package/dist/esm/array.js +13 -0
  77. package/dist/esm/array.js.map +1 -0
  78. package/dist/esm/caveats.js +23 -0
  79. package/dist/esm/caveats.js.map +1 -0
  80. package/dist/esm/checksum.js +36 -0
  81. package/dist/esm/checksum.js.map +1 -0
  82. package/dist/esm/cronjob.js +66 -0
  83. package/dist/esm/cronjob.js.map +1 -0
  84. package/dist/esm/deep-clone.js +7 -0
  85. package/dist/esm/deep-clone.js.map +1 -0
  86. package/dist/{default-endowments.js → esm/default-endowments.js} +3 -6
  87. package/dist/esm/default-endowments.js.map +1 -0
  88. package/dist/esm/entropy.js +6 -0
  89. package/dist/esm/entropy.js.map +1 -0
  90. package/dist/esm/enum.js +12 -0
  91. package/dist/esm/enum.js.map +1 -0
  92. package/dist/esm/eval-worker.js +47 -0
  93. package/dist/esm/eval-worker.js.map +1 -0
  94. package/dist/esm/eval.js +25 -0
  95. package/dist/esm/eval.js.map +1 -0
  96. package/dist/{fs.js → esm/fs.js} +33 -55
  97. package/dist/esm/fs.js.map +1 -0
  98. package/dist/esm/handlers.js +3 -0
  99. package/dist/esm/handlers.js.map +1 -0
  100. package/dist/esm/icon.js +11 -0
  101. package/dist/esm/icon.js.map +1 -0
  102. package/dist/esm/iframe.js +49 -0
  103. package/dist/esm/iframe.js.map +1 -0
  104. package/dist/esm/index.browser.js +23 -0
  105. package/dist/esm/index.browser.js.map +1 -0
  106. package/dist/esm/index.executionenv.js +7 -0
  107. package/dist/esm/index.executionenv.js.map +1 -0
  108. package/dist/esm/index.js +28 -0
  109. package/dist/esm/index.js.map +1 -0
  110. package/dist/esm/json-rpc.js +39 -0
  111. package/dist/esm/json-rpc.js.map +1 -0
  112. package/dist/esm/json.js +17 -0
  113. package/dist/esm/json.js.map +1 -0
  114. package/dist/{logging.js → esm/logging.js} +6 -14
  115. package/dist/esm/logging.js.map +1 -0
  116. package/dist/esm/manifest/index.browser.js +3 -0
  117. package/dist/esm/manifest/index.browser.js.map +1 -0
  118. package/dist/esm/manifest/index.js +4 -0
  119. package/dist/esm/manifest/index.js.map +1 -0
  120. package/dist/{manifest → esm/manifest}/manifest.js +91 -107
  121. package/dist/esm/manifest/manifest.js.map +1 -0
  122. package/dist/esm/manifest/validation.js +152 -0
  123. package/dist/esm/manifest/validation.js.map +1 -0
  124. package/dist/{mock.js → esm/mock.js} +40 -42
  125. package/dist/esm/mock.js.map +1 -0
  126. package/dist/esm/namespace.js +110 -0
  127. package/dist/esm/namespace.js.map +1 -0
  128. package/dist/{npm.js → esm/npm.js} +23 -30
  129. package/dist/esm/npm.js.map +1 -0
  130. package/dist/esm/path.js +17 -0
  131. package/dist/esm/path.js.map +1 -0
  132. package/dist/{post-process.js → esm/post-process.js} +110 -99
  133. package/dist/esm/post-process.js.map +1 -0
  134. package/dist/esm/snaps.js +215 -0
  135. package/dist/esm/snaps.js.map +1 -0
  136. package/dist/esm/types.js +85 -0
  137. package/dist/esm/types.js.map +1 -0
  138. package/dist/esm/validation.js +17 -0
  139. package/dist/esm/validation.js.map +1 -0
  140. package/dist/{versions.js → esm/versions.js} +15 -18
  141. package/dist/esm/versions.js.map +1 -0
  142. package/dist/{virtual-file → esm/virtual-file}/VirtualFile.js +47 -33
  143. package/dist/esm/virtual-file/VirtualFile.js.map +1 -0
  144. package/dist/esm/virtual-file/index.browser.js +3 -0
  145. package/dist/esm/virtual-file/index.browser.js.map +1 -0
  146. package/dist/esm/virtual-file/index.js +4 -0
  147. package/dist/esm/virtual-file/index.js.map +1 -0
  148. package/dist/esm/virtual-file/toVirtualFile.js +26 -0
  149. package/dist/esm/virtual-file/toVirtualFile.js.map +1 -0
  150. package/dist/types/array.d.ts +10 -0
  151. package/dist/{caveats.d.ts → types/caveats.d.ts} +0 -4
  152. package/dist/types/enum.d.ts +30 -0
  153. package/dist/{handlers.d.ts → types/handlers.d.ts} +1 -38
  154. package/dist/{index.browser.d.ts → types/index.browser.d.ts} +3 -1
  155. package/dist/{index.d.ts → types/index.d.ts} +3 -1
  156. package/dist/types/index.executionenv.d.ts +4 -0
  157. package/dist/types/json.d.ts +13 -0
  158. package/dist/{manifest → types/manifest}/validation.d.ts +6 -69
  159. package/dist/types/namespace.d.ts +124 -0
  160. package/dist/{types.d.ts → types/types.d.ts} +2 -5
  161. package/package.json +46 -21
  162. package/dist/caveats.js +0 -35
  163. package/dist/caveats.js.map +0 -1
  164. package/dist/checksum.js +0 -42
  165. package/dist/checksum.js.map +0 -1
  166. package/dist/cronjob.js +0 -71
  167. package/dist/cronjob.js.map +0 -1
  168. package/dist/deep-clone.js +0 -9
  169. package/dist/deep-clone.js.map +0 -1
  170. package/dist/default-endowments.js.map +0 -1
  171. package/dist/entropy.js +0 -8
  172. package/dist/entropy.js.map +0 -1
  173. package/dist/eval-worker.js.map +0 -1
  174. package/dist/eval.js +0 -27
  175. package/dist/eval.js.map +0 -1
  176. package/dist/fs.js.map +0 -1
  177. package/dist/handlers.js +0 -3
  178. package/dist/handlers.js.map +0 -1
  179. package/dist/icon.js +0 -17
  180. package/dist/icon.js.map +0 -1
  181. package/dist/iframe.js.map +0 -1
  182. package/dist/iframe.test.browser.js +0 -15
  183. package/dist/iframe.test.browser.js.map +0 -1
  184. package/dist/index.browser.js +0 -36
  185. package/dist/index.browser.js.map +0 -1
  186. package/dist/index.js +0 -41
  187. package/dist/index.js.map +0 -1
  188. package/dist/json-rpc.js +0 -46
  189. package/dist/json-rpc.js.map +0 -1
  190. package/dist/logging.js.map +0 -1
  191. package/dist/manifest/index.browser.js +0 -18
  192. package/dist/manifest/index.browser.js.map +0 -1
  193. package/dist/manifest/index.js +0 -19
  194. package/dist/manifest/index.js.map +0 -1
  195. package/dist/manifest/manifest.js.map +0 -1
  196. package/dist/manifest/validation.js +0 -146
  197. package/dist/manifest/validation.js.map +0 -1
  198. package/dist/mock.js.map +0 -1
  199. package/dist/namespace.d.ts +0 -275
  200. package/dist/namespace.js +0 -225
  201. package/dist/namespace.js.map +0 -1
  202. package/dist/notification.d.ts +0 -66
  203. package/dist/notification.js +0 -58
  204. package/dist/notification.js.map +0 -1
  205. package/dist/npm.js.map +0 -1
  206. package/dist/path.js +0 -21
  207. package/dist/path.js.map +0 -1
  208. package/dist/post-process.js.map +0 -1
  209. package/dist/snaps.js +0 -212
  210. package/dist/snaps.js.map +0 -1
  211. package/dist/types.js +0 -103
  212. package/dist/types.js.map +0 -1
  213. package/dist/validation.js +0 -21
  214. package/dist/validation.js.map +0 -1
  215. package/dist/versions.js.map +0 -1
  216. package/dist/virtual-file/VirtualFile.js.map +0 -1
  217. package/dist/virtual-file/index.browser.js +0 -18
  218. package/dist/virtual-file/index.browser.js.map +0 -1
  219. package/dist/virtual-file/index.js +0 -19
  220. package/dist/virtual-file/index.js.map +0 -1
  221. package/dist/virtual-file/toVirtualFile.js +0 -30
  222. package/dist/virtual-file/toVirtualFile.js.map +0 -1
  223. /package/dist/{checksum.d.ts → types/checksum.d.ts} +0 -0
  224. /package/dist/{cronjob.d.ts → types/cronjob.d.ts} +0 -0
  225. /package/dist/{deep-clone.d.ts → types/deep-clone.d.ts} +0 -0
  226. /package/dist/{default-endowments.d.ts → types/default-endowments.d.ts} +0 -0
  227. /package/dist/{entropy.d.ts → types/entropy.d.ts} +0 -0
  228. /package/dist/{eval-worker.d.ts → types/eval-worker.d.ts} +0 -0
  229. /package/dist/{eval.d.ts → types/eval.d.ts} +0 -0
  230. /package/dist/{fs.d.ts → types/fs.d.ts} +0 -0
  231. /package/dist/{icon.d.ts → types/icon.d.ts} +0 -0
  232. /package/dist/{iframe.d.ts → types/iframe.d.ts} +0 -0
  233. /package/dist/{iframe.test.browser.d.ts → types/iframe.test.browser.d.ts} +0 -0
  234. /package/dist/{json-rpc.d.ts → types/json-rpc.d.ts} +0 -0
  235. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  236. /package/dist/{manifest → types/manifest}/index.browser.d.ts +0 -0
  237. /package/dist/{manifest → types/manifest}/index.d.ts +0 -0
  238. /package/dist/{manifest → types/manifest}/manifest.d.ts +0 -0
  239. /package/dist/{mock.d.ts → types/mock.d.ts} +0 -0
  240. /package/dist/{npm.d.ts → types/npm.d.ts} +0 -0
  241. /package/dist/{path.d.ts → types/path.d.ts} +0 -0
  242. /package/dist/{post-process.d.ts → types/post-process.d.ts} +0 -0
  243. /package/dist/{snaps.d.ts → types/snaps.d.ts} +0 -0
  244. /package/dist/{validation.d.ts → types/validation.d.ts} +0 -0
  245. /package/dist/{versions.d.ts → types/versions.d.ts} +0 -0
  246. /package/dist/{virtual-file → types/virtual-file}/VirtualFile.d.ts +0 -0
  247. /package/dist/{virtual-file → types/virtual-file}/index.browser.d.ts +0 -0
  248. /package/dist/{virtual-file → types/virtual-file}/index.d.ts +0 -0
  249. /package/dist/{virtual-file → types/virtual-file}/toVirtualFile.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport {\n array,\n boolean,\n create,\n enums,\n Infer,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n Struct,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <T extends { path: string[]; curve: string }, S>(\n struct: Struct<T, S>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:long-running': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","pattern","refine","record","size","string","type","union","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","RpcOriginsStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","PermissionsStruct","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","wallet_snap","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest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AwB,oBACA,CAAC,CAAC,EAAEzC,iBAAiB2D,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmB3C,KAAc;IAC/C,qEAAqE;IACrE,OAAOtC,OAAOsC,OAAOwB;AACvB"}
@@ -1,36 +1,35 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.generateMockEndowments = exports.isConstructor = exports.ALL_APIS = void 0;
7
- const crypto_1 = __importDefault(require("crypto"));
8
- const events_1 = __importDefault(require("events"));
9
- const default_endowments_1 = require("./default-endowments");
10
- const NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];
11
- exports.ALL_APIS = [
12
- ...default_endowments_1.DEFAULT_ENDOWMENTS,
1
+ import crypto from 'crypto';
2
+ import EventEmitter from 'events';
3
+ import { DEFAULT_ENDOWMENTS } from './default-endowments';
4
+ const NETWORK_APIS = [
5
+ 'fetch',
6
+ 'Request',
7
+ 'Headers',
8
+ 'Response'
9
+ ];
10
+ export const ALL_APIS = [
11
+ ...DEFAULT_ENDOWMENTS,
13
12
  ...NETWORK_APIS,
14
- 'WebAssembly',
13
+ 'WebAssembly'
15
14
  ];
16
15
  /**
17
16
  * Get a mock snap API, that always returns `true` for requests.
18
17
  *
19
18
  * @returns A mocked snap provider.
20
- */
21
- function getMockSnapGlobal() {
19
+ */ function getMockSnapGlobal() {
22
20
  // eslint-disable-next-line @typescript-eslint/require-await
23
- return { request: async () => true };
21
+ return {
22
+ request: async ()=>true
23
+ };
24
24
  }
25
25
  /**
26
26
  * Get a mock Ethereum provider, that always returns `true` for requests.
27
27
  *
28
28
  * @returns A mocked ethereum provider.
29
- */
30
- function getMockEthereumProvider() {
31
- const mockProvider = new events_1.default();
29
+ */ function getMockEthereumProvider() {
30
+ const mockProvider = new EventEmitter();
32
31
  // eslint-disable-next-line @typescript-eslint/require-await
33
- mockProvider.request = async () => true;
32
+ mockProvider.request = async ()=>true;
34
33
  return mockProvider;
35
34
  }
36
35
  /**
@@ -38,25 +37,22 @@ function getMockEthereumProvider() {
38
37
  *
39
38
  * @param value - The value to check.
40
39
  * @returns `true` if the value is a constructor, or `false` otherwise.
41
- */
42
- const isConstructor = (value) => Boolean(typeof value?.prototype?.constructor?.name === 'string');
43
- exports.isConstructor = isConstructor;
40
+ */ export const isConstructor = (value)=>Boolean(typeof value?.prototype?.constructor?.name === 'string');
44
41
  /**
45
42
  * A function that always returns `true`.
46
43
  *
47
44
  * @returns `true`.
48
- */
49
- const mockFunction = () => true;
45
+ */ const mockFunction = ()=>true;
50
46
  class MockClass {
51
47
  }
52
48
  const handler = {
53
49
  // eslint-disable-next-line @typescript-eslint/naming-convention
54
- construct(Target, args) {
50
+ construct (Target, args) {
55
51
  return new Proxy(new Target(...args), handler);
56
52
  },
57
- get(_target, _prop) {
53
+ get (_target, _prop) {
58
54
  return mockFunction;
59
- },
55
+ }
60
56
  };
61
57
  /**
62
58
  * Generate a mock class for a given value. The value is wrapped in a Proxy, and
@@ -64,15 +60,14 @@ const handler = {
64
60
  *
65
61
  * @param value - The value to mock.
66
62
  * @returns A mock class.
67
- */
68
- const generateMockClass = (value) => {
63
+ */ const generateMockClass = (value)=>{
69
64
  return new Proxy(value, handler);
70
65
  };
71
66
  // Things not currently auto-mocked because of NodeJS, by adding them here we
72
67
  // have types for them and can use that to generate mocks if needed.
73
68
  const mockWindow = {
74
- crypto: crypto_1.default,
75
- SubtleCrypto: MockClass,
69
+ crypto,
70
+ SubtleCrypto: MockClass
76
71
  };
77
72
  /**
78
73
  * Generate a mock endowment for a certain class or function on the `globalThis`
@@ -81,21 +76,19 @@ const mockWindow = {
81
76
  * @param key - The key to generate the mock endowment for.
82
77
  * @returns A mocked class or function. If the key is part of the default
83
78
  * endowments, the original value is returned.
84
- */
85
- const generateMockEndowment = (key) => {
79
+ */ const generateMockEndowment = (key)=>{
86
80
  const globalValue = globalThis[key];
87
81
  // Default exposed APIs don't need to be mocked
88
- if (globalValue && default_endowments_1.DEFAULT_ENDOWMENTS.includes(key)) {
82
+ if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {
89
83
  return globalValue;
90
84
  }
91
85
  // Fall back to mockWindow for certain APIs not exposed in global in Node.JS
92
86
  const globalOrMocked = globalValue ?? mockWindow[key];
93
87
  const type = typeof globalOrMocked;
94
88
  const isFunction = type === 'function';
95
- if (isFunction && (0, exports.isConstructor)(globalOrMocked)) {
89
+ if (isFunction && isConstructor(globalOrMocked)) {
96
90
  return generateMockClass(globalOrMocked);
97
- }
98
- else if (isFunction || !globalOrMocked) {
91
+ } else if (isFunction || !globalOrMocked) {
99
92
  // Fall back to function mock for now
100
93
  return mockFunction;
101
94
  }
@@ -105,9 +98,14 @@ const generateMockEndowment = (key) => {
105
98
  * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.
106
99
  *
107
100
  * @returns A map of endowments.
108
- */
109
- const generateMockEndowments = () => {
110
- return exports.ALL_APIS.reduce((acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }), { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() });
101
+ */ export const generateMockEndowments = ()=>{
102
+ return ALL_APIS.reduce((acc, cur)=>({
103
+ ...acc,
104
+ [cur]: generateMockEndowment(cur)
105
+ }), {
106
+ snap: getMockSnapGlobal(),
107
+ ethereum: getMockEthereumProvider()
108
+ });
111
109
  };
112
- exports.generateMockEndowments = generateMockEndowments;
110
+
113
111
  //# sourceMappingURL=mock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/mock.ts"],"sourcesContent":["import crypto from 'crypto';\nimport EventEmitter from 'events';\n\nimport { DEFAULT_ENDOWMENTS } from './default-endowments';\n\nconst NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];\n\nexport const ALL_APIS: string[] = [\n ...DEFAULT_ENDOWMENTS,\n ...NETWORK_APIS,\n 'WebAssembly',\n];\n\ntype MockSnapGlobal = {\n request: () => Promise<any>;\n};\n\ntype MockEthereumProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap API, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapGlobal(): MockSnapGlobal {\n // eslint-disable-next-line @typescript-eslint/require-await\n return { request: async () => true };\n}\n\n/**\n * Get a mock Ethereum provider, that always returns `true` for requests.\n *\n * @returns A mocked ethereum provider.\n */\nfunction getMockEthereumProvider(): MockEthereumProvider {\n const mockProvider = new EventEmitter() as Partial<MockEthereumProvider>;\n // eslint-disable-next-line @typescript-eslint/require-await\n mockProvider.request = async () => true;\n return mockProvider as MockEthereumProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we\n// have types for them and can use that to generate mocks if needed.\nconst mockWindow: Record<string, unknown> = {\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? mockWindow[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() },\n );\n};\n"],"names":["crypto","EventEmitter","DEFAULT_ENDOWMENTS","NETWORK_APIS","ALL_APIS","getMockSnapGlobal","request","getMockEthereumProvider","mockProvider","isConstructor","value","Boolean","prototype","constructor","name","mockFunction","MockClass","handler","construct","Target","args","Proxy","get","_target","_prop","generateMockClass","mockWindow","SubtleCrypto","generateMockEndowment","key","globalValue","globalThis","includes","globalOrMocked","type","isFunction","generateMockEndowments","reduce","acc","cur","snap","ethereum"],"mappings":"AAAA,OAAOA,YAAY,SAAS;AAC5B,OAAOC,kBAAkB,SAAS;AAElC,SAASC,kBAAkB,QAAQ,uBAAuB;AAE1D,MAAMC,eAAe;IAAC;IAAS;IAAW;IAAW;CAAW;AAEhE,OAAO,MAAMC,WAAqB;OAC7BF;OACAC;IACH;CACD,CAAC;AAUF;;;;CAIC,GACD,SAASE;IACP,4DAA4D;IAC5D,OAAO;QAAEC,SAAS,UAAY;IAAK;AACrC;AAEA;;;;CAIC,GACD,SAASC;IACP,MAAMC,eAAe,IAAIP;IACzB,4DAA4D;IAC5DO,aAAaF,OAAO,GAAG,UAAY;IACnC,OAAOE;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,gBAAgB,CAACC,QAC5BC,QAAQ,OAAOD,OAAOE,WAAWC,aAAaC,SAAS,UAAU;AAEnE;;;;CAIC,GACD,MAAMC,eAAe,IAAM;AAC3B,MAAMC;AAAW;AAEjB,MAAMC,UAAU;IACd,gEAAgE;IAChEC,WAAUC,MAAW,EAAEC,IAAW;QAChC,OAAO,IAAIC,MAAM,IAAIF,UAAUC,OAAOH;IACxC;IACAK,KAAIC,OAAY,EAAEC,KAAU;QAC1B,OAAOT;IACT;AACF;AAEA;;;;;;CAMC,GACD,MAAMU,oBAAoB,CAACf;IACzB,OAAO,IAAIW,MAAMX,OAAOO;AAC1B;AAEA,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMS,aAAsC;IAC1C1B;IACA2B,cAAcX;AAChB;AAEA;;;;;;;CAOC,GACD,MAAMY,wBAAwB,CAACC;IAC7B,MAAMC,cAAc,AAACC,UAAkB,CAACF,IAAI;IAE5C,+CAA+C;IAC/C,IAAIC,eAAe5B,mBAAmB8B,QAAQ,CAACH,MAAM;QACnD,OAAOC;IACT;IAEA,4EAA4E;IAC5E,MAAMG,iBAAiBH,eAAeJ,UAAU,CAACG,IAAI;IAErD,MAAMK,OAAO,OAAOD;IACpB,MAAME,aAAaD,SAAS;IAC5B,IAAIC,cAAc1B,cAAcwB,iBAAiB;QAC/C,OAAOR,kBAAkBQ;IAC3B,OAAO,IAAIE,cAAc,CAACF,gBAAgB;QACxC,qCAAqC;QACrC,OAAOlB;IACT;IACA,OAAOkB;AACT;AAEA;;;;CAIC,GACD,OAAO,MAAMG,yBAAyB;IACpC,OAAOhC,SAASiC,MAAM,CACpB,CAACC,KAAKC,MAAS,CAAA;YAAE,GAAGD,GAAG;YAAE,CAACC,IAAI,EAAEX,sBAAsBW;QAAK,CAAA,GAC3D;QAAEC,MAAMnC;QAAqBoC,UAAUlC;IAA0B;AAErE,EAAE"}
@@ -0,0 +1,110 @@
1
+ import { array, is, object, optional, pattern, size, string } from 'superstruct';
2
+ export const CHAIN_ID_REGEX = RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u");
3
+ export const ACCOUNT_ID_REGEX = RegExp("^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
4
+ /**
5
+ * Parse a chain ID string to an object containing the namespace and reference.
6
+ * This validates the chain ID before parsing it.
7
+ *
8
+ * @param chainId - The chain ID to validate and parse.
9
+ * @returns The parsed chain ID.
10
+ */ export function parseChainId(chainId) {
11
+ const match = CHAIN_ID_REGEX.exec(chainId);
12
+ if (!match?.groups) {
13
+ throw new Error('Invalid chain ID.');
14
+ }
15
+ return {
16
+ namespace: match.groups.namespace,
17
+ reference: match.groups.reference
18
+ };
19
+ }
20
+ /**
21
+ * Parse an account ID to an object containing the chain, chain ID and address.
22
+ * This validates the account ID before parsing it.
23
+ *
24
+ * @param accountId - The account ID to validate and parse.
25
+ * @returns The parsed account ID.
26
+ */ export function parseAccountId(accountId) {
27
+ const match = ACCOUNT_ID_REGEX.exec(accountId);
28
+ if (!match?.groups) {
29
+ throw new Error('Invalid account ID.');
30
+ }
31
+ return {
32
+ address: match.groups.accountAddress,
33
+ chainId: match.groups.chainId,
34
+ chain: {
35
+ namespace: match.groups.namespace,
36
+ reference: match.groups.reference
37
+ }
38
+ };
39
+ }
40
+ /**
41
+ * A helper struct for a string with a minimum length of 1 and a maximum length
42
+ * of 40.
43
+ */ export const LimitedString = size(string(), 1, 40);
44
+ /**
45
+ * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
46
+ */ export const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);
47
+ export const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);
48
+ export const AccountIdArrayStruct = array(AccountIdStruct);
49
+ /**
50
+ * A chain descriptor.
51
+ */ export const ChainStruct = object({
52
+ id: ChainIdStruct,
53
+ name: LimitedString
54
+ });
55
+ export const NamespaceStruct = object({
56
+ /**
57
+ * A list of supported chains in the namespace.
58
+ */ chains: array(ChainStruct),
59
+ /**
60
+ * A list of supported RPC methods on the namespace, that a DApp can call.
61
+ */ methods: optional(array(LimitedString)),
62
+ /**
63
+ * A list of supported RPC events on the namespace, that a DApp can listen to.
64
+ */ events: optional(array(LimitedString))
65
+ });
66
+ /**
67
+ * A CAIP-2 namespace, i.e., the first part of a chain ID.
68
+ */ export const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);
69
+ /**
70
+ * Check if the given value is a CAIP-2 namespace ID.
71
+ *
72
+ * @param value - The value to check.
73
+ * @returns Whether the value is a CAIP-2 namespace ID.
74
+ */ export function isNamespaceId(value) {
75
+ return is(value, NamespaceIdStruct);
76
+ }
77
+ /**
78
+ * Check if the given value is a CAIP-2 chain ID.
79
+ *
80
+ * @param value - The value to check.
81
+ * @returns Whether the value is a CAIP-2 chain ID.
82
+ */ export function isChainId(value) {
83
+ return is(value, ChainIdStruct);
84
+ }
85
+ /**
86
+ * Check if the given value is a CAIP-10 account ID.
87
+ *
88
+ * @param value - The value to check.
89
+ * @returns Whether the value is a CAIP-10 account ID.
90
+ */ export function isAccountId(value) {
91
+ return is(value, AccountIdStruct);
92
+ }
93
+ /**
94
+ * Check if the given value is an array of CAIP-10 account IDs.
95
+ *
96
+ * @param value - The value to check.
97
+ * @returns Whether the value is an array of CAIP-10 account IDs.
98
+ */ export function isAccountIdArray(value) {
99
+ return is(value, AccountIdArrayStruct);
100
+ }
101
+ /**
102
+ * Check if a value is a {@link Namespace}.
103
+ *
104
+ * @param value - The value to validate.
105
+ * @returns True if the value is a valid {@link Namespace}.
106
+ */ export function isNamespace(value) {
107
+ return is(value, NamespaceStruct);
108
+ }
109
+
110
+ //# sourceMappingURL=namespace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import {\n array,\n Infer,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\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\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\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\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"],"names":["array","is","object","optional","pattern","size","string","CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","parseChainId","chainId","match","exec","groups","Error","namespace","reference","parseAccountId","accountId","address","accountAddress","chain","LimitedString","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","ChainStruct","id","name","NamespaceStruct","chains","methods","events","NamespaceIdStruct","isNamespaceId","value","isChainId","isAccountId","isAccountIdArray","isNamespace"],"mappings":"AAAA,SACEA,KAAK,EAELC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,IAAI,EACJC,MAAM,QACD,cAAc;AAErB,OAAO,MAAMC,iBACX,+EAAmE;AAErE,OAAO,MAAMC,mBACX,gIAAoH;AAEtH;;;;;;CAMC,GACD,OAAO,SAASC,aAAaC,OAAgB;IAI3C,MAAMC,QAAQJ,eAAeK,IAAI,CAACF;IAClC,IAAI,CAACC,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLC,WAAWJ,MAAME,MAAM,CAACE,SAAS;QACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;IACnC;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,eAAeC,SAAoB;IAKjD,MAAMP,QAAQH,iBAAiBI,IAAI,CAACM;IACpC,IAAI,CAACP,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLK,SAASR,MAAME,MAAM,CAACO,cAAc;QACpCV,SAASC,MAAME,MAAM,CAACH,OAAO;QAC7BW,OAAO;YACLN,WAAWJ,MAAME,MAAM,CAACE,SAAS;YACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;QACnC;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,MAAMM,gBAAgBjB,KAAKC,UAAU,GAAG,IAAI;AAEnD;;CAEC,GACD,OAAO,MAAMiB,gBAAgBnB,QAAQE,UAAUC,gBAAgB;AAG/D,OAAO,MAAMiB,kBAAkBpB,QAAQE,UAAUE,kBAAkB;AAGnE,OAAO,MAAMiB,uBAAuBzB,MAAMwB,iBAAiB;AAE3D;;CAEC,GACD,OAAO,MAAME,cAAcxB,OAAO;IAChCyB,IAAIJ;IACJK,MAAMN;AACR,GAAG;AAGH,OAAO,MAAMO,kBAAkB3B,OAAO;IACpC;;GAEC,GACD4B,QAAQ9B,MAAM0B;IAEd;;GAEC,GACDK,SAAS5B,SAASH,MAAMsB;IAExB;;GAEC,GACDU,QAAQ7B,SAASH,MAAMsB;AACzB,GAAG;AAGH;;CAEC,GACD,OAAO,MAAMW,oBAAoB7B,QAAQE,UAAU,qBAAqB;AAGxE;;;;;CAKC,GACD,OAAO,SAAS4B,cAAcC,KAAc;IAC1C,OAAOlC,GAAGkC,OAAOF;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASG,UAAUD,KAAc;IACtC,OAAOlC,GAAGkC,OAAOZ;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,YAAYF,KAAc;IACxC,OAAOlC,GAAGkC,OAAOX;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,iBAAiBH,KAAc;IAC7C,OAAOlC,GAAGkC,OAAOV;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,YAAYJ,KAAc;IACxC,OAAOlC,GAAGkC,OAAON;AACnB"}
@@ -1,19 +1,16 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateNpmSnap = exports.SnapFileNameFromKey = exports.EXPECTED_SNAP_FILES = void 0;
4
- const icon_1 = require("./icon");
5
- const manifest_1 = require("./manifest/manifest");
6
- const validation_1 = require("./manifest/validation");
7
- const types_1 = require("./types");
8
- exports.EXPECTED_SNAP_FILES = [
1
+ import { assertIsSnapIcon } from './icon';
2
+ import { validateNpmSnapManifest } from './manifest/manifest';
3
+ import { assertIsSnapManifest } from './manifest/validation';
4
+ import { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';
5
+ export const EXPECTED_SNAP_FILES = [
9
6
  'manifest',
10
7
  'packageJson',
11
- 'sourceCode',
8
+ 'sourceCode'
12
9
  ];
13
- exports.SnapFileNameFromKey = {
14
- manifest: types_1.NpmSnapFileNames.Manifest,
15
- packageJson: types_1.NpmSnapFileNames.PackageJson,
16
- sourceCode: 'source code bundle',
10
+ export const SnapFileNameFromKey = {
11
+ manifest: NpmSnapFileNames.Manifest,
12
+ packageJson: NpmSnapFileNames.PackageJson,
13
+ sourceCode: 'source code bundle'
17
14
  };
18
15
  // TODO: Refactor this to be more shared with other validation.
19
16
  /**
@@ -25,19 +22,17 @@ exports.SnapFileNameFromKey = {
25
22
  * if any.
26
23
  * @param errorPrefix - The prefix of the error message.
27
24
  * @returns A tuple of the Snap manifest object and the Snap source code.
28
- */
29
- function validateNpmSnap(snapFiles, errorPrefix) {
30
- exports.EXPECTED_SNAP_FILES.forEach((key) => {
25
+ */ export function validateNpmSnap(snapFiles, errorPrefix) {
26
+ EXPECTED_SNAP_FILES.forEach((key)=>{
31
27
  if (!snapFiles[key]) {
32
- throw new Error(`${errorPrefix ?? ''}Missing file "${exports.SnapFileNameFromKey[key]}".`);
28
+ throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
33
29
  }
34
30
  });
35
31
  // Typecast: We are assured that the required files exist if we get here.
36
32
  const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
37
33
  try {
38
- (0, validation_1.assertIsSnapManifest)(manifest.result);
39
- }
40
- catch (error) {
34
+ assertIsSnapManifest(manifest.result);
35
+ } catch (error) {
41
36
  throw new Error(`${errorPrefix ?? ''}${error.message}`);
42
37
  }
43
38
  const validatedManifest = manifest;
@@ -46,23 +41,21 @@ function validateNpmSnap(snapFiles, errorPrefix) {
46
41
  throw new Error(`Missing file "${iconPath}".`);
47
42
  }
48
43
  try {
49
- (0, types_1.assertIsNpmSnapPackageJson)(packageJson.result);
50
- }
51
- catch (error) {
44
+ assertIsNpmSnapPackageJson(packageJson.result);
45
+ } catch (error) {
52
46
  throw new Error(`${errorPrefix ?? ''}${error.message}`);
53
47
  }
54
48
  const validatedPackageJson = packageJson;
55
- (0, manifest_1.validateNpmSnapManifest)({
49
+ validateNpmSnapManifest({
56
50
  manifest: validatedManifest,
57
51
  packageJson: validatedPackageJson,
58
52
  sourceCode,
59
- svgIcon,
53
+ svgIcon
60
54
  });
61
55
  if (svgIcon) {
62
56
  try {
63
- (0, icon_1.assertIsSnapIcon)(svgIcon);
64
- }
65
- catch (error) {
57
+ assertIsSnapIcon(svgIcon);
58
+ } catch (error) {
66
59
  throw new Error(`${errorPrefix ?? ''}${error.message}`);
67
60
  }
68
61
  }
@@ -70,8 +63,8 @@ function validateNpmSnap(snapFiles, errorPrefix) {
70
63
  manifest: validatedManifest,
71
64
  packageJson: validatedPackageJson,
72
65
  sourceCode,
73
- svgIcon,
66
+ svgIcon
74
67
  };
75
68
  }
76
- exports.validateNpmSnap = validateNpmSnap;
69
+
77
70
  //# sourceMappingURL=npm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport {\n assertIsNpmSnapPackageJson,\n NpmSnapFileNames,\n SnapFiles,\n UnvalidatedSnapFiles,\n} from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"],"names":["assertIsSnapIcon","validateNpmSnapManifest","assertIsSnapManifest","assertIsNpmSnapPackageJson","NpmSnapFileNames","EXPECTED_SNAP_FILES","SnapFileNameFromKey","manifest","Manifest","packageJson","PackageJson","sourceCode","validateNpmSnap","snapFiles","errorPrefix","forEach","key","Error","svgIcon","result","error","message","validatedManifest","iconPath","source","location","npm","validatedPackageJson"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,uBAAuB,QAAQ,sBAAsB;AAC9D,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SACEC,0BAA0B,EAC1BC,gBAAgB,QAGX,UAAU;AAEjB,OAAO,MAAMC,sBAAsB;IACjC;IACA;IACA;CACD,CAAU;AAEX,OAAO,MAAMC,sBAAsB;IACjCC,UAAUH,iBAAiBI,QAAQ;IACnCC,aAAaL,iBAAiBM,WAAW;IACzCC,YAAY;AACd,EAAW;AAEX,+DAA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ask/utils';
2
+ /**
3
+ * Normalizes relative paths by optionally removing `./` prefix.
4
+ *
5
+ * @param path - Path to make normalize.
6
+ * @returns The same path, with `./` prefix remove.
7
+ */ // TODO(ritave): Include NodeJS path polyfill and use path.normalize as well
8
+ export function normalizeRelative(path) {
9
+ assert(!path.startsWith('/'));
10
+ assert(path.search(/:|\/\//u) === -1, `Path "${path}" potentially an URI instead of local relative`);
11
+ if (path.startsWith('./')) {
12
+ return path.slice(2);
13
+ }
14
+ return path;
15
+ }
16
+
17
+ //# sourceMappingURL=path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/path.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\n/**\n * Normalizes relative paths by optionally removing `./` prefix.\n *\n * @param path - Path to make normalize.\n * @returns The same path, with `./` prefix remove.\n */\n// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well\nexport function normalizeRelative(path: string): string {\n assert(!path.startsWith('/'));\n assert(\n path.search(/:|\\/\\//u) === -1,\n `Path \"${path}\" potentially an URI instead of local relative`,\n );\n\n if (path.startsWith('./')) {\n return path.slice(2);\n }\n return path;\n}\n"],"names":["assert","normalizeRelative","path","startsWith","search","slice"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC;;;;;CAKC,GACD,4EAA4E;AAC5E,OAAO,SAASC,kBAAkBC,IAAY;IAC5CF,OAAO,CAACE,KAAKC,UAAU,CAAC;IACxBH,OACEE,KAAKE,MAAM,CAAC,eAAe,CAAC,GAC5B,CAAC,MAAM,EAAEF,KAAK,8CAA8C,CAAC;IAG/D,IAAIA,KAAKC,UAAU,CAAC,OAAO;QACzB,OAAOD,KAAKG,KAAK,CAAC;IACpB;IACA,OAAOH;AACT"}