@metamask/snaps-utils 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/cjs/auxiliary-files.js +40 -0
  3. package/dist/cjs/auxiliary-files.js.map +1 -0
  4. package/dist/cjs/errors.js +353 -3
  5. package/dist/cjs/errors.js.map +1 -1
  6. package/dist/cjs/eval-worker.js +2 -2
  7. package/dist/cjs/eval-worker.js.map +1 -1
  8. package/dist/cjs/handler-types.js +31 -0
  9. package/dist/cjs/handler-types.js.map +1 -0
  10. package/dist/cjs/handlers.js +24 -27
  11. package/dist/cjs/handlers.js.map +1 -1
  12. package/dist/cjs/index.browser.js +2 -0
  13. package/dist/cjs/index.browser.js.map +1 -1
  14. package/dist/cjs/index.executionenv.js +2 -0
  15. package/dist/cjs/index.executionenv.js.map +1 -1
  16. package/dist/cjs/index.js +9 -0
  17. package/dist/cjs/index.js.map +1 -1
  18. package/dist/cjs/manifest/manifest.js +25 -5
  19. package/dist/cjs/manifest/manifest.js.map +1 -1
  20. package/dist/cjs/manifest/validation.js +6 -1
  21. package/dist/cjs/manifest/validation.js.map +1 -1
  22. package/dist/cjs/npm.js +5 -3
  23. package/dist/cjs/npm.js.map +1 -1
  24. package/dist/cjs/snaps.js +3 -2
  25. package/dist/cjs/snaps.js.map +1 -1
  26. package/dist/cjs/types.js +0 -5
  27. package/dist/cjs/types.js.map +1 -1
  28. package/dist/cjs/validation.js.map +1 -1
  29. package/dist/cjs/virtual-file/VirtualFile.js +6 -0
  30. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -1
  31. package/dist/esm/auxiliary-files.js +28 -0
  32. package/dist/esm/auxiliary-files.js.map +1 -0
  33. package/dist/esm/errors.js +350 -1
  34. package/dist/esm/errors.js.map +1 -1
  35. package/dist/esm/eval-worker.js +1 -1
  36. package/dist/esm/eval-worker.js.map +1 -1
  37. package/dist/esm/handler-types.js +13 -0
  38. package/dist/esm/handler-types.js.map +1 -0
  39. package/dist/esm/handlers.js +7 -10
  40. package/dist/esm/handlers.js.map +1 -1
  41. package/dist/esm/index.browser.js +2 -0
  42. package/dist/esm/index.browser.js.map +1 -1
  43. package/dist/esm/index.executionenv.js +2 -0
  44. package/dist/esm/index.executionenv.js.map +1 -1
  45. package/dist/esm/index.js +3 -0
  46. package/dist/esm/index.js.map +1 -1
  47. package/dist/esm/manifest/manifest.js +30 -5
  48. package/dist/esm/manifest/manifest.js.map +1 -1
  49. package/dist/esm/manifest/validation.js +3 -1
  50. package/dist/esm/manifest/validation.js.map +1 -1
  51. package/dist/esm/npm.js +5 -3
  52. package/dist/esm/npm.js.map +1 -1
  53. package/dist/esm/snaps.js +3 -2
  54. package/dist/esm/snaps.js.map +1 -1
  55. package/dist/esm/types.js +0 -2
  56. package/dist/esm/types.js.map +1 -1
  57. package/dist/esm/validation.js.map +1 -1
  58. package/dist/esm/virtual-file/VirtualFile.js +7 -1
  59. package/dist/esm/virtual-file/VirtualFile.js.map +1 -1
  60. package/dist/types/auxiliary-files.d.ts +13 -0
  61. package/dist/types/errors.d.ts +182 -0
  62. package/dist/types/handler-types.d.ts +31 -0
  63. package/dist/types/handlers.d.ts +49 -36
  64. package/dist/types/index.browser.d.ts +2 -0
  65. package/dist/types/index.d.ts +3 -0
  66. package/dist/types/index.executionenv.d.ts +2 -0
  67. package/dist/types/manifest/manifest.d.ts +11 -1
  68. package/dist/types/manifest/validation.d.ts +6 -2
  69. package/dist/types/snaps.d.ts +13 -6
  70. package/dist/types/types.d.ts +8 -9
  71. package/dist/types/validation.d.ts +2 -2
  72. package/package.json +17 -18
