@metamask/snaps-utils 5.2.0 → 6.1.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 +23 -3
- package/dist/cjs/caveats.js +6 -0
- package/dist/cjs/caveats.js.map +1 -1
- package/dist/cjs/eval-worker.js +3 -1
- package/dist/cjs/eval-worker.js.map +1 -1
- package/dist/cjs/handler-types.js +1 -0
- package/dist/cjs/handler-types.js.map +1 -1
- package/dist/cjs/handlers.js +74 -3
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/icon.js +38 -9
- package/dist/cjs/icon.js.map +1 -1
- package/dist/cjs/manifest/manifest.js +8 -0
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js +50 -14
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/post-process.js +1 -1
- package/dist/cjs/post-process.js.map +1 -1
- package/dist/cjs/structs.js +86 -17
- package/dist/cjs/structs.js.map +1 -1
- package/dist/esm/caveats.js +6 -0
- package/dist/esm/caveats.js.map +1 -1
- package/dist/esm/eval-worker.js +3 -1
- package/dist/esm/eval-worker.js.map +1 -1
- package/dist/esm/handler-types.js +1 -0
- package/dist/esm/handler-types.js.map +1 -1
- package/dist/esm/handlers.js +45 -4
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/icon.js +43 -3
- package/dist/esm/icon.js.map +1 -1
- package/dist/esm/manifest/manifest.js +8 -0
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js +38 -16
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/post-process.js +1 -1
- package/dist/esm/post-process.js.map +1 -1
- package/dist/esm/structs.js +133 -21
- package/dist/esm/structs.js.map +1 -1
- package/dist/types/caveats.d.ts +9 -1
- package/dist/types/handler-types.d.ts +2 -1
- package/dist/types/handlers.d.ts +349 -10
- package/dist/types/icon.d.ts +16 -1
- package/dist/types/localization.d.ts +33 -13
- package/dist/types/manifest/validation.d.ts +230 -75
- package/dist/types/post-process.d.ts +1 -1
- package/dist/types/structs.d.ts +61 -7
- package/package.json +5 -6
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [6.1.0]
|
|
10
|
+
### Added
|
|
11
|
+
- Add a manifest warning when no icon is found and when icon is not square ([#2185](https://github.com/MetaMask/snaps/pull/2185))
|
|
12
|
+
|
|
13
|
+
## [6.0.0]
|
|
14
|
+
### Added
|
|
15
|
+
- Add support for dynamic user interfaces ([#1465](https://github.com/MetaMask/snaps/pull/1465), [#2126](https://github.com/MetaMask/snaps/pull/2126))
|
|
16
|
+
- Add support for snap defined execution timeouts ([#2098](https://github.com/MetaMask/snaps/pull/2098))
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
- **BREAKING:** Update name lookup type validation ([#2113](https://github.com/MetaMask/snaps/pull/2113))
|
|
20
|
+
- The return value and the permission format has changed, see [SIP-12](https://metamask.github.io/SIPs/SIPS/sip-12) for more details.
|
|
21
|
+
- Speed up eval-worker for improved CLI performance ([#2147](https://github.com/MetaMask/snaps/pull/2147))
|
|
22
|
+
- Update MetaMask dependencies ([#2132](https://github.com/MetaMask/snaps/pull/2132), [#2142](https://github.com/MetaMask/snaps/pull/2142))
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
- Fix initial permissions types ([#2111](https://github.com/MetaMask/snaps/pull/2111))
|
|
26
|
+
|
|
9
27
|
## [5.2.0]
|
|
10
28
|
### Added
|
|
11
29
|
- Add support for initial connections ([#2048](https://github.com/MetaMask/snaps/pull/2048))
|
|
@@ -134,8 +152,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
134
152
|
## [0.38.1-flask.1]
|
|
135
153
|
### Changed
|
|
136
154
|
- Update transaction insights response and add severity level enum ([#1653](https://github.com/MetaMask/snaps/pull/1653))
|
|
137
|
-
|
|
138
|
-
|
|
155
|
+
- Snaps are now able to specify a `severity` for alongside their insights.
|
|
156
|
+
- See [SIP-11](https://metamask.github.io/SIPs/SIPS/sip-11) for more information.
|
|
139
157
|
|
|
140
158
|
## [0.38.0-flask.1]
|
|
141
159
|
### Added
|
|
@@ -151,7 +169,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
151
169
|
- The version of the package no longer needs to match the version of all other
|
|
152
170
|
MetaMask Snaps packages.
|
|
153
171
|
|
|
154
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@
|
|
172
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@6.1.0...HEAD
|
|
173
|
+
[6.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@6.0.0...@metamask/snaps-utils@6.1.0
|
|
174
|
+
[6.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.2.0...@metamask/snaps-utils@6.0.0
|
|
155
175
|
[5.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.2...@metamask/snaps-utils@5.2.0
|
|
156
176
|
[5.1.2]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.1...@metamask/snaps-utils@5.1.2
|
|
157
177
|
[5.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.0...@metamask/snaps-utils@5.1.1
|
package/dist/cjs/caveats.js
CHANGED
|
@@ -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
|
package/dist/cjs/caveats.js.map
CHANGED
|
@@ -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;
|
|
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"}
|
package/dist/cjs/eval-worker.js
CHANGED
|
@@ -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
|
-
|
|
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\
|
|
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":";;;;;;;;;;;;;;
|
|
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"}
|
package/dist/cjs/handlers.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
package/dist/cjs/handlers.js.map
CHANGED
|
@@ -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 {
|
|
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,CAACL,yBAAW,CAACQ,YAAY,CAAC,EAAE;QAC1BN,MAAMF,yB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AAAA,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"}
|
package/dist/cjs/icon.js
CHANGED
|
@@ -17,21 +17,50 @@ _export(exports, {
|
|
|
17
17
|
},
|
|
18
18
|
assertIsSnapIcon: function() {
|
|
19
19
|
return assertIsSnapIcon;
|
|
20
|
+
},
|
|
21
|
+
getSvgDimensions: function() {
|
|
22
|
+
return getSvgDimensions;
|
|
20
23
|
}
|
|
21
24
|
});
|
|
25
|
+
const _snapssdk = require("@metamask/snaps-sdk");
|
|
22
26
|
const _utils = require("@metamask/utils");
|
|
23
|
-
const _issvg = /*#__PURE__*/ _interop_require_default(require("is-svg"));
|
|
24
|
-
function _interop_require_default(obj) {
|
|
25
|
-
return obj && obj.__esModule ? obj : {
|
|
26
|
-
default: obj
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
27
|
const SVG_MAX_BYTE_SIZE = 100000;
|
|
30
28
|
const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(SVG_MAX_BYTE_SIZE / 1000)}kb`;
|
|
31
|
-
|
|
29
|
+
function assertIsSnapIcon(icon) {
|
|
32
30
|
(0, _utils.assert)(icon.path.endsWith('.svg'), 'Expected snap icon to end in ".svg".');
|
|
33
31
|
(0, _utils.assert)(Buffer.byteLength(icon.value, 'utf8') <= SVG_MAX_BYTE_SIZE, `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`);
|
|
34
|
-
(0, _utils.assert)((0,
|
|
35
|
-
}
|
|
32
|
+
(0, _utils.assert)((0, _snapssdk.isSvg)(icon.toString()), 'Snap icon must be a valid SVG.');
|
|
33
|
+
}
|
|
34
|
+
function getSvgDimensions(svg) {
|
|
35
|
+
try {
|
|
36
|
+
const parsed = (0, _snapssdk.parseSvg)(svg);
|
|
37
|
+
const height = parsed['@_height'];
|
|
38
|
+
const width = parsed['@_width'];
|
|
39
|
+
if (height && width) {
|
|
40
|
+
return {
|
|
41
|
+
height,
|
|
42
|
+
width
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const viewBox = parsed['@_viewBox'];
|
|
46
|
+
if (viewBox) {
|
|
47
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
48
|
+
const [_minX, _minY, viewBoxWidth, viewBoxHeight] = viewBox.split(' ');
|
|
49
|
+
if (viewBoxWidth && viewBoxHeight) {
|
|
50
|
+
const parsedWidth = parseInt(viewBoxWidth, 10);
|
|
51
|
+
const parsedHeight = parseInt(viewBoxHeight, 10);
|
|
52
|
+
(0, _utils.assert)(Number.isInteger(parsedWidth) && parsedWidth > 0);
|
|
53
|
+
(0, _utils.assert)(Number.isInteger(parsedHeight) && parsedHeight > 0);
|
|
54
|
+
return {
|
|
55
|
+
width: parsedWidth,
|
|
56
|
+
height: parsedHeight
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
} catch {
|
|
61
|
+
throw new Error('Snap icon must be a valid SVG.');
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
36
65
|
|
|
37
66
|
//# sourceMappingURL=icon.js.map
|
package/dist/cjs/icon.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/icon.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/icon.ts"],"sourcesContent":["import { isSvg, parseSvg } from '@metamask/snaps-sdk';\nimport { assert } from '@metamask/utils';\n\nimport type { VirtualFile } from './virtual-file';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\n/**\n * Assert that a virtual file containing a Snap icon is valid.\n *\n * @param icon - A virtual file containing a Snap icon.\n */\nexport function assertIsSnapIcon(icon: VirtualFile) {\n assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in \".svg\".');\n\n assert(\n Buffer.byteLength(icon.value, 'utf8') <= SVG_MAX_BYTE_SIZE,\n `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n\n assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');\n}\n\n/**\n * Extract the dimensions of an image from an SVG string if possible.\n *\n * @param svg - An SVG string.\n * @returns The height and width of the SVG or null.\n */\nexport function getSvgDimensions(svg: string): {\n height: number;\n width: number;\n} | null {\n try {\n const parsed = parseSvg(svg);\n\n const height = parsed['@_height'];\n const width = parsed['@_width'];\n\n if (height && width) {\n return { height, width };\n }\n\n const viewBox = parsed['@_viewBox'];\n if (viewBox) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [_minX, _minY, viewBoxWidth, viewBoxHeight] = viewBox.split(' ');\n\n if (viewBoxWidth && viewBoxHeight) {\n const parsedWidth = parseInt(viewBoxWidth, 10);\n const parsedHeight = parseInt(viewBoxHeight, 10);\n\n assert(Number.isInteger(parsedWidth) && parsedWidth > 0);\n assert(Number.isInteger(parsedHeight) && parsedHeight > 0);\n\n return {\n width: parsedWidth,\n height: parsedHeight,\n };\n }\n }\n } catch {\n throw new Error('Snap icon must be a valid SVG.');\n }\n\n return null;\n}\n"],"names":["SVG_MAX_BYTE_SIZE","SVG_MAX_BYTE_SIZE_TEXT","assertIsSnapIcon","getSvgDimensions","Math","floor","icon","assert","path","endsWith","Buffer","byteLength","value","isSvg","toString","svg","parsed","parseSvg","height","width","viewBox","_minX","_minY","viewBoxWidth","viewBoxHeight","split","parsedWidth","parseInt","parsedHeight","Number","isInteger","Error"],"mappings":";;;;;;;;;;;IAKaA,iBAAiB;eAAjBA;;IACAC,sBAAsB;eAAtBA;;IASGC,gBAAgB;eAAhBA;;IAiBAC,gBAAgB;eAAhBA;;;0BAhCgB;uBACT;AAIhB,MAAMH,oBAAoB;AAC1B,MAAMC,yBAAyB,CAAC,EAAEG,KAAKC,KAAK,CACjDL,oBAAoB,MACpB,EAAE,CAAC;AAOE,SAASE,iBAAiBI,IAAiB;IAChDC,IAAAA,aAAM,EAACD,KAAKE,IAAI,CAACC,QAAQ,CAAC,SAAS;IAEnCF,IAAAA,aAAM,EACJG,OAAOC,UAAU,CAACL,KAAKM,KAAK,EAAE,WAAWZ,mBACzC,CAAC,mDAAmD,EAAEC,uBAAuB,CAAC,CAAC;IAGjFM,IAAAA,aAAM,EAACM,IAAAA,eAAK,EAACP,KAAKQ,QAAQ,KAAK;AACjC;AAQO,SAASX,iBAAiBY,GAAW;IAI1C,IAAI;QACF,MAAMC,SAASC,IAAAA,kBAAQ,EAACF;QAExB,MAAMG,SAASF,MAAM,CAAC,WAAW;QACjC,MAAMG,QAAQH,MAAM,CAAC,UAAU;QAE/B,IAAIE,UAAUC,OAAO;YACnB,OAAO;gBAAED;gBAAQC;YAAM;QACzB;QAEA,MAAMC,UAAUJ,MAAM,CAAC,YAAY;QACnC,IAAII,SAAS;YACX,6DAA6D;YAC7D,MAAM,CAACC,OAAOC,OAAOC,cAAcC,cAAc,GAAGJ,QAAQK,KAAK,CAAC;YAElE,IAAIF,gBAAgBC,eAAe;gBACjC,MAAME,cAAcC,SAASJ,cAAc;gBAC3C,MAAMK,eAAeD,SAASH,eAAe;gBAE7CjB,IAAAA,aAAM,EAACsB,OAAOC,SAAS,CAACJ,gBAAgBA,cAAc;gBACtDnB,IAAAA,aAAM,EAACsB,OAAOC,SAAS,CAACF,iBAAiBA,eAAe;gBAExD,OAAO;oBACLT,OAAOO;oBACPR,QAAQU;gBACV;YACF;QACF;IACF,EAAE,OAAM;QACN,MAAM,IAAIG,MAAM;IAClB;IAEA,OAAO;AACT"}
|
|
@@ -41,6 +41,7 @@ const _fs = require("fs");
|
|
|
41
41
|
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
|
|
42
42
|
const _deepclone = require("../deep-clone");
|
|
43
43
|
const _fs1 = require("../fs");
|
|
44
|
+
const _icon = require("../icon");
|
|
44
45
|
const _npm = require("../npm");
|
|
45
46
|
const _snaps = require("../snaps");
|
|
46
47
|
const _types = require("../types");
|
|
@@ -133,6 +134,13 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
|
|
|
133
134
|
return `${allMissing}\t${currentField}\n`;
|
|
134
135
|
}, '')}`);
|
|
135
136
|
}
|
|
137
|
+
if (!snapFiles.svgIcon) {
|
|
138
|
+
warnings.push('No icon found in the Snap manifest. It is recommended to include an icon for the Snap. See https://docs.metamask.io/snaps/how-to/design-a-snap/#guidelines-at-a-glance for more information.');
|
|
139
|
+
}
|
|
140
|
+
const iconDimensions = snapFiles.svgIcon && (0, _icon.getSvgDimensions)(snapFiles.svgIcon.toString());
|
|
141
|
+
if (iconDimensions && iconDimensions.height !== iconDimensions.width) {
|
|
142
|
+
warnings.push('The icon in the Snap manifest is not square. It is recommended to use a square icon for the Snap.');
|
|
143
|
+
}
|
|
136
144
|
if (writeManifest) {
|
|
137
145
|
try {
|
|
138
146
|
const newManifest = `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\n`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialConnections: 7,\n initialPermissions: 8,\n manifestVersion: 9,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n // Intentionally pass null as the encoding here since the files may be binary\n auxiliaryFiles:\n (await getSnapFiles(basePath, auxiliaryFilePaths, null)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @param encoding - An optional encoding to pass down to readVirtualFile.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n encoding: BufferEncoding | null = 'utf8',\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), encoding),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapFilePaths","getSnapFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialConnections","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","svgIcon","auxiliaryFiles","localizationFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","selector","snapManifest","paths","Array","isArray","encoding","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAmEsBA,aAAa;eAAbA;;IA+JAC,WAAW;eAAXA;;IA8CAC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAiCNC,gBAAgB;eAAhBA;;IA2BMC,YAAY;eAAZA;;IA2BNC,mBAAmB;eAAnBA;;IAgCMC,uBAAuB;eAAvBA;;;0BAnbU;uBAEwB;sEAClC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,oBAAoB;IACpBC,iBAAiB;AACnB;AAqCO,eAAejB,cACpBkB,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCC,YAAE,CAACC,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAeC,aAAS,CAACC,IAAI,CAACX,UAAUY,uBAAgB,CAACC,QAAQ;IACvE,MAAMC,eAAe,MAAMC,IAAAA,iBAAY,EAACN;IACxC,MAAMO,sBAAsBF,aAAaG,MAAM;IAE/C,MAAMC,cAAc,MAAMH,IAAAA,iBAAY,EACpCL,aAAS,CAACC,IAAI,CAACX,UAAUY,uBAAgB,CAACO,WAAW;IAGvD,MAAMC,qBAAqBlC,iBACzB8B,qBACA,CAACK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CAACO,WAAW,CAAC,oBAAoB,EAAEiF,mBAAmB,GAAG,CAAC,EAClL3D,kCAA2B,CAAC2B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiC,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIxE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HsB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEA,MAAMqC,IAAAA,yBAAkB,EACtB;QAAErF;QAAUnB;QAAYyB;QAASC;QAAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { getSvgDimensions } from '../icon';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialConnections: 7,\n initialPermissions: 8,\n manifestVersion: 9,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n // Intentionally pass null as the encoding here since the files may be binary\n auxiliaryFiles:\n (await getSnapFiles(basePath, auxiliaryFilePaths, null)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (!snapFiles.svgIcon) {\n warnings.push(\n 'No icon found in the Snap manifest. It is recommended to include an icon for the Snap. See https://docs.metamask.io/snaps/how-to/design-a-snap/#guidelines-at-a-glance for more information.',\n );\n }\n\n const iconDimensions =\n snapFiles.svgIcon && getSvgDimensions(snapFiles.svgIcon.toString());\n if (iconDimensions && iconDimensions.height !== iconDimensions.width) {\n warnings.push(\n 'The icon in the Snap manifest is not square. It is recommended to use a square icon for the Snap.',\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @param encoding - An optional encoding to pass down to readVirtualFile.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n encoding: BufferEncoding | null = 'utf8',\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), encoding),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapFilePaths","getSnapFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialConnections","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","svgIcon","auxiliaryFiles","localizationFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","iconDimensions","getSvgDimensions","toString","height","width","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","selector","snapManifest","paths","Array","isArray","encoding","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAoEsBA,aAAa;eAAbA;;IA6KAC,WAAW;eAAXA;;IA8CAC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAiCNC,gBAAgB;eAAhBA;;IA2BMC,YAAY;eAAZA;;IA2BNC,mBAAmB;eAAnBA;;IAgCMC,uBAAuB;eAAvBA;;;0BAlcU;uBAEwB;sEAClC;oBACS;6DACT;2BAEI;qBACG;sBACI;qBACD;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SA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B,kCAA2B,CAACiC,kBAAkB;IAElD;IAEA,MAAMqC,IAAAA,yBAAkB,EACtB;QAAE1F;QAAUnB;QAAYyB;QAASC;QAAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
@@ -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:
|
|
136
|
-
'endowment:
|
|
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:
|
|
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)({})),
|