@metamask/snaps-utils 0.37.2-flask.1 → 0.38.0-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.
package/CHANGELOG.md CHANGED
@@ -6,11 +6,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.38.0-flask.1]
10
+ ### Added
11
+ - Add `onInstall` and `onUpdate` lifecycle hooks ([#1643](https://github.com/MetaMask/snaps/pull/1643))
12
+
13
+ ### Changed
14
+ - Move source code and snap state back to controller state ([#1634](https://github.com/MetaMask/snaps/pull/1634))
15
+ - Bump `semver` to `^7.5.4` ([#1631](https://github.com/MetaMask/snaps/pull/1631))
16
+
9
17
  ## [0.37.2-flask.1]
10
18
  ### Changed
11
19
  - Release package independently ([#1600](https://github.com/MetaMask/snaps/pull/1600))
12
20
  - The version of the package no longer needs to match the version of all other
13
21
  MetaMask Snaps packages.
14
22
 
15
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@0.37.2-flask.1...HEAD
23
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@0.38.0-flask.1...HEAD
24
+ [0.38.0-flask.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@0.37.2-flask.1...@metamask/snaps-utils@0.38.0-flask.1
16
25
  [0.37.2-flask.1]: https://github.com/MetaMask/snaps/releases/tag/@metamask/snaps-utils@0.37.2-flask.1
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getErrorMessage", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getErrorMessage;
9
+ }
10
+ });
11
+ const _utils = require("@metamask/utils");
12
+ function getErrorMessage(error) {
13
+ if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'message') && typeof error.message === 'string') {
14
+ return error.message;
15
+ }
16
+ return String(error);
17
+ }
18
+
19
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +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":["getErrorMessage","error","isObject","hasProperty","message","String"],"mappings":";;;;+BAWgBA;;;eAAAA;;;uBAXsB;AAW/B,SAASA,gBAAgBC,KAAc;IAC5C,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,cACnB,OAAOA,MAAMG,OAAO,KAAK,UACzB;QACA,OAAOH,MAAMG,OAAO;IACtB;IAEA,OAAOC,OAAOJ;AAChB"}
@@ -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 { generateMockEndowments } from './mock';\nimport type { HandlerType } from './types';\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":["lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","generateMockEndowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;sBAEU;uBAEL;AAIlCA,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,aAAaC,IAAAA,4BAAsB;IACzC,OAAO;QACL,GAAGD,UAAU;QACbE,QAAQF;QACRG,MAAMH;IACR;AACF;AAEA,MAAMI,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGV,mBAAmB;IACtBW,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACC,IAAAA,gBAAY,EAACR,cAAc;AAEvC,MAAMS,iBAAiBC,OAAOC,IAAI,CAACR,WAAWC,OAAO,EAAEQ,MAAM,CAC3D,CAACC,aAAe,CAACC,wBAAiB,CAACC,QAAQ,CAACF;AAG9C,IAAIJ,eAAeO,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAET,eAAeU,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMnB,QAAQoB,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 './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":["lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","generateMockEndowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;sBAGU;uBACL;AAIlCA,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,aAAaC,IAAAA,4BAAsB;IACzC,OAAO;QACL,GAAGD,UAAU;QACbE,QAAQF;QACRG,MAAMH;IACR;AACF;AAEA,MAAMI,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGV,mBAAmB;IACtBW,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACC,IAAAA,gBAAY,EAACR,cAAc;AAEvC,MAAMS,iBAAiBC,OAAOC,IAAI,CAACR,WAAWC,OAAO,EAAEQ,MAAM,CAC3D,CAACC,aAAe,CAACC,wBAAiB,CAACC,QAAQ,CAACF;AAG9C,IAAIJ,eAAeO,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAET,eAAeU,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMnB,QAAQoB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
@@ -2,5 +2,64 @@
2
2
  Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ HandlerType: function() {
13
+ return HandlerType;
14
+ },
15
+ SNAP_EXPORTS: function() {
16
+ return SNAP_EXPORTS;
17
+ }
18
+ });
19
+ var HandlerType;
20
+ (function(HandlerType) {
21
+ HandlerType["OnRpcRequest"] = 'onRpcRequest';
22
+ HandlerType["OnTransaction"] = 'onTransaction';
23
+ HandlerType["OnCronjob"] = 'onCronjob';
24
+ HandlerType["OnInstall"] = 'onInstall';
25
+ HandlerType["OnUpdate"] = 'onUpdate';
26
+ })(HandlerType || (HandlerType = {}));
27
+ const SNAP_EXPORTS = {
28
+ [HandlerType.OnRpcRequest]: {
29
+ type: HandlerType.OnRpcRequest,
30
+ required: true,
31
+ validator: (snapExport)=>{
32
+ return typeof snapExport === 'function';
33
+ }
34
+ },
35
+ [HandlerType.OnTransaction]: {
36
+ type: HandlerType.OnTransaction,
37
+ required: true,
38
+ validator: (snapExport)=>{
39
+ return typeof snapExport === 'function';
40
+ }
41
+ },
42
+ [HandlerType.OnCronjob]: {
43
+ type: HandlerType.OnCronjob,
44
+ required: true,
45
+ validator: (snapExport)=>{
46
+ return typeof snapExport === 'function';
47
+ }
48
+ },
49
+ [HandlerType.OnInstall]: {
50
+ type: HandlerType.OnInstall,
51
+ required: false,
52
+ validator: (snapExport)=>{
53
+ return typeof snapExport === 'function';
54
+ }
55
+ },
56
+ [HandlerType.OnUpdate]: {
57
+ type: HandlerType.OnUpdate,
58
+ required: false,
59
+ validator: (snapExport)=>{
60
+ return typeof snapExport === 'function';
61
+ }
62
+ }
63
+ };
5
64
 
6
65
  //# sourceMappingURL=handlers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/handlers.ts"],"names":[],"mappings":""}
1
+ {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nexport enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n}\n\ntype 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_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n }) => Promise<unknown>;\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = {\n content: Component | null;\n};\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * A handler that can be used for the lifecycle hooks.\n */\nexport type LifecycleEventHandler = (args: {\n request: JsonRpcRequest;\n}) => Promise<unknown>;\n\n/**\n * The `onInstall` handler. This is called after the snap is installed.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnInstallHandler = LifecycleEventHandler;\n\n/**\n * The `onUpdate` handler. This is called after the snap is updated.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnUpdateHandler = LifecycleEventHandler;\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n typeof SNAP_EXPORTS[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":["SNAP_EXPORTS","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","type","required","validator","snapExport"],"mappings":";;;;;;;;;;;;;;IAmCaA,YAAY;eAAZA;;;IAhCN;UAAKC,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;GALDL,gBAAAA;AAgCL,MAAMD,eAAe;IAC1B,CAACC,YAAYC,YAAY,CAAC,EAAE;QAC1BK,MAAMN,YAAYC,YAAY;QAC9BM,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACT,YAAYE,aAAa,CAAC,EAAE;QAC3BI,MAAMN,YAAYE,aAAa;QAC/BK,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACT,YAAYG,SAAS,CAAC,EAAE;QACvBG,MAAMN,YAAYG,SAAS;QAC3BI,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACT,YAAYI,SAAS,CAAC,EAAE;QACvBE,MAAMN,YAAYI,SAAS;QAC3BG,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACT,YAAYK,QAAQ,CAAC,EAAE;QACtBC,MAAMN,YAAYK,QAAQ;QAC1BE,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;AACF"}
@@ -10,6 +10,7 @@ _export_star(require("./deep-clone"), exports);
10
10
  _export_star(require("./default-endowments"), exports);
11
11
  _export_star(require("./entropy"), exports);
12
12
  _export_star(require("./enum"), exports);
13
+ _export_star(require("./errors"), exports);
13
14
  _export_star(require("./handlers"), exports);
14
15
  _export_star(require("./iframe"), exports);
15
16
  _export_star(require("./json"), exports);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
1
+ {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './errors';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
package/dist/cjs/index.js CHANGED
@@ -11,6 +11,7 @@ _export_star(require("./default-endowments"), exports);
11
11
  _export_star(require("./entropy"), exports);
12
12
  _export_star(require("./enum"), exports);
13
13
  _export_star(require("./eval"), exports);
14
+ _export_star(require("./errors"), exports);
14
15
  _export_star(require("./fs"), exports);
15
16
  _export_star(require("./handlers"), exports);
16
17
  _export_star(require("./iframe"), exports);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["PROPOSED_NAME_REGEX","ProgrammaticallyFixableSnapError","getSnapChecksum","validateSnapShasum","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdStruct","NpmSnapIdStruct","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","stripSnapPrefix","assertIsValidSnapId","isCaipChainId","isSnapPermitted","verifyRequestedSnapPermissions","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","stableStringify","files","sourceCode","svgIcon","all","filter","file","undefined","base64","encode","checksumFiles","errorMessage","SnapValidationFailureReason","ShasumMismatch","pattern","string","LocalSnapIdSubUrlStruct","uri","protocol","enums","hostname","hash","empty","search","refine","startsWith","SnapIdPrefixes","local","error","validate","slice","length","intersection","literal","npm","pathname","normalized","errors","validForNewPackages","warnings","validateNPMPackage","assert","union","snapId","prefix","Object","values","find","possiblePrefix","replace","assertStruct","chainId","test","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapCaveatType","SnapIds","requestedPermissions","isObject","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;;;;;IAyCaA,mBAAmB;eAAnBA;;IA4HAC,gCAAgC;eAAhCA;;IAiCGC,eAAe;eAAfA;;IAiBAC,kBAAkB;eAAlBA;;IAYHC,mBAAmB;eAAnBA;;IAGAC,gBAAgB;eAAhBA;;IAQAC,iBAAiB;eAAjBA;;IAeAC,eAAe;eAAfA;;IAuBAC,gBAAgB;eAAhBA;;IASAC,YAAY;eAAZA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A,EACN7D,KAAK,EACN,CAAC4C,OAAO;AAEf;AASO,SAASnE,+BACdqF,oBAA6B;IAE7BpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACD,uBACT;IAGF,MAAM,EAAEN,aAAaQ,oBAAoB,EAAE,GAAGF;IAE9CpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACC,uBACT;IAGF,MAAM,EAAEP,OAAO,EAAE,GAAGO;IAEpBtB,IAAAA,aAAM,EACJuB,MAAMC,OAAO,CAACT,YAAYA,QAAQzB,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC0B,OAAO,GAAGD;IAEjBf,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACL,WACPA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,IACtCE,IAAAA,eAAQ,EAACL,OAAO1D,KAAK,GACvB,CAAC,8CAA8C,EAAE4D,uBAAc,CAACC,OAAO,CAAC,QAAQ,CAAC;AAErF"}
1
+ {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["PROPOSED_NAME_REGEX","ProgrammaticallyFixableSnapError","getSnapChecksum","validateSnapShasum","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdStruct","NpmSnapIdStruct","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","stripSnapPrefix","assertIsValidSnapId","isCaipChainId","isSnapPermitted","verifyRequestedSnapPermissions","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","stableStringify","files","sourceCode","svgIcon","all","filter","file","undefined","base64","encode","checksumFiles","errorMessage","SnapValidationFailureReason","ShasumMismatch","pattern","string","LocalSnapIdSubUrlStruct","uri","protocol","enums","hostname","hash","empty","search","refine","startsWith","SnapIdPrefixes","local","error","validate","slice","length","intersection","literal","npm","pathname","normalized","errors","validForNewPackages","warnings","validateNPMPackage","assert","union","snapId","prefix","Object","values","find","possiblePrefix","replace","assertStruct","chainId","test","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapCaveatType","SnapIds","requestedPermissions","isObject","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;;;;;IAyCaA,mBAAmB;eAAnBA;;IA4HAC,gCAAgC;eAAhCA;;IAiCGC,eAAe;eAAfA;;IAiBAC,kBAAkB;eAAlBA;;IAYHC,mBAAmB;eAAnBA;;IAGAC,gBAAgB;eAAhBA;;IAQAC,iBAAiB;eAAjBA;;IAeAC,eAAe;eAAfA;;IAuBAC,gBAAgB;eAAhBA;;IASAC,YAAY;eAAZA;;IAWGC,aAAa;eAAbA;;IAgBAC,eAAe;eAAfA;;IAUAC,mBAAmB;eAAnBA;;IAYAC,aAAa;eAAbA;;IAgBAC,eAAe;eAAfA;;IAsBAC,8BAA8B;eAA9BA;;;uBA7W+B;sBACxB;gFAEK;6BAYrB;+EACwB;yBAEA;0BACD;uBAGmC;;;;;;;;;;;;;;;;;;;AAY1D,MAAMf,sBACX;IAWK;UAAKgB,UAAU;IAAVA,WACVC,gBAAa;IADHD,WAEVE,cAAW;IAFDF,WAGVG,aAAU;IAHAH,WAIVI,aAAU;IAJAJ,WAKVK,aAAU;GALAL,eAAAA;IAQL;UAAKM,gBAAgB;IAAhBA,iBACVC,WAAQ;IADED,iBAEVE,UAAO;IAFGF,iBAGVG,WAAQ;IAHEH,iBAIVI,YAAS;GAJCJ,qBAAAA;AAwGL,MAAMrB,yCAAyC0B;IAGpDC,YAAYC,OAAe,EAAEC,MAAmC,CAAE;QAChE,KAAK,CAACD;QAHRC,uBAAAA,UAAAA,KAAAA;QAIE,IAAI,CAACA,MAAM,GAAGA;IAChB;AACF;AAEA;;;;;CAKC,GACD,SAASC,yBACPC,QAAmC;I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
  },
24
- HandlerType: function() {
25
- return HandlerType;
26
- },
27
24
  NameStruct: function() {
28
25
  return NameStruct;
29
26
  },
@@ -51,6 +48,7 @@ _export(exports, {
51
48
  });
52
49
  const _utils = require("@metamask/utils");
53
50
  const _superstruct = require("superstruct");
51
+ const _handlers = require("./handlers");
54
52
  var NpmSnapFileNames;
55
53
  (function(NpmSnapFileNames) {
56
54
  NpmSnapFileNames["PackageJson"] = 'package.json';
@@ -89,13 +87,7 @@ var SNAP_STREAM_NAMES;
89
87
  SNAP_STREAM_NAMES["JSON_RPC"] = 'jsonRpc';
90
88
  SNAP_STREAM_NAMES["COMMAND"] = 'command';
91
89
  })(SNAP_STREAM_NAMES || (SNAP_STREAM_NAMES = {}));
92
- var HandlerType;
93
- (function(HandlerType) {
94
- HandlerType["OnRpcRequest"] = 'onRpcRequest';
95
- HandlerType["OnTransaction"] = 'onTransaction';
96
- HandlerType["OnCronjob"] = 'onCronjob';
97
- })(HandlerType || (HandlerType = {}));
98
- const SNAP_EXPORT_NAMES = Object.values(HandlerType);
90
+ const SNAP_EXPORT_NAMES = Object.values(_handlers.HandlerType);
99
91
  const uri = (opts = {})=>(0, _superstruct.refine)((0, _superstruct.union)([
100
92
  (0, _superstruct.string)(),
101
93
  (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 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 enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n}\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","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","Object","values","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;IA2BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IAmEHC,iBAAiB;eAAjBA;;IA0BAC,GAAG;eAAHA;;IAoBGC,UAAU;eAAVA;;IAQHC,0BAA0B;eAA1BA;;;uBA/L+B;6BAcrC;IAOA;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,IA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ACF,KAAKlB,IAAIuC;AACrB;AAGO,MAAMrC,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 } 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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AAM,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"}
@@ -0,0 +1,17 @@
1
+ import { hasProperty, isObject } from '@metamask/utils';
2
+ /**
3
+ * Get the error message from an unknown error type.
4
+ *
5
+ * - If the error is an object with a `message` property, return the message.
6
+ * - Otherwise, return the error converted to a string.
7
+ *
8
+ * @param error - The error to get the message from.
9
+ * @returns The error message.
10
+ */ export function getErrorMessage(error) {
11
+ if (isObject(error) && hasProperty(error, 'message') && typeof error.message === 'string') {
12
+ return error.message;
13
+ }
14
+ return String(error);
15
+ }
16
+
17
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +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 +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 { generateMockEndowments } from './mock';\nimport type { HandlerType } from './types';\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;AAElC,SAASC,sBAAsB,QAAQ,SAAS;AAEhD,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 './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,3 +1,47 @@
1
- export { };
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 || (HandlerType = {}));
9
+ export const SNAP_EXPORTS = {
10
+ [HandlerType.OnRpcRequest]: {
11
+ type: HandlerType.OnRpcRequest,
12
+ required: true,
13
+ validator: (snapExport)=>{
14
+ return typeof snapExport === 'function';
15
+ }
16
+ },
17
+ [HandlerType.OnTransaction]: {
18
+ type: HandlerType.OnTransaction,
19
+ required: true,
20
+ validator: (snapExport)=>{
21
+ return typeof snapExport === 'function';
22
+ }
23
+ },
24
+ [HandlerType.OnCronjob]: {
25
+ type: HandlerType.OnCronjob,
26
+ required: true,
27
+ validator: (snapExport)=>{
28
+ return typeof snapExport === 'function';
29
+ }
30
+ },
31
+ [HandlerType.OnInstall]: {
32
+ type: HandlerType.OnInstall,
33
+ required: false,
34
+ validator: (snapExport)=>{
35
+ return typeof snapExport === 'function';
36
+ }
37
+ },
38
+ [HandlerType.OnUpdate]: {
39
+ type: HandlerType.OnUpdate,
40
+ required: false,
41
+ validator: (snapExport)=>{
42
+ return typeof snapExport === 'function';
43
+ }
44
+ }
45
+ };
2
46
 
