@metamask/snaps-controllers 3.6.0 → 4.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/cjs/cronjob/CronjobController.js +2 -2
  3. package/dist/cjs/cronjob/CronjobController.js.map +1 -1
  4. package/dist/cjs/services/ProxyPostMessageStream.js +3 -10
  5. package/dist/cjs/services/ProxyPostMessageStream.js.map +1 -1
  6. package/dist/cjs/services/node/NodeProcessExecutionService.js +13 -1
  7. package/dist/cjs/services/node/NodeProcessExecutionService.js.map +1 -1
  8. package/dist/cjs/services/node/NodeThreadExecutionService.js +14 -1
  9. package/dist/cjs/services/node/NodeThreadExecutionService.js.map +1 -1
  10. package/dist/cjs/services/offscreen/OffscreenExecutionService.js +36 -99
  11. package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +1 -1
  12. package/dist/cjs/services/proxy/ProxyExecutionService.js +110 -0
  13. package/dist/cjs/services/proxy/ProxyExecutionService.js.map +1 -0
  14. package/dist/cjs/snaps/SnapController.js +206 -96
  15. package/dist/cjs/snaps/SnapController.js.map +1 -1
  16. package/dist/cjs/snaps/endowments/enum.js +1 -0
  17. package/dist/cjs/snaps/endowments/enum.js.map +1 -1
  18. package/dist/cjs/snaps/endowments/index.js +12 -4
  19. package/dist/cjs/snaps/endowments/index.js.map +1 -1
  20. package/dist/cjs/snaps/endowments/signature-insight.js +106 -0
  21. package/dist/cjs/snaps/endowments/signature-insight.js.map +1 -0
  22. package/dist/cjs/utils.js +32 -0
  23. package/dist/cjs/utils.js.map +1 -1
  24. package/dist/esm/cronjob/CronjobController.js +2 -2
  25. package/dist/esm/cronjob/CronjobController.js.map +1 -1
  26. package/dist/esm/services/ProxyPostMessageStream.js +3 -10
  27. package/dist/esm/services/ProxyPostMessageStream.js.map +1 -1
  28. package/dist/esm/services/node/NodeProcessExecutionService.js +13 -1
  29. package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -1
  30. package/dist/esm/services/node/NodeThreadExecutionService.js +14 -1
  31. package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -1
  32. package/dist/esm/services/offscreen/OffscreenExecutionService.js +36 -99
  33. package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -1
  34. package/dist/esm/services/proxy/ProxyExecutionService.js +100 -0
  35. package/dist/esm/services/proxy/ProxyExecutionService.js.map +1 -0
  36. package/dist/esm/snaps/SnapController.js +208 -98
  37. package/dist/esm/snaps/SnapController.js.map +1 -1
  38. package/dist/esm/snaps/endowments/enum.js +1 -0
  39. package/dist/esm/snaps/endowments/enum.js.map +1 -1
  40. package/dist/esm/snaps/endowments/index.js +10 -4
  41. package/dist/esm/snaps/endowments/index.js.map +1 -1
  42. package/dist/esm/snaps/endowments/signature-insight.js +99 -0
  43. package/dist/esm/snaps/endowments/signature-insight.js.map +1 -0
  44. package/dist/esm/utils.js +37 -0
  45. package/dist/esm/utils.js.map +1 -1
  46. package/dist/types/cronjob/CronjobController.d.ts +2 -2
  47. package/dist/types/services/ProxyPostMessageStream.d.ts +1 -2
  48. package/dist/types/services/offscreen/OffscreenExecutionService.d.ts +5 -22
  49. package/dist/types/services/proxy/ProxyExecutionService.d.ts +39 -0
  50. package/dist/types/snaps/SnapController.d.ts +33 -20
  51. package/dist/types/snaps/endowments/enum.d.ts +1 -0
  52. package/dist/types/snaps/endowments/index.d.ts +12 -0
  53. package/dist/types/snaps/endowments/signature-insight.d.ts +39 -0
  54. package/dist/types/utils.d.ts +99 -0
  55. package/package.json +10 -10
