@metamask/snaps-controllers 3.2.0 → 3.4.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 +21 -1
- package/dist/cjs/cronjob/CronjobController.js.map +1 -1
- package/dist/cjs/services/ExecutionService.js.map +1 -1
- package/dist/cjs/snaps/SnapController.js +63 -25
- package/dist/cjs/snaps/SnapController.js.map +1 -1
- package/dist/cjs/snaps/endowments/enum.js +1 -0
- package/dist/cjs/snaps/endowments/enum.js.map +1 -1
- package/dist/cjs/snaps/endowments/home-page.js +37 -0
- package/dist/cjs/snaps/endowments/home-page.js.map +1 -0
- package/dist/cjs/snaps/endowments/index.js +5 -2
- package/dist/cjs/snaps/endowments/index.js.map +1 -1
- package/dist/cjs/snaps/registry/json.js.map +1 -1
- package/dist/cjs/snaps/registry/registry.js.map +1 -1
- package/dist/cjs/utils.js +9 -0
- package/dist/cjs/utils.js.map +1 -1
- package/dist/esm/cronjob/CronjobController.js.map +1 -1
- package/dist/esm/services/ExecutionService.js.map +1 -1
- package/dist/esm/snaps/SnapController.js +61 -23
- package/dist/esm/snaps/SnapController.js.map +1 -1
- package/dist/esm/snaps/endowments/enum.js +1 -0
- package/dist/esm/snaps/endowments/enum.js.map +1 -1
- package/dist/esm/snaps/endowments/home-page.js +27 -0
- package/dist/esm/snaps/endowments/home-page.js.map +1 -0
- package/dist/esm/snaps/endowments/index.js +5 -2
- package/dist/esm/snaps/endowments/index.js.map +1 -1
- package/dist/esm/snaps/registry/json.js.map +1 -1
- package/dist/esm/snaps/registry/registry.js.map +1 -1
- package/dist/esm/utils.js +12 -0
- package/dist/esm/utils.js.map +1 -1
- package/dist/types/cronjob/CronjobController.d.ts +5 -4
- package/dist/types/services/ExecutionService.d.ts +4 -4
- package/dist/types/snaps/SnapController.d.ts +40 -35
- package/dist/types/snaps/endowments/enum.d.ts +2 -1
- package/dist/types/snaps/endowments/home-page.d.ts +15 -0
- package/dist/types/snaps/endowments/index.d.ts +9 -0
- package/dist/types/snaps/registry/registry.d.ts +3 -3
- package/dist/types/utils.d.ts +9 -0
- package/package.json +6 -6
|
@@ -9,6 +9,7 @@ export var SnapEndowments;
|
|
|
9
9
|
SnapEndowments["NameLookup"] = 'endowment:name-lookup';
|
|
10
10
|
SnapEndowments["LifecycleHooks"] = 'endowment:lifecycle-hooks';
|
|
11
11
|
SnapEndowments["Keyring"] = 'endowment:keyring';
|
|
12
|
+
SnapEndowments["HomePage"] = 'endowment:page-home';
|
|
12
13
|
})(SnapEndowments || (SnapEndowments = {}));
|
|
13
14
|
|
|
14
15
|
//# sourceMappingURL=enum.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/endowments/enum.ts"],"sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n TransactionInsight = 'endowment:transaction-insight',\n Cronjob = 'endowment:cronjob',\n EthereumProvider = 'endowment:ethereum-provider',\n Rpc = 'endowment:rpc',\n WebAssemblyAccess = 'endowment:webassembly',\n NameLookup = 'endowment:name-lookup',\n LifecycleHooks = 'endowment:lifecycle-hooks',\n Keyring = 'endowment:keyring',\n}\n"],"names":["SnapEndowments","NetworkAccess","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks","Keyring"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,wBAAqB;IAFXF,eAGVG,aAAU;IAHAH,eAIVI,sBAAmB;IAJTJ,eAKVK,SAAM;IALIL,eAMVM,uBAAoB;IANVN,eAOVO,gBAAa;IAPHP,eAQVQ,oBAAiB;IARPR,eASVS,aAAU;
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/endowments/enum.ts"],"sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n TransactionInsight = 'endowment:transaction-insight',\n Cronjob = 'endowment:cronjob',\n EthereumProvider = 'endowment:ethereum-provider',\n Rpc = 'endowment:rpc',\n WebAssemblyAccess = 'endowment:webassembly',\n NameLookup = 'endowment:name-lookup',\n LifecycleHooks = 'endowment:lifecycle-hooks',\n Keyring = 'endowment:keyring',\n HomePage = 'endowment:page-home',\n}\n"],"names":["SnapEndowments","NetworkAccess","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks","Keyring","HomePage"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,wBAAqB;IAFXF,eAGVG,aAAU;IAHAH,eAIVI,sBAAmB;IAJTJ,eAKVK,SAAM;IALIL,eAMVM,uBAAoB;IANVN,eAOVO,gBAAa;IAPHP,eAQVQ,oBAAiB;IARPR,eASVS,aAAU;IATAT,eAUVU,cAAW;GAVDV,mBAAAA"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { PermissionType, SubjectType } from '@metamask/permission-controller';
|
|
2
|
+
import { SnapEndowments } from './enum';
|
|
3
|
+
const permissionName = SnapEndowments.HomePage;
|
|
4
|
+
/**
|
|
5
|
+
* `endowment:page-home` returns nothing; it is intended to be used as a
|
|
6
|
+
* flag by the snap controller to detect whether the snap has the capability to
|
|
7
|
+
* use the snap home page feature.
|
|
8
|
+
*
|
|
9
|
+
* @param _builderOptions - Optional specification builder options.
|
|
10
|
+
* @returns The specification for the `snap-pages` endowment.
|
|
11
|
+
*/ const specificationBuilder = (_builderOptions)=>{
|
|
12
|
+
return {
|
|
13
|
+
permissionType: PermissionType.Endowment,
|
|
14
|
+
targetName: permissionName,
|
|
15
|
+
allowedCaveats: null,
|
|
16
|
+
endowmentGetter: (_getterOptions)=>undefined,
|
|
17
|
+
subjectTypes: [
|
|
18
|
+
SubjectType.Snap
|
|
19
|
+
]
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
export const homePageEndowmentBuilder = Object.freeze({
|
|
23
|
+
targetName: permissionName,
|
|
24
|
+
specificationBuilder
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=home-page.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/endowments/home-page.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.HomePage;\n\ntype HomePageEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetName: typeof permissionName;\n endowmentGetter: (_options?: EndowmentGetterParams) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * `endowment:page-home` returns nothing; it is intended to be used as a\n * flag by the snap controller to detect whether the snap has the capability to\n * use the snap home page feature.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the `snap-pages` endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n HomePageEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: null,\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const homePageEndowmentBuilder = Object.freeze({\n targetName: permissionName,\n specificationBuilder,\n} as const);\n"],"names":["PermissionType","SubjectType","SnapEndowments","permissionName","HomePage","specificationBuilder","_builderOptions","permissionType","Endowment","targetName","allowedCaveats","endowmentGetter","_getterOptions","undefined","subjectTypes","Snap","homePageEndowmentBuilder","Object","freeze"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAG9E,SAASC,cAAc,QAAQ,SAAS;AAExC,MAAMC,iBAAiBD,eAAeE,QAAQ;AAS9C;;;;;;;CAOC,GACD,MAAMC,uBAIF,CAACC;IACH,OAAO;QACLC,gBAAgBP,eAAeQ,SAAS;QACxCC,YAAYN;QACZO,gBAAgB;QAChBC,iBAAiB,CAACC,iBAA2CC;QAC7DC,cAAc;YAACb,YAAYc,IAAI;SAAC;IAClC;AACF;AAEA,OAAO,MAAMC,2BAA2BC,OAAOC,MAAM,CAAC;IACpDT,YAAYN;IACZE;AACF,GAAY"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { HandlerType } from '@metamask/snaps-utils';
|
|
2
2
|
import { cronjobCaveatSpecifications, cronjobEndowmentBuilder, getCronjobCaveatMapper } from './cronjob';
|
|
3
3
|
import { ethereumProviderEndowmentBuilder } from './ethereum-provider';
|
|
4
|
+
import { homePageEndowmentBuilder } from './home-page';
|
|
4
5
|
import { getKeyringCaveatMapper, keyringCaveatSpecifications, keyringEndowmentBuilder } from './keyring';
|
|
5
6
|
import { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';
|
|
6
7
|
import { getNameLookupCaveatMapper, nameLookupCaveatSpecifications, nameLookupEndowmentBuilder } from './name-lookup';
|
|
@@ -17,7 +18,8 @@ export const endowmentPermissionBuilders = {
|
|
|
17
18
|
[webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,
|
|
18
19
|
[nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder,
|
|
19
20
|
[lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder,
|
|
20
|
-
[keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder
|
|
21
|
+
[keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder,
|
|
22
|
+
[homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder
|
|
21
23
|
};
|
|
22
24
|
export const endowmentCaveatSpecifications = {
|
|
23
25
|
...cronjobCaveatSpecifications,
|
|
@@ -40,7 +42,8 @@ export const handlerEndowments = {
|
|
|
40
42
|
[HandlerType.OnNameLookup]: nameLookupEndowmentBuilder.targetName,
|
|
41
43
|
[HandlerType.OnInstall]: lifecycleHooksEndowmentBuilder.targetName,
|
|
42
44
|
[HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName,
|
|
43
|
-
[HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName
|
|
45
|
+
[HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName,
|
|
46
|
+
[HandlerType.OnHomePage]: homePageEndowmentBuilder.targetName
|
|
44
47
|
};
|
|
45
48
|
export * from './enum';
|
|
46
49
|
export { getRpcCaveatOrigins } from './rpc';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/endowments/index.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\n\nimport {\n cronjobCaveatSpecifications,\n cronjobEndowmentBuilder,\n getCronjobCaveatMapper,\n} from './cronjob';\nimport { ethereumProviderEndowmentBuilder } from './ethereum-provider';\nimport {\n getKeyringCaveatMapper,\n keyringCaveatSpecifications,\n keyringEndowmentBuilder,\n} from './keyring';\nimport { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';\nimport {\n getNameLookupCaveatMapper,\n nameLookupCaveatSpecifications,\n nameLookupEndowmentBuilder,\n} from './name-lookup';\nimport { networkAccessEndowmentBuilder } from './network-access';\nimport {\n getRpcCaveatMapper,\n rpcCaveatSpecifications,\n rpcEndowmentBuilder,\n} from './rpc';\nimport {\n getTransactionInsightCaveatMapper,\n transactionInsightCaveatSpecifications,\n transactionInsightEndowmentBuilder,\n} from './transaction-insight';\nimport { webAssemblyEndowmentBuilder } from './web-assembly';\n\nexport const endowmentPermissionBuilders = {\n [networkAccessEndowmentBuilder.targetName]: networkAccessEndowmentBuilder,\n [transactionInsightEndowmentBuilder.targetName]:\n transactionInsightEndowmentBuilder,\n [cronjobEndowmentBuilder.targetName]: cronjobEndowmentBuilder,\n [ethereumProviderEndowmentBuilder.targetName]:\n ethereumProviderEndowmentBuilder,\n [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder,\n [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,\n [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder,\n [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder,\n [keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n ...nameLookupCaveatSpecifications,\n ...keyringCaveatSpecifications,\n};\n\nexport const endowmentCaveatMappers: Record<\n string,\n (value: Json) => Pick<PermissionConstraint, 'caveats'>\n> = {\n [cronjobEndowmentBuilder.targetName]: getCronjobCaveatMapper,\n [transactionInsightEndowmentBuilder.targetName]:\n getTransactionInsightCaveatMapper,\n [rpcEndowmentBuilder.targetName]: getRpcCaveatMapper,\n [nameLookupEndowmentBuilder.targetName]: getNameLookupCaveatMapper,\n [keyringEndowmentBuilder.targetName]: getKeyringCaveatMapper,\n};\n\nexport const handlerEndowments: Record<HandlerType, string> = {\n [HandlerType.OnRpcRequest]: rpcEndowmentBuilder.targetName,\n [HandlerType.OnTransaction]: transactionInsightEndowmentBuilder.targetName,\n [HandlerType.OnCronjob]: cronjobEndowmentBuilder.targetName,\n [HandlerType.OnNameLookup]: nameLookupEndowmentBuilder.targetName,\n [HandlerType.OnInstall]: lifecycleHooksEndowmentBuilder.targetName,\n [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName,\n [HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName,\n};\n\nexport * from './enum';\nexport { getRpcCaveatOrigins } from './rpc';\nexport { getTransactionOriginCaveat } from './transaction-insight';\nexport { getChainIdsCaveat } from './name-lookup';\nexport { getKeyringCaveatOrigins } from './keyring';\n"],"names":["HandlerType","cronjobCaveatSpecifications","cronjobEndowmentBuilder","getCronjobCaveatMapper","ethereumProviderEndowmentBuilder","getKeyringCaveatMapper","keyringCaveatSpecifications","keyringEndowmentBuilder","lifecycleHooksEndowmentBuilder","getNameLookupCaveatMapper","nameLookupCaveatSpecifications","nameLookupEndowmentBuilder","networkAccessEndowmentBuilder","getRpcCaveatMapper","rpcCaveatSpecifications","rpcEndowmentBuilder","getTransactionInsightCaveatMapper","transactionInsightCaveatSpecifications","transactionInsightEndowmentBuilder","webAssemblyEndowmentBuilder","endowmentPermissionBuilders","targetName","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","getRpcCaveatOrigins","getTransactionOriginCaveat","getChainIdsCaveat","getKeyringCaveatOrigins"],"mappings":"AACA,SAASA,WAAW,QAAQ,wBAAwB;AAGpD,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,sBAAsB,QACjB,YAAY;AACnB,SAASC,gCAAgC,QAAQ,sBAAsB;AACvE,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,uBAAuB,QAClB,YAAY;AACnB,SAASC,8BAA8B,QAAQ,oBAAoB;AACnE,SACEC,yBAAyB,EACzBC,8BAA8B,EAC9BC,0BAA0B,QACrB,gBAAgB;AACvB,SAASC,6BAA6B,QAAQ,mBAAmB;AACjE,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,mBAAmB,QACd,QAAQ;AACf,SACEC,iCAAiC,EACjCC,sCAAsC,EACtCC,kCAAkC,QAC7B,wBAAwB;AAC/B,SAASC,2BAA2B,QAAQ,iBAAiB;AAE7D,OAAO,MAAMC,8BAA8B;IACzC,CAACR,8BAA8BS,UAAU,CAAC,EAAET;IAC5C,CAACM,mCAAmCG,UAAU,CAAC,EAC7CH;IACF,
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/endowments/index.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\n\nimport {\n cronjobCaveatSpecifications,\n cronjobEndowmentBuilder,\n getCronjobCaveatMapper,\n} from './cronjob';\nimport { ethereumProviderEndowmentBuilder } from './ethereum-provider';\nimport { homePageEndowmentBuilder } from './home-page';\nimport {\n getKeyringCaveatMapper,\n keyringCaveatSpecifications,\n keyringEndowmentBuilder,\n} from './keyring';\nimport { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';\nimport {\n getNameLookupCaveatMapper,\n nameLookupCaveatSpecifications,\n nameLookupEndowmentBuilder,\n} from './name-lookup';\nimport { networkAccessEndowmentBuilder } from './network-access';\nimport {\n getRpcCaveatMapper,\n rpcCaveatSpecifications,\n rpcEndowmentBuilder,\n} from './rpc';\nimport {\n getTransactionInsightCaveatMapper,\n transactionInsightCaveatSpecifications,\n transactionInsightEndowmentBuilder,\n} from './transaction-insight';\nimport { webAssemblyEndowmentBuilder } from './web-assembly';\n\nexport const endowmentPermissionBuilders = {\n [networkAccessEndowmentBuilder.targetName]: networkAccessEndowmentBuilder,\n [transactionInsightEndowmentBuilder.targetName]:\n transactionInsightEndowmentBuilder,\n [cronjobEndowmentBuilder.targetName]: cronjobEndowmentBuilder,\n [ethereumProviderEndowmentBuilder.targetName]:\n ethereumProviderEndowmentBuilder,\n [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder,\n [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,\n [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder,\n [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder,\n [keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder,\n [homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n ...nameLookupCaveatSpecifications,\n ...keyringCaveatSpecifications,\n};\n\nexport const endowmentCaveatMappers: Record<\n string,\n (value: Json) => Pick<PermissionConstraint, 'caveats'>\n> = {\n [cronjobEndowmentBuilder.targetName]: getCronjobCaveatMapper,\n [transactionInsightEndowmentBuilder.targetName]:\n getTransactionInsightCaveatMapper,\n [rpcEndowmentBuilder.targetName]: getRpcCaveatMapper,\n [nameLookupEndowmentBuilder.targetName]: getNameLookupCaveatMapper,\n [keyringEndowmentBuilder.targetName]: getKeyringCaveatMapper,\n};\n\nexport const handlerEndowments: Record<HandlerType, string> = {\n [HandlerType.OnRpcRequest]: rpcEndowmentBuilder.targetName,\n [HandlerType.OnTransaction]: transactionInsightEndowmentBuilder.targetName,\n [HandlerType.OnCronjob]: cronjobEndowmentBuilder.targetName,\n [HandlerType.OnNameLookup]: nameLookupEndowmentBuilder.targetName,\n [HandlerType.OnInstall]: lifecycleHooksEndowmentBuilder.targetName,\n [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName,\n [HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName,\n [HandlerType.OnHomePage]: homePageEndowmentBuilder.targetName,\n};\n\nexport * from './enum';\nexport { getRpcCaveatOrigins } from './rpc';\nexport { getTransactionOriginCaveat } from './transaction-insight';\nexport { getChainIdsCaveat } from './name-lookup';\nexport { getKeyringCaveatOrigins } from './keyring';\n"],"names":["HandlerType","cronjobCaveatSpecifications","cronjobEndowmentBuilder","getCronjobCaveatMapper","ethereumProviderEndowmentBuilder","homePageEndowmentBuilder","getKeyringCaveatMapper","keyringCaveatSpecifications","keyringEndowmentBuilder","lifecycleHooksEndowmentBuilder","getNameLookupCaveatMapper","nameLookupCaveatSpecifications","nameLookupEndowmentBuilder","networkAccessEndowmentBuilder","getRpcCaveatMapper","rpcCaveatSpecifications","rpcEndowmentBuilder","getTransactionInsightCaveatMapper","transactionInsightCaveatSpecifications","transactionInsightEndowmentBuilder","webAssemblyEndowmentBuilder","endowmentPermissionBuilders","targetName","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","getRpcCaveatOrigins","getTransactionOriginCaveat","getChainIdsCaveat","getKeyringCaveatOrigins"],"mappings":"AACA,SAASA,WAAW,QAAQ,wBAAwB;AAGpD,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,sBAAsB,QACjB,YAAY;AACnB,SAASC,gCAAgC,QAAQ,sBAAsB;AACvE,SAASC,wBAAwB,QAAQ,cAAc;AACvD,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,uBAAuB,QAClB,YAAY;AACnB,SAASC,8BAA8B,QAAQ,oBAAoB;AACnE,SACEC,yBAAyB,EACzBC,8BAA8B,EAC9BC,0BAA0B,QACrB,gBAAgB;AACvB,SAASC,6BAA6B,QAAQ,mBAAmB;AACjE,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,mBAAmB,QACd,QAAQ;AACf,SACEC,iCAAiC,EACjCC,sCAAsC,EACtCC,kCAAkC,QAC7B,wBAAwB;AAC/B,SAASC,2BAA2B,QAAQ,iBAAiB;AAE7D,OAAO,MAAMC,8BAA8B;IACzC,CAACR,8BAA8BS,UAAU,CAAC,EAAET;IAC5C,CAACM,mCAAmCG,UAAU,CAAC,EAC7CH;IACF,CAACjB,wBAAwBoB,UAAU,CAAC,EAAEpB;IACtC,CAACE,iCAAiCkB,UAAU,CAAC,EAC3ClB;IACF,CAACY,oBAAoBM,UAAU,CAAC,EAAEN;IAClC,CAACI,4BAA4BE,UAAU,CAAC,EAAEF;IAC1C,CAACR,2BAA2BU,UAAU,CAAC,EAAEV;IACzC,CAACH,+BAA+Ba,UAAU,CAAC,EAAEb;IAC7C,CAACD,wBAAwBc,UAAU,CAAC,EAAEd;IACtC,CAACH,yBAAyBiB,UAAU,CAAC,EAAEjB;AACzC,EAAW;AAEX,OAAO,MAAMkB,gCAAgC;IAC3C,GAAGtB,2BAA2B;IAC9B,GAAGiB,sCAAsC;IACzC,GAAGH,uBAAuB;IAC1B,GAAGJ,8BAA8B;IACjC,GAAGJ,2BAA2B;AAChC,EAAE;AAEF,OAAO,MAAMiB,yBAGT;IACF,CAACtB,wBAAwBoB,UAAU,CAAC,EAAEnB;IACtC,CAACgB,mCAAmCG,UAAU,CAAC,EAC7CL;IACF,CAACD,oBAAoBM,UAAU,CAAC,EAAER;IAClC,CAACF,2BAA2BU,UAAU,CAAC,EAAEZ;IACzC,CAACF,wBAAwBc,UAAU,CAAC,EAAEhB;AACxC,EAAE;AAEF,OAAO,MAAMmB,oBAAiD;IAC5D,CAACzB,YAAY0B,YAAY,CAAC,EAAEV,oBAAoBM,UAAU;IAC1D,CAACtB,YAAY2B,aAAa,CAAC,EAAER,mCAAmCG,UAAU;IAC1E,CAACtB,YAAY4B,SAAS,CAAC,EAAE1B,wBAAwBoB,UAAU;IAC3D,CAACtB,YAAY6B,YAAY,CAAC,EAAEjB,2BAA2BU,UAAU;IACjE,CAACtB,YAAY8B,SAAS,CAAC,EAAErB,+BAA+Ba,UAAU;IAClE,CAACtB,YAAY+B,QAAQ,CAAC,EAAEtB,+BAA+Ba,UAAU;IACjE,CAACtB,YAAYgC,gBAAgB,CAAC,EAAExB,wBAAwBc,UAAU;IAClE,CAACtB,YAAYiC,UAAU,CAAC,EAAE5B,yBAAyBiB,UAAU;AAC/D,EAAE;AAEF,cAAc,SAAS;AACvB,SAASY,mBAAmB,QAAQ,QAAQ;AAC5C,SAASC,0BAA0B,QAAQ,wBAAwB;AACnE,SAASC,iBAAiB,QAAQ,gBAAgB;AAClD,SAASC,uBAAuB,QAAQ,YAAY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/registry/json.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { SnapsRegistryDatabase } from '@metamask/snaps-registry';\nimport { verify } from '@metamask/snaps-registry';\nimport { getTargetVersion, type SnapId } from '@metamask/snaps-utils';\nimport type { Hex, SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerRange,\n Duration,\n inMilliseconds,\n satisfiesVersionRange,\n} from '@metamask/utils';\n\nimport type {\n SnapsRegistry,\n SnapsRegistryInfo,\n SnapsRegistryMetadata,\n SnapsRegistryRequest,\n SnapsRegistryResult,\n} from './registry';\nimport { SnapsRegistryStatus } from './registry';\n\n// TODO: Replace with a Codefi URL\nconst SNAP_REGISTRY_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/registry.json';\n\nconst SNAP_REGISTRY_SIGNATURE_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/signature.json';\n\ntype JsonSnapsRegistryUrl = {\n registry: string;\n signature: string;\n};\n\nexport type JsonSnapsRegistryArgs = {\n messenger: SnapsRegistryMessenger;\n state?: SnapsRegistryState;\n fetchFunction?: typeof fetch;\n url?: JsonSnapsRegistryUrl;\n recentFetchThreshold?: number;\n refetchOnAllowlistMiss?: boolean;\n failOnUnavailableRegistry?: boolean;\n publicKey?: Hex;\n};\n\nexport type GetResult = {\n type: `${typeof controllerName}:get`;\n handler: SnapsRegistry['get'];\n};\n\nexport type ResolveVersion = {\n type: `${typeof controllerName}:resolveVersion`;\n handler: SnapsRegistry['resolveVersion'];\n};\n\nexport type GetMetadata = {\n type: `${typeof controllerName}:getMetadata`;\n handler: SnapsRegistry['getMetadata'];\n};\n\nexport type Update = {\n type: `${typeof controllerName}:update`;\n handler: SnapsRegistry['update'];\n};\n\nexport type SnapsRegistryActions =\n | GetResult\n | GetMetadata\n | Update\n | ResolveVersion;\n\nexport type SnapsRegistryEvents = never;\n\nexport type SnapsRegistryMessenger = RestrictedControllerMessenger<\n 'SnapsRegistry',\n SnapsRegistryActions,\n SnapsRegistryEvents,\n SnapsRegistryActions['type'],\n SnapsRegistryEvents['type']\n>;\n\nexport type SnapsRegistryState = {\n database: SnapsRegistryDatabase | null;\n lastUpdated: number | null;\n};\n\nconst controllerName = 'SnapsRegistry';\n\nconst defaultState = {\n database: null,\n lastUpdated: null,\n};\n\nexport class JsonSnapsRegistry extends BaseController<\n typeof controllerName,\n SnapsRegistryState,\n SnapsRegistryMessenger\n> {\n #url: JsonSnapsRegistryUrl;\n\n #publicKey?: Hex;\n\n #fetchFunction: typeof fetch;\n\n #recentFetchThreshold: number;\n\n #refetchOnAllowlistMiss: boolean;\n\n #failOnUnavailableRegistry: boolean;\n\n #currentUpdate: Promise<void> | null;\n\n constructor({\n messenger,\n state,\n url = {\n registry: SNAP_REGISTRY_URL,\n signature: SNAP_REGISTRY_SIGNATURE_URL,\n },\n publicKey,\n fetchFunction = globalThis.fetch.bind(globalThis),\n recentFetchThreshold = inMilliseconds(5, Duration.Minute),\n failOnUnavailableRegistry = true,\n refetchOnAllowlistMiss = true,\n }: JsonSnapsRegistryArgs) {\n super({\n messenger,\n metadata: {\n database: { persist: true, anonymous: false },\n lastUpdated: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n ...defaultState,\n ...state,\n },\n });\n this.#url = url;\n this.#publicKey = publicKey;\n this.#fetchFunction = fetchFunction;\n this.#recentFetchThreshold = recentFetchThreshold;\n this.#refetchOnAllowlistMiss = refetchOnAllowlistMiss;\n this.#failOnUnavailableRegistry = failOnUnavailableRegistry;\n this.#currentUpdate = null;\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:get',\n async (...args) => this.#get(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:getMetadata',\n async (...args) => this.#getMetadata(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:resolveVersion',\n async (...args) => this.#resolveVersion(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:update',\n async () => this.#triggerUpdate(),\n );\n }\n\n #wasRecentlyFetched() {\n return (\n this.state.lastUpdated &&\n Date.now() - this.state.lastUpdated < this.#recentFetchThreshold\n );\n }\n\n /**\n * Triggers an update of the registry database.\n *\n * If an existing update is in progress this function will await that update.\n */\n async #triggerUpdate() {\n // If an update is ongoing, wait for that.\n if (this.#currentUpdate) {\n await this.#currentUpdate;\n return;\n }\n // If no update exists, create promise and store globally.\n if (this.#currentUpdate === null) {\n this.#currentUpdate = this.#update();\n }\n await this.#currentUpdate;\n this.#currentUpdate = null;\n }\n\n /**\n * Updates the registry database if the registry hasn't been updated recently.\n *\n * NOTE: SHOULD NOT be called directly, instead `triggerUpdate` should be used.\n */\n async #update() {\n // No-op if we recently fetched the registry.\n if (this.#wasRecentlyFetched()) {\n return;\n }\n\n try {\n const database = await this.#safeFetch(this.#url.registry);\n\n if (this.#publicKey) {\n const signature = await this.#safeFetch(this.#url.signature);\n await this.#verifySignature(database, signature);\n }\n\n this.update((state) => {\n state.database = JSON.parse(database);\n state.lastUpdated = Date.now();\n });\n } catch {\n // Ignore\n }\n }\n\n async #getDatabase(): Promise<SnapsRegistryDatabase | null> {\n if (this.state.database === null) {\n await this.#triggerUpdate();\n }\n\n // If the database is still null and we require it, throw.\n if (this.#failOnUnavailableRegistry && this.state.database === null) {\n throw new Error('Snaps registry is unavailable, installation blocked.');\n }\n return this.state.database;\n }\n\n async #getSingle(\n snapId: SnapId,\n snapInfo: SnapsRegistryInfo,\n refetch = false,\n ): Promise<SnapsRegistryResult> {\n const database = await this.#getDatabase();\n\n const blockedEntry = database?.blockedSnaps.find((blocked) => {\n if ('id' in blocked) {\n return (\n blocked.id === snapId &&\n satisfiesVersionRange(snapInfo.version, blocked.versionRange)\n );\n }\n\n return blocked.checksum === snapInfo.checksum;\n });\n\n if (blockedEntry) {\n return {\n status: SnapsRegistryStatus.Blocked,\n reason: blockedEntry.reason,\n };\n }\n\n const verified = database?.verifiedSnaps[snapId];\n const version = verified?.versions?.[snapInfo.version];\n if (version && version.checksum === snapInfo.checksum) {\n return { status: SnapsRegistryStatus.Verified };\n }\n // For now, if we have an allowlist miss, we can refetch once and try again.\n if (this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#getSingle(snapId, snapInfo, true);\n }\n return { status: SnapsRegistryStatus.Unverified };\n }\n\n async #get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<SnapId, SnapsRegistryResult>> {\n return Object.entries(snaps).reduce<\n Promise<Record<SnapId, SnapsRegistryResult>>\n >(async (previousPromise, [snapId, snapInfo]) => {\n const result = await this.#getSingle(snapId, snapInfo);\n const acc = await previousPromise;\n acc[snapId] = result;\n return acc;\n }, Promise.resolve({}));\n }\n\n /**\n * Find an allowlisted version within a specified version range.\n *\n * @param snapId - The ID of the snap we are trying to resolve a version for.\n * @param versionRange - The version range.\n * @param refetch - An optional flag used to determine if we are refetching the registry.\n * @returns An allowlisted version within the specified version range.\n * @throws If an allowlisted version does not exist within the version range.\n */\n async #resolveVersion(\n snapId: SnapId,\n versionRange: SemVerRange,\n refetch = false,\n ): Promise<SemVerRange> {\n const database = await this.#getDatabase();\n const versions = database?.verifiedSnaps[snapId]?.versions ?? null;\n\n if (!versions && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(versions, 'The snap is not on the allowlist');\n\n const targetVersion = getTargetVersion(\n Object.keys(versions) as SemVerVersion[],\n versionRange,\n );\n\n if (!targetVersion && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(\n targetVersion,\n 'No matching versions of the snap are on the allowlist',\n );\n\n // A semver version is technically also a valid semver range.\n assertIsSemVerRange(targetVersion);\n return targetVersion;\n }\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n async #getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null> {\n const database = await this.#getDatabase();\n return database?.verifiedSnaps[snapId]?.metadata ?? null;\n }\n\n /**\n * Verify the signature of the registry.\n *\n * @param database - The registry database.\n * @param signature - The signature of the registry.\n * @throws If the signature is invalid.\n * @private\n */\n async #verifySignature(database: string, signature: string) {\n assert(this.#publicKey, 'No public key provided.');\n\n const valid = await verify({\n registry: database,\n signature: JSON.parse(signature),\n publicKey: this.#publicKey,\n });\n\n assert(valid, 'Invalid registry signature.');\n }\n\n /**\n * Fetch the given URL, throwing if the response is not OK.\n *\n * @param url - The URL to fetch.\n * @returns The response body.\n * @private\n */\n async #safeFetch(url: string) {\n const response = await this.#fetchFunction(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}.`);\n }\n\n return await response.text();\n }\n}\n"],"names":["BaseControllerV2","BaseController","verify","getTargetVersion","assert","assertIsSemVerRange","Duration","inMilliseconds","satisfiesVersionRange","SnapsRegistryStatus","SNAP_REGISTRY_URL","SNAP_REGISTRY_SIGNATURE_URL","controllerName","defaultState","database","lastUpdated","JsonSnapsRegistry","constructor","messenger","state","url","registry","signature","publicKey","fetchFunction","globalThis","fetch","bind","recentFetchThreshold","Minute","failOnUnavailableRegistry","refetchOnAllowlistMiss","metadata","persist","anonymous","name","currentUpdate","messagingSystem","registerActionHandler","args","get","getMetadata","resolveVersion","triggerUpdate","Date","now","update","wasRecentlyFetched","safeFetch","verifySignature","JSON","parse","Error","snapId","snapInfo","refetch","getDatabase","blockedEntry","blockedSnaps","find","blocked","id","version","versionRange","checksum","status","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","targetVersion","keys","valid","response","ok","text"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,oBAAoBC,cAAc,QAAQ,4BAA4B;AAE/E,SAASC,MAAM,QAAQ,2BAA2B;AAClD,SAASC,gBAAgB,QAAqB,wBAAwB;AAEtE,SACEC,MAAM,EACNC,mBAAmB,EACnBC,QAAQ,EACRC,cAAc,EACdC,qBAAqB,QAChB,kBA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P;IAGF,IAAI,CAACoB,0CAAiB,IAAI,EAAEpD,4BAA0B,CAACwB,SAAS;QAC9D,MAAM,0BAAA,IAAI,EAAEZ,gBAAAA,oBAAN,IAAI;QACV,OAAO,0BAAA,IAAI,EAAED,iBAAAA,qBAAN,IAAI,EAAiBW,QAAQU,cAAc;IACpD;IAEA3D,OACE+E,eACA;IAGF,6DAA6D;IAC7D9E,oBAAoB8E;IACpB,OAAOA;AACT;AASA,eAAA,YAAmB9B,MAAc;IAC/B,MAAMvC,WAAW,MAAM,0BAAA,IAAI,EAAE0C,cAAAA,kBAAN,IAAI;IAC3B,OAAO1C,UAAUuD,aAAa,CAAChB,OAAO,EAAErB,YAAY;AACtD;AAUA,eAAA,gBAAuBlB,QAAgB,EAAEQ,SAAiB;IACxDlB,gCAAO,IAAI,EAAEmB,aAAW;IAExB,MAAM8D,QAAQ,MAAMnF,OAAO;QACzBmB,UAAUP;QACVQ,WAAW4B,KAAKC,KAAK,CAAC7B;QACtBC,SAAS,2BAAE,IAAI,EAAEA;IACnB;IAEAnB,OAAOiF,OAAO;AAChB;AASA,eAAA,UAAiBjE,GAAW;IAC1B,MAAMkE,WAAW,MAAM,yBAAA,IAAI,EAAE9D,qBAAN,IAAI,EAAgBJ;IAC3C,IAAI,CAACkE,SAASC,EAAE,EAAE;QAChB,MAAM,IAAInC,MAAM,CAAC,gBAAgB,EAAEhC,IAAI,CAAC,CAAC;IAC3C;IAEA,OAAO,MAAMkE,SAASE,IAAI;AAC5B"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/registry/json.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { SnapsRegistryDatabase } from '@metamask/snaps-registry';\nimport { verify } from '@metamask/snaps-registry';\nimport { getTargetVersion } from '@metamask/snaps-utils';\nimport type { Hex, SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerRange,\n Duration,\n inMilliseconds,\n satisfiesVersionRange,\n} from '@metamask/utils';\n\nimport type {\n SnapsRegistry,\n SnapsRegistryInfo,\n SnapsRegistryMetadata,\n SnapsRegistryRequest,\n SnapsRegistryResult,\n} from './registry';\nimport { SnapsRegistryStatus } from './registry';\n\n// TODO: Replace with a Codefi URL\nconst SNAP_REGISTRY_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/registry.json';\n\nconst SNAP_REGISTRY_SIGNATURE_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/signature.json';\n\ntype JsonSnapsRegistryUrl = {\n registry: string;\n signature: string;\n};\n\nexport type JsonSnapsRegistryArgs = {\n messenger: SnapsRegistryMessenger;\n state?: SnapsRegistryState;\n fetchFunction?: typeof fetch;\n url?: JsonSnapsRegistryUrl;\n recentFetchThreshold?: number;\n refetchOnAllowlistMiss?: boolean;\n failOnUnavailableRegistry?: boolean;\n publicKey?: Hex;\n};\n\nexport type GetResult = {\n type: `${typeof controllerName}:get`;\n handler: SnapsRegistry['get'];\n};\n\nexport type ResolveVersion = {\n type: `${typeof controllerName}:resolveVersion`;\n handler: SnapsRegistry['resolveVersion'];\n};\n\nexport type GetMetadata = {\n type: `${typeof controllerName}:getMetadata`;\n handler: SnapsRegistry['getMetadata'];\n};\n\nexport type Update = {\n type: `${typeof controllerName}:update`;\n handler: SnapsRegistry['update'];\n};\n\nexport type SnapsRegistryActions =\n | GetResult\n | GetMetadata\n | Update\n | ResolveVersion;\n\nexport type SnapsRegistryEvents = never;\n\nexport type SnapsRegistryMessenger = RestrictedControllerMessenger<\n 'SnapsRegistry',\n SnapsRegistryActions,\n SnapsRegistryEvents,\n SnapsRegistryActions['type'],\n SnapsRegistryEvents['type']\n>;\n\nexport type SnapsRegistryState = {\n database: SnapsRegistryDatabase | null;\n lastUpdated: number | null;\n};\n\nconst controllerName = 'SnapsRegistry';\n\nconst defaultState = {\n database: null,\n lastUpdated: null,\n};\n\nexport class JsonSnapsRegistry extends BaseController<\n typeof controllerName,\n SnapsRegistryState,\n SnapsRegistryMessenger\n> {\n #url: JsonSnapsRegistryUrl;\n\n #publicKey?: Hex;\n\n #fetchFunction: typeof fetch;\n\n #recentFetchThreshold: number;\n\n #refetchOnAllowlistMiss: boolean;\n\n #failOnUnavailableRegistry: boolean;\n\n #currentUpdate: Promise<void> | null;\n\n constructor({\n messenger,\n state,\n url = {\n registry: SNAP_REGISTRY_URL,\n signature: SNAP_REGISTRY_SIGNATURE_URL,\n },\n publicKey,\n fetchFunction = globalThis.fetch.bind(globalThis),\n recentFetchThreshold = inMilliseconds(5, Duration.Minute),\n failOnUnavailableRegistry = true,\n refetchOnAllowlistMiss = true,\n }: JsonSnapsRegistryArgs) {\n super({\n messenger,\n metadata: {\n database: { persist: true, anonymous: false },\n lastUpdated: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n ...defaultState,\n ...state,\n },\n });\n this.#url = url;\n this.#publicKey = publicKey;\n this.#fetchFunction = fetchFunction;\n this.#recentFetchThreshold = recentFetchThreshold;\n this.#refetchOnAllowlistMiss = refetchOnAllowlistMiss;\n this.#failOnUnavailableRegistry = failOnUnavailableRegistry;\n this.#currentUpdate = null;\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:get',\n async (...args) => this.#get(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:getMetadata',\n async (...args) => this.#getMetadata(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:resolveVersion',\n async (...args) => this.#resolveVersion(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:update',\n async () => this.#triggerUpdate(),\n );\n }\n\n #wasRecentlyFetched() {\n return (\n this.state.lastUpdated &&\n Date.now() - this.state.lastUpdated < this.#recentFetchThreshold\n );\n }\n\n /**\n * Triggers an update of the registry database.\n *\n * If an existing update is in progress this function will await that update.\n */\n async #triggerUpdate() {\n // If an update is ongoing, wait for that.\n if (this.#currentUpdate) {\n await this.#currentUpdate;\n return;\n }\n // If no update exists, create promise and store globally.\n if (this.#currentUpdate === null) {\n this.#currentUpdate = this.#update();\n }\n await this.#currentUpdate;\n this.#currentUpdate = null;\n }\n\n /**\n * Updates the registry database if the registry hasn't been updated recently.\n *\n * NOTE: SHOULD NOT be called directly, instead `triggerUpdate` should be used.\n */\n async #update() {\n // No-op if we recently fetched the registry.\n if (this.#wasRecentlyFetched()) {\n return;\n }\n\n try {\n const database = await this.#safeFetch(this.#url.registry);\n\n if (this.#publicKey) {\n const signature = await this.#safeFetch(this.#url.signature);\n await this.#verifySignature(database, signature);\n }\n\n this.update((state) => {\n state.database = JSON.parse(database);\n state.lastUpdated = Date.now();\n });\n } catch {\n // Ignore\n }\n }\n\n async #getDatabase(): Promise<SnapsRegistryDatabase | null> {\n if (this.state.database === null) {\n await this.#triggerUpdate();\n }\n\n // If the database is still null and we require it, throw.\n if (this.#failOnUnavailableRegistry && this.state.database === null) {\n throw new Error('Snaps registry is unavailable, installation blocked.');\n }\n return this.state.database;\n }\n\n async #getSingle(\n snapId: string,\n snapInfo: SnapsRegistryInfo,\n refetch = false,\n ): Promise<SnapsRegistryResult> {\n const database = await this.#getDatabase();\n\n const blockedEntry = database?.blockedSnaps.find((blocked) => {\n if ('id' in blocked) {\n return (\n blocked.id === snapId &&\n satisfiesVersionRange(snapInfo.version, blocked.versionRange)\n );\n }\n\n return blocked.checksum === snapInfo.checksum;\n });\n\n if (blockedEntry) {\n return {\n status: SnapsRegistryStatus.Blocked,\n reason: blockedEntry.reason,\n };\n }\n\n const verified = database?.verifiedSnaps[snapId];\n const version = verified?.versions?.[snapInfo.version];\n if (version && version.checksum === snapInfo.checksum) {\n return { status: SnapsRegistryStatus.Verified };\n }\n // For now, if we have an allowlist miss, we can refetch once and try again.\n if (this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#getSingle(snapId, snapInfo, true);\n }\n return { status: SnapsRegistryStatus.Unverified };\n }\n\n async #get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<string, SnapsRegistryResult>> {\n return Object.entries(snaps).reduce<\n Promise<Record<string, SnapsRegistryResult>>\n >(async (previousPromise, [snapId, snapInfo]) => {\n const result = await this.#getSingle(snapId, snapInfo);\n const acc = await previousPromise;\n acc[snapId] = result;\n return acc;\n }, Promise.resolve({}));\n }\n\n /**\n * Find an allowlisted version within a specified version range.\n *\n * @param snapId - The ID of the snap we are trying to resolve a version for.\n * @param versionRange - The version range.\n * @param refetch - An optional flag used to determine if we are refetching the registry.\n * @returns An allowlisted version within the specified version range.\n * @throws If an allowlisted version does not exist within the version range.\n */\n async #resolveVersion(\n snapId: string,\n versionRange: SemVerRange,\n refetch = false,\n ): Promise<SemVerRange> {\n const database = await this.#getDatabase();\n const versions = database?.verifiedSnaps[snapId]?.versions ?? null;\n\n if (!versions && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(versions, 'The snap is not on the allowlist');\n\n const targetVersion = getTargetVersion(\n Object.keys(versions) as SemVerVersion[],\n versionRange,\n );\n\n if (!targetVersion && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(\n targetVersion,\n 'No matching versions of the snap are on the allowlist',\n );\n\n // A semver version is technically also a valid semver range.\n assertIsSemVerRange(targetVersion);\n return targetVersion;\n }\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n async #getMetadata(snapId: string): Promise<SnapsRegistryMetadata | null> {\n const database = await this.#getDatabase();\n return database?.verifiedSnaps[snapId]?.metadata ?? null;\n }\n\n /**\n * Verify the signature of the registry.\n *\n * @param database - The registry database.\n * @param signature - The signature of the registry.\n * @throws If the signature is invalid.\n * @private\n */\n async #verifySignature(database: string, signature: string) {\n assert(this.#publicKey, 'No public key provided.');\n\n const valid = await verify({\n registry: database,\n signature: JSON.parse(signature),\n publicKey: this.#publicKey,\n });\n\n assert(valid, 'Invalid registry signature.');\n }\n\n /**\n * Fetch the given URL, throwing if the response is not OK.\n *\n * @param url - The URL to fetch.\n * @returns The response body.\n * @private\n */\n async #safeFetch(url: string) {\n const response = await this.#fetchFunction(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}.`);\n }\n\n return await response.text();\n }\n}\n"],"names":["BaseControllerV2","BaseController","verify","getTargetVersion","assert","assertIsSemVerRange","Duration","inMilliseconds","satisfiesVersionRange","SnapsRegistryStatus","SNAP_REGISTRY_URL","SNAP_REGISTRY_SIGNATURE_URL","controllerName","defaultState","database","lastUpdated","JsonSnapsRegistry","constructor","messenger","state","url","registry","signature","publicKey","fetchFunction","globalThis","fetch","bind","recentFetchThreshold","Minute","failOnUnavailableRegistry","refetchOnAllowlistMiss","metadata","persist","anonymous","name","currentUpdate","messagingSystem","registerActionHandler","args","get","getMetadata","resolveVersion","triggerUpdate","Date","now","update","wasRecentlyFetched","safeFetch","verifySignature","JSON","parse","Error","snapId","snapInfo","refetch","getDatabase","blockedEntry","blockedSnaps","find","blocked","id","version","versionRange","checksum","status","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","targetVersion","keys","valid","response","ok","text"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,oBAAoBC,cAAc,QAAQ,4BAA4B;AAE/E,SAASC,MAAM,QAAQ,2BAA2B;AAClD,SAASC,gBAAgB,QAAQ,wBAAwB;AAEzD,SACEC,MAAM,EACNC,mBAAmB,EACnBC,QAAQ,EACRC,cAAc,EACdC,qBAAqB,QAChB,kBAAkB;AASzB,SAASC,mBAAmB,QAAQ,aAAa;AAEjD,kCAAkC;AAClC,MAAMC,oBACJ;AAEF,MAAMC,8BACJ;AA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Z,gBAAAA,oBAAN,IAAI;QACV,OAAO,0BAAA,IAAI,EAAED,iBAAAA,qBAAN,IAAI,EAAiBW,QAAQU,cAAc;IACpD;IAEA3D,OACE+E,eACA;IAGF,6DAA6D;IAC7D9E,oBAAoB8E;IACpB,OAAOA;AACT;AASA,eAAA,YAAmB9B,MAAc;IAC/B,MAAMvC,WAAW,MAAM,0BAAA,IAAI,EAAE0C,cAAAA,kBAAN,IAAI;IAC3B,OAAO1C,UAAUuD,aAAa,CAAChB,OAAO,EAAErB,YAAY;AACtD;AAUA,eAAA,gBAAuBlB,QAAgB,EAAEQ,SAAiB;IACxDlB,gCAAO,IAAI,EAAEmB,aAAW;IAExB,MAAM8D,QAAQ,MAAMnF,OAAO;QACzBmB,UAAUP;QACVQ,WAAW4B,KAAKC,KAAK,CAAC7B;QACtBC,SAAS,2BAAE,IAAI,EAAEA;IACnB;IAEAnB,OAAOiF,OAAO;AAChB;AASA,eAAA,UAAiBjE,GAAW;IAC1B,MAAMkE,WAAW,MAAM,yBAAA,IAAI,EAAE9D,qBAAN,IAAI,EAAgBJ;IAC3C,IAAI,CAACkE,SAASC,EAAE,EAAE;QAChB,MAAM,IAAInC,MAAM,CAAC,gBAAgB,EAAEhC,IAAI,CAAC,CAAC;IAC3C;IAEA,OAAO,MAAMkE,SAASE,IAAI;AAC5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/registry/registry.ts"],"sourcesContent":["import type {\n BlockReason,\n SnapsRegistryDatabase,\n} from '@metamask/snaps-registry';\nimport type { SnapId
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/registry/registry.ts"],"sourcesContent":["import type {\n BlockReason,\n SnapsRegistryDatabase,\n} from '@metamask/snaps-registry';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\n\nexport type SnapsRegistryInfo = { version: SemVerVersion; checksum: string };\nexport type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;\nexport type SnapsRegistryMetadata =\n SnapsRegistryDatabase['verifiedSnaps'][SnapId]['metadata'];\n\n// TODO: Decide on names for these\nexport enum SnapsRegistryStatus {\n Unverified = 0,\n Blocked = 1,\n Verified = 2,\n}\n\nexport type SnapsRegistryResult = {\n status: SnapsRegistryStatus;\n reason?: BlockReason;\n};\n\nexport type SnapsRegistry = {\n get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<SnapId, SnapsRegistryResult>>;\n\n update(): Promise<void>;\n\n /**\n * Find an allowlisted version within a specified version range.\n *\n * @param snapId - The ID of the snap we are trying to resolve a version for.\n * @param versionRange - The version range.\n * @param refetch - An optional flag used to determine if we are refetching the registry.\n * @returns An allowlisted version within the specified version range.\n * @throws If an allowlisted version does not exist within the version range.\n */\n resolveVersion(\n snapId: SnapId,\n versionRange: SemVerRange,\n ): Promise<SemVerRange>;\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;\n};\n"],"names":["SnapsRegistryStatus","Unverified","Blocked","Verified"],"mappings":"WAaO;UAAKA,mBAAmB;IAAnBA,oBAAAA,oBACVC,gBAAa,KAAbA;IADUD,oBAAAA,oBAEVE,aAAU,KAAVA;IAFUF,oBAAAA,oBAGVG,cAAW,KAAXA;GAHUH,wBAAAA"}
|
package/dist/esm/utils.js
CHANGED
|
@@ -79,5 +79,17 @@ import { Timer } from './snaps/Timer';
|
|
|
79
79
|
delayPromise.cancel();
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Get all files in a Snap from an array of file paths.
|
|
84
|
+
*
|
|
85
|
+
* @param location - The location of the Snap.
|
|
86
|
+
* @param files - The array of file paths.
|
|
87
|
+
* @returns The array of files as {@link VirtualFile}s.
|
|
88
|
+
*/ export async function getSnapFiles(location, files) {
|
|
89
|
+
if (!files || files.length === 0) {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
return await Promise.all(files.map(async (filePath)=>location.fetch(filePath)));
|
|
93
|
+
}
|
|
82
94
|
|
|
83
95
|
//# sourceMappingURL=utils.js.map
|
package/dist/esm/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n"],"names":["Timer","setDiff","objectA","objectB","Object","entries","reduce","acc","key","value","delay","ms","result","delayWithTimer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","hasTimedOut","Symbol","withTimeout","timerOrMs","delayPromise","race"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n"],"names":["Timer","setDiff","objectA","objectB","Object","entries","reduce","acc","key","value","delay","ms","result","delayWithTimer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","hasTimedOut","Symbol","withTimeout","timerOrMs","delayPromise","race","getSnapFiles","location","files","length","all","map","filePath","fetch"],"mappings":"AACA,SAASA,KAAK,QAAQ,gBAAgB;AAEtC;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,QAGdC,OAAgB,EAAEC,OAAgB;IAClC,OAAOC,OAAOC,OAAO,CAACH,SAASI,MAAM,CACnC,CAACC,KAAK,CAACC,KAAKC,MAAM;QAChB,IAAI,CAAED,CAAAA,OAAOL,OAAM,GAAI;YACrBI,GAAG,CAACC,IAAI,GAAGC;QACb;QACA,OAAOF;IACT,GACA,CAAC;AAEL;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,MACdC,EAAU,EACVC,MAAe;IAEf,OAAOC,eAAe,IAAIb,MAAMW,KAAKC;AACvC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,eACdC,KAAY,EACZF,MAAe;IAEf,IAAIG;IACJ,MAAMC,UAAe,IAAIC,QAAgB,CAACC,SAAcC;QACtDL,MAAMM,KAAK,CAAC;YACVR,WAAWS,YAAYH,YAAYA,QAAQN;QAC7C;QACAG,aAAaI;IACf;IAEAH,QAAQM,MAAM,GAAG;QACf,IAAIR,MAAMS,MAAM,KAAK,YAAY;YAC/BT,MAAMQ,MAAM;YACZP,WAAW,IAAIS,MAAM;QACvB;IACF;IACA,OAAOR;AACT;AAEA;;;CAGC,GACD,OAAO,MAAMS,cAAcC,OACzB,wEACA;AAEF;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,YACpBX,OAA8B,EAC9BY,SAAyB;IAEzB,MAAMd,QACJ,OAAOc,cAAc,WAAW,IAAI5B,MAAM4B,aAAaA;IACzD,MAAMC,eAAehB,eAAeC,OAAOW;IAC3C,IAAI;QACF,OAAO,MAAMR,QAAQa,IAAI,CAAC;YAACd;YAASa;SAAa;IACnD,SAAU;QACRA,aAAaP,MAAM;IACrB;AACF;AA+FA;;;;;;CAMC,GACD,OAAO,eAAeS,aACpBC,QAAsB,EACtBC,KAA4B;IAE5B,IAAI,CAACA,SAASA,MAAMC,MAAM,KAAK,GAAG;QAChC,OAAO,EAAE;IACX;IAEA,OAAO,MAAMjB,QAAQkB,GAAG,CACtBF,MAAMG,GAAG,CAAC,OAAOC,WAAaL,SAASM,KAAK,CAACD;AAEjD"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
2
2
|
import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
|
|
3
3
|
import type { GetPermissions } from '@metamask/permission-controller';
|
|
4
|
-
import type { SnapId
|
|
4
|
+
import type { SnapId } from '@metamask/snaps-sdk';
|
|
5
|
+
import type { CronjobSpecification } from '@metamask/snaps-utils';
|
|
5
6
|
import type { GetAllSnaps, HandleSnapRequest, SnapDisabled, SnapEnabled, SnapInstalled, SnapRemoved, SnapUpdated } from '..';
|
|
6
7
|
import { Timer } from '../snaps/Timer';
|
|
7
8
|
export declare type CronjobControllerActions = GetAllSnaps | HandleSnapRequest | GetPermissions;
|
|
@@ -18,7 +19,7 @@ export declare type CronjobControllerArgs = {
|
|
|
18
19
|
export declare type Cronjob = {
|
|
19
20
|
timer?: Timer;
|
|
20
21
|
id: string;
|
|
21
|
-
snapId:
|
|
22
|
+
snapId: SnapId;
|
|
22
23
|
} & CronjobSpecification;
|
|
23
24
|
export declare type StoredJobInformation = {
|
|
24
25
|
lastRun: number;
|
|
@@ -53,7 +54,7 @@ export declare class CronjobController extends BaseController<typeof controllerN
|
|
|
53
54
|
*
|
|
54
55
|
* @param snapId - ID of a snap.
|
|
55
56
|
*/
|
|
56
|
-
register(snapId:
|
|
57
|
+
register(snapId: SnapId): void;
|
|
57
58
|
/**
|
|
58
59
|
* Schedule a new job.
|
|
59
60
|
* This will interpret the cron expression and tell the timer to execute the job
|
|
@@ -77,7 +78,7 @@ export declare class CronjobController extends BaseController<typeof controllerN
|
|
|
77
78
|
*
|
|
78
79
|
* @param snapId - ID of a snap.
|
|
79
80
|
*/
|
|
80
|
-
unregister(snapId:
|
|
81
|
+
unregister(snapId: string): void;
|
|
81
82
|
/**
|
|
82
83
|
* Update time of a last run for the Cronjob specified by ID.
|
|
83
84
|
*
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
2
|
-
import type {
|
|
2
|
+
import type { SnapRpcHookArgs } from '@metamask/snaps-utils';
|
|
3
3
|
import type { Json } from '@metamask/utils';
|
|
4
4
|
declare type TerminateSnap = (snapId: string) => Promise<void>;
|
|
5
5
|
declare type TerminateAll = () => Promise<void>;
|
|
@@ -24,15 +24,15 @@ export declare type SnapErrorJson = {
|
|
|
24
24
|
declare const controllerName = "ExecutionService";
|
|
25
25
|
export declare type ErrorMessageEvent = {
|
|
26
26
|
type: 'ExecutionService:unhandledError';
|
|
27
|
-
payload: [
|
|
27
|
+
payload: [string, SnapErrorJson];
|
|
28
28
|
};
|
|
29
29
|
export declare type OutboundRequest = {
|
|
30
30
|
type: 'ExecutionService:outboundRequest';
|
|
31
|
-
payload: [
|
|
31
|
+
payload: [string];
|
|
32
32
|
};
|
|
33
33
|
export declare type OutboundResponse = {
|
|
34
34
|
type: 'ExecutionService:outboundResponse';
|
|
35
|
-
payload: [
|
|
35
|
+
payload: [string];
|
|
36
36
|
};
|
|
37
37
|
export declare type ExecutionServiceEvents = ErrorMessageEvent | OutboundRequest | OutboundResponse;
|
|
38
38
|
/**
|
|
@@ -4,8 +4,10 @@ import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
|
|
|
4
4
|
import type { GetEndowments, GetPermissions, GetSubjectMetadata, GetSubjects, GrantPermissions, HasPermission, HasPermissions, RevokeAllPermissions, RevokePermissionForAllSubjects, RevokePermissions, UpdateCaveat } from '@metamask/permission-controller';
|
|
5
5
|
import type { MaybeUpdateState, TestOrigin } from '@metamask/phishing-controller';
|
|
6
6
|
import type { BlockReason } from '@metamask/snaps-registry';
|
|
7
|
-
import type {
|
|
8
|
-
import { AuxiliaryFileEncoding
|
|
7
|
+
import type { RequestSnapsParams, RequestSnapsResult, SnapId } from '@metamask/snaps-sdk';
|
|
8
|
+
import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';
|
|
9
|
+
import type { PersistedSnap, Snap, SnapRpcHook, SnapRpcHookArgs, StatusContext, StatusEvents, StatusStates, TruncatedSnap } from '@metamask/snaps-utils';
|
|
10
|
+
import { SnapStatusEvents } from '@metamask/snaps-utils';
|
|
9
11
|
import type { Json, NonEmptyArray } from '@metamask/utils';
|
|
10
12
|
import type { StateMachine } from '@xstate/fsm';
|
|
11
13
|
import type { Patch } from 'immer';
|
|
@@ -67,14 +69,15 @@ export declare type SnapError = {
|
|
|
67
69
|
data?: Json;
|
|
68
70
|
};
|
|
69
71
|
declare type CloseAllConnectionsFunction = (origin: string) => void;
|
|
70
|
-
declare type StoredSnaps = Record<
|
|
72
|
+
declare type StoredSnaps = Record<SnapId, Snap>;
|
|
71
73
|
export declare type SnapControllerState = {
|
|
72
74
|
snaps: StoredSnaps;
|
|
73
|
-
snapStates: Record<
|
|
75
|
+
snapStates: Record<SnapId, string | null>;
|
|
76
|
+
unencryptedSnapStates: Record<SnapId, string | null>;
|
|
74
77
|
};
|
|
75
78
|
export declare type PersistedSnapControllerState = SnapControllerState & {
|
|
76
|
-
snaps: Record<
|
|
77
|
-
snapStates: Record<
|
|
79
|
+
snaps: Record<SnapId, PersistedSnap>;
|
|
80
|
+
snapStates: Record<SnapId, string>;
|
|
78
81
|
};
|
|
79
82
|
/**
|
|
80
83
|
* Gets the specified Snap from state.
|
|
@@ -338,30 +341,30 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
338
341
|
* for more information.
|
|
339
342
|
*/
|
|
340
343
|
updateBlockedSnaps(): Promise<void>;
|
|
341
|
-
_onUnhandledSnapError(snapId:
|
|
342
|
-
_onOutboundRequest(snapId:
|
|
343
|
-
_onOutboundResponse(snapId:
|
|
344
|
+
_onUnhandledSnapError(snapId: string, _error: SnapErrorJson): void;
|
|
345
|
+
_onOutboundRequest(snapId: string): void;
|
|
346
|
+
_onOutboundResponse(snapId: string): void;
|
|
344
347
|
/**
|
|
345
348
|
* Starts the given snap. Throws an error if no such snap exists
|
|
346
349
|
* or if it is already running.
|
|
347
350
|
*
|
|
348
351
|
* @param snapId - The id of the Snap to start.
|
|
349
352
|
*/
|
|
350
|
-
startSnap(snapId:
|
|
353
|
+
startSnap(snapId: SnapId): Promise<void>;
|
|
351
354
|
/**
|
|
352
355
|
* Enables the given snap. A snap can only be started if it is enabled. A snap
|
|
353
356
|
* can only be enabled if it isn't blocked.
|
|
354
357
|
*
|
|
355
358
|
* @param snapId - The id of the Snap to enable.
|
|
356
359
|
*/
|
|
357
|
-
enableSnap(snapId:
|
|
360
|
+
enableSnap(snapId: SnapId): void;
|
|
358
361
|
/**
|
|
359
362
|
* Disables the given snap. A snap can only be started if it is enabled.
|
|
360
363
|
*
|
|
361
364
|
* @param snapId - The id of the Snap to disable.
|
|
362
365
|
* @returns A promise that resolves once the snap has been disabled.
|
|
363
366
|
*/
|
|
364
|
-
disableSnap(snapId:
|
|
367
|
+
disableSnap(snapId: SnapId): Promise<void>;
|
|
365
368
|
/**
|
|
366
369
|
* Stops the given snap, removes all hooks, closes all connections, and
|
|
367
370
|
* terminates its worker.
|
|
@@ -370,7 +373,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
370
373
|
* @param statusEvent - The Snap status event that caused the snap to be
|
|
371
374
|
* stopped.
|
|
372
375
|
*/
|
|
373
|
-
stopSnap(snapId:
|
|
376
|
+
stopSnap(snapId: SnapId, statusEvent?: SnapStatusEvents.Stop | SnapStatusEvents.Crash): Promise<void>;
|
|
374
377
|
/**
|
|
375
378
|
* Returns whether the given snap is running.
|
|
376
379
|
* Throws an error if the snap doesn't exist.
|
|
@@ -378,14 +381,14 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
378
381
|
* @param snapId - The id of the Snap to check.
|
|
379
382
|
* @returns `true` if the snap is running, otherwise `false`.
|
|
380
383
|
*/
|
|
381
|
-
isRunning(snapId:
|
|
384
|
+
isRunning(snapId: SnapId): boolean;
|
|
382
385
|
/**
|
|
383
386
|
* Returns whether the given snap has been added to state.
|
|
384
387
|
*
|
|
385
388
|
* @param snapId - The id of the Snap to check for.
|
|
386
389
|
* @returns `true` if the snap exists in the controller state, otherwise `false`.
|
|
387
390
|
*/
|
|
388
|
-
has(snapId:
|
|
391
|
+
has(snapId: SnapId): boolean;
|
|
389
392
|
/**
|
|
390
393
|
* Gets the snap with the given id if it exists, including all data.
|
|
391
394
|
* This should not be used if the snap is to be serializable, as e.g.
|
|
@@ -394,7 +397,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
394
397
|
* @param snapId - The id of the Snap to get.
|
|
395
398
|
* @returns The entire snap object from the controller state.
|
|
396
399
|
*/
|
|
397
|
-
get(snapId:
|
|
400
|
+
get(snapId: string): Snap | undefined;
|
|
398
401
|
/**
|
|
399
402
|
* Gets the snap with the given id, throws if doesn't.
|
|
400
403
|
* This should not be used if the snap is to be serializable, as e.g.
|
|
@@ -405,7 +408,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
405
408
|
* @param snapId - The id of the snap to get.
|
|
406
409
|
* @returns The entire snap object.
|
|
407
410
|
*/
|
|
408
|
-
getExpect(snapId:
|
|
411
|
+
getExpect(snapId: SnapId): Snap;
|
|
409
412
|
/**
|
|
410
413
|
* Gets the snap with the given id if it exists, excluding any
|
|
411
414
|
* non-serializable or expensive-to-serialize data.
|
|
@@ -413,7 +416,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
413
416
|
* @param snapId - The id of the Snap to get.
|
|
414
417
|
* @returns A truncated version of the snap state, that is less expensive to serialize.
|
|
415
418
|
*/
|
|
416
|
-
getTruncated(snapId:
|
|
419
|
+
getTruncated(snapId: SnapId): TruncatedSnap | null;
|
|
417
420
|
/**
|
|
418
421
|
* Gets the snap with the given id, throw if it doesn't exist.
|
|
419
422
|
*
|
|
@@ -421,31 +424,33 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
421
424
|
* @param snapId - The id of the snap to get.
|
|
422
425
|
* @returns A truncated version of the snap state, that is less expensive to serialize.
|
|
423
426
|
*/
|
|
424
|
-
getTruncatedExpect(snapId:
|
|
427
|
+
getTruncatedExpect(snapId: SnapId): TruncatedSnap;
|
|
425
428
|
/**
|
|
426
429
|
* Updates the own state of the snap with the given id.
|
|
427
430
|
* This is distinct from the state MetaMask uses to manage snaps.
|
|
428
431
|
*
|
|
429
432
|
* @param snapId - The id of the Snap whose state should be updated.
|
|
430
433
|
* @param newSnapState - The new state of the snap.
|
|
434
|
+
* @param encrypted - A flag to indicate whether to use encrypted storage or not.
|
|
431
435
|
*/
|
|
432
|
-
updateSnapState(snapId:
|
|
436
|
+
updateSnapState(snapId: SnapId, newSnapState: string, encrypted: boolean): void;
|
|
433
437
|
/**
|
|
434
438
|
* Clears the state of the snap with the given id.
|
|
435
439
|
* This is distinct from the state MetaMask uses to manage snaps.
|
|
436
440
|
*
|
|
437
441
|
* @param snapId - The id of the Snap whose state should be cleared.
|
|
442
|
+
* @param encrypted - A flag to indicate whether to use encrypted storage or not.
|
|
438
443
|
*/
|
|
439
|
-
clearSnapState(snapId:
|
|
444
|
+
clearSnapState(snapId: SnapId, encrypted: boolean): void;
|
|
440
445
|
/**
|
|
441
446
|
* Gets the own state of the snap with the given id.
|
|
442
447
|
* This is distinct from the state MetaMask uses to manage snaps.
|
|
443
448
|
*
|
|
444
449
|
* @param snapId - The id of the Snap whose state to get.
|
|
445
|
-
* @
|
|
446
|
-
* @
|
|
450
|
+
* @param encrypted - A flag to indicate whether to use encrypted storage or not.
|
|
451
|
+
* @returns The requested snap state or null if no state exists.
|
|
447
452
|
*/
|
|
448
|
-
getSnapState(snapId:
|
|
453
|
+
getSnapState(snapId: SnapId, encrypted: boolean): Json;
|
|
449
454
|
/**
|
|
450
455
|
* Gets a static auxiliary snap file in a chosen file encoding.
|
|
451
456
|
*
|
|
@@ -454,7 +459,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
454
459
|
* @param encoding - An optional requested file encoding.
|
|
455
460
|
* @returns The file requested in the chosen file encoding or null if the file is not found.
|
|
456
461
|
*/
|
|
457
|
-
getSnapFile(snapId:
|
|
462
|
+
getSnapFile(snapId: SnapId, path: string, encoding?: AuxiliaryFileEncoding): string | null;
|
|
458
463
|
/**
|
|
459
464
|
* Completely clear the controller's state: delete all associated data,
|
|
460
465
|
* handlers, event listeners, and permissions; tear down all snap providers.
|
|
@@ -467,21 +472,21 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
467
472
|
* @param snapId - The id of the Snap.
|
|
468
473
|
* @returns A promise that resolves once the snap has been removed.
|
|
469
474
|
*/
|
|
470
|
-
removeSnap(snapId:
|
|
475
|
+
removeSnap(snapId: SnapId): Promise<void>;
|
|
471
476
|
/**
|
|
472
477
|
* Stops the given snaps, removes them from state, and clears all associated
|
|
473
478
|
* permissions, handlers, and listeners.
|
|
474
479
|
*
|
|
475
480
|
* @param snapIds - The ids of the Snaps.
|
|
476
481
|
*/
|
|
477
|
-
removeSnaps(snapIds:
|
|
482
|
+
removeSnaps(snapIds: SnapId[]): Promise<void>;
|
|
478
483
|
/**
|
|
479
484
|
* Removes a snap's permission (caveat) from the specified subject.
|
|
480
485
|
*
|
|
481
486
|
* @param origin - The origin from which to remove the snap.
|
|
482
487
|
* @param snapId - The id of the snap to remove.
|
|
483
488
|
*/
|
|
484
|
-
removeSnapFromSubject(origin: string, snapId:
|
|
489
|
+
removeSnapFromSubject(origin: string, snapId: SnapId): void;
|
|
485
490
|
/**
|
|
486
491
|
* Checks if a list of permissions are dynamic and allowed to be revoked, if they are they will all be revoked.
|
|
487
492
|
*
|
|
@@ -495,13 +500,13 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
495
500
|
*
|
|
496
501
|
* @param snapId - The snap id of the snap that was referenced.
|
|
497
502
|
*/
|
|
498
|
-
incrementActiveReferences(snapId:
|
|
503
|
+
incrementActiveReferences(snapId: SnapId): void;
|
|
499
504
|
/**
|
|
500
505
|
* Handles decrement the activeReferences counter.
|
|
501
506
|
*
|
|
502
507
|
* @param snapId - The snap id of the snap that was referenced..
|
|
503
508
|
*/
|
|
504
|
-
decrementActiveReferences(snapId:
|
|
509
|
+
decrementActiveReferences(snapId: SnapId): void;
|
|
505
510
|
/**
|
|
506
511
|
* Gets all snaps in their truncated format.
|
|
507
512
|
*
|
|
@@ -514,7 +519,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
514
519
|
* @param origin - The origin whose permitted snaps to retrieve.
|
|
515
520
|
* @returns The serialized permitted snaps for the origin.
|
|
516
521
|
*/
|
|
517
|
-
getPermittedSnaps(origin: string):
|
|
522
|
+
getPermittedSnaps(origin: string): RequestSnapsResult;
|
|
518
523
|
/**
|
|
519
524
|
* Installs the snaps requested by the given origin, returning the snap
|
|
520
525
|
* object if the origin is permitted to install it, and an authorization error
|
|
@@ -525,7 +530,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
525
530
|
* @returns An object of snap ids and snap objects, or errors if a
|
|
526
531
|
* snap couldn't be installed.
|
|
527
532
|
*/
|
|
528
|
-
installSnaps(origin: string, requestedSnaps:
|
|
533
|
+
installSnaps(origin: string, requestedSnaps: RequestSnapsParams): Promise<RequestSnapsResult>;
|
|
529
534
|
/**
|
|
530
535
|
* Adds, authorizes, and runs the given snap with a snap provider.
|
|
531
536
|
* Results from this method should be efficiently serializable.
|
|
@@ -556,7 +561,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
556
561
|
* @param emitEvent - An optional boolean flag to indicate whether this update should emit an event.
|
|
557
562
|
* @returns The snap metadata if updated, `null` otherwise.
|
|
558
563
|
*/
|
|
559
|
-
updateSnap(origin: string, snapId:
|
|
564
|
+
updateSnap(origin: string, snapId: SnapId, location: SnapLocation, newVersionRange?: string, emitEvent?: boolean): Promise<TruncatedSnap>;
|
|
560
565
|
/**
|
|
561
566
|
* Get metadata for the given snap ID.
|
|
562
567
|
*
|
|
@@ -564,7 +569,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
564
569
|
* @returns The metadata for the given snap ID, or `null` if the snap is not
|
|
565
570
|
* verified.
|
|
566
571
|
*/
|
|
567
|
-
getRegistryMetadata(snapId:
|
|
572
|
+
getRegistryMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;
|
|
568
573
|
/**
|
|
569
574
|
* Initiates a request for the given snap's initial permissions.
|
|
570
575
|
* Must be called in order. See processRequestedSnap.
|
|
@@ -588,7 +593,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
|
|
|
588
593
|
* @returns The result of the JSON-RPC request.
|
|
589
594
|
*/
|
|
590
595
|
handleRequest({ snapId, origin, handler: handlerType, request: rawRequest, }: SnapRpcHookArgs & {
|
|
591
|
-
snapId:
|
|
596
|
+
snapId: SnapId;
|
|
592
597
|
}): Promise<unknown>;
|
|
593
598
|
}
|
|
594
599
|
export {};
|
|
@@ -7,5 +7,6 @@ export declare enum SnapEndowments {
|
|
|
7
7
|
WebAssemblyAccess = "endowment:webassembly",
|
|
8
8
|
NameLookup = "endowment:name-lookup",
|
|
9
9
|
LifecycleHooks = "endowment:lifecycle-hooks",
|
|
10
|
-
Keyring = "endowment:keyring"
|
|
10
|
+
Keyring = "endowment:keyring",
|
|
11
|
+
HomePage = "endowment:page-home"
|
|
11
12
|
}
|