3
47
  //# sourceMappingURL=handlers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<\n Params extends Json[] | Record<string, Json> | undefined =\n | Json[]\n | Record<string, Json>\n | undefined,\n> = (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n}) => Promise<unknown>;\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = {\n content: Component | null;\n};\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<\n Params extends Json[] | Record<string, Json> | undefined =\n | Json[]\n | Record<string, Json>\n | undefined,\n> = (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n onRpcRequest?: OnRpcRequestHandler;\n onTransaction?: OnTransactionHandler;\n onCronjob?: OnCronjobHandler;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":[],"mappings":"AAAA,WAgF8C"}
1
+ {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nexport enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n}\n\ntype 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_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n }) => Promise<unknown>;\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = {\n content: Component | null;\n};\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * A handler that can be used for the lifecycle hooks.\n */\nexport type LifecycleEventHandler = (args: {\n request: JsonRpcRequest;\n}) => Promise<unknown>;\n\n/**\n * The `onInstall` handler. This is called after the snap is installed.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnInstallHandler = LifecycleEventHandler;\n\n/**\n * The `onUpdate` handler. This is called after the snap is updated.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnUpdateHandler = LifecycleEventHandler;\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n typeof SNAP_EXPORTS[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":["HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","SNAP_EXPORTS","type","required","validator","snapExport"],"mappings":"WAGO;UAAKA,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;GALDL,gBAAAA;AAgCZ,OAAO,MAAMM,eAAe;IAC1B,CAACN,YAAYC,YAAY,CAAC,EAAE;QAC1BM,MAAMP,YAAYC,YAAY;QAC9BO,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYE,aAAa,CAAC,EAAE;QAC3BK,MAAMP,YAAYE,aAAa;QAC/BM,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYG,SAAS,CAAC,EAAE;QACvBI,MAAMP,YAAYG,SAAS;QAC3BK,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYI,SAAS,CAAC,EAAE;QACvBG,MAAMP,YAAYI,SAAS;QAC3BI,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYK,QAAQ,CAAC,EAAE;QACtBE,MAAMP,YAAYK,QAAQ;QAC1BG,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;AACF,EAAW"}
@@ -6,6 +6,7 @@ export * from './deep-clone';
6
6
  export * from './default-endowments';
7
7
  export * from './entropy';
8
8
  export * from './enum';
9
+ export * from './errors';
9
10
  export * from './handlers';
10
11
  export * from './iframe';
11
12
  export * from './json';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
1
+ {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './errors';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,WAAW;AACzB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
package/dist/esm/index.js CHANGED
@@ -7,6 +7,7 @@ export * from './default-endowments';
7
7
  export * from './entropy';
8
8
  export * from './enum';
9
9
  export * from './eval';
10
+ export * from './errors';
10
11
  export * from './fs';
11
12
  export * from './handlers';
12
13
  export * from './iframe';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,WAAW;AACzB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAOA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AAErC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,aAAa,QAAQ,aAAa;AAG3C,SAASC,cAAc,EAAEC,2BAA2B,EAAEC,GAAG,QAAQ,UAAU;AAG3E,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACnI,OAAO,MAAMC,sBACX,mHAAmH;WAW9G;UAAKC,UAAU;IAAVA,WACVC,gBAAa;IADHD,WAEVE,cAAW;IAFDF,WAGVG,aAAU;IAHAH,WAIVI,aAAU;IAJAJ,WAKVK,aAAU;GALAL,eAAAA;WAQL;UAAKM,gBAAgB;IAAhBA,iBACVC,WAAQ;IADED,iBAEVE,UAAO;IAFGF,iBAGVG,WAAQ;IAHEH,iBAIVI,YAAS;GAJCJ,qBAAAA;AAoGZ;;;CAGC,GACD,OAAO,MAAMK,yCAAyCC;IAGpDC,YAAYC,OAAe,EAAEC,MAAmC,CAAE;QAChE,KAAK,CA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O,CAACR,cAAcC,SAAS;AAC/C;AAEA;;;;;CAKC,GACD,OAAO,SAASQ,oBACd5C,KAAc;IAEd1C,aAAa0C,OAAOkC,cAAc;AACpC;AAEA;;;;;CAKC,GACD,OAAO,SAASW,cAAcC,OAAgB;IAC5C,OACE,OAAOA,YAAY,YACnB,+EAAmEC,IAAI,CACrED;AAGN;AAEA;;;;;;CAMC,GACD,OAAO,SAASE,gBACdC,WAAqD,EACrDb,MAAc;IAEd,OAAOc,QAEH,AACGD,CAAAA,aAAaE,aAAaC,SAASZ,KAClC,CAACa,SAAWA,OAAOC,IAAI,KAAKnF,eAAeoF,OAAO,KAC/C,CAAC,CAAA,EACNvD,KAAK,EACN,CAACoC,OAAO;AAEf;AAEA;;;;;;CAMC,GACD,OAAO,SAASoB,+BACdC,oBAA6B;IAE7BrG,OACEC,SAASoG,uBACT;IAGF,MAAM,EAAEN,aAAaO,oBAAoB,EAAE,GAAGD;IAE9CrG,OACEC,SAASqG,uBACT;IAGF,MAAM,EAAEN,OAAO,EAAE,GAAGM;IAEpBtG,OACEuG,MAAMC,OAAO,CAACR,YAAYA,QAAQ3B,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC4B,OAAO,GAAGD;IAEjBhG,OACEC,SAASgG,WACPA,OAAOC,IAAI,KAAKnF,eAAeoF,OAAO,IACtClG,SAASgG,OAAOrD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAeoF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
1
+ {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAOA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AAErC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,aAAa,QAAQ,aAAa;AAG3C,SAASC,cAAc,EAAEC,2BAA2B,EAAEC,GAAG,QAAQ,UAAU;AAG3E,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACnI,OAAO,MAAMC,sBACX,mHAAmH;WAW9G;UAAKC,UAAU;IAAVA,WACVC,gBAAa;IADHD,WAEVE,cAAW;IAFD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GED
@@ -1,5 +1,6 @@
1
1
  import { assertStruct, VersionStruct } from '@metamask/utils';
2
2
  import { instance, is, object, optional, pattern, refine, size, string, type, union, assert as assertSuperstruct } from 'superstruct';
3
+ import { HandlerType } from './handlers';
3
4
  export var NpmSnapFileNames;
4
5
  (function(NpmSnapFileNames) {
5
6
  NpmSnapFileNames["PackageJson"] = 'package.json';
@@ -50,13 +51,7 @@ export var SNAP_STREAM_NAMES;
50
51
  SNAP_STREAM_NAMES["JSON_RPC"] = 'jsonRpc';
51
52
  SNAP_STREAM_NAMES["COMMAND"] = 'command';
52
53
  })(SNAP_STREAM_NAMES || (SNAP_STREAM_NAMES = {}));
53
- export var HandlerType;
54
- (function(HandlerType) {
55
- HandlerType["OnRpcRequest"] = 'onRpcRequest';
56
- HandlerType["OnTransaction"] = 'onTransaction';
57
- HandlerType["OnCronjob"] = 'onCronjob';
58
- })(HandlerType || (HandlerType = {}));
59
- export const SNAP_EXPORT_NAMES = Object.values(HandlerType);
54
+ /* eslint-enable @typescript-eslint/naming-convention */ export const SNAP_EXPORT_NAMES = Object.values(HandlerType);
60
55
  export const uri = (opts = {})=>refine(union([
61
56
  string(),
62
57
  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 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 enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n}\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":["assertStruct","VersionStruct","instance","is","object","optional","pattern","refine","size","string","type","union","assert","assertSuperstruct","NpmSnapFileNames","PackageJson","Manifest","NameStruct","NpmSnapPackageJsonStruct","version","name","main","Infinity","repository","url","isNpmSnapPackageJson","value","assertIsNpmSnapPackageJson","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","SNAP_EXPORT_NAMES","Object","values","uri","opts","URL","UrlStruct","toString","isValidUrl","WALLET_SNAP_PERMISSION_KEY"],"mappings":"AACA,SAASA,YAAY,EAAEC,aAAa,QAAQ,kBAAkB;AAE9D,SACEC,QAAQ,EACRC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,UAAUC,iBAAiB,QACtB,cAAc;WAOd;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKZ,OAAO,MAAMG,aAAaT,KACxBF,QACEG,UACA,gEAEF,GACA,KACA;AAEF,2EAA2E;AAC3E,sBAAsB;AACtB,OAAO,MAAMS,2BAA2BR,KAAK;IAC3CS,SAASlB;IACTmB,MAAMH;IACNI,MAAMhB,SAASG,KAAKC,UAAU,GAAGa;IACjCC,YAAYlB,SACVD,OAAO;QACLM,MAAMF,KAAKC,UAAU,GAAGa;QACxBE,KAAKhB,KAAKC,UAAU,GAAGa;IACzB;AAEJ,GAAG;AAKH;;;;;CAKC,GACD,OAAO,SAASG,qBACdC,KAAc;IAEd,OAAOvB,GAAGuB,OAAOR;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASS,2BACdD,KAAc;IAEd1B,aACE0B,OACAR,0BACA,CAAC,CAAC,EAAEJ,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;WA2BO;UAAKa,cAAc;IAAdA,eACVC,SAAM;IADID,eAEVE,WAAQ;GAFEF,mBAAAA;WAYL;UAAKG,2BAA2B;IAA3BA,4BACVC,kBAAe;IADLD,4BAEVE,qBAAkB;IAFRF,4BAGVG,wBAAqB;IAHXH,4BAIVI,oBAAiB;GAJPJ,gCAAAA;WAQL;UAAKK,iBAAiB;IAAjBA,kBACVC,cAAW;IADDD,kBAEVE,aAAU;GAFAF,sBAAAA;WAML;UAAKG,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;GAHFH,gBAAAA;AAMZ,OAAO,MAAMI,oBAAoBC,OAAOC,MAAM,CAACN,aAAa;AA0B5D,OAAO,MAAMO,MAAM,CAACC,OAAwB,CAAC,CAAC,GAC5CxC,OAAOI,MAAM;QAACF;QAAUP,SAAS8C;KAAK,GAAG,OAAO,CAACtB;QAC/C,IAAI;YACF,MAAMF,MAAM,IAAIwB,IAAItB;YAEpB,MAAMuB,YAAYvC,KAAKqC;YACvBlC,kBAAkBW,KAAKyB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEvB,MAAMwB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF,GAAG;AAEL;;;;;;CAMC,GACD,OAAO,SAASC,WACd3B,GAAY,EACZuB,OAAwB,CAAC,CAAC;IAE1B,OAAO5C,GAAGqB,KAAKsB,IAAIC;AACrB;AAEA,+CAA+C;AAC/C,OAAO,MAAMK,6BAA6B,cAAc"}
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":["assertStruct","VersionStruct","instance","is","object","optional","pattern","refine","size","string","type","union","assert","assertSuperstruct","HandlerType","NpmSnapFileNames","PackageJson","Manifest","NameStruct","NpmSnapPackageJsonStruct","version","name","main","Infinity","repository","url","isNpmSnapPackageJson","value","assertIsNpmSnapPackageJson","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","SNAP_EXPORT_NAMES","Object","values","uri","opts","URL","UrlStruct","toString","isValidUrl","WALLET_SNAP_PERMISSION_KEY"],"mappings":"AACA,SAASA,YAAY,EAAEC,aAAa,QAAQ,kBAAkB;AAE9D,SACEC,QAAQ,EACRC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,UAAUC,iBAAiB,QACtB,cAAc;AAIrB,SAASC,WAAW,QAAQ,aAAa;WAIlC;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKZ,OAAO,MAAMG,aAAaV,KACxBF,QACEG,UACA,gEAEF,GACA,KACA;AAEF,2EAA2E;AAC3E,sBAAsB;AACtB,OAAO,MAAMU,2BAA2BT,KAAK;IAC3CU,SAASnB;IACToB,MAAMH;IACNI,MAAMjB,SAASG,KAAKC,UAAU,GAAGc;IACjCC,YAAYnB,SACVD,OA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error type.
3
+ *
4
+ * - If the error is an object with a `message` property, return the message.
5
+ * - Otherwise, return the error converted to a string.
6
+ *
7
+ * @param error - The error to get the message from.
8
+ * @returns The error message.
9
+ */
10
+ export declare function getErrorMessage(error: unknown): string;
@@ -1,5 +1,60 @@
1
1
  import type { Component } from '@metamask/snaps-ui';
2
- import type { Json, JsonRpcRequest } from '@metamask/utils';
2
+ import type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';
3
+ export declare enum HandlerType {
4
+ OnRpcRequest = "onRpcRequest",
5
+ OnTransaction = "onTransaction",
6
+ OnCronjob = "onCronjob",
7
+ OnInstall = "onInstall",
8
+ OnUpdate = "onUpdate"
9
+ }
10
+ declare type SnapHandler = {
11
+ /**
12
+ * The type of handler.
13
+ */
14
+ type: HandlerType;
15
+ /**
16
+ * Whether the handler is required, i.e., whether the request will fail if the
17
+ * handler is called, but the snap does not export it.
18
+ *
19
+ * This is primarily used for the lifecycle handlers, which are optional.
20
+ */
21
+ required: boolean;
22
+ /**
23
+ * Validate the given snap export. This should return a type guard for the
24
+ * handler type.
25
+ *
26
+ * @param snapExport - The export to validate.
27
+ * @returns Whether the export is valid.
28
+ */
29
+ validator: (snapExport: unknown) => boolean;
30
+ };
31
+ export declare const SNAP_EXPORTS: {
32
+ readonly onRpcRequest: {
33
+ readonly type: HandlerType.OnRpcRequest;
34
+ readonly required: true;
35
+ readonly validator: (snapExport: unknown) => snapExport is OnRpcRequestHandler<Record<string, Json> | Json[] | undefined>;
36
+ };
37
+ readonly onTransaction: {
38
+ readonly type: HandlerType.OnTransaction;
39
+ readonly required: true;
40
+ readonly validator: (snapExport: unknown) => snapExport is OnTransactionHandler;
41
+ };
42
+ readonly onCronjob: {
43
+ readonly type: HandlerType.OnCronjob;
44
+ readonly required: true;
45
+ readonly validator: (snapExport: unknown) => snapExport is OnCronjobHandler<Record<string, Json> | Json[] | undefined>;
46
+ };
47
+ readonly onInstall: {
48
+ readonly type: HandlerType.OnInstall;
49
+ readonly required: false;
50
+ readonly validator: (snapExport: unknown) => snapExport is LifecycleEventHandler;
51
+ };
52
+ readonly onUpdate: {
53
+ readonly type: HandlerType.OnUpdate;
54
+ readonly required: false;
55
+ readonly validator: (snapExport: unknown) => snapExport is LifecycleEventHandler;
56
+ };
57
+ };
3
58
  /**
4
59
  * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is
5
60
  * made to the snap.
@@ -10,7 +65,7 @@ import type { Json, JsonRpcRequest } from '@metamask/utils';
10
65
  * @param args.request - The JSON-RPC request sent to the snap.
11
66
  * @returns The JSON-RPC response. This must be a JSON-serializable value.
12
67
  */
13
- export declare type OnRpcRequestHandler<Params extends Json[] | Record<string, Json> | undefined = Json[] | Record<string, Json> | undefined> = (args: {
68
+ export declare type OnRpcRequestHandler<Params extends JsonRpcParams = JsonRpcParams> = (args: {
14
69
  origin: string;
15
70
  request: JsonRpcRequest<Params>;
16
71
  }) => Promise<unknown>;
@@ -51,18 +106,39 @@ export declare type OnTransactionHandler = (args: {
51
106
  * @param args - The request arguments.
52
107
  * @param args.request - The JSON-RPC request sent to the snap.
53
108
  */
54
- export declare type OnCronjobHandler<Params extends Json[] | Record<string, Json> | undefined = Json[] | Record<string, Json> | undefined> = (args: {
109
+ export declare type OnCronjobHandler<Params extends JsonRpcParams = JsonRpcParams> = (args: {
55
110
  request: JsonRpcRequest<Params>;
56
111
  }) => Promise<unknown>;
112
+ /**
113
+ * A handler that can be used for the lifecycle hooks.
114
+ */
115
+ export declare type LifecycleEventHandler = (args: {
116
+ request: JsonRpcRequest;
117
+ }) => Promise<unknown>;
118
+ /**
119
+ * The `onInstall` handler. This is called after the snap is installed.
120
+ *
121
+ * This type is an alias for {@link LifecycleEventHandler}.
122
+ */
123
+ export declare type OnInstallHandler = LifecycleEventHandler;
124
+ /**
125
+ * The `onUpdate` handler. This is called after the snap is updated.
126
+ *
127
+ * This type is an alias for {@link LifecycleEventHandler}.
128
+ */
129
+ export declare type OnUpdateHandler = LifecycleEventHandler;
130
+ /**
131
+ * Utility type for getting the handler function type from a handler type.
132
+ */
133
+ export declare type HandlerFunction<Type extends SnapHandler> = Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler ? Handler : never;
57
134
  /**
58
135
  * All the function-based handlers that a snap can implement.
59
136
  */
60
137
  export declare type SnapFunctionExports = {
61
- onRpcRequest?: OnRpcRequestHandler;
62
- onTransaction?: OnTransactionHandler;
63
- onCronjob?: OnCronjobHandler;
138
+ [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<typeof SNAP_EXPORTS[Key]>;
64
139
  };
65
140
  /**
66
141
  * All handlers that a snap can implement.
67
142
  */
68
143
  export declare type SnapExports = SnapFunctionExports;
144
+ export {};
@@ -6,6 +6,7 @@ export * from './deep-clone';
6
6
  export * from './default-endowments';
7
7
  export * from './entropy';
8
8
  export * from './enum';
9
+ export * from './errors';
9
10
  export * from './handlers';
10
11
  export * from './iframe';
11
12
  export * from './json';
@@ -7,6 +7,7 @@ export * from './default-endowments';
7
7
  export * from './entropy';
8
8
  export * from './enum';
9
9
  export * from './eval';
10
+ export * from './errors';
10
11
  export * from './fs';
11
12
  export * from './handlers';
12
13
  export * from './iframe';
@@ -44,12 +44,7 @@ export declare type VersionHistory = {
44
44
  version: string;
45
45
  date: number;
46
46
  };
47
- export declare type PersistedSnap = Snap & {
48
- /**
49
- * The source code of the Snap.
50
- */
51
- sourceCode: string;
52
- };
47
+ export declare type PersistedSnap = Snap;
53
48
  /**
54
49
  * A Snap as it exists in {@link SnapController} state.
55
50
  */
@@ -67,6 +62,10 @@ export declare type Snap = {
67
62
  * installed.
68
63
  */
69
64
  initialPermissions: SnapPermissions;
65
+ /**
66
+ * The source code of the Snap.
67
+ */
68
+ sourceCode: string;
70
69
  /**
71
70
  * The Snap's manifest file.
72
71
  */
@@ -2,6 +2,7 @@ import type { Json } from '@metamask/utils';
2
2
  import type { Infer, Struct } from 'superstruct';
3
3
  import type { SnapCaveatType } from './caveats';
4
4
  import type { SnapFunctionExports } from './handlers';
5
+ import { HandlerType } from './handlers';
5
6
  import type { SnapManifest } from './manifest';
6
7
  import type { VirtualFile } from './virtual-file';
7
8
  export declare enum NpmSnapFileNames {
@@ -85,11 +86,6 @@ export declare enum SNAP_STREAM_NAMES {
85
86
  JSON_RPC = "jsonRpc",
86
87
  COMMAND = "command"
87
88
  }
88
- export declare enum HandlerType {
89
- OnRpcRequest = "onRpcRequest",
90
- OnTransaction = "onTransaction",
91
- OnCronjob = "onCronjob"
92
- }
93
89
  export declare const SNAP_EXPORT_NAMES: HandlerType[];
94
90
  export declare type SnapRpcHookArgs = {
95
91
  origin: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-utils",
3
- "version": "0.37.2-flask.1",
3
+ "version": "0.38.0-flask.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/MetaMask/snaps.git"
@@ -72,7 +72,7 @@
72
72
  "@metamask/permission-controller": "^4.0.0",
73
73
  "@metamask/providers": "^11.0.0",
74
74
  "@metamask/snaps-registry": "^1.2.1",
75
- "@metamask/snaps-ui": "^0.37.2-flask.1",
75
+ "@metamask/snaps-ui": "^0.37.3-flask.1",
76
76
  "@metamask/utils": "^6.0.1",
77
77
  "@noble/hashes": "^1.3.1",
78
78
  "@scure/base": "^1.1.1",
@@ -83,7 +83,7 @@
83
83
  "fast-json-stable-stringify": "^2.1.0",
84
84
  "is-svg": "^4.4.0",
85
85
  "rfdc": "^1.3.0",
86
- "semver": "^7.3.7",
86
+ "semver": "^7.5.4",
87
87
  "ses": "^0.18.1",
88
88
  "superstruct": "^1.0.3",
89
89
  "validate-npm-package-name": "^5.0.0"
@@ -104,7 +104,7 @@
104
104
  "@types/jest": "^27.5.1",
105
105
  "@types/mocha": "^10.0.1",
106
106
  "@types/node": "^20.3.1",
107
- "@types/semver": "^7.3.10",
107
+ "@types/semver": "^7.5.0",
108
108
  "@types/validate-npm-package-name": "^4.0.0",
109
109
  "@typescript-eslint/eslint-plugin": "^5.42.1",
110
110
  "@typescript-eslint/parser": "^5.42.1",