package/dist/cjs/types.js CHANGED
@@ -33,9 +33,6 @@ _export(exports, {
33
33
  assertIsNpmSnapPackageJson: function() {
34
34
  return assertIsNpmSnapPackageJson;
35
35
  },
36
- SNAP_EXPORT_NAMES: function() {
37
- return SNAP_EXPORT_NAMES;
38
- },
39
36
  uri: function() {
40
37
  return uri;
41
38
  },
@@ -48,7 +45,6 @@ _export(exports, {
48
45
  });
49
46
  const _utils = require("@metamask/utils");
50
47
  const _superstruct = require("superstruct");
51
- const _handlers = require("./handlers");
52
48
  var NpmSnapFileNames;
53
49
  (function(NpmSnapFileNames) {
54
50
  NpmSnapFileNames["PackageJson"] = 'package.json';
@@ -87,7 +83,6 @@ var SNAP_STREAM_NAMES;
87
83
  SNAP_STREAM_NAMES["JSON_RPC"] = 'jsonRpc';
88
84
  SNAP_STREAM_NAMES["COMMAND"] = 'command';
89
85
  })(SNAP_STREAM_NAMES || (SNAP_STREAM_NAMES = {}));
90
- const SNAP_EXPORT_NAMES = Object.values(_handlers.HandlerType);
91
86
  const uri = (opts = {})=>(0, _superstruct.refine)((0, _superstruct.union)([
92
87
  (0, _superstruct.string)(),
93
88
  (0, _superstruct.instance)(URL)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from '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 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports } from './handlers';\nimport { HandlerType } from './handlers';\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};\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};\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\nexport type SnapId = string;\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\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\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"],"names":["NameStruct","NpmSnapPackageJsonStruct","isNpmSnapPackageJson","assertIsNpmSnapPackageJson","SNAP_EXPORT_NAMES","uri","isValidUrl","WALLET_SNAP_PERMISSION_KEY","NpmSnapFileNames","PackageJson","Manifest","size","pattern","string","type","version","VersionStruct","name","main","optional","Infinity","repository","object","url","value","is","assertStruct","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","Object","values","HandlerType","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IA4BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IA6DHC,iBAAiB;eAAjBA;;IA0BAC,GAAG;eAAHA;;IAoBGC,UAAU;eAAVA;;IAQHC,0BAA0B;eAA1BA;;;uBA1L+B;6BAcrC;0BAIqB;IAIrB;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKL,MAAMR,aAAaW,IAAAA,iBAAI,EAC5BC,IAAAA,oBAAO,EACLC,IAAAA,mBAAM,KACN,gEAEF,GACA;AAKK,MAAMZ,2BAA2Ba,IAAAA,iBAAI,EAAC;IAC3CC,SAASC,oBAAa;IACtBC,MAAMjB;IACNkB,MAAMC,IAAAA,qBAAQ,EAACR,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACjCC,YAAYF,IAAAA,qBAAQ,EAClBG,IAAAA,mBAAM,EAAC;QACLR,MAAMH,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;QACxBG,KAAKZ,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACzB;AAEJ;AAWO,SAASlB,qBACdsB,KAAc;IAEd,OAAOC,IAAAA,eAAE,EAACD,OAAOvB;AACnB;AAQO,SAASE,2BACdqB,KAAc;IAEdE,IAAAA,mBAAY,EACVF,OACAvB,0BACA,CAAC,CAAC,EAAEO,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;IA2BO;UAAKkB,cAAc;IAAdA,eACVC,SAAM;IADID,eAEVE,WAAQ;GAFEF,mBAAAA;IAYL;UAAKG,2BAA2B;IAA3BA,4BACVC,kBAAe;IADLD,4BAEVE,qBAAkB;IAFRF,4BAGVG,wBAAqB;IAHXH,4BAIVI,oBAAiB;GAJPJ,gCAAAA;IAQL;UAAKK,iBAAiB;IAAjBA,kBACVC,cAAW;IADDD,kBAEVE,aAAU;GAFAF,sBAAAA;AAML,MAAM/B,oBAAoBkC,OAAOC,MAAM,CAACC,qBAAW;AA0BnD,MAAMnC,MAAM,CAACoC,OAAwB,CAAC,CAAC,GAC5CC,IAAAA,mBAAM,EAACC,IAAAA,kBAAK,EAAC;QAAC9B,IAAAA,mBAAM;QAAI+B,IAAAA,qBAAQ,EAACC;KAAK,GAAG,OAAO,CAACrB;QAC/C,IAAI;YACF,MAAMD,MAAM,IAAIsB,IAAIrB;YAEpB,MAAMsB,YAAYhC,IAAAA,iBAAI,EAAC2B;YACvBM,IAAAA,mBAAiB,EAACxB,KAAKuB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEtB,MAAMwB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF;AASK,SAAS1C,WACdiB,GAAY,EACZkB,OAAwB,CAAC,CAAC;IAE1B,OAAOhB,IAAAA,eAAE,EAACF,KAAKlB,IAAIoC;AACrB;AAGO,MAAMlC,6BAA6B"}
1
+ {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from '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 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\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};\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};\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'\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\nexport type SnapId = string;\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"],"names":["NameStruct","NpmSnapPackageJsonStruct","isNpmSnapPackageJson","assertIsNpmSnapPackageJson","uri","isValidUrl","WALLET_SNAP_PERMISSION_KEY","NpmSnapFileNames","PackageJson","Manifest","size","pattern","string","type","version","VersionStruct","name","main","optional","Infinity","repository","object","url","value","is","assertStruct","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IA2BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IAyFHC,GAAG;eAAHA;;IAoBGC,UAAU;eAAVA;;IAQHC,0BAA0B;eAA1BA;;;uBA3L+B;6BAcrC;IAOA;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKL,MAAMP,aAAaU,IAAAA,iBAAI,EAC5BC,IAAAA,oBAAO,EACLC,IAAAA,mBAAM,KACN,gEAEF,GACA;AAKK,MAAMX,2BAA2BY,IAAAA,iBAAI,EAAC;IAC3CC,SAASC,oBAAa;IACtBC,MAAMhB;IACNiB,MAAMC,IAAAA,qBAAQ,EAACR,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACjCC,YAAYF,IAAAA,qBAAQ,EAClBG,IAAAA,mBAAM,EAAC;QACLR,MAAMH,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;QACxBG,KAAKZ,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACzB;AAEJ;AAWO,SAASjB,qBACdqB,KAAc;IAEd,OAAOC,IAAAA,eAAE,EAACD,OAAOtB;AACnB;AAQO,SAASE,2BACdoB,KAAc;IAEdE,IAAAA,mBAAY,EACVF,OACAtB,0BACA,CAAC,CAAC,EAAEM,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;IAqCO;UAAKkB,cAAc;IAAdA,eACVC,SAAM;IADID,eAEVE,WAAQ;GAFEF,mBAAAA;IAYL;UAAKG,2BAA2B;IAA3BA,4BACVC,kBAAe;IADLD,4BAEVE,qBAAkB;IAFRF,4BAGVG,wBAAqB;IAHXH,4BAIVI,oBAAiB;GAJPJ,gCAAAA;IAQL;UAAKK,iBAAiB;IAAjBA,kBACVC,cAAW;IADDD,kBAEVE,aAAU;GAFAF,sBAAAA;AAwBL,MAAM9B,MAAM,CAACiC,OAAwB,CAAC,CAAC,GAC5CC,IAAAA,mBAAM,EAACC,IAAAA,kBAAK,EAAC;QAAC3B,IAAAA,mBAAM;QAAI4B,IAAAA,qBAAQ,EAACC;KAAK,GAAG,OAAO,CAAClB;QAC/C,IAAI;YACF,MAAMD,MAAM,IAAImB,IAAIlB;YAEpB,MAAMmB,YAAY7B,IAAAA,iBAAI,EAACwB;YACvBM,IAAAA,mBAAiB,EAACrB,KAAKoB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEnB,MAAMqB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF;AASK,SAASvC,WACdiB,GAAY,EACZe,OAAwB,CAAC,CAAC;IAE1B,OAAOb,IAAAA,eAAE,EAACF,KAAKlB,IAAIiC;AACrB;AAGO,MAAM/B,6BAA6B"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { SnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["validateFetchedSnap","files","assertIsSnapManifest","manifest","result","validateSnapShasum","svgIcon","assertIsSnapIcon"],"mappings":";;;;+BAWgBA;;;eAAAA;;;sBAXiB;4BACI;uBACF;AAS5B,SAASA,oBACdC,KAA6D;IAE7DC,IAAAA,gCAAoB,EAACD,MAAME,QAAQ,CAACC,MAAM;IAC1CC,IAAAA,yBAAkB,EAACJ;IAEnB,IAAIA,MAAMK,OAAO,EAAE;QACjBC,IAAAA,sBAAgB,EAACN,MAAMK,OAAO;IAChC;AACF"}
1
+ {"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(files: FetchedSnapFiles): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["validateFetchedSnap","files","assertIsSnapManifest","manifest","result","validateSnapShasum","svgIcon","assertIsSnapIcon"],"mappings":";;;;+BAWgBA;;;eAAAA;;;sBAXiB;4BACI;uBACF;AAS5B,SAASA,oBAAoBC,KAAuB;IACzDC,IAAAA,gCAAoB,EAACD,MAAME,QAAQ,CAACC,MAAM;IAC1CC,IAAAA,yBAAkB,EAACJ;IAEnB,IAAIA,MAAMK,OAAO,EAAE;QACjBC,IAAAA,sBAAgB,EAACN,MAAMK,OAAO;IAChC;AACF"}
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "VirtualFile", {
17
17
  }
18
18
  });
19
19
  const _utils = require("@metamask/utils");
20
+ const _base = require("@scure/base");
20
21
  const _deepclone = require("../deep-clone");
21
22
  function _define_property(obj, key, value) {
22
23
  if (key in obj) {
@@ -36,6 +37,11 @@ class VirtualFile {
36
37
  if (typeof this.value === 'string') {
37
38
  (0, _utils.assert)(encoding === undefined, 'Tried to encode string.');
38
39
  return this.value;
40
+ } else if (this.value instanceof Uint8Array && encoding === 'hex') {
41
+ return (0, _utils.bytesToHex)(this.value);
42
+ } else if (this.value instanceof Uint8Array && encoding === 'base64') {
43
+ // TODO: Use @metamask/utils for this
44
+ return _base.base64.encode(this.value);
39
45
  }
40
46
  const decoder = new TextDecoder(encoding);
41
47
  return decoder.decode(this.value);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/virtual-file/VirtualFile.ts"],"sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert } from '@metamask/utils';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"],"names":["VirtualFile","toString","encoding","value","assert","undefined","decoder","TextDecoder","decode","clone","vfile","slice","result","deepClone","data","path","constructor","options","Uint8Array"],"mappings":"AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;;;;;+BAkCzCA;;;eAAAA;;;uBAjCU;2BAEG;;;;;;;;;;;;;;AA+BnB,MAAMA;IAgCXC,SAASC,QAAiB,EAAE;QAC1B,IAAI,OAAO,IAAI,CAACC,KAAK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-file/VirtualFile.ts"],"sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert, bytesToHex } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n } else if (this.value instanceof Uint8Array && encoding === 'hex') {\n return bytesToHex(this.value);\n } else if (this.value instanceof Uint8Array && encoding === 'base64') {\n // TODO: Use @metamask/utils for this\n return base64.encode(this.value);\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"],"names":["VirtualFile","toString","encoding","value","assert","undefined","Uint8Array","bytesToHex","base64","encode","decoder","TextDecoder","decode","clone","vfile","slice","result","deepClone","data","path","constructor","options"],"mappings":"AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;;;;;+BAmCzCA;;;eAAAA;;;uBAlCsB;sBACZ;2BAEG;;;;;;;;;;;;;;AA+BnB,MAAMA;IAgCXC,SAASC,QAAiB,EAAE;QAC1B,IAAI,OAAO,IAAI,CAACC,KAAK,KAAK,UAAU;YAClCC,IAAAA,aAAM,EAACF,aAAaG,WAAW;YAC/B,OAAO,IAAI,CAACF,KAAK;QACnB,OAAO,IAAI,IAAI,CAACA,KAAK,YAAYG,cAAcJ,aAAa,OAAO;YACjE,OAAOK,IAAAA,iBAAU,EAAC,IAAI,CAACJ,KAAK;QAC9B,OAAO,IAAI,IAAI,CAACA,KAAK,YAAYG,cAAcJ,aAAa,UAAU;YACpE,qCAAqC;YACrC,OAAOM,YAAM,CAACC,MAAM,CAAC,IAAI,CAACN,KAAK;QACjC;QACA,MAAMO,UAAU,IAAIC,YAAYT;QAChC,OAAOQ,QAAQE,MAAM,CAAC,IAAI,CAACT,KAAK;IAClC;IAEAU,QAAQ;QACN,MAAMC,QAAQ,IAAId;QAClB,IAAI,OAAO,IAAI,CAACG,KAAK,KAAK,UAAU;YAClCW,MAAMX,KAAK,GAAG,IAAI,CAACA,KAAK;QAC1B,OAAO;YACL,mFAAmF;YACnFW,MAAMX,KAAK,GAAG,IAAI,CAACA,KAAK,CAACY,KAAK,CAAC;QACjC;QACAD,MAAME,MAAM,GAAGC,IAAAA,oBAAS,EAAC,IAAI,CAACD,MAAM;QACpCF,MAAMI,IAAI,GAAGD,IAAAA,oBAAS,EAAC,IAAI,CAACC,IAAI;QAChCJ,MAAMK,IAAI,GAAG,IAAI,CAACA,IAAI;QACtB,OAAOL;IACT;IAzDAM,YAAYjB,KAA0B,CAAE;QAuBxCA,uBAAAA,SAAAA,KAAAA;QAEAa,uBAAAA,UAAAA,KAAAA;QAEAE,uBAAAA,QAAAA,KAAAA;QAEAC,uBAAAA,QAAAA,KAAAA;QA5BE,IAAIE;QACJ,IAAI,OAAOlB,UAAU,YAAYA,iBAAiBG,YAAY;YAC5De,UAAU;gBAAElB;YAAM;QACpB,OAAO;YACLkB,UAAUlB;QACZ;QAEA,IAAI,CAACA,KAAK,GAAGkB,SAASlB,SAAS;QAC/B,wDAAwD;QACxD,gEAAgE;QAChE,4DAA4D;QAC5D,EAAE;QACF,wEAAwE;QACxE,4EAA4E;QAC5E,8EAA8E;QAC9E,EAAE;QACF,iDAAiD;QACjD,IAAI,CAACa,MAAM,GAAGK,SAASL,UAAWX;QAClC,IAAI,CAACa,IAAI,GAAGG,SAASH,QAAQ,CAAC;QAC9B,IAAI,CAACC,IAAI,GAAGE,SAASF,QAAQ;IAC/B;AAqCF"}
@@ -0,0 +1,28 @@
1
+ import { bytesToHex, bytesToString } from '@metamask/utils';
2
+ import { base64 } from '@scure/base';
3
+ export var AuxiliaryFileEncoding;
4
+ (function(AuxiliaryFileEncoding) {
5
+ AuxiliaryFileEncoding["Base64"] = 'base64';
6
+ AuxiliaryFileEncoding["Hex"] = 'hex';
7
+ AuxiliaryFileEncoding["Utf8"] = 'utf8';
8
+ })(AuxiliaryFileEncoding || (AuxiliaryFileEncoding = {}));
9
+ /**
10
+ * Re-encodes an auxiliary file if needed depending on the requested file encoding.
11
+ *
12
+ * @param value - The base64 value stored for the auxiliary file.
13
+ * @param encoding - The chosen encoding.
14
+ * @returns The file encoded in the requested encoding.
15
+ */ export function encodeAuxiliaryFile(value, encoding) {
16
+ // Input is assumed to be the stored file in base64.
17
+ if (encoding === AuxiliaryFileEncoding.Base64) {
18
+ return value;
19
+ }
20
+ // TODO: Use @metamask/utils for this
21
+ const decoded = base64.decode(value);
22
+ if (encoding === AuxiliaryFileEncoding.Utf8) {
23
+ return bytesToString(decoded);
24
+ }
25
+ return bytesToHex(decoded);
26
+ }
27
+
28
+ //# sourceMappingURL=auxiliary-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nexport enum AuxiliaryFileEncoding {\n Base64 = 'base64',\n Hex = 'hex',\n Utf8 = 'utf8',\n}\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 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 = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["bytesToHex","bytesToString","base64","AuxiliaryFileEncoding","Base64","Hex","Utf8","encodeAuxiliaryFile","value","encoding","decoded","decode"],"mappings":"AAAA,SAASA,UAAU,EAAEC,aAAa,QAAQ,kBAAkB;AAC5D,SAASC,MAAM,QAAQ,cAAc;WAE9B;UAAKC,qBAAqB;IAArBA,sBACVC,YAAS;IADCD,sBAEVE,SAAM;IAFIF,sBAGVG,UAAO;GAHGH,0BAAAA;AAMZ;;;;;;CAMC,GACD,OAAO,SAASI,oBACdC,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaN,sBAAsBC,MAAM,EAAE;QAC7C,OAAOI;IACT;IAEA,qCAAqC;IACrC,MAAME,UAAUR,OAAOS,MAAM,CAACH;IAC9B,IAAIC,aAAaN,sBAAsBG,IAAI,EAAE;QAC3C,OAAOL,cAAcS;IACvB;IAEA,OAAOV,WAAWU;AACpB"}
@@ -1,4 +1,45 @@
1
- import { hasProperty, isObject } from '@metamask/utils';
1
+ function _check_private_redeclaration(obj, privateCollection) {
2
+ if (privateCollection.has(obj)) {
3
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
4
+ }
5
+ }
6
+ function _class_apply_descriptor_get(receiver, descriptor) {
7
+ if (descriptor.get) {
8
+ return descriptor.get.call(receiver);
9
+ }
10
+ return descriptor.value;
11
+ }
12
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
13
+ if (descriptor.set) {
14
+ descriptor.set.call(receiver, value);
15
+ } else {
16
+ if (!descriptor.writable) {
17
+ throw new TypeError("attempted to set read only private field");
18
+ }
19
+ descriptor.value = value;
20
+ }
21
+ }
22
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
23
+ if (!privateMap.has(receiver)) {
24
+ throw new TypeError("attempted to " + action + " private field on non-instance");
25
+ }
26
+ return privateMap.get(receiver);
27
+ }
28
+ function _class_private_field_get(receiver, privateMap) {
29
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
30
+ return _class_apply_descriptor_get(receiver, descriptor);
31
+ }
32
+ function _class_private_field_init(obj, privateMap, value) {
33
+ _check_private_redeclaration(obj, privateMap);
34
+ privateMap.set(obj, value);
35
+ }
36
+ function _class_private_field_set(receiver, privateMap, value) {
37
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
38
+ _class_apply_descriptor_set(receiver, descriptor, value);
39
+ return value;
40
+ }
41
+ import { errorCodes, JsonRpcError as RpcError, serializeCause } from '@metamask/rpc-errors';
42
+ import { hasProperty, isJsonRpcError, isObject, isValidJson } from '@metamask/utils';
2
43
  /**
3
44
  * Get the error message from an unknown error type.
4
45
  *
@@ -13,5 +54,313 @@ import { hasProperty, isObject } from '@metamask/utils';
13
54
  }
14
55
  return String(error);
15
56
  }
57
+ /**
58
+ * Get the error stack from an unknown error type.
59
+ *
60
+ * @param error - The error to get the stack from.
61
+ * @returns The error stack, or undefined if the error does not have a valid
62
+ * stack.
63
+ */ export function getErrorStack(error) {
64
+ if (isObject(error) && hasProperty(error, 'stack') && typeof error.stack === 'string') {
65
+ return error.stack;
66
+ }
67
+ return undefined;
68
+ }
69
+ /**
70
+ * Get the error code from an unknown error type.
71
+ *
72
+ * @param error - The error to get the code from.
73
+ * @returns The error code, or `-32603` if the error does not have a valid code.
74
+ */ export function getErrorCode(error) {
75
+ if (isObject(error) && hasProperty(error, 'code') && typeof error.code === 'number' && Number.isInteger(error.code)) {
76
+ return error.code;
77
+ }
78
+ return errorCodes.rpc.internal;
79
+ }
80
+ /**
81
+ * Get the error data from an unknown error type.
82
+ *
83
+ * @param error - The error to get the data from.
84
+ * @returns The error data, or an empty object if the error does not have valid
85
+ * data.
86
+ */ export function getErrorData(error) {
87
+ if (isObject(error) && hasProperty(error, 'data') && typeof error.data === 'object' && error.data !== null && isValidJson(error.data) && !Array.isArray(error.data)) {
88
+ return error.data;
89
+ }
90
+ return {};
91
+ }
92
+ export const SNAP_ERROR_WRAPPER_CODE = -31001;
93
+ export const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';
94
+ export const SNAP_ERROR_CODE = -31002;
95
+ export const SNAP_ERROR_MESSAGE = 'Snap Error';
96
+ var _error = /*#__PURE__*/ new WeakMap(), _message = /*#__PURE__*/ new WeakMap(), _stack = /*#__PURE__*/ new WeakMap();
97
+ export class WrappedSnapError extends Error {
98
+ /**
99
+ * The error name.
100
+ *
101
+ * @returns The error name.
102
+ */ get name() {
103
+ return 'WrappedSnapError';
104
+ }
105
+ /**
106
+ * The error message.
107
+ *
108
+ * @returns The error message.
109
+ */ get message() {
110
+ return _class_private_field_get(this, _message);
111
+ }
112
+ /**
113
+ * The error stack.
114
+ *
115
+ * @returns The error stack.
116
+ */ get stack() {
117
+ return _class_private_field_get(this, _stack);
118
+ }
119
+ /**
120
+ * Convert the error to a JSON object.
121
+ *
122
+ * @returns The JSON object.
123
+ */ toJSON() {
124
+ const cause = isSnapError(_class_private_field_get(this, _error)) ? _class_private_field_get(this, _error).serialize() : serializeCause(_class_private_field_get(this, _error));
125
+ return {
126
+ code: SNAP_ERROR_WRAPPER_CODE,
127
+ message: SNAP_ERROR_WRAPPER_MESSAGE,
128
+ data: {
129
+ cause
130
+ }
131
+ };
132
+ }
133
+ /**
134
+ * Serialize the error to a JSON object. This is called by
135
+ * `@metamask/rpc-errors` when serializing the error.
136
+ *
137
+ * @returns The JSON object.
138
+ */ serialize() {
139
+ return this.toJSON();
140
+ }
141
+ /**
142
+ * Create a new `WrappedSnapError`.
143
+ *
144
+ * @param error - The error to create the `WrappedSnapError` from.
145
+ */ constructor(error){
146
+ const message = getErrorMessage(error);
147
+ super(message);
148
+ _class_private_field_init(this, _error, {
149
+ writable: true,
150
+ value: void 0
151
+ });
152
+ _class_private_field_init(this, _message, {
153
+ writable: true,
154
+ value: void 0
155
+ });
156
+ _class_private_field_init(this, _stack, {
157
+ writable: true,
158
+ value: void 0
159
+ });
160
+ _class_private_field_set(this, _error, error);
161
+ _class_private_field_set(this, _message, message);
162
+ _class_private_field_set(this, _stack, getErrorStack(error));
163
+ }
164
+ }
165
+ var _code = /*#__PURE__*/ new WeakMap(), _message1 = /*#__PURE__*/ new WeakMap(), _data = /*#__PURE__*/ new WeakMap(), _stack1 = /*#__PURE__*/ new WeakMap();
166
+ /**
167
+ * A generic error which can be thrown by a Snap, without it causing the Snap to
168
+ * crash.
169
+ */ export class SnapError extends Error {
170
+ /**
171
+ * The error name.
172
+ *
173
+ * @returns The error name.
174
+ */ get name() {
175
+ return 'SnapError';
176
+ }
177
+ /**
178
+ * The error code.
179
+ *
180
+ * @returns The error code.
181
+ */ get code() {
182
+ return _class_private_field_get(this, _code);
183
+ }
184
+ /**
185
+ * The error message.
186
+ *
187
+ * @returns The error message.
188
+ */ get message() {
189
+ return _class_private_field_get(this, _message1);
190
+ }
191
+ /**
192
+ * Additional data for the error.
193
+ *
194
+ * @returns Additional data for the error.
195
+ */ get data() {
196
+ return _class_private_field_get(this, _data);
197
+ }
198
+ /**
199
+ * The error stack.
200
+ *
201
+ * @returns The error stack.
202
+ */ get stack() {
203
+ return _class_private_field_get(this, _stack1);
204
+ }
205
+ /**
206
+ * Convert the error to a JSON object.
207
+ *
208
+ * @returns The JSON object.
209
+ */ toJSON() {
210
+ return {
211
+ code: SNAP_ERROR_CODE,
212
+ message: SNAP_ERROR_MESSAGE,
213
+ data: {
214
+ cause: {
215
+ code: this.code,
216
+ message: this.message,
217
+ stack: this.stack,
218
+ data: this.data
219
+ }
220
+ }
221
+ };
222
+ }
223
+ /**
224
+ * Serialize the error to a JSON object. This is called by
225
+ * `@metamask/rpc-errors` when serializing the error.
226
+ *
227
+ * @returns The JSON object.
228
+ */ serialize() {
229
+ return this.toJSON();
230
+ }
231
+ /**
232
+ * Create a new `SnapError`.
233
+ *
234
+ * @param error - The error to create the `SnapError` from. If this is a
235
+ * `string`, it will be used as the error message. If this is an `Error`, its
236
+ * `message` property will be used as the error message. If this is a
237
+ * `JsonRpcError`, its `message` property will be used as the error message
238
+ * and its `code` property will be used as the error code. Otherwise, the
239
+ * error will be converted to a string and used as the error message.
240
+ * @param data - Additional data to include in the error. This will be merged
241
+ * with the error data, if any.
242
+ */ constructor(error, data = {}){
243
+ const message = getErrorMessage(error);
244
+ super(message);
245
+ _class_private_field_init(this, _code, {
246
+ writable: true,
247
+ value: void 0
248
+ });
249
+ _class_private_field_init(this, _message1, {
250
+ writable: true,
251
+ value: void 0
252
+ });
253
+ _class_private_field_init(this, _data, {
254
+ writable: true,
255
+ value: void 0
256
+ });
257
+ _class_private_field_init(this, _stack1, {
258
+ writable: true,
259
+ value: void 0
260
+ });
261
+ _class_private_field_set(this, _message1, message);
262
+ _class_private_field_set(this, _code, getErrorCode(error));
263
+ _class_private_field_set(this, _data, {
264
+ ...getErrorData(error),
265
+ ...data
266
+ });
267
+ _class_private_field_set(this, _stack1, super.stack);
268
+ }
269
+ }
270
+ /**
271
+ * Check if an object is a `SnapError`.
272
+ *
273
+ * @param error - The object to check.
274
+ * @returns Whether the object is a `SnapError`.
275
+ */ export function isSnapError(error) {
276
+ if (isObject(error) && 'serialize' in error && typeof error.serialize === 'function') {
277
+ const serialized = error.serialize();
278
+ return isJsonRpcError(serialized) && isSerializedSnapError(serialized);
279
+ }
280
+ return false;
281
+ }
282
+ /**
283
+ * Check if a JSON-RPC error is a `SnapError`.
284
+ *
285
+ * @param error - The object to check.
286
+ * @returns Whether the object is a `SnapError`.
287
+ */ export function isSerializedSnapError(error) {
288
+ return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;
289
+ }
290
+ /**
291
+ * Check if a JSON-RPC error is a `WrappedSnapError`.
292
+ *
293
+ * @param error - The object to check.
294
+ * @returns Whether the object is a `WrappedSnapError`.
295
+ */ export function isWrappedSnapError(error) {
296
+ return isJsonRpcError(error) && error.code === SNAP_ERROR_WRAPPER_CODE && error.message === SNAP_ERROR_WRAPPER_MESSAGE;
297
+ }
298
+ /**
299
+ * Get a JSON-RPC error with the given code, message, stack, and data.
300
+ *
301
+ * @param code - The error code.
302
+ * @param message - The error message.
303
+ * @param stack - The error stack.
304
+ * @param data - Additional data for the error.
305
+ * @returns The JSON-RPC error.
306
+ */ function getJsonRpcError(code, message, stack, data) {
307
+ const error = new RpcError(code, message, data);
308
+ error.stack = stack;
309
+ return error;
310
+ }
311
+ /**
312
+ * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will
313
+ * try to get the error code, message, and data from the error, and return a
314
+ * `JsonRpcError` with those properties.
315
+ *
316
+ * @param error - The error to unwrap.
317
+ * @returns A tuple containing the unwrapped error and a boolean indicating
318
+ * whether the error was handled.
319
+ */ export function unwrapError(error) {
320
+ // This logic is a bit complicated, but it's necessary to handle all the
321
+ // different types of errors that can be thrown by a Snap.
322
+ // If the error is a wrapped Snap error, unwrap it.
323
+ if (isWrappedSnapError(error)) {
324
+ // The wrapped error can be a JSON-RPC error, or an unknown error. If it's
325
+ // a JSON-RPC error, we can unwrap it further.
326
+ if (isJsonRpcError(error.data.cause)) {
327
+ // If the JSON-RPC error is a wrapped Snap error, unwrap it further.
328
+ if (isSerializedSnapError(error.data.cause)) {
329
+ const { code, message, stack, data } = error.data.cause.data.cause;
330
+ return [
331
+ getJsonRpcError(code, message, stack, data),
332
+ true
333
+ ];
334
+ }
335
+ // Otherwise, we use the original JSON-RPC error.
336
+ const { code, message, stack, data } = error.data.cause;
337
+ return [
338
+ getJsonRpcError(code, message, stack, data),
339
+ false
340
+ ];
341
+ }
342
+ // Otherwise, we throw an internal error with the wrapped error as the
343
+ // message.
344
+ return [
345
+ getJsonRpcError(errorCodes.rpc.internal, getErrorMessage(error.data.cause), getErrorStack(error.data.cause)),
346
+ false
347
+ ];
348
+ }
349
+ // The error can be a non-wrapped JSON-RPC error, in which case we can just
350
+ // re-throw it with the same code, message, and data.
351
+ if (isJsonRpcError(error)) {
352
+ const { code, message, stack, data } = error;
353
+ return [
354
+ getJsonRpcError(code, message, stack, data),
355
+ false
356
+ ];
357
+ }
358
+ // If the error is not a wrapped error, we don't know how to handle it, so we
359
+ // throw an internal error with the error as the message.
360
+ return [
361
+ getJsonRpcError(errorCodes.rpc.internal, getErrorMessage(error), getErrorStack(error)),
362
+ false
363
+ ];
364
+ }
16
365
 
17
366
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import { hasProperty, isObject } from '@metamask/utils';\n\n/**\n * Get the error message from an unknown error type.\n *\n * - If the error is an object with a `message` property, return the message.\n * - Otherwise, return the error converted to a string.\n *\n * @param error - The error to get the message from.\n * @returns The error message.\n */\nexport function getErrorMessage(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return String(error);\n}\n"],"names":["hasProperty","isObject","getErrorMessage","error","message","String"],"mappings":"AAAA,SAASA,WAAW,EAAEC,QAAQ,QAAQ,kBAAkB;AAExD;;;;;;;;CAQC,GACD,OAAO,SAASC,gBAAgBC,KAAc;IAC5C,IACEF,SAASE,UACTH,YAAYG,OAAO,cACnB,OAAOA,MAAMC,OAAO,KAAK,UACzB;QACA,OAAOD,MAAMC,OAAO;IACtB;IAEA,OAAOC,OAAOF;AAChB"}
1
+ {"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcError } from '@metamask/utils';\nimport {\n hasProperty,\n isJsonRpcError,\n isObject,\n isValidJson,\n} from '@metamask/utils';\n\n/**\n * Get the error message from an unknown error type.\n *\n * - If the error is an object with a `message` property, return the message.\n * - Otherwise, return the error converted to a string.\n *\n * @param error - The error to get the message from.\n * @returns The error message.\n */\nexport function getErrorMessage(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return String(error);\n}\n\n/**\n * Get the error stack from an unknown error type.\n *\n * @param error - The error to get the stack from.\n * @returns The error stack, or undefined if the error does not have a valid\n * stack.\n */\nexport function getErrorStack(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'stack') &&\n typeof error.stack === 'string'\n ) {\n return error.stack;\n }\n\n return undefined;\n}\n\n/**\n * Get the error code from an unknown error type.\n *\n * @param error - The error to get the code from.\n * @returns The error code, or `-32603` if the error does not have a valid code.\n */\nexport function getErrorCode(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'code') &&\n typeof error.code === 'number' &&\n Number.isInteger(error.code)\n ) {\n return error.code;\n }\n\n return errorCodes.rpc.internal;\n}\n\n/**\n * Get the error data from an unknown error type.\n *\n * @param error - The error to get the data from.\n * @returns The error data, or an empty object if the error does not have valid\n * data.\n */\nexport function getErrorData(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'data') &&\n typeof error.data === 'object' &&\n error.data !== null &&\n isValidJson(error.data) &&\n !Array.isArray(error.data)\n ) {\n return error.data;\n }\n\n return {};\n}\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport const SNAP_ERROR_CODE = -31002;\nexport const SNAP_ERROR_MESSAGE = 'Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport type SerializedSnapError = {\n code: typeof SNAP_ERROR_CODE;\n message: typeof SNAP_ERROR_MESSAGE;\n data: {\n cause: JsonRpcError & {\n data: Record<string, Json>;\n };\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error);\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * A generic error which can be thrown by a Snap, without it causing the Snap to\n * crash.\n */\nexport class SnapError extends Error {\n readonly #code: number;\n\n readonly #message: string;\n\n readonly #data: Record<string, Json>;\n\n readonly #stack?: string;\n\n /**\n * Create a new `SnapError`.\n *\n * @param error - The error to create the `SnapError` from. If this is a\n * `string`, it will be used as the error message. If this is an `Error`, its\n * `message` property will be used as the error message. If this is a\n * `JsonRpcError`, its `message` property will be used as the error message\n * and its `code` property will be used as the error code. Otherwise, the\n * error will be converted to a string and used as the error message.\n * @param data - Additional data to include in the error. This will be merged\n * with the error data, if any.\n */\n constructor(\n error: string | Error | JsonRpcError,\n data: Record<string, Json> = {},\n ) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#message = message;\n this.#code = getErrorCode(error);\n this.#data = { ...getErrorData(error), ...data };\n this.#stack = super.stack;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'SnapError';\n }\n\n /**\n * The error code.\n *\n * @returns The error code.\n */\n get code() {\n return this.#code;\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * Additional data for the error.\n *\n * @returns Additional data for the error.\n */\n get data() {\n return this.#data;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapError {\n return {\n code: SNAP_ERROR_CODE,\n message: SNAP_ERROR_MESSAGE,\n data: {\n cause: {\n code: this.code,\n message: this.message,\n stack: this.stack,\n data: this.data,\n },\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if an object is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSnapError(error: unknown): error is SnapError {\n if (\n isObject(error) &&\n 'serialize' in error &&\n typeof error.serialize === 'function'\n ) {\n const serialized = error.serialize();\n return isJsonRpcError(serialized) && isSerializedSnapError(serialized);\n }\n\n return false;\n}\n\n/**\n * Check if a JSON-RPC error is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSerializedSnapError(\n error: JsonRpcError,\n): error is SerializedSnapError {\n return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n"],"names":["errorCodes","JsonRpcError","RpcError","serializeCause","hasProperty","isJsonRpcError","isObject","isValidJson","getErrorMessage","error","message","String","getErrorStack","stack","undefined","getErrorCode","code","Number","isInteger","rpc","internal","getErrorData","data","Array","isArray","SNAP_ERROR_WRAPPER_CODE","SNAP_ERROR_WRAPPER_MESSAGE","SNAP_ERROR_CODE","SNAP_ERROR_MESSAGE","WrappedSnapError","Error","name","toJSON","cause","isSnapError","serialize","constructor","SnapError","serialized","isSerializedSnapError","isWrappedSnapError","getJsonRpcError","unwrapError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SACEA,UAAU,EACVC,gBAAgBC,QAAQ,EACxBC,cAAc,QACT,uBAAuB;AAG9B,SACEC,WAAW,EACXC,cAAc,EACdC,QAAQ,EACRC,WAAW,QACN,kBAAkB;AAEzB;;;;;;;;CAQC,GACD,OAAO,SAASC,gBAAgBC,KAAc;IAC5C,IACEH,SAASG,UACTL,YAAYK,OAAO,cACnB,OAAOA,MAAMC,OAAO,KAAK,UACzB;QACA,OAAOD,MAAMC,OAAO;IACtB;IAEA,OAAOC,OAAOF;AAChB;AAEA;;;;;;CAMC,GACD,OAAO,SAASG,cAAcH,KAAc;IAC1C,IACEH,SAASG,UACTL,YAAYK,OAAO,YACnB,OAAOA,MAAMI,KAAK,KAAK,UACvB;QACA,OAAOJ,MAAMI,KAAK;IACpB;IAEA,OAAOC;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASC,aAAaN,KAAc;IACzC,IACEH,SAASG,UACTL,YAAYK,OAAO,WACnB,OAAOA,MAAMO,IAAI,KAAK,YACtBC,OAAOC,SAAS,CAACT,MAAMO,IAAI,GAC3B;QACA,OAAOP,MAAMO,IAAI;IACnB;IAEA,OAAOhB,WAAWmB,GAAG,CAACC,QAAQ;AAChC;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,aAAaZ,KAAc;IACzC,IACEH,SAASG,UACTL,YAAYK,OAAO,WACnB,OAAOA,MAAMa,IAAI,KAAK,YACtBb,MAAMa,IAAI,KAAK,QACff,YAAYE,MAAMa,IAAI,KACtB,CAACC,MAAMC,OAAO,CAACf,MAAMa,IAAI,GACzB;QACA,OAAOb,MAAMa,IAAI;IACnB;IAEA,OAAO,CAAC;AACV;AAEA,OAAO,MAAMG,0BAA0B,CAAC,MAAM;AAC9C,OAAO,MAAMC,6BAA6B,qBAAqB;AAE/D,OAAO,M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,QAAQ,EACvBZ,gBAAgBC,QAChBG,cAAcH;QAEhB;KACD;AACH"}
@@ -1,8 +1,8 @@
1
1
  // eslint-disable-next-line import/no-unassigned-import
2
2
  import 'ses/lockdown';
3
3
  import { readFileSync } from 'fs';
4
+ import { SNAP_EXPORT_NAMES } from './handler-types';
4
5
  import { generateMockEndowments } from './mock';
5
- import { SNAP_EXPORT_NAMES } from './types';
6
6
  lockdown({
7
7
  consoleTaming: 'unsafe',
8
8
  errorTaming: 'unsafe',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handlers';\nimport { generateMockEndowments } from './mock';\nimport { SNAP_EXPORT_NAMES } from './types';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["readFileSync","generateMockEndowments","SNAP_EXPORT_NAMES","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","invalidExports","Object","keys","filter","snapExport","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe;AAEtB,SAASA,YAAY,QAAQ,KAAK;AAGlC,SAASC,sBAAsB,QAAQ,SAAS;AAChD,SAASC,iBAAiB,QAAQ,UAAU;AAI5CC,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA;;;;;;CAMC,GACD,SAASC;IACP,MAAMC,aAAaV;IACnB,OAAO;QACL,GAAGU,UAAU;QACbC,QAAQD;QACRE,MAAMF;IACR;AACF;AAEA,MAAMG,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGT,mBAAmB;IACtBU,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACrB,aAAac,cAAc;AAEvC,MAAMQ,iBAAiBC,OAAOC,IAAI,CAACP,WAAWC,OAAO,EAAEO,MAAM,CAC3D,CAACC,aAAe,CAACxB,kBAAkByB,QAAQ,CAACD;AAG9C,IAAIJ,eAAeM,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAER,eAAeS,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMjB,QAAQkB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
1
+ {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["readFileSync","SNAP_EXPORT_NAMES","generateMockEndowments","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","invalidExports","Object","keys","filter","snapExport","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe;AAEtB,SAASA,YAAY,QAAQ,KAAK;AAGlC,SAASC,iBAAiB,QAAQ,kBAAkB;AACpD,SAASC,sBAAsB,QAAQ,SAAS;AAIhDC,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA;;;;;;CAMC,GACD,SAASC;IACP,MAAMC,aAAaT;IACnB,OAAO;QACL,GAAGS,UAAU;QACbC,QAAQD;QACRE,MAAMF;IACR;AACF;AAEA,MAAMG,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGT,mBAAmB;IACtBU,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACrB,aAAac,cAAc;AAEvC,MAAMQ,iBAAiBC,OAAOC,IAAI,CAACP,WAAWC,OAAO,EAAEO,MAAM,CAC3D,CAACC,aAAe,CAACzB,kBAAkB0B,QAAQ,CAACD;AAG9C,IAAIJ,eAAeM,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAER,eAAeS,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMjB,QAAQkB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
@@ -0,0 +1,13 @@
1
+ export var HandlerType;
2
+ (function(HandlerType) {
3
+ HandlerType["OnRpcRequest"] = 'onRpcRequest';
4
+ HandlerType["OnTransaction"] = 'onTransaction';
5
+ HandlerType["OnCronjob"] = 'onCronjob';
6
+ HandlerType["OnInstall"] = 'onInstall';
7
+ HandlerType["OnUpdate"] = 'onUpdate';
8
+ HandlerType["OnNameLookup"] = 'onNameLookup';
9
+ HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
10
+ })(HandlerType || (HandlerType = {}));
11
+ export const SNAP_EXPORT_NAMES = Object.values(HandlerType);
12
+
13
+ //# sourceMappingURL=handler-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","SNAP_EXPORT_NAMES","Object","values"],"mappings":"WAAO;UAAKA,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;IALDL,YAMVM,kBAAe;IANLN,YAOVO,sBAAmB;GAPTP,gBAAAA;AAkCZ,OAAO,MAAMQ,oBAAoBC,OAAOC,MAAM,CAACV,aAAa"}
@@ -1,13 +1,6 @@
1
- export var HandlerType;
2
- (function(HandlerType) {
3
- HandlerType["OnRpcRequest"] = 'onRpcRequest';
4
- HandlerType["OnTransaction"] = 'onTransaction';
5
- HandlerType["OnCronjob"] = 'onCronjob';
6
- HandlerType["OnInstall"] = 'onInstall';
7
- HandlerType["OnUpdate"] = 'onUpdate';
8
- HandlerType["OnNameLookup"] = 'onNameLookup';
9
- HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
10
- })(HandlerType || (HandlerType = {}));
1
+ import { ComponentStruct } from '@metamask/snaps-ui';
2
+ import { literal, object, optional } from 'superstruct';
3
+ import { HandlerType } from './handler-types';
11
4
  export const SNAP_EXPORTS = {
12
5
  [HandlerType.OnRpcRequest]: {
13
6
  type: HandlerType.OnRpcRequest,
@@ -63,5 +56,9 @@ export var SeverityLevel;
63
56
  (function(SeverityLevel) {
64
57
  SeverityLevel["Critical"] = 'critical';
65
58
  })(SeverityLevel || (SeverityLevel = {}));
59
+ export const OnTransactionResponseStruct = object({
60
+ content: ComponentStruct,
61
+ severity: optional(literal(SeverityLevel.Critical))
62
+ });
66
63
 
67
64
  //# sourceMappingURL=handlers.js.map