@metamask/snaps-utils 5.2.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [6.0.0]
10
+ ### Added
11
+ - Add support for dynamic user interfaces ([#1465](https://github.com/MetaMask/snaps/pull/1465), [#2126](https://github.com/MetaMask/snaps/pull/2126))
12
+ - Add support for snap defined execution timeouts ([#2098](https://github.com/MetaMask/snaps/pull/2098))
13
+
14
+ ### Changed
15
+ - **BREAKING:** Update name lookup type validation ([#2113](https://github.com/MetaMask/snaps/pull/2113))
16
+ - The return value and the permission format has changed, see [SIP-12](https://metamask.github.io/SIPs/SIPS/sip-12) for more details.
17
+ - Speed up eval-worker for improved CLI performance ([#2147](https://github.com/MetaMask/snaps/pull/2147))
18
+ - Update MetaMask dependencies ([#2132](https://github.com/MetaMask/snaps/pull/2132), [#2142](https://github.com/MetaMask/snaps/pull/2142))
19
+
20
+ ### Fixed
21
+ - Fix initial permissions types ([#2111](https://github.com/MetaMask/snaps/pull/2111))
22
+
9
23
  ## [5.2.0]
10
24
  ### Added
11
25
  - Add support for initial connections ([#2048](https://github.com/MetaMask/snaps/pull/2048))
@@ -134,8 +148,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
134
148
  ## [0.38.1-flask.1]
135
149
  ### Changed
136
150
  - Update transaction insights response and add severity level enum ([#1653](https://github.com/MetaMask/snaps/pull/1653))
137
- - Snaps are now able to specify a `severity` for alongside their insights.
138
- - See [SIP-11](https://metamask.github.io/SIPs/SIPS/sip-11) for more information.
151
+ - Snaps are now able to specify a `severity` for alongside their insights.
152
+ - See [SIP-11](https://metamask.github.io/SIPs/SIPS/sip-11) for more information.
139
153
 
140
154
  ## [0.38.0-flask.1]
141
155
  ### Added
@@ -151,7 +165,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
151
165
  - The version of the package no longer needs to match the version of all other
152
166
  MetaMask Snaps packages.
153
167
 
154
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.2.0...HEAD
168
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@6.0.0...HEAD
169
+ [6.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.2.0...@metamask/snaps-utils@6.0.0
155
170
  [5.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.2...@metamask/snaps-utils@5.2.0
156
171
  [5.1.2]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.1...@metamask/snaps-utils@5.1.2
157
172
  [5.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.0...@metamask/snaps-utils@5.1.1
@@ -37,6 +37,12 @@ var SnapCaveatType;
37
37
  SnapCaveatType[/**
38
38
  * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.
39
39
  */ "ChainIds"] = 'chainIds';
40
+ SnapCaveatType[/**
41
+ * Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
42
+ */ "LookupMatchers"] = 'lookupMatchers';
43
+ SnapCaveatType[/**
44
+ * Caveat specifying the max request time for a handler endowment.
45
+ */ "MaxRequestTime"] = 'maxRequestTime';
40
46
  })(SnapCaveatType || (SnapCaveatType = {}));
41
47
 
42
48
  //# sourceMappingURL=caveats.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/caveats.ts"],"sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * Caveat specifying access to the signature origin, used by `endowment:signature-insight`.\n */\n SignatureOrigin = 'signatureOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n\n /**\n * The origins that a Snap can receive keyring messages from.\n */\n KeyringOrigin = 'keyringOrigin',\n\n /**\n * Caveat specifying the snap IDs that can be interacted with.\n */\n SnapIds = 'snapIds',\n\n /**\n * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.\n */\n ChainIds = 'chainIds',\n}\n"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","SignatureOrigin","RpcOrigin","KeyringOrigin","SnapIds","ChainIds"],"mappings":";;;;;;;;;;IAAO;UAAKA,cAAc;IAAdA,eACV;;GAEC,GACDC,8BAA2B;IAJjBD,eAMV;;GAEC,GACDE,wBAAqB;IATXF,eAWV;;GAEC,GACDG,iBAAc;IAdJH,eAgBV;;GAEC,GACDI,uBAAoB;IAnBVJ,eAqBV;;GAEC,GACDK,qBAAkB;IAxBRL,eA0BV;;GAEC,GACDM,eAAY;IA7BFN,eA+BV;;GAEC,GACDO,mBAAgB;IAlCNP,eAoCV;;GAEC,GACDQ,aAAU;IAvCAR,eAyCV;;GAEC,GACDS,cAAW;GA5CDT,mBAAAA"}
1
+ {"version":3,"sources":["../../src/caveats.ts"],"sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * Caveat specifying access to the signature origin, used by `endowment:signature-insight`.\n */\n SignatureOrigin = 'signatureOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n\n /**\n * The origins that a Snap can receive keyring messages from.\n */\n KeyringOrigin = 'keyringOrigin',\n\n /**\n * Caveat specifying the snap IDs that can be interacted with.\n */\n SnapIds = 'snapIds',\n\n /**\n * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.\n */\n ChainIds = 'chainIds',\n\n /**\n * Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.\n */\n LookupMatchers = 'lookupMatchers',\n\n /**\n * Caveat specifying the max request time for a handler endowment.\n */\n MaxRequestTime = 'maxRequestTime',\n}\n"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","SignatureOrigin","RpcOrigin","KeyringOrigin","SnapIds","ChainIds","LookupMatchers","MaxRequestTime"],"mappings":";;;;;;;;;;IAAO;UAAKA,cAAc;IAAdA,eACV;;GAEC,GACDC,8BAA2B;IAJjBD,eAMV;;GAEC,GACDE,wBAAqB;IATXF,eAWV;;GAEC,GACDG,iBAAc;IAdJH,eAgBV;;GAEC,GACDI,uBAAoB;IAnBVJ,eAqBV;;GAEC,GACDK,qBAAkB;IAxBRL,eA0BV;;GAEC,GACDM,eAAY;IA7BFN,eA+BV;;GAEC,GACDO,mBAAgB;IAlCNP,eAoCV;;GAEC,GACDQ,aAAU;IAvCAR,eAyCV;;GAEC,GACDS,cAAW;IA5CDT,eA8CV;;GAEC,GACDU,oBAAiB;IAjDPV,eAmDV;;GAEC,GACDW,oBAAiB;GAtDPX,mBAAAA"}
@@ -37,6 +37,8 @@ if (invalidExports.length > 0) {
37
37
  // eslint-disable-next-line no-console
38
38
  console.warn(`Invalid snap exports detected:\n${invalidExports.join('\n')}`);
39
39
  }
40
- setTimeout(()=>process.exit(0), 1000); // Hack to ensure worker exits
40
+ // To ensure the worker exits we explicitly call exit here
41
+ // If we didn't the eval would wait for timers set during Compartment eval
42
+ process.exit(0);
41
43
 
42
44
  //# sourceMappingURL=eval-worker.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nconst compartment = new Compartment({\n ...generateMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n});\n\n// Mirror BaseSnapExecutor\ncompartment.globalThis.self = compartment.globalThis;\ncompartment.globalThis.global = compartment.globalThis;\ncompartment.globalThis.window = compartment.globalThis;\n\ncompartment.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","snapFilePath","process","argv","snapModule","exports","compartment","Compartment","generateMockEndowments","module","globalThis","self","global","window","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;8BAGK;sBACK;AAIvCA,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA,MAAMC,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,MAAMC,cAAc,IAAIC,YAAY;IAClC,GAAGC,IAAAA,4BAAsB,GAAE;IAC3BC,QAAQL;IACRC,SAASD,WAAWC,OAAO;AAC7B;AAEA,0BAA0B;AAC1BC,YAAYI,UAAU,CAACC,IAAI,GAAGL,YAAYI,UAAU;AACpDJ,YAAYI,UAAU,CAACE,MAAM,GAAGN,YAAYI,UAAU;AACtDJ,YAAYI,UAAU,CAACG,MAAM,GAAGP,YAAYI,UAAU;AAEtDJ,YAAYQ,QAAQ,CAACC,IAAAA,gBAAY,EAACd,cAAc;AAEhD,MAAMe,iBAAiBC,OAAOC,IAAI,CAACd,WAAWC,OAAO,EAAEc,MAAM,CAC3D,CAACC,aAAe,CAACC,+BAAiB,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,IAAMzB,QAAQ0B,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
1
+ {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nconst compartment = new Compartment({\n ...generateMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n});\n\n// Mirror BaseSnapExecutor\ncompartment.globalThis.self = compartment.globalThis;\ncompartment.globalThis.global = compartment.globalThis;\ncompartment.globalThis.window = compartment.globalThis;\n\ncompartment.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\n// To ensure the worker exits we explicitly call exit here\n// If we didn't the eval would wait for timers set during Compartment eval\nprocess.exit(0);\n"],"names":["lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","snapFilePath","process","argv","snapModule","exports","compartment","Compartment","generateMockEndowments","module","globalThis","self","global","window","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;8BAGK;sBACK;AAIvCA,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA,MAAMC,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,MAAMC,cAAc,IAAIC,YAAY;IAClC,GAAGC,IAAAA,4BAAsB,GAAE;IAC3BC,QAAQL;IACRC,SAASD,WAAWC,OAAO;AAC7B;AAEA,0BAA0B;AAC1BC,YAAYI,UAAU,CAACC,IAAI,GAAGL,YAAYI,UAAU;AACpDJ,YAAYI,UAAU,CAACE,MAAM,GAAGN,YAAYI,UAAU;AACtDJ,YAAYI,UAAU,CAACG,MAAM,GAAGP,YAAYI,UAAU;AAEtDJ,YAAYQ,QAAQ,CAACC,IAAAA,gBAAY,EAACd,cAAc;AAEhD,MAAMe,iBAAiBC,OAAOC,IAAI,CAACd,WAAWC,OAAO,EAAEc,MAAM,CAC3D,CAACC,aAAe,CAACC,+BAAiB,CAACC,QAAQ,CAACF;AAG9C,IAAIJ,eAAeO,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAET,eAAeU,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEA,0DAA0D;AAC1D,0EAA0E;AAC1ExB,QAAQyB,IAAI,CAAC"}
@@ -27,6 +27,7 @@ var HandlerType;
27
27
  HandlerType["OnNameLookup"] = 'onNameLookup';
28
28
  HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
29
29
  HandlerType["OnHomePage"] = 'onHomePage';
30
+ HandlerType["OnUserInput"] = 'onUserInput';
30
31
  })(HandlerType || (HandlerType = {}));
31
32
  const SNAP_EXPORT_NAMES = Object.values(HandlerType);
32
33
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnSignature = 'onSignature',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["SNAP_EXPORT_NAMES","HandlerType","OnRpcRequest","OnSignature","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","Object","values"],"mappings":";;;;;;;;;;;;;;IAoCaA,iBAAiB;eAAjBA;;;IApCN;UAAKC,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,iBAAc;IAFJF,YAGVG,mBAAgB;IAHNH,YAIVI,eAAY;IAJFJ,YAKVK,eAAY;IALFL,YAMVM,cAAW;IANDN,YAOVO,kBAAe;IAPLP,YAQVQ,sBAAmB;IARTR,YASVS,gBAAa;GATHT,gBAAAA;AAoCL,MAAMD,oBAAoBW,OAAOC,MAAM,CAACX"}
1
+ {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnSignature = 'onSignature',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n OnUserInput = 'onUserInput',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["SNAP_EXPORT_NAMES","HandlerType","OnRpcRequest","OnSignature","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","OnUserInput","Object","values"],"mappings":";;;;;;;;;;;;;;IAqCaA,iBAAiB;eAAjBA;;;IArCN;UAAKC,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,iBAAc;IAFJF,YAGVG,mBAAgB;IAHNH,YAIVI,eAAY;IAJFJ,YAKVK,eAAY;IALFL,YAMVM,cAAW;IANDN,YAOVO,kBAAe;IAPLP,YAQVQ,sBAAmB;IARTR,YASVS,gBAAa;IATHT,YAUVU,iBAAc;GAVJV,gBAAAA;AAqCL,MAAMD,oBAAoBY,OAAOC,MAAM,CAACZ"}
@@ -12,14 +12,44 @@ _export(exports, {
12
12
  SNAP_EXPORTS: function() {
13
13
  return SNAP_EXPORTS;
14
14
  },
15
+ OnTransactionSeverityResponseStruct: function() {
16
+ return OnTransactionSeverityResponseStruct;
17
+ },
18
+ OnTransactionResponseWithIdStruct: function() {
19
+ return OnTransactionResponseWithIdStruct;
20
+ },
21
+ OnTransactionResponseWithContentStruct: function() {
22
+ return OnTransactionResponseWithContentStruct;
23
+ },
15
24
  OnTransactionResponseStruct: function() {
16
25
  return OnTransactionResponseStruct;
17
26
  },
18
27
  OnSignatureResponseStruct: function() {
19
28
  return OnSignatureResponseStruct;
20
29
  },
30
+ OnHomePageResponseWithContentStruct: function() {
31
+ return OnHomePageResponseWithContentStruct;
32
+ },
33
+ OnHomePageResponseWithIdStruct: function() {
34
+ return OnHomePageResponseWithIdStruct;
35
+ },
21
36
  OnHomePageResponseStruct: function() {
22
37
  return OnHomePageResponseStruct;
38
+ },
39
+ AddressResolutionStruct: function() {
40
+ return AddressResolutionStruct;
41
+ },
42
+ DomainResolutionStruct: function() {
43
+ return DomainResolutionStruct;
44
+ },
45
+ AddressResolutionResponseStruct: function() {
46
+ return AddressResolutionResponseStruct;
47
+ },
48
+ DomainResolutionResponseStruct: function() {
49
+ return DomainResolutionResponseStruct;
50
+ },
51
+ OnNameLookupResponseStruct: function() {
52
+ return OnNameLookupResponseStruct;
23
53
  }
24
54
  });
25
55
  const _snapssdk = require("@metamask/snaps-sdk");
@@ -88,15 +118,56 @@ const SNAP_EXPORTS = {
88
118
  validator: (snapExport)=>{
89
119
  return typeof snapExport === 'function';
90
120
  }
121
+ },
122
+ [_handlertypes.HandlerType.OnUserInput]: {
123
+ type: _handlertypes.HandlerType.OnUserInput,
124
+ required: true,
125
+ validator: (snapExport)=>{
126
+ return typeof snapExport === 'function';
127
+ }
91
128
  }
92
129
  };
93
- const OnTransactionResponseStruct = (0, _superstruct.nullable)((0, _superstruct.object)({
94
- content: _snapssdk.ComponentStruct,
130
+ const OnTransactionSeverityResponseStruct = (0, _superstruct.object)({
95
131
  severity: (0, _superstruct.optional)((0, _superstruct.literal)(_snapssdk.SeverityLevel.Critical))
132
+ });
133
+ const OnTransactionResponseWithIdStruct = (0, _superstruct.assign)(OnTransactionSeverityResponseStruct, (0, _superstruct.object)({
134
+ id: (0, _superstruct.string)()
135
+ }));
136
+ const OnTransactionResponseWithContentStruct = (0, _superstruct.assign)(OnTransactionSeverityResponseStruct, (0, _superstruct.object)({
137
+ content: _snapssdk.ComponentStruct
96
138
  }));
139
+ const OnTransactionResponseStruct = (0, _superstruct.nullable)((0, _superstruct.union)([
140
+ OnTransactionResponseWithContentStruct,
141
+ OnTransactionResponseWithIdStruct
142
+ ]));
97
143
  const OnSignatureResponseStruct = OnTransactionResponseStruct;
98
- const OnHomePageResponseStruct = (0, _superstruct.object)({
144
+ const OnHomePageResponseWithContentStruct = (0, _superstruct.object)({
99
145
  content: _snapssdk.ComponentStruct
100
146
  });
147
+ const OnHomePageResponseWithIdStruct = (0, _superstruct.object)({
148
+ id: (0, _superstruct.string)()
149
+ });
150
+ const OnHomePageResponseStruct = (0, _superstruct.union)([
151
+ OnHomePageResponseWithContentStruct,
152
+ OnHomePageResponseWithIdStruct
153
+ ]);
154
+ const AddressResolutionStruct = (0, _superstruct.object)({
155
+ protocol: (0, _superstruct.string)(),
156
+ resolvedDomain: (0, _superstruct.string)()
157
+ });
158
+ const DomainResolutionStruct = (0, _superstruct.object)({
159
+ protocol: (0, _superstruct.string)(),
160
+ resolvedAddress: (0, _superstruct.string)()
161
+ });
162
+ const AddressResolutionResponseStruct = (0, _superstruct.object)({
163
+ resolvedDomains: (0, _superstruct.size)((0, _superstruct.array)(AddressResolutionStruct), 1, Infinity)
164
+ });
165
+ const DomainResolutionResponseStruct = (0, _superstruct.object)({
166
+ resolvedAddresses: (0, _superstruct.size)((0, _superstruct.array)(DomainResolutionStruct), 1, Infinity)
167
+ });
168
+ const OnNameLookupResponseStruct = (0, _superstruct.nullable)((0, _superstruct.union)([
169
+ AddressResolutionResponseStruct,
170
+ DomainResolutionResponseStruct
171
+ ]));
101
172
 
102
173
  //# sourceMappingURL=handlers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type {\n OnCronjobHandler,\n OnHomePageHandler,\n OnInstallHandler,\n OnKeyringRequestHandler,\n OnNameLookupHandler,\n OnRpcRequestHandler,\n OnSignatureHandler,\n OnTransactionHandler,\n OnUpdateHandler,\n} from '@metamask/snaps-sdk';\nimport { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';\nimport { literal, nullable, object, optional } from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\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.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\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 [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnSignature]: {\n type: HandlerType.OnSignature,\n required: true,\n validator: (snapExport: unknown): snapExport is OnSignatureHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\nexport const OnTransactionResponseStruct = nullable(\n object({\n content: ComponentStruct,\n severity: optional(literal(SeverityLevel.Critical)),\n }),\n);\n\nexport const OnSignatureResponseStruct = OnTransactionResponseStruct;\n\nexport const OnHomePageResponseStruct = object({\n content: ComponentStruct,\n});\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","OnTransactionResponseStruct","OnSignatureResponseStruct","OnHomePageResponseStruct","HandlerType","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","OnSignature","nullable","object","content","ComponentStruct","severity","optional","literal","SeverityLevel","Critical"],"mappings":";;;;;;;;;;;IAuBaA,YAAY;eAAZA;;IAkEAC,2BAA2B;eAA3BA;;IAOAC,yBAAyB;eAAzBA;;IAEAC,wBAAwB;eAAxBA;;;0BAvFkC;6BACK;8BAGxB;AAQrB,MAAMH,eAAe;IAC1B,CAACI,yBAAW,CAACC,YAAY,CAAC,EAAE;QAC1BC,MAAMF,yBAAW,CAACC,YAAY;QAC9BE,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACM,aAAa,CAAC,EAAE;QAC3BJ,MAAMF,yBAAW,CAACM,aAAa;QAC/BH,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACO,SAAS,CAAC,EAAE;QACvBL,MAAMF,yBAAW,CAACO,SAAS;QAC3BJ,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACQ,YAAY,CAAC,EAAE;QAC1BN,MAAMF,yBAAW,CAACQ,YAAY;QAC9BL,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACS,SAAS,CAAC,EAAE;QACvBP,MAAMF,yBAAW,CAACS,SAAS;QAC3BN,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACU,QAAQ,CAAC,EAAE;QACtBR,MAAMF,yBAAW,CAACU,QAAQ;QAC1BP,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACW,gBAAgB,CAAC,EAAE;QAC9BT,MAAMF,yBAAW,CAACW,gBAAgB;QAClCR,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACY,UAAU,CAAC,EAAE;QACxBV,MAAMF,yBAAW,CAACY,UAAU;QAC5BT,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACa,WAAW,CAAC,EAAE;QACzBX,MAAMF,yBAAW,CAACa,WAAW;QAC7BV,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;AACF;AAEO,MAAMR,8BAA8BiB,IAAAA,qBAAQ,EACjDC,IAAAA,mBAAM,EAAC;IACLC,SAASC,yBAAe;IACxBC,UAAUC,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO,EAACC,uBAAa,CAACC,QAAQ;AACnD;AAGK,MAAMxB,4BAA4BD;AAElC,MAAME,2BAA2BgB,IAAAA,mBAAM,EAAC;IAC7CC,SAASC,yBAAe;AAC1B"}
1
+ {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type {\n OnCronjobHandler,\n OnHomePageHandler,\n OnInstallHandler,\n OnKeyringRequestHandler,\n OnNameLookupHandler,\n OnRpcRequestHandler,\n OnSignatureHandler,\n OnTransactionHandler,\n OnUpdateHandler,\n OnUserInputHandler,\n} from '@metamask/snaps-sdk';\nimport { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';\nimport {\n assign,\n literal,\n nullable,\n object,\n optional,\n string,\n array,\n size,\n union,\n} from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\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.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\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 [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnSignature]: {\n type: HandlerType.OnSignature,\n required: true,\n validator: (snapExport: unknown): snapExport is OnSignatureHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUserInput]: {\n type: HandlerType.OnUserInput,\n required: true,\n validator: (snapExport: unknown): snapExport is OnUserInputHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\nexport const OnTransactionSeverityResponseStruct = object({\n severity: optional(literal(SeverityLevel.Critical)),\n});\n\nexport const OnTransactionResponseWithIdStruct = assign(\n OnTransactionSeverityResponseStruct,\n object({\n id: string(),\n }),\n);\n\nexport const OnTransactionResponseWithContentStruct = assign(\n OnTransactionSeverityResponseStruct,\n object({\n content: ComponentStruct,\n }),\n);\n\nexport const OnTransactionResponseStruct = nullable(\n union([\n OnTransactionResponseWithContentStruct,\n OnTransactionResponseWithIdStruct,\n ]),\n);\n\nexport const OnSignatureResponseStruct = OnTransactionResponseStruct;\n\nexport const OnHomePageResponseWithContentStruct = object({\n content: ComponentStruct,\n});\n\nexport const OnHomePageResponseWithIdStruct = object({\n id: string(),\n});\n\nexport const OnHomePageResponseStruct = union([\n OnHomePageResponseWithContentStruct,\n OnHomePageResponseWithIdStruct,\n]);\n\nexport const AddressResolutionStruct = object({\n protocol: string(),\n resolvedDomain: string(),\n});\n\nexport const DomainResolutionStruct = object({\n protocol: string(),\n resolvedAddress: string(),\n});\n\nexport const AddressResolutionResponseStruct = object({\n resolvedDomains: size(array(AddressResolutionStruct), 1, Infinity),\n});\n\nexport const DomainResolutionResponseStruct = object({\n resolvedAddresses: size(array(DomainResolutionStruct), 1, Infinity),\n});\n\nexport const OnNameLookupResponseStruct = nullable(\n union([AddressResolutionResponseStruct, DomainResolutionResponseStruct]),\n);\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","OnTransactionSeverityResponseStruct","OnTransactionResponseWithIdStruct","OnTransactionResponseWithContentStruct","OnTransactionResponseStruct","OnSignatureResponseStruct","OnHomePageResponseWithContentStruct","OnHomePageResponseWithIdStruct","OnHomePageResponseStruct","AddressResolutionStruct","DomainResolutionStruct","AddressResolutionResponseStruct","DomainResolutionResponseStruct","OnNameLookupResponseStruct","HandlerType","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","OnSignature","OnUserInput","object","severity","optional","literal","SeverityLevel","Critical","assign","id","string","content","ComponentStruct","nullable","union","protocol","resolvedDomain","resolvedAddress","resolvedDomains","size","array","Infinity","resolvedAddresses"],"mappings":";;;;;;;;;;;IAkCaA,YAAY;eAAZA;;IAyEAC,mCAAmC;eAAnCA;;IAIAC,iCAAiC;eAAjCA;;IAOAC,sCAAsC;eAAtCA;;IAOAC,2BAA2B;eAA3BA;;IAOAC,yBAAyB;eAAzBA;;IAEAC,mCAAmC;eAAnCA;;IAIAC,8BAA8B;eAA9BA;;IAIAC,wBAAwB;eAAxBA;;IAKAC,uBAAuB;eAAvBA;;IAKAC,sBAAsB;eAAtBA;;IAKAC,+BAA+B;eAA/BA;;IAIAC,8BAA8B;eAA9BA;;IAIAC,0BAA0B;eAA1BA;;;0BAzJkC;6BAWxC;8BAGqB;AAQrB,MAAMb,eAAe;IAC1B,CAACc,yBAAW,CAACC,YAAY,CAAC,EAAE;QAC1BC,MAAMF,yBAAW,CAACC,YAAY;QAC9BE,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACM,aAAa,CAAC,EAAE;QAC3BJ,MAAMF,yBAAW,CAACM,aAAa;QAC/BH,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACO,SAAS,CAAC,EAAE;QACvBL,MAAMF,yBAAW,CAACO,SAAS;QAC3BJ,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAAC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AAIC,IAAAA,mBAAM;AACZ;AAGK,MAAMlC,yCAAyCgC,IAAAA,mBAAM,EAC1DlC,qCACA4B,IAAAA,mBAAM,EAAC;IACLS,SAASC,yBAAe;AAC1B;AAGK,MAAMnC,8BAA8BoC,IAAAA,qBAAQ,EACjDC,IAAAA,kBAAK,EAAC;IACJtC;IACAD;CACD;AAGI,MAAMG,4BAA4BD;AAElC,MAAME,sCAAsCuB,IAAAA,mBAAM,EAAC;IACxDS,SAASC,yBAAe;AAC1B;AAEO,MAAMhC,iCAAiCsB,IAAAA,mBAAM,EAAC;IACnDO,IAAIC,IAAAA,mBAAM;AACZ;AAEO,MAAM7B,2BAA2BiC,IAAAA,kBAAK,EAAC;IAC5CnC;IACAC;CACD;AAEM,MAAME,0BAA0BoB,IAAAA,mBAAM,EAAC;IAC5Ca,UAAUL,IAAAA,mBAAM;IAChBM,gBAAgBN,IAAAA,mBAAM;AACxB;AAEO,MAAM3B,yBAAyBmB,IAAAA,mBAAM,EAAC;IAC3Ca,UAAUL,IAAAA,mBAAM;IAChBO,iBAAiBP,IAAAA,mBAAM;AACzB;AAEO,MAAM1B,kCAAkCkB,IAAAA,mBAAM,EAAC;IACpDgB,iBAAiBC,IAAAA,iBAAI,EAACC,IAAAA,kBAAK,EAACtC,0BAA0B,GAAGuC;AAC3D;AAEO,MAAMpC,iCAAiCiB,IAAAA,mBAAM,EAAC;IACnDoB,mBAAmBH,IAAAA,iBAAI,EAACC,IAAAA,kBAAK,EAACrC,yBAAyB,GAAGsC;AAC5D;AAEO,MAAMnC,6BAA6B2B,IAAAA,qBAAQ,EAChDC,IAAAA,kBAAK,EAAC;IAAC9B;IAAiCC;CAA+B"}
@@ -33,6 +33,21 @@ _export(exports, {
33
33
  ChainIdsStruct: function() {
34
34
  return ChainIdsStruct;
35
35
  },
36
+ LookupMatchersStruct: function() {
37
+ return LookupMatchersStruct;
38
+ },
39
+ MINIMUM_REQUEST_TIMEOUT: function() {
40
+ return MINIMUM_REQUEST_TIMEOUT;
41
+ },
42
+ MAXIMUM_REQUEST_TIMEOUT: function() {
43
+ return MAXIMUM_REQUEST_TIMEOUT;
44
+ },
45
+ MaxRequestTimeStruct: function() {
46
+ return MaxRequestTimeStruct;
47
+ },
48
+ HandlerCaveatsStruct: function() {
49
+ return HandlerCaveatsStruct;
50
+ },
36
51
  PermissionsStruct: function() {
37
52
  return PermissionsStruct;
38
53
  },
@@ -128,26 +143,47 @@ const SnapIdsStruct = (0, _superstruct.refine)((0, _superstruct.record)(_snaps.S
128
143
  }
129
144
  return true;
130
145
  });
131
- const ChainIdsStruct = (0, _superstruct.array)(_namespace.ChainIdStruct);
146
+ const ChainIdsStruct = (0, _superstruct.size)((0, _superstruct.array)(_namespace.ChainIdStruct), 1, Infinity);
147
+ const LookupMatchersStruct = (0, _superstruct.union)([
148
+ (0, _superstruct.object)({
149
+ tlds: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity)
150
+ }),
151
+ (0, _superstruct.object)({
152
+ schemes: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity)
153
+ }),
154
+ (0, _superstruct.object)({
155
+ tlds: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity),
156
+ schemes: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity)
157
+ })
158
+ ]);
159
+ const MINIMUM_REQUEST_TIMEOUT = (0, _utils.inMilliseconds)(5, _utils.Duration.Second);
160
+ const MAXIMUM_REQUEST_TIMEOUT = (0, _utils.inMilliseconds)(3, _utils.Duration.Minute);
161
+ const MaxRequestTimeStruct = (0, _superstruct.size)((0, _superstruct.integer)(), MINIMUM_REQUEST_TIMEOUT, MAXIMUM_REQUEST_TIMEOUT);
162
+ const HandlerCaveatsStruct = (0, _superstruct.object)({
163
+ maxRequestTime: (0, _superstruct.optional)(MaxRequestTimeStruct)
164
+ });
132
165
  const PermissionsStruct = (0, _superstruct.type)({
166
+ 'endowment:cronjob': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
167
+ jobs: _cronjob.CronjobSpecificationArrayStruct
168
+ }))),
133
169
  'endowment:ethereum-provider': (0, _superstruct.optional)((0, _superstruct.object)({})),
170
+ 'endowment:keyring': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, _jsonrpc.KeyringOriginsStruct)),
171
+ 'endowment:lifecycle-hooks': (0, _superstruct.optional)(HandlerCaveatsStruct),
172
+ 'endowment:name-lookup': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
173
+ chains: (0, _superstruct.optional)(ChainIdsStruct),
174
+ matchers: (0, _superstruct.optional)(LookupMatchersStruct)
175
+ }))),
134
176
  'endowment:network-access': (0, _superstruct.optional)((0, _superstruct.object)({})),
135
- 'endowment:webassembly': (0, _superstruct.optional)((0, _superstruct.object)({})),
136
- 'endowment:signature-insight': (0, _superstruct.optional)((0, _superstruct.object)({
177
+ 'endowment:page-home': (0, _superstruct.optional)(HandlerCaveatsStruct),
178
+ 'endowment:rpc': (0, _superstruct.optional)(_jsonrpc.RpcOriginsStruct),
179
+ 'endowment:signature-insight': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
137
180
  allowSignatureOrigin: (0, _superstruct.optional)((0, _superstruct.boolean)())
138
- })),
139
- 'endowment:transaction-insight': (0, _superstruct.optional)((0, _superstruct.object)({
181
+ }))),
182
+ 'endowment:transaction-insight': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
140
183
  allowTransactionOrigin: (0, _superstruct.optional)((0, _superstruct.boolean)())
141
- })),
142
- 'endowment:cronjob': (0, _superstruct.optional)((0, _superstruct.object)({
143
- jobs: _cronjob.CronjobSpecificationArrayStruct
144
- })),
145
- 'endowment:rpc': (0, _superstruct.optional)(_jsonrpc.RpcOriginsStruct),
146
- 'endowment:name-lookup': (0, _superstruct.optional)(ChainIdsStruct),
147
- 'endowment:keyring': (0, _superstruct.optional)(_jsonrpc.KeyringOriginsStruct),
184
+ }))),
185
+ 'endowment:webassembly': (0, _superstruct.optional)((0, _superstruct.object)({})),
148
186
  snap_dialog: (0, _superstruct.optional)((0, _superstruct.object)({})),
149
- // TODO: Remove
150
- snap_confirm: (0, _superstruct.optional)((0, _superstruct.object)({})),
151
187
  snap_manageState: (0, _superstruct.optional)((0, _superstruct.object)({})),
152
188
  snap_manageAccounts: (0, _superstruct.optional)((0, _superstruct.object)({})),
153
189
  snap_notify: (0, _superstruct.optional)((0, _superstruct.object)({})),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n intersection,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport type { InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames, uri } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:ethereum-provider': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:signature-insight': optional(\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n snap_getLocale: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const InitialConnectionsStruct = record(\n intersection([string(), uri()]),\n object({}),\n);\n\nexport type InitialConnections = Infer<typeof InitialConnectionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialConnections: optional(InitialConnectionsStruct),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","InitialConnectionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowSignatureOrigin","boolean","allowTransactionOrigin","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","KeyringOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","snap_getLocale","wallet_snap","intersection","uri","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","files","locales","initialConnections","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA4CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAGAC,iBAAiB;eAAjBA;;IA8CAC,uBAAuB;eAAvBA;;IAEAC,wBAAwB;eAAxBA;;IAOAC,kBAAkB;eAAlBA;;IAwCGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBA5QwB;uBAOjC;6BAmBA;uBAEiB;yBACwB;yBACgB;yBACT;2BACzB;uBACD;uBAEqB;AAElD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCC,0BAAiB;IACjBC,qCAA4B;CAC7B;AAEM,MAAMjB,uBAAiC;IAAC;CAAG;AAClD,MAAMkB,kBAA8BlB,qBAAqBmB,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAEM,MAAMnB,kBAAkBoB,IAAAA,mBAAM,EACnCC,IA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BAAM,KAAI,GAAGkB;IACzB;IAEFoC,QAAQhC,IAAAA,mBAAM,EAAC;QACbiC,QAAQC,qBAAc;QACtBC,UAAUnC,IAAAA,mBAAM,EAAC;YACfoC,KAAKpC,IAAAA,mBAAM,EAAC;gBACVqC,UAAU1C,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBAC5B0C,UAAUpC,IAAAA,qBAAQ,EAACP,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBACrC2C,aAAaC,iBAAU;gBACvBC,UAAUC,IAAAA,kBAAK,EAAC;oBACdC,IAAAA,oBAAO,EAAC;oBACRA,IAAAA,oBAAO,EAAC;iBACT;YACH;QACF;QACAC,OAAO1C,IAAAA,qBAAQ,EAACtC;QAChBiF,SAAS3C,IAAAA,qBAAQ,EAACtC;IACpB;IACAkF,oBAAoB5C,IAAAA,qBAAQ,EAACrC;IAC7BkF,oBAAoBpF;IACpBqF,iBAAiBL,IAAAA,oBAAO,EAAC;IACzBM,SAAS/C,IAAAA,qBAAQ,EAACxB,IAAAA,mBAAM;AAC1B;AAUO,SAASX,eAAeuB,KAAc;IAC3C,OAAO4D,IAAAA,eAAE,EAAC5D,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEd6D,IAAAA,mBAAY,EACV7D,OACAxB,oBACA,CAAC,CAAC,EAAEsF,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAASpF,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAOgE,IAAAA,mBAAM,EAAChE,OAAOxB;AACvB"}
1
+ {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n inMilliseconds,\n Duration,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n intersection,\n assign,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport type { InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames, uri } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = size(array(ChainIdStruct), 1, Infinity);\n\nexport const LookupMatchersStruct = union([\n object({\n tlds: size(array(string()), 1, Infinity),\n }),\n object({\n schemes: size(array(string()), 1, Infinity),\n }),\n object({\n tlds: size(array(string()), 1, Infinity),\n schemes: size(array(string()), 1, Infinity),\n }),\n]);\n\nexport const MINIMUM_REQUEST_TIMEOUT = inMilliseconds(5, Duration.Second);\nexport const MAXIMUM_REQUEST_TIMEOUT = inMilliseconds(3, Duration.Minute);\n\nexport const MaxRequestTimeStruct = size(\n integer(),\n MINIMUM_REQUEST_TIMEOUT,\n MAXIMUM_REQUEST_TIMEOUT,\n);\n\n// Utility type to union with for all handler structs\nexport const HandlerCaveatsStruct = object({\n maxRequestTime: optional(MaxRequestTimeStruct),\n});\n\nexport type HandlerCaveats = Infer<typeof HandlerCaveatsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:cronjob': optional(\n assign(\n HandlerCaveatsStruct,\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n ),\n 'endowment:ethereum-provider': optional(object({})),\n 'endowment:keyring': optional(\n assign(HandlerCaveatsStruct, KeyringOriginsStruct),\n ),\n 'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),\n 'endowment:name-lookup': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n chains: optional(ChainIdsStruct),\n matchers: optional(LookupMatchersStruct),\n }),\n ),\n ),\n 'endowment:network-access': optional(object({})),\n 'endowment:page-home': optional(HandlerCaveatsStruct),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:signature-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:transaction-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:webassembly': optional(object({})),\n snap_dialog: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n snap_getLocale: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const InitialConnectionsStruct = record(\n intersection([string(), uri()]),\n object({}),\n);\n\nexport type InitialConnections = Infer<typeof InitialConnectionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialConnections: optional(InitialConnectionsStruct),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","LookupMatchersStruct","MINIMUM_REQUEST_TIMEOUT","MAXIMUM_REQUEST_TIMEOUT","MaxRequestTimeStruct","HandlerCaveatsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","InitialConnectionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","union","tlds","schemes","inMilliseconds","Duration","Second","Minute","integer","maxRequestTime","assign","jobs","CronjobSpecificationArrayStruct","KeyringOriginsStruct","chains","matchers","RpcOriginsStruct","allowSignatureOrigin","boolean","allowTransactionOrigin","snap_dialog","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","snap_getLocale","wallet_snap","intersection","uri","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","literal","files","locales","initialConnections","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA+CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAEAC,oBAAoB;eAApBA;;IAaAC,uBAAuB;eAAvBA;;IACAC,uBAAuB;eAAvBA;;IAEAC,oBAAoB;eAApBA;;IAOAC,oBAAoB;eAApBA;;IAOAC,iBAAiB;eAAjBA;;IAiEAC,uBAAuB;eAAvBA;;IAEAC,wBAAwB;eAAxBA;;IAOAC,kBAAkB;eAAlBA;;IAwCGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC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ACrE,OAAOyE,IAAAA,mBAAM,EAACzE,OAAOxB;AACvB"}
@@ -41,13 +41,36 @@ _export(exports, {
41
41
  },
42
42
  getStructErrorMessage: function() {
43
43
  return getStructErrorMessage;
44
+ },
45
+ validateUnion: function() {
46
+ return validateUnion;
47
+ },
48
+ createUnion: function() {
49
+ return createUnion;
44
50
  }
45
51
  });
52
+ const _snapssdk = require("@metamask/snaps-sdk");
46
53
  const _utils = require("@metamask/utils");
47
54
  const _chalk = require("chalk");
48
55
  const _path = require("path");
49
56
  const _superstruct = require("superstruct");
50
57
  const _strings = require("./strings");
58
+ /**
59
+ * Colorize a value with a color function. This is useful for colorizing values
60
+ * in error messages. If colorization is disabled, the original value is
61
+ * returned.
62
+ *
63
+ * @param value - The value to colorize.
64
+ * @param colorFunction - The color function to use.
65
+ * @param enabled - Whether to colorize the value.
66
+ * @returns The colorized value, or the original value if colorization is
67
+ * disabled.
68
+ */ function color(value, colorFunction, enabled) {
69
+ if (enabled) {
70
+ return colorFunction(value);
71
+ }
72
+ return value;
73
+ }
51
74
  function file() {
52
75
  return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{
53
76
  return (0, _path.resolve)(process.cwd(), value);
@@ -60,12 +83,12 @@ function named(name, struct) {
60
83
  });
61
84
  }
62
85
  class SnapsStructError extends _superstruct.StructError {
63
- constructor(struct, prefix, suffix, failure, failures){
86
+ constructor(struct, prefix, suffix, failure, failures, colorize = true){
64
87
  super(failure, failures);
65
88
  this.name = 'SnapsStructError';
66
89
  this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
67
90
  ...failures()
68
- ])}${suffix ? `\n\n${suffix}` : ''}`;
91
+ ], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
69
92
  }
70
93
  }
71
94
  function* arrayToGenerator(array) {
@@ -73,8 +96,8 @@ function* arrayToGenerator(array) {
73
96
  yield item;
74
97
  }
75
98
  }
76
- function getError({ struct, prefix, suffix = '', error }) {
77
- return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
99
+ function getError({ struct, prefix, suffix = '', error, colorize }) {
100
+ return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
78
101
  }
79
102
  function createFromStruct(value, struct, prefix, suffix = '') {
80
103
  try {
@@ -99,24 +122,24 @@ function getStructFromPath(struct, path) {
99
122
  return result;
100
123
  }, struct);
101
124
  }
102
- function getUnionStructNames(struct) {
125
+ function getUnionStructNames(struct, colorize = true) {
103
126
  if (Array.isArray(struct.schema)) {
104
- return struct.schema.map(({ type })=>(0, _chalk.green)(type));
127
+ return struct.schema.map(({ type })=>color(type, _chalk.green, colorize));
105
128
  }
106
129
  return null;
107
130
  }
108
- function getStructErrorPrefix(failure) {
131
+ function getStructErrorPrefix(failure, colorize = true) {
109
132
  if (failure.type === 'never' || failure.path.length === 0) {
110
133
  return '';
111
134
  }
112
- return `At path: ${(0, _chalk.bold)(failure.path.join('.'))} — `;
135
+ return `At path: ${color(failure.path.join('.'), _chalk.bold, colorize)} — `;
113
136
  }
114
- function getStructFailureMessage(struct, failure) {
115
- const received = (0, _chalk.red)(JSON.stringify(failure.value));
116
- const prefix = getStructErrorPrefix(failure);
137
+ function getStructFailureMessage(struct, failure, colorize = true) {
138
+ const received = color(JSON.stringify(failure.value), _chalk.red, colorize);
139
+ const prefix = getStructErrorPrefix(failure, colorize);
117
140
  if (failure.type === 'union') {
118
141
  const childStruct = getStructFromPath(struct, failure.path);
119
- const unionNames = getUnionStructNames(childStruct);
142
+ const unionNames = getUnionStructNames(childStruct, colorize);
120
143
  if (unionNames) {
121
144
  return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
122
145
  }
@@ -125,17 +148,63 @@ function getStructFailureMessage(struct, failure) {
125
148
  if (failure.type === 'literal') {
126
149
  // Superstruct's failure does not provide information about which literal
127
150
  // value was expected, so we need to parse the message to get the literal.
128
- const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${(0, _chalk.green)('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${(0, _chalk.red)('$1')}`);
151
+ const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', _chalk.green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', _chalk.red, colorize)}`);
129
152
  return `${prefix}${message}.`;
130
153
  }
131
154
  if (failure.type === 'never') {
132
- return `Unknown key: ${(0, _chalk.bold)(failure.path.join('.'))}, received: ${received}.`;
155
+ return `Unknown key: ${color(failure.path.join('.'), _chalk.bold, colorize)}, received: ${received}.`;
133
156
  }
134
- return `${prefix}Expected a value of type ${(0, _chalk.green)(failure.type)}, but received: ${received}.`;
157
+ if (failure.refinement === 'size') {
158
+ const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', _chalk.green, colorize)} and ${color('$2', _chalk.green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', _chalk.red, colorize)}`).replace(/a array/u, 'an array');
159
+ return `${prefix}${message}.`;
160
+ }
161
+ return `${prefix}Expected a value of type ${color(failure.type, _chalk.green, colorize)}, but received: ${received}.`;
135
162
  }
136
- function getStructErrorMessage(struct, failures) {
137
- const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure)}`));
163
+ function getStructErrorMessage(struct, failures, colorize = true) {
164
+ const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure, colorize)}`));
138
165
  return formattedFailures.join('\n');