@@ -11,6 +11,7 @@ Object.defineProperty(exports, "SnapEndowments", {
11
11
  var SnapEndowments;
12
12
  (function(SnapEndowments) {
13
13
  SnapEndowments["NetworkAccess"] = 'endowment:network-access';
14
+ SnapEndowments["SignatureInsight"] = 'endowment:signature-insight';
14
15
  SnapEndowments["TransactionInsight"] = 'endowment:transaction-insight';
15
16
  SnapEndowments["Cronjob"] = 'endowment:cronjob';
16
17
  SnapEndowments["EthereumProvider"] = 'endowment:ethereum-provider';
@@ -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 HomePage = 'endowment:page-home',\n}\n"],"names":["SnapEndowments","NetworkAccess","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks","Keyring","HomePage"],"mappings":";;;;;;;;;;IAAO;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"}
1
+ {"version":3,"sources":["../../../../src/snaps/endowments/enum.ts"],"sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n SignatureInsight = 'endowment:signature-insight',\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","SignatureInsight","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks","Keyring","HomePage"],"mappings":";;;;;;;;;;IAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,sBAAmB;IAFTF,eAGVG,wBAAqB;IAHXH,eAIVI,aAAU;IAJAJ,eAKVK,sBAAmB;IALTL,eAMVM,SAAM;IANIN,eAOVO,uBAAoB;IAPVP,eAQVQ,gBAAa;IARHR,eASVS,oBAAiB;IATPT,eAUVU,aAAU;IAVAV,eAWVW,cAAW;GAXDX,mBAAAA"}
@@ -24,6 +24,9 @@ _export(exports, {
24
24
  getRpcCaveatOrigins: function() {
25
25
  return _rpc.getRpcCaveatOrigins;
26
26
  },
27
+ getSignatureOriginCaveat: function() {
28
+ return _signatureinsight.getSignatureOriginCaveat;
29
+ },
27
30
  getTransactionOriginCaveat: function() {
28
31
  return _transactioninsight.getTransactionOriginCaveat;
29
32
  },
@@ -43,6 +46,7 @@ const _lifecyclehooks = require("./lifecycle-hooks");
43
46
  const _namelookup = require("./name-lookup");
44
47
  const _networkaccess = require("./network-access");
45
48
  const _rpc = require("./rpc");
49
+ const _signatureinsight = require("./signature-insight");
46
50
  const _transactioninsight = require("./transaction-insight");
47
51
  const _webassembly = require("./web-assembly");
48
52
  _export_star(require("./enum"), exports);
@@ -69,21 +73,24 @@ const endowmentPermissionBuilders = {
69
73
  [_namelookup.nameLookupEndowmentBuilder.targetName]: _namelookup.nameLookupEndowmentBuilder,
70
74
  [_lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName]: _lifecyclehooks.lifecycleHooksEndowmentBuilder,
71
75
  [_keyring.keyringEndowmentBuilder.targetName]: _keyring.keyringEndowmentBuilder,
72
- [_homepage.homePageEndowmentBuilder.targetName]: _homepage.homePageEndowmentBuilder
76
+ [_homepage.homePageEndowmentBuilder.targetName]: _homepage.homePageEndowmentBuilder,
77
+ [_signatureinsight.signatureInsightEndowmentBuilder.targetName]: _signatureinsight.signatureInsightEndowmentBuilder
73
78
  };
74
79
  const endowmentCaveatSpecifications = {
75
80
  ..._cronjob.cronjobCaveatSpecifications,
76
81
  ..._transactioninsight.transactionInsightCaveatSpecifications,
77
82
  ..._rpc.rpcCaveatSpecifications,
78
83
  ..._namelookup.nameLookupCaveatSpecifications,
79
- ..._keyring.keyringCaveatSpecifications
84
+ ..._keyring.keyringCaveatSpecifications,
85
+ ..._signatureinsight.signatureInsightCaveatSpecifications
80
86
  };
81
87
  const endowmentCaveatMappers = {
82
88
  [_cronjob.cronjobEndowmentBuilder.targetName]: _cronjob.getCronjobCaveatMapper,
83
89
  [_transactioninsight.transactionInsightEndowmentBuilder.targetName]: _transactioninsight.getTransactionInsightCaveatMapper,
84
90
  [_rpc.rpcEndowmentBuilder.targetName]: _rpc.getRpcCaveatMapper,
85
91
  [_namelookup.nameLookupEndowmentBuilder.targetName]: _namelookup.getNameLookupCaveatMapper,
86
- [_keyring.keyringEndowmentBuilder.targetName]: _keyring.getKeyringCaveatMapper
92
+ [_keyring.keyringEndowmentBuilder.targetName]: _keyring.getKeyringCaveatMapper,
93
+ [_signatureinsight.signatureInsightEndowmentBuilder.targetName]: _signatureinsight.getSignatureInsightCaveatMapper
87
94
  };
88
95
  const handlerEndowments = {
89
96
  [_snapsutils.HandlerType.OnRpcRequest]: _rpc.rpcEndowmentBuilder.targetName,
@@ -93,7 +100,8 @@ const handlerEndowments = {
93
100
  [_snapsutils.HandlerType.OnInstall]: _lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName,
94
101
  [_snapsutils.HandlerType.OnUpdate]: _lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName,
95
102
  [_snapsutils.HandlerType.OnKeyringRequest]: _keyring.keyringEndowmentBuilder.targetName,
96
- [_snapsutils.HandlerType.OnHomePage]: _homepage.homePageEndowmentBuilder.targetName
103
+ [_snapsutils.HandlerType.OnHomePage]: _homepage.homePageEndowmentBuilder.targetName,
104
+ [_snapsutils.HandlerType.OnSignature]: _signatureinsight.signatureInsightEndowmentBuilder.targetName
97
105
  };
98
106
 
99
107
  //# sourceMappingURL=index.js.map
@@ -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 { 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":["endowmentPermissionBuilders","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","getRpcCaveatOrigins","getTransactionOriginCaveat","getChainIdsCaveat","getKeyringCaveatOrigins","networkAccessEndowmentBuilder","targetName","transactionInsightEndowmentBuilder","cronjobEndowmentBuilder","ethereumProviderEndowmentBuilder","rpcEndowmentBuilder","webAssemblyEndowmentBuilder","nameLookupEndowmentBuilder","lifecycleHooksEndowmentBuilder","keyringEndowmentBuilder","homePageEndowmentBuilder","cronjobCaveatSpecifications","transactionInsightCaveatSpecifications","rpcCaveatSpecifications","nameLookupCaveatSpecifications","keyringCaveatSpecifications","getCronjobCaveatMapper","getTransactionInsightCaveatMapper","getRpcCaveatMapper","getNameLookupCaveatMapper","getKeyringCaveatMapper","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage"],"mappings":";;;;;;;;;;;IAmCaA,2BAA2B;eAA3BA;;IAeAC,6BAA6B;eAA7BA;;IAQAC,sBAAsB;eAAtBA;;IAYAC,iBAAiB;eAAjBA;;IAYJC,mBAAmB;eAAnBA,wBAAmB;;IACnBC,0BAA0B;eAA1BA,8CAA0B;;IAC1BC,iBAAiB;eAAjBA,6BAAiB;;IACjBC,uBAAuB;eAAvBA,gCAAuB;;;4BApFJ;yBAOrB;kCAC0C;0BACR;yBAKlC;gCACwC;4BAKxC;+BACuC;qBAKvC;oCAKA;6BACqC;qBAgD9B;;;;;;;;;;;;;;AA9CP,MAAMP,8BAA8B;IACzC,CAACQ,4CAA6B,CAACC,UAAU,CAAC,EAAED,4CAA6B;IACzE,CAACE,sDAAkC,CAACD,UAAU,CAAC,EAC7CC,sDAAkC;IACpC,CAACC,gCAAuB,CAACF,UAAU,CAAC,EAAEE,gCAAuB;IAC7D,CAACC,kDAAgC,CAACH,UAAU,CAAC,EAC3CG,kDAAgC;IAClC,CAACC,wBAAmB,CAACJ,UAAU,CAAC,EAAEI,wBAAmB;IACrD,CAACC,wCAA2B,CAACL,UAAU,CAAC,EAAEK,wCAA2B;IACrE,CAACC,sCAA0B,CAACN,UAAU,CAAC,EAAEM,sCAA0B;IACnE,CAACC,8CAA8B,CAACP,UAAU,CAAC,EAAEO,8CAA8B;IAC3E,CAACC,gCAAuB,CAACR,UAAU,CAAC,EAAEQ,gCAAuB;IAC7D,CAACC,kCAAwB,CAACT,UAAU,CAAC,EAAES,kCAAwB;AACjE;AAEO,MAAMjB,gCAAgC;IAC3C,GAAGkB,oCAA2B;IAC9B,GAAGC,0DAAsC;IACzC,GAAGC,4BAAuB;IAC1B,GAAGC,0CAA8B;IACjC,GAAGC,oCAA2B;AAChC;AAEO,MAAMrB,yBAGT;IACF,CAACS,gCAAuB,CAACF,UAAU,CAAC,EAAEe,+BAAsB;IAC5D,CAACd,sDAAkC,CAACD,UAAU,CAAC,EAC7CgB,qDAAiC;IACnC,CAACZ,wBAAmB,CAACJ,UAAU,CAAC,EAAEiB,uBAAkB;IACpD,CAACX,sCAA0B,CAACN,UAAU,CAAC,EAAEkB,qCAAyB;IAClE,CAACV,gCAAuB,CAACR,UAAU,CAAC,EAAEmB,+BAAsB;AAC9D;AAEO,MAAMzB,oBAAiD;IAC5D,CAAC0B,uBAAW,CAACC,YAAY,CAAC,EAAEjB,wBAAmB,CAACJ,UAAU;IAC1D,CAACoB,uBAAW,CAACE,aAAa,CAAC,EAAErB,sDAAkC,CAACD,UAAU;IAC1E,CAACoB,uBAAW,CAACG,SAAS,CAAC,EAAErB,gCAAuB,CAACF,UAAU;IAC3D,CAACoB,uBAAW,CAACI,YAAY,CAAC,EAAElB,sCAA0B,CAACN,UAAU;IACjE,CAACoB,uBAAW,CAACK,SAAS,CAAC,EAAElB,8CAA8B,CAACP,UAAU;IAClE,CAACoB,uBAAW,CAACM,QAAQ,CAAC,EAAEnB,8CAA8B,CAACP,UAAU;IACjE,CAACoB,uBAAW,CAACO,gBAAgB,CAAC,EAAEnB,gCAAuB,CAACR,UAAU;IAClE,CAACoB,uBAAW,CAACQ,UAAU,CAAC,EAAEnB,kCAAwB,CAACT,UAAU;AAC/D"}
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 getSignatureInsightCaveatMapper,\n signatureInsightCaveatSpecifications,\n signatureInsightEndowmentBuilder,\n} from './signature-insight';\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 [signatureInsightEndowmentBuilder.targetName]:\n signatureInsightEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n ...nameLookupCaveatSpecifications,\n ...keyringCaveatSpecifications,\n ...signatureInsightCaveatSpecifications,\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 [signatureInsightEndowmentBuilder.targetName]:\n getSignatureInsightCaveatMapper,\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 [HandlerType.OnSignature]: signatureInsightEndowmentBuilder.targetName,\n};\n\nexport * from './enum';\nexport { getRpcCaveatOrigins } from './rpc';\nexport { getSignatureOriginCaveat } from './signature-insight';\nexport { getTransactionOriginCaveat } from './transaction-insight';\nexport { getChainIdsCaveat } from './name-lookup';\nexport { getKeyringCaveatOrigins } from './keyring';\n"],"names":["endowmentPermissionBuilders","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","getRpcCaveatOrigins","getSignatureOriginCaveat","getTransactionOriginCaveat","getChainIdsCaveat","getKeyringCaveatOrigins","networkAccessEndowmentBuilder","targetName","transactionInsightEndowmentBuilder","cronjobEndowmentBuilder","ethereumProviderEndowmentBuilder","rpcEndowmentBuilder","webAssemblyEndowmentBuilder","nameLookupEndowmentBuilder","lifecycleHooksEndowmentBuilder","keyringEndowmentBuilder","homePageEndowmentBuilder","signatureInsightEndowmentBuilder","cronjobCaveatSpecifications","transactionInsightCaveatSpecifications","rpcCaveatSpecifications","nameLookupCaveatSpecifications","keyringCaveatSpecifications","signatureInsightCaveatSpecifications","getCronjobCaveatMapper","getTransactionInsightCaveatMapper","getRpcCaveatMapper","getNameLookupCaveatMapper","getKeyringCaveatMapper","getSignatureInsightCaveatMapper","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","OnSignature"],"mappings":";;;;;;;;;;;IAwCaA,2BAA2B;eAA3BA;;IAiBAC,6BAA6B;eAA7BA;;IASAC,sBAAsB;eAAtBA;;IAcAC,iBAAiB;eAAjBA;;IAaJC,mBAAmB;eAAnBA,wBAAmB;;IACnBC,wBAAwB;eAAxBA,0CAAwB;;IACxBC,0BAA0B;eAA1BA,8CAA0B;;IAC1BC,iBAAiB;eAAjBA,6BAAiB;;IACjBC,uBAAuB;eAAvBA,gCAAuB;;;4BAhGJ;yBAOrB;kCAC0C;0BACR;yBAKlC;gCACwC;4BAKxC;+BACuC;qBAKvC;kCAKA;oCAKA;6BACqC;qBAsD9B;;;;;;;;;;;;;;AApDP,MAAMR,8BAA8B;IACzC,CAACS,4CAA6B,CAACC,UAAU,CAAC,EAAED,4CAA6B;IACzE,CAACE,sDAAkC,CAACD,UAAU,CAAC,EAC7CC,sDAAkC;IACpC,CAACC,gCAAuB,CAACF,UAAU,CAAC,EAAEE,gCAAuB;IAC7D,CAACC,kDAAgC,CAACH,UAAU,CAAC,EAC3CG,kDAAgC;IAClC,CAACC,wBAAmB,CAACJ,UAAU,CAAC,EAAEI,wBAAmB;IACrD,CAACC,wCAA2B,CAACL,UAAU,CAAC,EAAEK,wCAA2B;IACrE,CAACC,sCAA0B,CAACN,UAAU,CAAC,EAAEM,sCAA0B;IACnE,CAACC,8CAA8B,CAACP,UAAU,CAAC,EAAEO,8CAA8B;IAC3E,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CAAC,EAAEtB,kCAAwB,CAACT,UAAU;IAC7D,CAACuB,uBAAW,CAACS,WAAW,CAAC,EAAEtB,kDAAgC,CAACV,UAAU;AACxE"}
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ signatureInsightEndowmentBuilder: function() {
13
+ return signatureInsightEndowmentBuilder;
14
+ },
15
+ getSignatureInsightCaveatMapper: function() {
16
+ return getSignatureInsightCaveatMapper;
17
+ },
18
+ getSignatureOriginCaveat: function() {
19
+ return getSignatureOriginCaveat;
20
+ },
21
+ signatureInsightCaveatSpecifications: function() {
22
+ return signatureInsightCaveatSpecifications;
23
+ }
24
+ });
25
+ const _permissioncontroller = require("@metamask/permission-controller");
26
+ const _rpcerrors = require("@metamask/rpc-errors");
27
+ const _snapsutils = require("@metamask/snaps-utils");
28
+ const _utils = require("@metamask/utils");
29
+ const _enum = require("./enum");
30
+ const permissionName = _enum.SnapEndowments.SignatureInsight;
31
+ /**
32
+ * `endowment:signature-insight` returns nothing; it is intended to be used as a flag
33
+ * by the extension to detect whether the snap has the capability to show information on the signature confirmation screen.
34
+ *
35
+ * @param _builderOptions - Optional specification builder options.
36
+ * @returns The specification for the signature-insight endowment.
37
+ */ const specificationBuilder = (_builderOptions)=>{
38
+ return {
39
+ permissionType: _permissioncontroller.PermissionType.Endowment,
40
+ targetName: permissionName,
41
+ allowedCaveats: [
42
+ _snapsutils.SnapCaveatType.SignatureOrigin
43
+ ],
44
+ endowmentGetter: (_getterOptions)=>undefined,
45
+ validator: ({ caveats })=>{
46
+ if (caveats !== null && caveats?.length > 1 || caveats?.length === 1 && caveats[0].type !== _snapsutils.SnapCaveatType.SignatureOrigin) {
47
+ throw _rpcerrors.rpcErrors.invalidParams({
48
+ message: `Expected a single "${_snapsutils.SnapCaveatType.SignatureOrigin}" caveat.`
49
+ });
50
+ }
51
+ },
52
+ subjectTypes: [
53
+ _permissioncontroller.SubjectType.Snap
54
+ ]
55
+ };
56
+ };
57
+ const signatureInsightEndowmentBuilder = Object.freeze({
58
+ targetName: permissionName,
59
+ specificationBuilder
60
+ });
61
+ /**
62
+ * Validates the type of the caveat value.
63
+ *
64
+ * @param caveat - The caveat to validate.
65
+ * @throws If the caveat value is invalid.
66
+ */ function validateCaveat(caveat) {
67
+ if (!(0, _utils.hasProperty)(caveat, 'value') || !(0, _utils.isPlainObject)(caveat)) {
68
+ throw _rpcerrors.rpcErrors.invalidParams({
69
+ message: 'Expected a plain object.'
70
+ });
71
+ }
72
+ const { value } = caveat;
73
+ (0, _utils.assert)(typeof value === 'boolean', 'Expected caveat value to have type "boolean"');
74
+ }
75
+ function getSignatureInsightCaveatMapper(value) {
76
+ if (!value || !(0, _utils.isObject)(value) || (0, _utils.isObject)(value) && Object.keys(value).length === 0) {
77
+ return {
78
+ caveats: null
79
+ };
80
+ }
81
+ return {
82
+ caveats: [
83
+ {
84
+ type: _snapsutils.SnapCaveatType.SignatureOrigin,
85
+ value: (0, _utils.hasProperty)(value, 'allowSignatureOrigin') && value.allowSignatureOrigin
86
+ }
87
+ ]
88
+ };
89
+ }
90
+ function getSignatureOriginCaveat(permission) {
91
+ if (!permission?.caveats) {
92
+ return null;
93
+ }
94
+ (0, _utils.assert)(permission.caveats.length === 1);
95
+ (0, _utils.assert)(permission.caveats[0].type === _snapsutils.SnapCaveatType.SignatureOrigin);
96
+ const caveat = permission.caveats[0];
97
+ return caveat.value ?? null;
98
+ }
99
+ const signatureInsightCaveatSpecifications = {
100
+ [_snapsutils.SnapCaveatType.SignatureOrigin]: Object.freeze({
101
+ type: _snapsutils.SnapCaveatType.SignatureOrigin,
102
+ validator: (caveat)=>validateCaveat(caveat)
103
+ })
104
+ };
105
+
106
+ //# sourceMappingURL=signature-insight.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/endowments/signature-insight.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionConstraint,\n CaveatSpecificationConstraint,\n Caveat,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { assert, hasProperty, isObject, isPlainObject } from '@metamask/utils';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.SignatureInsight;\n\ntype SignatureInsightEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetName: typeof permissionName;\n endowmentGetter: (_options?: EndowmentGetterParams) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * `endowment:signature-insight` returns nothing; it is intended to be used as a flag\n * by the extension to detect whether the snap has the capability to show information on the signature confirmation screen.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the signature-insight endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n SignatureInsightEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: [SnapCaveatType.SignatureOrigin],\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n validator: ({ caveats }) => {\n if (\n (caveats !== null && caveats?.length > 1) ||\n (caveats?.length === 1 &&\n caveats[0].type !== SnapCaveatType.SignatureOrigin)\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.SignatureOrigin}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const signatureInsightEndowmentBuilder = Object.freeze({\n targetName: permissionName,\n specificationBuilder,\n} as const);\n\n/**\n * Validates the type of the caveat value.\n *\n * @param caveat - The caveat to validate.\n * @throws If the caveat value is invalid.\n */\nfunction validateCaveat(caveat: Caveat<string, any>): void {\n if (!hasProperty(caveat, 'value') || !isPlainObject(caveat)) {\n throw rpcErrors.invalidParams({\n message: 'Expected a plain object.',\n });\n }\n\n const { value } = caveat;\n\n assert(\n typeof value === 'boolean',\n 'Expected caveat value to have type \"boolean\"',\n );\n}\n\n/**\n * Map a raw value from the `initialPermissions` to a caveat specification.\n * Note that this function does not do any validation, that's handled by the\n * PermissionController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getSignatureInsightCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n if (\n !value ||\n !isObject(value) ||\n (isObject(value) && Object.keys(value).length === 0)\n ) {\n return { caveats: null };\n }\n return {\n caveats: [\n {\n type: SnapCaveatType.SignatureOrigin,\n value:\n hasProperty(value, 'allowSignatureOrigin') &&\n (value.allowSignatureOrigin as boolean),\n },\n ],\n };\n}\n\n/**\n * Getter function to get the signature origin caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the signature origin caveat from.\n * @returns The signature origin, or `null` if the permission does not have a\n * signature origin caveat.\n */\nexport function getSignatureOriginCaveat(\n permission?: PermissionConstraint,\n): boolean | null {\n if (!permission?.caveats) {\n return null;\n }\n\n assert(permission.caveats.length === 1);\n assert(permission.caveats[0].type === SnapCaveatType.SignatureOrigin);\n\n const caveat = permission.caveats[0] as Caveat<string, boolean>;\n\n return caveat.value ?? null;\n}\n\nexport const signatureInsightCaveatSpecifications: Record<\n SnapCaveatType.SignatureOrigin,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.SignatureOrigin]: Object.freeze({\n type: SnapCaveatType.SignatureOrigin,\n validator: (caveat: Caveat<string, any>) => validateCaveat(caveat),\n }),\n};\n"],"names":["signatureInsightEndowmentBuilder","getSignatureInsightCaveatMapper","getSignatureOriginCaveat","signatureInsightCaveatSpecifications","permissionName","SnapEndowments","SignatureInsight","specificationBuilder","_builderOptions","permissionType","PermissionType","Endowment","targetName","allowedCaveats","SnapCaveatType","SignatureOrigin","endowmentGetter","_getterOptions","undefined","validator","caveats","length","type","rpcErrors","invalidParams","message","subjectTypes","SubjectType","Snap","Object","freeze","validateCaveat","caveat","hasProperty","isPlainObject","value","assert","isObject","keys","allowSignatureOrigin","permission"],"mappings":";;;;;;;;;;;IA2DaA,gCAAgC;eAAhCA;;IAkCGC,+BAA+B;eAA/BA;;IAiCAC,wBAAwB;eAAxBA;;IAeHC,oCAAoC;eAApCA;;;sCApI+B;2BAClB;4BACK;uBAE8B;sBAE9B;AAE/B,MAAMC,iBAAiBC,oBAAc,CAACC,gBAAgB;AAUtD;;;;;;CAMC,GACD,MAAMC,uBAIF,CAACC;IACH,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,SAAS;QACxCC,YAAYR;QACZS,gBAAgB;YAACC,0BAAc,CAACC,eAAe;SAAC;QAChDC,iBAAiB,CAACC,iBAA2CC;QAC7DC,WAAW,CAAC,EAAEC,OAAO,EAAE;YACrB,IACE,AAACA,YAAY,QAAQA,SAASC,SAAS,KACtCD,SAASC,WAAW,KACnBD,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKR,0BAAc,CAACC,eAAe,EACpD;gBACA,MAAMQ,oBAAS,CAACC,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAEX,0BAAc,CAACC,eAAe,CAAC,SAAS,CAAC;gBAC1E;YACF;QACF;QACAW,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAEO,MAAM5B,mCAAmC6B,OAAOC,MAAM,CAAC;IAC5DlB,YAAYR;IACZG;AACF;AAEA;;;;;CAKC,GACD,SAASwB,eAAeC,MAA2B;IACjD,IAAI,CAACC,IAAAA,kBAAW,EAACD,QAAQ,YAAY,CAACE,IAAAA,oBAAa,EAACF,SAAS;QAC3D,MAAMT,oBAAS,CAACC,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,MAAM,EAAEU,KAAK,EAAE,GAAGH;IAElBI,IAAAA,aAAM,EACJ,OAAOD,UAAU,WACjB;AAEJ;AAUO,SAASlC,gCACdkC,KAAW;IAEX,IACE,CAACA,SACD,CAACE,IAAAA,eAAQ,EAACF,UACTE,IAAAA,eAAQ,EAACF,UAAUN,OAAOS,IAAI,CAACH,OAAOd,MAAM,KAAK,GAClD;QACA,OAAO;YAAED,SAAS;QAAK;IACzB;IACA,OAAO;QACLA,SAAS;YACP;gBACEE,MAAMR,0BAAc,CAACC,eAAe;gBACpCoB,OACEF,IAAAA,kBAAW,EAACE,OAAO,2BAClBA,MAAMI,oBAAoB;YAC/B;SACD;IACH;AACF;AAaO,SAASrC,yBACdsC,UAAiC;IAEjC,IAAI,CAACA,YAAYpB,SAAS;QACxB,OAAO;IACT;IAEAgB,IAAAA,aAAM,EAACI,WAAWpB,OAAO,CAACC,MAAM,KAAK;IACrCe,IAAAA,aAAM,EAACI,WAAWpB,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKR,0BAAc,CAACC,eAAe;IAEpE,MAAMiB,SAASQ,WAAWpB,OAAO,CAAC,EAAE;IAEpC,OAAOY,OAAOG,KAAK,IAAI;AACzB;AAEO,MAAMhC,uCAGT;IACF,CAACW,0BAAc,CAACC,eAAe,CAAC,EAAEc,OAAOC,MAAM,CAAC;QAC9CR,MAAMR,0BAAc,CAACC,eAAe;QACpCI,WAAW,CAACa,SAAgCD,eAAeC;IAC7D;AACF"}
package/dist/cjs/utils.js CHANGED
@@ -26,8 +26,13 @@ _export(exports, {
26
26
  },
27
27
  getSnapFiles: function() {
28
28
  return getSnapFiles;
29
+ },
30
+ fetchSnap: function() {
31
+ return fetchSnap;
29
32
  }
30
33
  });
34
+ const _snapssdk = require("@metamask/snaps-sdk");
35
+ const _snapsutils = require("@metamask/snaps-utils");
31
36
  const _Timer = require("./snaps/Timer");
32
37
  function setDiff(objectA, objectB) {
33
38
  return Object.entries(objectA).reduce((acc, [key, value])=>{
@@ -75,5 +80,32 @@ async function getSnapFiles(location, files) {
75
80
  }
76
81
  return await Promise.all(files.map(async (filePath)=>location.fetch(filePath)));
77
82
  }
83
+ async function fetchSnap(snapId, location) {
84
+ try {
85
+ const manifest = await location.manifest();
86
+ const sourceCode = await location.fetch(manifest.result.source.location.npm.filePath);
87
+ const { iconPath } = manifest.result.source.location.npm;
88
+ const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;
89
+ const auxiliaryFiles = await getSnapFiles(location, manifest.result.source.files);
90
+ await Promise.all(auxiliaryFiles.map(async (file)=>{
91
+ // This should still be safe
92
+ // eslint-disable-next-line require-atomic-updates
93
+ file.data.base64 = await (0, _snapsutils.encodeBase64)(file);
94
+ }));
95
+ const localizationFiles = await getSnapFiles(location, manifest.result.source.locales);
96
+ const validatedLocalizationFiles = (0, _snapsutils.getValidatedLocalizationFiles)(localizationFiles);
97
+ const files = {
98
+ manifest,
99
+ sourceCode,
100
+ svgIcon,
101
+ auxiliaryFiles,
102
+ localizationFiles: validatedLocalizationFiles
103
+ };
104
+ await (0, _snapsutils.validateFetchedSnap)(files);
105
+ return files;
106
+ } catch (error) {
107
+ throw new Error(`Failed to fetch snap "${snapId}": ${(0, _snapssdk.getErrorMessage)(error)}.`);
108
+ }
109
+ }
78
110
 
79
111
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
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":["setDiff","delay","delayWithTimer","hasTimedOut","withTimeout","getSnapFiles","objectA","objectB","Object","entries","reduce","acc","key","value","ms","result","Timer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","Symbol","timerOrMs","delayPromise","race","location","files","length","all","map","filePath","fetch"],"mappings":";;;;;;;;;;;IAiBgBA,OAAO;eAAPA;;IAuBAC,KAAK;eAALA;;IAeAC,cAAc;eAAdA;;IAyBHC,WAAW;eAAXA;;IAeSC,WAAW;eAAXA;;IAkHAC,YAAY;eAAZA;;;uBAhNA;AAgBf,SAASL,QAGdM,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;AAUO,SAASV,MACda,EAAU,EACVC,MAAe;IAEf,OAAOb,eAAe,IAAIc,YAAK,CAACF,KAAKC;AACvC;AAUO,SAASb,eACde,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;AAMO,MAAMhB,cAAcyB,OACzB;AAcK,eAAexB,YACpBe,OAA8B,EAC9BU,SAAyB;IAEzB,MAAMZ,QACJ,OAAOY,cAAc,WAAW,IAAIb,YAAK,CAACa,aAAaA;IACzD,MAAMC,eAAe5B,eAAee,OAAOd;IAC3C,IAAI;QACF,OAAO,MAAMiB,QAAQW,IAAI,CAAC;YAACZ;YAASW;SAAa;IACnD,SAAU;QACRA,aAAaL,MAAM;IACrB;AACF;AAsGO,eAAepB,aACpB2B,QAAsB,EACtBC,KAA4B;IAE5B,IAAI,CAACA,SAASA,MAAMC,MAAM,KAAK,GAAG;QAChC,OAAO,EAAE;IACX;IAEA,OAAO,MAAMd,QAAQe,GAAG,CACtBF,MAAMG,GAAG,CAAC,OAAOC,WAAaL,SAASM,KAAK,CAACD;AAEjD"}
1
+ {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-sdk';\nimport { getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n encodeBase64,\n getValidatedLocalizationFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\n\nimport 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\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${snapId}\": ${getErrorMessage(error)}.`,\n );\n }\n}\n"],"names":["setDiff","delay","delayWithTimer","hasTimedOut","withTimeout","getSnapFiles","fetchSnap","objectA","objectB","Object","entries","reduce","acc","key","value","ms","result","Timer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","Symbol","timerOrMs","delayPromise","race","location","files","length","all","map","filePath","fetch","snapId","manifest","sourceCode","source","npm","iconPath","svgIcon","auxiliaryFiles","file","data","base64","encodeBase64","localizationFiles","locales","validatedLocalizationFiles","getValidatedLocalizationFiles","validateFetchedSnap","error","getErrorMessage"],"mappings":";;;;;;;;;;;IAyBgBA,OAAO;eAAPA;;IAuBAC,KAAK;eAALA;;IAeAC,cAAc;eAAdA;;IAyBHC,WAAW;eAAXA;;IAeSC,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D;AAEjD;AAWO,eAAehC,UAAUkC,MAAc,EAAEP,QAAsB;IACpE,IAAI;QACF,MAAMQ,WAAW,MAAMR,SAASQ,QAAQ;QACxC,MAAMC,aAAa,MAAMT,SAASM,KAAK,CACrCE,SAASzB,MAAM,CAAC2B,MAAM,CAACV,QAAQ,CAACW,GAAG,CAACN,QAAQ;QAE9C,MAAM,EAAEO,QAAQ,EAAE,GAAGJ,SAASzB,MAAM,CAAC2B,MAAM,CAACV,QAAQ,CAACW,GAAG;QACxD,MAAME,UAAUD,WAAW,MAAMZ,SAASM,KAAK,CAACM,YAAYpB;QAE5D,MAAMsB,iBAAiB,MAAM1C,aAC3B4B,UACAQ,SAASzB,MAAM,CAAC2B,MAAM,CAACT,KAAK;QAG9B,MAAMb,QAAQe,GAAG,CACfW,eAAeV,GAAG,CAAC,OAAOW;YACxB,4BAA4B;YAC5B,kDAAkD;YAClDA,KAAKC,IAAI,CAACC,MAAM,GAAG,MAAMC,IAAAA,wBAAY,EAACH;QACxC;QAGF,MAAMI,oBAAoB,MAAM/C,aAC9B4B,UACAQ,SAASzB,MAAM,CAAC2B,MAAM,CAACU,OAAO;QAGhC,MAAMC,6BACJC,IAAAA,yCAA6B,EAACH;QAEhC,MAAMlB,QAAQ;YACZO;YACAC;YACAI;YACAC;YACAK,mBAAmBE;QACrB;QAEA,MAAME,IAAAA,+BAAmB,EAACtB;QAE1B,OAAOA;IACT,EAAE,OAAOuB,OAAO;QACd,MAAM,IAAI7B,MACR,CAAC,sBAAsB,EAAEY,OAAO,GAAG,EAAEkB,IAAAA,yBAAe,EAACD,OAAO,CAAC,CAAC;IAElE;AACF"}
@@ -199,7 +199,7 @@ _snapIds = /*#__PURE__*/ new WeakMap();
199
199
  */ destroy() {
200
200
  super.destroy();
201
201
  /* eslint-disable @typescript-eslint/unbound-method */ this.messagingSystem.unsubscribe('SnapController:snapInstalled', this._handleSnapRegisterEvent);
202
- this.messagingSystem.unsubscribe('SnapController:snapRemoved', this._handleSnapUnregisterEvent);
202
+ this.messagingSystem.unsubscribe('SnapController:snapUninstalled', this._handleSnapUnregisterEvent);
203
203
  this.messagingSystem.unsubscribe('SnapController:snapEnabled', this._handleSnapRegisterEvent);
204
204
  this.messagingSystem.unsubscribe('SnapController:snapDisabled', this._handleSnapUnregisterEvent);
205
205
  this.messagingSystem.unsubscribe('SnapController:snapUpdated', this._handleEventSnapUpdated);
@@ -268,7 +268,7 @@ _snapIds = /*#__PURE__*/ new WeakMap();
268
268
  this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);
269
269
  // Subscribe to Snap events
270
270
  /* eslint-disable @typescript-eslint/unbound-method */ this.messagingSystem.subscribe('SnapController:snapInstalled', this._handleSnapRegisterEvent);
271
- this.messagingSystem.subscribe('SnapController:snapRemoved', this._handleSnapUnregisterEvent);
271
+ this.messagingSystem.subscribe('SnapController:snapUninstalled', this._handleSnapUnregisterEvent);
272
272
  this.messagingSystem.subscribe('SnapController:snapEnabled', this._handleSnapRegisterEvent);
273
273
  this.messagingSystem.subscribe('SnapController:snapDisabled', this._handleSnapUnregisterEvent);
274
274
  this.messagingSystem.subscribe('SnapController:snapUpdated', this._handleEventSnapUpdated);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapRemoved,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapRemoved\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: string) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["BaseController","HandlerType","parseCronExpression","logError","Duration","inMilliseconds","getRunnableSnaps","SnapEndowments","getCronjobCaveatJobs","Timer","DAILY_TIMEOUT","Hour","controllerName","CronjobController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","Cronjob","definitions","definition","idx","register","forEach","schedule","timers","has","parsed","expression","next","now","Date","ms","getTime","timer","start","executeCronjob","catch","error","delete","state","lastRun","updateJobLastRunState","set","snapIds","origin","handler","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","update","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,cAAc,QAAQ,4BAA4B;AAO3D,SACEC,WAAW,EACXC,mBAAmB,EACnBC,QAAQ,QACH,wBAAwB;AAC/B,SAASC,QAAQ,EAAEC,cAAc,QAAQ,kBAAkB;AAW3D,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,KAAK;AACtD,SAASC,oBAAoB,QAAQ,8BAA8B;AACnE,SAASC,KAAK,QAAQ,iBAAiB;AAsBvC,OAAO,MAAMC,gBAAgBL,eAAe,IAAID,SAASO,IAAI,EAAE;AAwB/D,MAAMC,iBAAiB;IAWrB,0CAEA,2CAEA,uCAEA,+BAA+B;AAC/B;AAhBF;;;CAGC,GACD,OAAO,MAAMC,0BAA0Bb;IAoErC;;;;GAIC,GACD,AAAQc,aAAwB;QAC9B,MAAMC,QAAQ,IAAI,CAACC,eAAe,CAACC,IAAI,CAAC;QACxC,MAAMC,gBAAgBZ,iBAAiBS;QAEvC,MAAMI,OAAOD,cAAcE,GAAG,CAAC,CAACC,OAAS,IAAI,CAACC,WAAW,CAACD,KAAKE,EAAE;QACjE,4EAA4E;QAC5E,OAAOJ,KAAKK,IAAI,GAAGC,MAA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T,0BAA0B;QAGjC,IAAI,CAAC/D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGrB,KAAK,CAAC,CAACC;YACzBjD,SAASiD;QACX;IACF;AAiPF"}
1
+ {"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: string) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["BaseController","HandlerType","parseCronExpression","logError","Duration","inMilliseconds","getRunnableSnaps","SnapEndowments","getCronjobCaveatJobs","Timer","DAILY_TIMEOUT","Hour","controllerName","CronjobController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","Cronjob","definitions","definition","idx","register","forEach","schedule","timers","has","parsed","expression","next","now","Date","ms","getTime","timer","start","executeCronjob","catch","error","delete","state","lastRun","updateJobLastRunState","set","snapIds","origin","handler","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","update","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,cAAc,QAAQ,4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AAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;QAGA,gCAAA;;mBAAA,KAAA;;uCAcQf,SAAS,IAAI+C;uCACb5B,UAAU,IAAI4B;uCACdxD,YAAYA;QAElB,IAAI,CAACgD,wBAAwB,GAAG,IAAI,CAACA,wBAAwB,CAACS,IAAI,CAAC,IAAI;QACvE,IAAI,CAACR,0BAA0B,GAC7B,IAAI,CAACA,0BAA0B,CAACQ,IAAI,CAAC,IAAI;QAC3C,IAAI,CAACP,uBAAuB,GAAG,IAAI,CAACA,uBAAuB,CAACO,IAAI,CAAC,IAAI;QAErE,2BAA2B;QAC3B,oDAAoD,GACpD,IAAI,CAACvE,eAAe,CAACwE,SAAS,CAC5B,gCACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAAC9D,eAAe,CAACwE,SAAS,CAC5B,kCACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAAC/D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAAC9D,eAAe,CAACwE,SAAS,CAC5B,+BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAAC/D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGrB,KAAK,CAAC,CAACC;YACzBjD,SAASiD;QACX;IACF;AAiPF"}
@@ -49,7 +49,7 @@ function _class_private_method_init(obj, privateSet) {
49
49
  privateSet.add(obj);
50
50
  }
51
51
  import { BasePostMessageStream } from '@metamask/post-message-stream';
52
- var _stream = /*#__PURE__*/ new WeakMap(), _jobId = /*#__PURE__*/ new WeakMap(), _extra = /*#__PURE__*/ new WeakMap(), /**
52
+ var _stream = /*#__PURE__*/ new WeakMap(), _jobId = /*#__PURE__*/ new WeakMap(), /**
53
53
  * Handle incoming data from the underlying stream. This checks that the job
54
54
  * ID matches the expected job ID, and pushes the data to the stream if so.
55
55
  *
@@ -67,8 +67,7 @@ var _stream = /*#__PURE__*/ new WeakMap(), _jobId = /*#__PURE__*/ new WeakMap(),
67
67
  */ _postMessage(data) {
68
68
  _class_private_field_get(this, _stream).write({
69
69
  jobId: _class_private_field_get(this, _jobId),
70
- data,
71
- extra: _class_private_field_get(this, _extra)
70
+ data
72
71
  });
73
72
  }
74
73
  /**
@@ -77,8 +76,7 @@ var _stream = /*#__PURE__*/ new WeakMap(), _jobId = /*#__PURE__*/ new WeakMap(),
77
76
  * @param args - The constructor arguments.
78
77
  * @param args.stream - The underlying stream to use for communication.
79
78
  * @param args.jobId - The ID of the job this stream is associated with.
80
- * @param args.extra - Extra data to include in the post message.
81
- */ constructor({ stream, jobId, extra }){
79
+ */ constructor({ stream, jobId }){
82
80
  super();
83
81
  _class_private_method_init(this, _onData);
84
82
  _class_private_field_init(this, _stream, {
@@ -89,13 +87,8 @@ var _stream = /*#__PURE__*/ new WeakMap(), _jobId = /*#__PURE__*/ new WeakMap(),
89
87
  writable: true,
90
88
  value: void 0
91
89
  });
92
- _class_private_field_init(this, _extra, {
93
- writable: true,
94
- value: void 0
95
- });
96
90
  _class_private_field_set(this, _stream, stream);
97
91
  _class_private_field_set(this, _jobId, jobId);
98
- _class_private_field_set(this, _extra, extra);
99
92
  _class_private_field_get(this, _stream).on('data', _class_private_method_get(this, _onData, onData).bind(this));
100
93
  }
101
94
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/services/ProxyPostMessageStream.ts"],"sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n readonly #extra?: Record<string, unknown>;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n * @param args.extra - Extra data to include in the post message.\n */\n constructor({ stream, jobId, extra }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n this.#extra = extra;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n extra: this.#extra,\n });\n }\n}\n"],"names":["BasePostMessageStream","ProxyPostMessageStream","_postMessage","data","stream","write","jobId","extra","constructor","on","onData","bind","push"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,qBAAqB,QAAQ,gCAAgC;IAoB3D,uCAEA,sCAEA,sCAoBT;;;;;GAKC,GACD;AAnCF;;;CAGC,GACD,OAAO,MAAMC,+BAA+BD;IAuC1C;;;;;GAKC,GACDE,aAAaC,IAAsB,EAAE;QACnC,yBAAA,IAAI,EAAEC,SAAOC,KAAK,CAAC;YACjBC,KAAK,2BAAE,IAAI,EAAEA;YACbH;YACAI,KAAK,2BAAE,IAAI,EAAEA;QACf;IACF;IA5CA;;;;;;;GAOC,GACDC,YAAY,EAAEJ,MAAM,EAAEE,KAAK,EAAEC,KAAK,EAA8B,CAAE;QAChE,KAAK;QAeP,iCAAA;QA9BA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;uCAaQH,SAASA;uCACTE,QAAQA;uCACRC,QAAQA;QAEd,yBAAA,IAAI,EAAEH,SAAOK,EAAE,CAAC,QAAQ,0BAAA,IAAI,EAAEC,SAAAA,QAAOC,IAAI,CAAC,IAAI;IAChD;AA6BF;AArBE,SAAA,OAAQR,IAAsB;IAC5B,IAAIA,KAAKG,KAAK,8BAAK,IAAI,EAAEA,SAAO;QAC9B;IACF;IAEA,IAAI,CAACM,IAAI,CAACT,KAAKA,IAAI;AACrB"}
1
+ {"version":3,"sources":["../../../src/services/ProxyPostMessageStream.ts"],"sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n */\n constructor({ stream, jobId }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n });\n }\n}\n"],"names":["BasePostMessageStream","ProxyPostMessageStream","_postMessage","data","stream","write","jobId","constructor","on","onData","bind","push"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,qBAAqB,QAAQ,gCAAgC;IAoB3D,uCAEA,sCAkBT;;;;;GAKC,GACD;AA/BF;;;CAGC,GACD,OAAO,MAAMC,+BAA+BD;IAmC1C;;;;;GAKC,GACDE,aAAaC,IAAsB,EAAE;QACnC,yBAAA,IAAI,EAAEC,SAAOC,KAAK,CAAC;YACjBC,KAAK,2BAAE,IAAI,EAAEA;YACbH;QACF;IACF;IAzCA;;;;;;GAMC,GACDI,YAAY,EAAEH,MAAM,EAAEE,KAAK,EAA8B,CAAE;QACzD,KAAK;QAcP,iCAAA;QA1BA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;uCAYQF,SAASA;uCACTE,QAAQA;QAEd,yBAAA,IAAI,EAAEF,SAAOI,EAAE,CAAC,QAAQ,0BAAA,IAAI,EAAEC,SAAAA,QAAOC,IAAI,CAAC,IAAI;IAChD;AA4BF;AApBE,SAAA,OAAQP,IAAsB;IAC5B,IAAIA,KAAKG,KAAK,8BAAK,IAAI,EAAEA,SAAO;QAC9B;IACF;IAEA,IAAI,CAACK,IAAI,CAACR,KAAKA,IAAI;AACrB"}
@@ -3,7 +3,19 @@ import { fork } from 'child_process';
3
3
  import { AbstractExecutionService } from '..';
4
4
  export class NodeProcessExecutionService extends AbstractExecutionService {
5
5
  async initEnvStream() {
6
- const worker = fork(require.resolve('@metamask/snaps-execution-environments/dist/browserify/node-process/bundle.js'));
6
+ const worker = fork(require.resolve('@metamask/snaps-execution-environments/dist/browserify/node-process/bundle.js'), {
7
+ stdio: 'pipe'
8
+ });
9
+ // Capturing `stdout` and `stderr` from the worker prevents the worker from
10
+ // writing to them directly, making it easier to capture them Jest.
11
+ worker.stdout?.on('data', (data)=>{
12
+ // eslint-disable-next-line no-console
13
+ console.log(data.toString());
14
+ });
15
+ worker.stderr?.on('data', (data)=>{
16
+ // eslint-disable-next-line no-console
17
+ console.error(data.toString());
18
+ });
7
19
  const stream = new ProcessParentMessageStream({
8
20
  process: worker
9
21
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/services/node/NodeProcessExecutionService.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { ProcessParentMessageStream } from '@metamask/post-message-stream';\nimport type { ChildProcess } from 'child_process';\nimport { fork } from 'child_process';\n\nimport type { Job } from '..';\nimport { AbstractExecutionService } from '..';\n\nexport class NodeProcessExecutionService extends AbstractExecutionService<ChildProcess> {\n protected async initEnvStream(): Promise<{\n worker: ChildProcess;\n stream: BasePostMessageStream;\n }> {\n const worker = fork(\n require.resolve(\n '@metamask/snaps-execution-environments/dist/browserify/node-process/bundle.js',\n ),\n );\n\n const stream = new ProcessParentMessageStream({ process: worker });\n return Promise.resolve({ worker, stream });\n }\n\n protected terminateJob(jobWrapper: Job<ChildProcess>): void {\n jobWrapper.worker.kill();\n }\n}\n"],"names":["ProcessParentMessageStream","fork","AbstractExecutionService","NodeProcessExecutionService","initEnvStream","worker","require","resolve","stream","process","Promise","terminateJob","jobWrapper","kill"],"mappings":"AACA,SAASA,0BAA0B,QAAQ,gCAAgC;AAE3E,SAASC,IAAI,QAAQ,gBAAgB;AAGrC,SAASC,wBAAwB,QAAQ,KAAK;AAE9C,OAAO,MAAMC,oCAAoCD;IAC/C,MAAgBE,gBAGb;QACD,MAAMC,SAASJ,KACbK,QAAQC,OAAO,CACb;QAIJ,MAAMC,SAAS,IAAIR,2BAA2B;YAAES,SAASJ;QAAO;QAChE,OAAOK,QAAQH,OAAO,CAAC;YAAEF;YAAQG;QAAO;IAC1C;IAEUG,aAAaC,UAA6B,EAAQ;QAC1DA,WAAWP,MAAM,CAACQ,IAAI;IACxB;AACF"}
1
+ {"version":3,"sources":["../../../../src/services/node/NodeProcessExecutionService.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { ProcessParentMessageStream } from '@metamask/post-message-stream';\nimport type { ChildProcess } from 'child_process';\nimport { fork } from 'child_process';\n\nimport type { Job } from '..';\nimport { AbstractExecutionService } from '..';\n\nexport class NodeProcessExecutionService extends AbstractExecutionService<ChildProcess> {\n protected async initEnvStream(): Promise<{\n worker: ChildProcess;\n stream: BasePostMessageStream;\n }> {\n const worker = fork(\n require.resolve(\n '@metamask/snaps-execution-environments/dist/browserify/node-process/bundle.js',\n ),\n {\n stdio: 'pipe',\n },\n );\n\n // Capturing `stdout` and `stderr` from the worker prevents the worker from\n // writing to them directly, making it easier to capture them Jest.\n worker.stdout?.on('data', (data) => {\n // eslint-disable-next-line no-console\n console.log(data.toString());\n });\n\n worker.stderr?.on('data', (data) => {\n // eslint-disable-next-line no-console\n console.error(data.toString());\n });\n\n const stream = new ProcessParentMessageStream({ process: worker });\n return Promise.resolve({ worker, stream });\n }\n\n protected terminateJob(jobWrapper: Job<ChildProcess>): void {\n jobWrapper.worker.kill();\n }\n}\n"],"names":["ProcessParentMessageStream","fork","AbstractExecutionService","NodeProcessExecutionService","initEnvStream","worker","require","resolve","stdio","stdout","on","data","console","log","toString","stderr","error","stream","process","Promise","terminateJob","jobWrapper","kill"],"mappings":"AACA,SAASA,0BAA0B,QAAQ,gCAAgC;AAE3E,SAASC,IAAI,QAAQ,gBAAgB;AAGrC,SAASC,wBAAwB,QAAQ,KAAK;AAE9C,OAAO,MAAMC,oCAAoCD;IAC/C,MAAgBE,gBAGb;QACD,MAAMC,SAASJ,KACbK,QAAQC,OAAO,CACb,kFAEF;YACEC,OAAO;QACT;QAGF,2EAA2E;QAC3E,mEAAmE;QACnEH,OAAOI,MAAM,EAAEC,GAAG,QAAQ,CAACC;YACzB,sCAAsC;YACtCC,QAAQC,GAAG,CAACF,KAAKG,QAAQ;QAC3B;QAEAT,OAAOU,MAAM,EAAEL,GAAG,QAAQ,CAACC;YACzB,sCAAsC;YACtCC,QAAQI,KAAK,CAACL,KAAKG,QAAQ;QAC7B;QAEA,MAAMG,SAAS,IAAIjB,2BAA2B;YAAEkB,SAASb;QAAO;QAChE,OAAOc,QAAQZ,OAAO,CAAC;YAAEF;YAAQY;QAAO;IAC1C;IAEUG,aAAaC,UAA6B,EAAQ;QAC1DA,WAAWhB,MAAM,CAACiB,IAAI;IACxB;AACF"}
@@ -4,7 +4,20 @@ import { Worker } from 'worker_threads';
4
4
  import { AbstractExecutionService } from '..';
5
5
  export class NodeThreadExecutionService extends AbstractExecutionService {
6
6
  async initEnvStream() {
7
- const worker = new Worker(require.resolve('@metamask/snaps-execution-environments/dist/browserify/node-thread/bundle.js'));
7
+ const worker = new Worker(require.resolve('@metamask/snaps-execution-environments/dist/browserify/node-thread/bundle.js'), {
8
+ stdout: true,
9
+ stderr: true
10
+ });
11
+ // Capturing `stdout` and `stderr` from the worker prevents the worker from
12
+ // writing to them directly, making it easier to capture them Jest.
13
+ worker.stdout.on('data', (data)=>{
14
+ // eslint-disable-next-line no-console
15
+ console.log(data.toString());
16
+ });
17
+ worker.stderr.on('data', (data)=>{
18
+ // eslint-disable-next-line no-console
19
+ console.error(data.toString());
20
+ });
8
21
  const stream = new ThreadParentMessageStream({
9
22
  thread: worker
10
23
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/services/node/NodeThreadExecutionService.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { ThreadParentMessageStream } from '@metamask/post-message-stream';\n// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { Worker } from 'worker_threads';\n\nimport type { Job } from '..';\nimport { AbstractExecutionService } from '..';\n\nexport class NodeThreadExecutionService extends AbstractExecutionService<Worker> {\n protected async initEnvStream(): Promise<{\n worker: Worker;\n stream: BasePostMessageStream;\n }> {\n const worker = new Worker(\n require.resolve(\n '@metamask/snaps-execution-environments/dist/browserify/node-thread/bundle.js',\n ),\n );\n const stream = new ThreadParentMessageStream({ thread: worker });\n return Promise.resolve({ worker, stream });\n }\n\n protected async terminateJob(jobWrapper: Job<Worker>): Promise<void> {\n await jobWrapper.worker.terminate();\n }\n}\n"],"names":["ThreadParentMessageStream","Worker","AbstractExecutionService","NodeThreadExecutionService","initEnvStream","worker","require","resolve","stream","thread","Promise","terminateJob","jobWrapper","terminate"],"mappings":"AACA,SAASA,yBAAyB,QAAQ,gCAAgC;AAC1E,wDAAwD;AACxD,SAASC,MAAM,QAAQ,iBAAiB;AAGxC,SAASC,wBAAwB,QAAQ,KAAK;AAE9C,OAAO,MAAMC,mCAAmCD;IAC9C,MAAgBE,gBAGb;QACD,MAAMC,SAAS,IAAIJ,OACjBK,QAAQC,OAAO,CACb;QAGJ,MAAMC,SAAS,IAAIR,0BAA0B;YAAES,QAAQJ;QAAO;QAC9D,OAAOK,QAAQH,OAAO,CAAC;YAAEF;YAAQG;QAAO;IAC1C;IAEA,MAAgBG,aAAaC,UAAuB,EAAiB;QACnE,MAAMA,WAAWP,MAAM,CAACQ,SAAS;IACnC;AACF"}
1
+ {"version":3,"sources":["../../../../src/services/node/NodeThreadExecutionService.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { ThreadParentMessageStream } from '@metamask/post-message-stream';\n// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { Worker } from 'worker_threads';\n\nimport type { Job } from '..';\nimport { AbstractExecutionService } from '..';\n\nexport class NodeThreadExecutionService extends AbstractExecutionService<Worker> {\n protected async initEnvStream(): Promise<{\n worker: Worker;\n stream: BasePostMessageStream;\n }> {\n const worker = new Worker(\n require.resolve(\n '@metamask/snaps-execution-environments/dist/browserify/node-thread/bundle.js',\n ),\n {\n stdout: true,\n stderr: true,\n },\n );\n\n // Capturing `stdout` and `stderr` from the worker prevents the worker from\n // writing to them directly, making it easier to capture them Jest.\n worker.stdout.on('data', (data) => {\n // eslint-disable-next-line no-console\n console.log(data.toString());\n });\n\n worker.stderr.on('data', (data) => {\n // eslint-disable-next-line no-console\n console.error(data.toString());\n });\n\n const stream = new ThreadParentMessageStream({ thread: worker });\n return Promise.resolve({ worker, stream });\n }\n\n protected async terminateJob(jobWrapper: Job<Worker>): Promise<void> {\n await jobWrapper.worker.terminate();\n }\n}\n"],"names":["ThreadParentMessageStream","Worker","AbstractExecutionService","NodeThreadExecutionService","initEnvStream","worker","require","resolve","stdout","stderr","on","data","console","log","toString","error","stream","thread","Promise","terminateJob","jobWrapper","terminate"],"mappings":"AACA,SAASA,yBAAyB,QAAQ,gCAAgC;AAC1E,wDAAwD;AACxD,SAASC,MAAM,QAAQ,iBAAiB;AAGxC,SAASC,wBAAwB,QAAQ,KAAK;AAE9C,OAAO,MAAMC,mCAAmCD;IAC9C,MAAgBE,gBAGb;QACD,MAAMC,SAAS,IAAIJ,OACjBK,QAAQC,OAAO,CACb,iFAEF;YACEC,QAAQ;YACRC,QAAQ;QACV;QAGF,2EAA2E;QAC3E,mEAAmE;QACnEJ,OAAOG,MAAM,CAACE,EAAE,CAAC,QAAQ,CAACC;YACxB,sCAAsC;YACtCC,QAAQC,GAAG,CAACF,KAAKG,QAAQ;QAC3B;QAEAT,OAAOI,MAAM,CAACC,EAAE,CAAC,QAAQ,CAACC;YACxB,sCAAsC;YACtCC,QAAQG,KAAK,CAACJ,KAAKG,QAAQ;QAC7B;QAEA,MAAME,SAAS,IAAIhB,0BAA0B;YAAEiB,QAAQZ;QAAO;QAC9D,OAAOa,QAAQX,OAAO,CAAC;YAAEF;YAAQW;QAAO;IAC1C;IAEA,MAAgBG,aAAaC,UAAuB,EAAiB;QACnE,MAAMA,WAAWf,MAAM,CAACgB,SAAS;IACnC;AACF"}