139
166
  }
167
+ function validateUnion(value, struct, structKey, coerce = false) {
168
+ (0, _utils.assert)(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
169
+ (0, _utils.assert)(struct.schema.length > 0, 'Expected a non-empty array of structs.');
170
+ const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
171
+ const key = (0, _superstruct.type)({
172
+ [structKey]: (0, _snapssdk.union)(keyUnion)
173
+ });
174
+ const [keyError] = (0, _superstruct.validate)(value, key, {
175
+ coerce
176
+ });
177
+ if (keyError) {
178
+ throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
179
+ }
180
+ // At this point it's guaranteed that the value is an object, so we can safely
181
+ // cast it to a Record.
182
+ const objectValue = value;
183
+ const objectStructs = struct.schema.filter((innerStruct)=>(0, _superstruct.is)(objectValue[structKey], innerStruct.schema[structKey]));
184
+ (0, _utils.assert)(objectStructs.length > 0, 'Expected a struct to match the value.');
185
+ // We need to validate the value against all the object structs that match the
186
+ // struct key, and return the first validated value.
187
+ const validationResults = objectStructs.map((objectStruct)=>(0, _superstruct.validate)(objectValue, objectStruct, {
188
+ coerce
189
+ }));
190
+ const validatedValue = validationResults.find(([error])=>!error);
191
+ if (validatedValue) {
192
+ return validatedValue[1];
193
+ }
194
+ (0, _utils.assert)(validationResults[0][0], 'Expected at least one error.');
195
+ // If there is no validated value, we need to find the error with the least
196
+ // number of failures (with the assumption that it's the most specific error).
197
+ const validationError = validationResults.reduce((error, [innerError])=>{
198
+ (0, _utils.assert)(innerError, 'Expected an error.');
199
+ if (innerError.failures().length < error.failures().length) {
200
+ return innerError;
201
+ }
202
+ return error;
203
+ }, validationResults[0][0]);
204
+ throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
205
+ }
206
+ function createUnion(value, struct, structKey) {
207
+ return validateUnion(value, struct, structKey, true);
208
+ }
140
209
 
141
210
  //# sourceMappingURL=structs.js.map