@metamask/snaps-controllers 8.1.0 → 8.2.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 (119) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/dist/{chunk-TO6ZEBIA.mjs → chunk-3A72M4GC.mjs} +2 -2
  3. package/dist/{chunk-ZVGZG25U.js → chunk-3AANDIXT.js} +3 -3
  4. package/dist/{chunk-X5MFC3VX.mjs → chunk-3OJFF5CK.mjs} +2 -2
  5. package/dist/{chunk-GTDDODNP.mjs → chunk-567BFPSL.mjs} +9 -2
  6. package/dist/chunk-567BFPSL.mjs.map +1 -0
  7. package/dist/{chunk-RS3WN6D3.mjs → chunk-7IJQGFT5.mjs} +2 -2
  8. package/dist/{chunk-U4DZUKNN.js → chunk-7TYZZFHZ.js} +16 -3
  9. package/dist/chunk-7TYZZFHZ.js.map +1 -0
  10. package/dist/{chunk-4DPX4O3T.js → chunk-CDTGUNSA.js} +9 -2
  11. package/dist/chunk-CDTGUNSA.js.map +1 -0
  12. package/dist/{chunk-74GN6MIJ.js → chunk-FPGAQ6MT.js} +3 -3
  13. package/dist/{chunk-Y7ZOSPEN.js → chunk-HK4OAMJT.js} +3 -3
  14. package/dist/{chunk-E5RRFMGF.js → chunk-HQ6HMINL.js} +3 -3
  15. package/dist/{chunk-FCRPOA4I.js → chunk-KH72WRHR.js} +3 -3
  16. package/dist/{chunk-QLEQIXCE.mjs → chunk-LRVK45HN.mjs} +2 -2
  17. package/dist/{chunk-2UAU42DO.js → chunk-PIQFC66N.js} +12 -8
  18. package/dist/chunk-PIQFC66N.js.map +1 -0
  19. package/dist/{chunk-PXKCSAT6.mjs → chunk-PMZXFAQI.mjs} +2 -2
  20. package/dist/{chunk-FCCGRGQS.mjs → chunk-QLFH3MC6.mjs} +2 -2
  21. package/dist/{chunk-QP5LV734.mjs → chunk-QLWR3M4Q.mjs} +9 -5
  22. package/dist/chunk-QLWR3M4Q.mjs.map +1 -0
  23. package/dist/{chunk-G4S6UXQ2.js → chunk-RW7AYHRG.js} +3 -3
  24. package/dist/{chunk-IPYO7FKR.mjs → chunk-RXZGXJOS.mjs} +48 -9
  25. package/dist/chunk-RXZGXJOS.mjs.map +1 -0
  26. package/dist/{chunk-SIW7ZXQF.js → chunk-S775IABY.js} +10 -10
  27. package/dist/{chunk-P5MRZOGW.mjs → chunk-SAAURQ5A.mjs} +2 -2
  28. package/dist/{chunk-YP37KUG5.js → chunk-TEBNQ3AE.js} +56 -17
  29. package/dist/chunk-TEBNQ3AE.js.map +1 -0
  30. package/dist/{chunk-ZQNBP53T.mjs → chunk-UJJCRV7W.mjs} +16 -3
  31. package/dist/chunk-UJJCRV7W.mjs.map +1 -0
  32. package/dist/{chunk-3Y4IJKZY.mjs → chunk-YUWYMNIX.mjs} +2 -2
  33. package/dist/{chunk-PAFO2KIN.js → chunk-ZRC46TUF.js} +3 -3
  34. package/dist/cronjob/CronjobController.js +9 -9
  35. package/dist/cronjob/CronjobController.mjs +9 -9
  36. package/dist/cronjob/index.js +9 -9
  37. package/dist/cronjob/index.mjs +9 -9
  38. package/dist/index.js +12 -10
  39. package/dist/index.mjs +11 -9
  40. package/dist/interface/SnapInterfaceController.js +3 -3
  41. package/dist/interface/SnapInterfaceController.mjs +2 -2
  42. package/dist/interface/index.js +3 -3
  43. package/dist/interface/index.mjs +2 -2
  44. package/dist/interface/utils.js +4 -2
  45. package/dist/interface/utils.mjs +5 -3
  46. package/dist/node.js +14 -12
  47. package/dist/node.mjs +13 -11
  48. package/dist/react-native.js +13 -11
  49. package/dist/react-native.mjs +12 -10
  50. package/dist/services/AbstractExecutionService.js +3 -3
  51. package/dist/services/AbstractExecutionService.mjs +2 -2
  52. package/dist/services/browser.js +8 -8
  53. package/dist/services/browser.mjs +7 -7
  54. package/dist/services/iframe/IframeExecutionService.js +4 -4
  55. package/dist/services/iframe/IframeExecutionService.mjs +3 -3
  56. package/dist/services/iframe/index.js +4 -4
  57. package/dist/services/iframe/index.mjs +3 -3
  58. package/dist/services/index.js +7 -7
  59. package/dist/services/index.mjs +6 -6
  60. package/dist/services/node-js/NodeProcessExecutionService.js +8 -8
  61. package/dist/services/node-js/NodeProcessExecutionService.mjs +7 -7
  62. package/dist/services/node-js/NodeThreadExecutionService.js +8 -8
  63. package/dist/services/node-js/NodeThreadExecutionService.mjs +7 -7
  64. package/dist/services/node-js/index.js +9 -9
  65. package/dist/services/node-js/index.mjs +8 -8
  66. package/dist/services/node.js +9 -9
  67. package/dist/services/node.mjs +8 -8
  68. package/dist/services/offscreen/OffscreenExecutionService.js +5 -5
  69. package/dist/services/offscreen/OffscreenExecutionService.mjs +4 -4
  70. package/dist/services/offscreen/index.js +5 -5
  71. package/dist/services/offscreen/index.mjs +4 -4
  72. package/dist/services/proxy/ProxyExecutionService.js +4 -4
  73. package/dist/services/proxy/ProxyExecutionService.mjs +3 -3
  74. package/dist/services/react-native.js +8 -8
  75. package/dist/services/react-native.mjs +7 -7
  76. package/dist/services/webview/WebViewExecutionService.js +5 -5
  77. package/dist/services/webview/WebViewExecutionService.mjs +4 -4
  78. package/dist/services/webview/index.js +5 -5
  79. package/dist/services/webview/index.mjs +4 -4
  80. package/dist/services/webworker/WebWorkerExecutionService.js +4 -4
  81. package/dist/services/webworker/WebWorkerExecutionService.mjs +3 -3
  82. package/dist/services/webworker/index.js +4 -4
  83. package/dist/services/webworker/index.mjs +3 -3
  84. package/dist/snaps/SnapController.js +3 -3
  85. package/dist/snaps/SnapController.mjs +2 -2
  86. package/dist/snaps/index.js +3 -3
  87. package/dist/snaps/index.mjs +2 -2
  88. package/dist/tsconfig.build.tsbuildinfo +1 -1
  89. package/dist/types/interface/SnapInterfaceController.d.ts +4 -2
  90. package/dist/types/interface/utils.d.ts +8 -1
  91. package/dist/types/snaps/SnapController.d.ts +11 -2
  92. package/dist/types/utils.d.ts +13 -0
  93. package/dist/utils.js +4 -2
  94. package/dist/utils.mjs +3 -1
  95. package/package.json +7 -7
  96. package/dist/chunk-2UAU42DO.js.map +0 -1
  97. package/dist/chunk-4DPX4O3T.js.map +0 -1
  98. package/dist/chunk-GTDDODNP.mjs.map +0 -1
  99. package/dist/chunk-IPYO7FKR.mjs.map +0 -1
  100. package/dist/chunk-QP5LV734.mjs.map +0 -1
  101. package/dist/chunk-U4DZUKNN.js.map +0 -1
  102. package/dist/chunk-YP37KUG5.js.map +0 -1
  103. package/dist/chunk-ZQNBP53T.mjs.map +0 -1
  104. /package/dist/{chunk-TO6ZEBIA.mjs.map → chunk-3A72M4GC.mjs.map} +0 -0
  105. /package/dist/{chunk-ZVGZG25U.js.map → chunk-3AANDIXT.js.map} +0 -0
  106. /package/dist/{chunk-X5MFC3VX.mjs.map → chunk-3OJFF5CK.mjs.map} +0 -0
  107. /package/dist/{chunk-RS3WN6D3.mjs.map → chunk-7IJQGFT5.mjs.map} +0 -0
  108. /package/dist/{chunk-74GN6MIJ.js.map → chunk-FPGAQ6MT.js.map} +0 -0
  109. /package/dist/{chunk-Y7ZOSPEN.js.map → chunk-HK4OAMJT.js.map} +0 -0
  110. /package/dist/{chunk-E5RRFMGF.js.map → chunk-HQ6HMINL.js.map} +0 -0
  111. /package/dist/{chunk-FCRPOA4I.js.map → chunk-KH72WRHR.js.map} +0 -0
  112. /package/dist/{chunk-QLEQIXCE.mjs.map → chunk-LRVK45HN.mjs.map} +0 -0
  113. /package/dist/{chunk-PXKCSAT6.mjs.map → chunk-PMZXFAQI.mjs.map} +0 -0
  114. /package/dist/{chunk-FCCGRGQS.mjs.map → chunk-QLFH3MC6.mjs.map} +0 -0
  115. /package/dist/{chunk-G4S6UXQ2.js.map → chunk-RW7AYHRG.js.map} +0 -0
  116. /package/dist/{chunk-SIW7ZXQF.js.map → chunk-S775IABY.js.map} +0 -0
  117. /package/dist/{chunk-P5MRZOGW.mjs.map → chunk-SAAURQ5A.mjs.map} +0 -0
  118. /package/dist/{chunk-3Y4IJKZY.mjs.map → chunk-YUWYMNIX.mjs.map} +0 -0
  119. /package/dist/{chunk-PAFO2KIN.js.map → chunk-ZRC46TUF.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import type { RestrictedControllerMessenger } from '@metamask/base-controller';
2
2
  import { BaseController } from '@metamask/base-controller';
3
3
  import type { MaybeUpdateState, TestOrigin } from '@metamask/phishing-controller';
4
- import type { InterfaceState, SnapId, ComponentOrElement } from '@metamask/snaps-sdk';
4
+ import type { InterfaceState, SnapId, ComponentOrElement, InterfaceContext } from '@metamask/snaps-sdk';
5
5
  import type { JSXElement } from '@metamask/snaps-sdk/jsx';
6
6
  declare const controllerName = "SnapInterfaceController";
7
7
  export declare type CreateInterface = {
@@ -31,6 +31,7 @@ export declare type StoredInterface = {
31
31
  snapId: SnapId;
32
32
  content: JSXElement;
33
33
  state: InterfaceState;
34
+ context: InterfaceContext | null;
34
35
  };
35
36
  export declare type SnapInterfaceControllerState = {
36
37
  interfaces: Record<string, StoredInterface>;
@@ -50,9 +51,10 @@ export declare class SnapInterfaceController extends BaseController<typeof contr
50
51
  *
51
52
  * @param snapId - The snap id that created the interface.
52
53
  * @param content - The interface content.
54
+ * @param context - An optional interface context object.
53
55
  * @returns The newly interface id.
54
56
  */
55
- createInterface(snapId: SnapId, content: ComponentOrElement): Promise<string>;
57
+ createInterface(snapId: SnapId, content: ComponentOrElement, context?: InterfaceContext): Promise<string>;
56
58
  /**
57
59
  * Get the data of a given interface id.
58
60
  *
@@ -1,4 +1,4 @@
1
- import type { InterfaceState, ComponentOrElement } from '@metamask/snaps-sdk';
1
+ import type { InterfaceState, ComponentOrElement, InterfaceContext } from '@metamask/snaps-sdk';
2
2
  import type { JSXElement } from '@metamask/snaps-sdk/jsx';
3
3
  /**
4
4
  * Get a JSX element from a component or JSX element. If the component is a
@@ -25,3 +25,10 @@ export declare function assertNameIsUnique(state: InterfaceState, name: string):
25
25
  * @returns The interface state of the passed component.
26
26
  */
27
27
  export declare function constructState(oldState: InterfaceState, component: JSXElement, newState?: InterfaceState): InterfaceState;
28
+ /**
29
+ * Validate a JSON blob to be used as the interface context.
30
+ *
31
+ * @param context - The JSON blob.
32
+ * @throws If the JSON blob is too large.
33
+ */
34
+ export declare function validateInterfaceContext(context?: InterfaceContext): void;
@@ -295,6 +295,9 @@ declare type FeatureFlags = {
295
295
  requireAllowlist?: boolean;
296
296
  allowLocalSnaps?: boolean;
297
297
  };
298
+ declare type DynamicFeatureFlags = {
299
+ disableSnaps?: boolean;
300
+ };
298
301
  declare type SnapControllerArgs = {
299
302
  /**
300
303
  * A teardown function that allows the host to clean up its instrumentation
@@ -358,7 +361,7 @@ declare type SnapControllerArgs = {
358
361
  /**
359
362
  * A list of snaps to be preinstalled into the SnapController state on initialization.
360
363
  */
361
- preinstalledSnaps?: PreinstalledSnap[];
364
+ preinstalledSnaps?: PreinstalledSnap[] | null;
362
365
  /**
363
366
  * A utility object containing functions required for state encryption.
364
367
  */
@@ -369,11 +372,17 @@ declare type SnapControllerArgs = {
369
372
  * @returns The mnemonic as bytes.
370
373
  */
371
374
  getMnemonic: () => Promise<Uint8Array>;
375
+ /**
376
+ * A hook to get dynamic feature flags at runtime.
377
+ *
378
+ * @returns The feature flags.
379
+ */
380
+ getFeatureFlags: () => DynamicFeatureFlags;
372
381
  };
373
382
  export declare class SnapController extends BaseController<string, SnapControllerState, SnapControllerMessenger> {
374
383
  #private;
375
384
  private readonly maxRequestTime;
376
- constructor({ closeAllConnections, messenger, state, dynamicPermissions, environmentEndowmentPermissions, excludedPermissions, idleTimeCheckInterval, maxIdleTime, maxRequestTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, preinstalledSnaps, encryptor, getMnemonic, }: SnapControllerArgs);
385
+ constructor({ closeAllConnections, messenger, state, dynamicPermissions, environmentEndowmentPermissions, excludedPermissions, idleTimeCheckInterval, maxIdleTime, maxRequestTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, preinstalledSnaps, encryptor, getMnemonic, getFeatureFlags, }: SnapControllerArgs);
377
386
  /**
378
387
  * Checks all installed snaps against the block list and
379
388
  * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}
@@ -1,5 +1,6 @@
1
1
  import type { PermissionConstraint } from '@metamask/permission-controller';
2
2
  import type { SnapId } from '@metamask/snaps-sdk';
3
+ import type { Json } from '@metamask/utils';
3
4
  import type { SnapLocation } from './snaps';
4
5
  import { Timer } from './snaps/Timer';
5
6
  /**
@@ -241,4 +242,16 @@ export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promi
241
242
  }>;
242
243
  }>[];
243
244
  }>;
245
+ /**
246
+ * Calculate change of initialConnections.
247
+ *
248
+ * @param oldConnectionsSet - Previously approved connections.
249
+ * @param desiredConnectionsSet - New connections.
250
+ * @returns Object containing newConnections, unusedConnections and approvedConnections.
251
+ */
252
+ export declare function calculateConnectionsChange(oldConnectionsSet: Record<string, Json>, desiredConnectionsSet: Record<string, Json>): {
253
+ newConnections: Record<string, Json>;
254
+ unusedConnections: Record<string, Json>;
255
+ approvedConnections: Record<string, Json>;
256
+ };
244
257
  export {};
package/dist/utils.js CHANGED
@@ -7,7 +7,8 @@
7
7
 
8
8
 
9
9
 
10
- var _chunk4DPX4O3Tjs = require('./chunk-4DPX4O3T.js');
10
+
11
+ var _chunkCDTGUNSAjs = require('./chunk-CDTGUNSA.js');
11
12
  require('./chunk-BOFPNIRX.js');
12
13
  require('./chunk-EXN2TFDJ.js');
13
14
 
@@ -19,5 +20,6 @@ require('./chunk-EXN2TFDJ.js');
19
20
 
20
21
 
21
22
 
22
- exports.delay = _chunk4DPX4O3Tjs.delay; exports.delayWithTimer = _chunk4DPX4O3Tjs.delayWithTimer; exports.fetchSnap = _chunk4DPX4O3Tjs.fetchSnap; exports.getSnapFiles = _chunk4DPX4O3Tjs.getSnapFiles; exports.hasTimedOut = _chunk4DPX4O3Tjs.hasTimedOut; exports.permissionsDiff = _chunk4DPX4O3Tjs.permissionsDiff; exports.setDiff = _chunk4DPX4O3Tjs.setDiff; exports.withTimeout = _chunk4DPX4O3Tjs.withTimeout;
23
+
24
+ exports.calculateConnectionsChange = _chunkCDTGUNSAjs.calculateConnectionsChange; exports.delay = _chunkCDTGUNSAjs.delay; exports.delayWithTimer = _chunkCDTGUNSAjs.delayWithTimer; exports.fetchSnap = _chunkCDTGUNSAjs.fetchSnap; exports.getSnapFiles = _chunkCDTGUNSAjs.getSnapFiles; exports.hasTimedOut = _chunkCDTGUNSAjs.hasTimedOut; exports.permissionsDiff = _chunkCDTGUNSAjs.permissionsDiff; exports.setDiff = _chunkCDTGUNSAjs.setDiff; exports.withTimeout = _chunkCDTGUNSAjs.withTimeout;
23
25
  //# sourceMappingURL=utils.js.map
package/dist/utils.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ calculateConnectionsChange,
2
3
  delay,
3
4
  delayWithTimer,
4
5
  fetchSnap,
@@ -7,10 +8,11 @@ import {
7
8
  permissionsDiff,
8
9
  setDiff,
9
10
  withTimeout
10
- } from "./chunk-GTDDODNP.mjs";
11
+ } from "./chunk-567BFPSL.mjs";
11
12
  import "./chunk-XO7KDFBY.mjs";
12
13
  import "./chunk-YRZVIDCF.mjs";
13
14
  export {
15
+ calculateConnectionsChange,
14
16
  delay,
15
17
  delayWithTimer,
16
18
  fetchSnap,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-controllers",
3
- "version": "8.1.0",
3
+ "version": "8.2.0",
4
4
  "description": "Controllers for MetaMask Snaps.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -58,12 +58,12 @@
58
58
  "@metamask/object-multiplex": "^2.0.0",
59
59
  "@metamask/permission-controller": "^9.0.2",
60
60
  "@metamask/phishing-controller": "^9.0.1",
61
- "@metamask/post-message-stream": "^8.0.0",
61
+ "@metamask/post-message-stream": "^8.1.0",
62
62
  "@metamask/rpc-errors": "^6.2.1",
63
63
  "@metamask/snaps-registry": "^3.1.0",
64
- "@metamask/snaps-rpc-methods": "^8.1.0",
65
- "@metamask/snaps-sdk": "^4.1.0",
66
- "@metamask/snaps-utils": "^7.3.0",
64
+ "@metamask/snaps-rpc-methods": "^9.1.0",
65
+ "@metamask/snaps-sdk": "^4.3.0",
66
+ "@metamask/snaps-utils": "^7.4.0",
67
67
  "@metamask/utils": "^8.3.0",
68
68
  "@xstate/fsm": "^2.0.0",
69
69
  "browserify-zlib": "^0.2.0",
@@ -79,7 +79,7 @@
79
79
  "devDependencies": {
80
80
  "@esbuild-plugins/node-globals-polyfill": "^0.2.3",
81
81
  "@esbuild-plugins/node-modules-polyfill": "^0.2.2",
82
- "@lavamoat/allow-scripts": "^3.0.3",
82
+ "@lavamoat/allow-scripts": "^3.0.4",
83
83
  "@metamask/auto-changelog": "^3.4.4",
84
84
  "@metamask/browser-passworder": "^5.0.0",
85
85
  "@metamask/eslint-config": "^12.1.0",
@@ -136,7 +136,7 @@
136
136
  "webdriverio": "^8.19.0"
137
137
  },
138
138
  "peerDependencies": {
139
- "@metamask/snaps-execution-environments": "^6.1.0"
139
+ "@metamask/snaps-execution-environments": "^6.2.0"
140
140
  },
141
141
  "peerDependenciesMeta": {
142
142
  "@metamask/snaps-execution-environments": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":";;;;;;;;;;AACA,SAAS,sBAAsB;AAW/B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc;AACvB,SAAS,cAAc;AAIvB,IAAM,sBAAsB;AAE5B,IAAM,iBAAiB;AApBvB;AAoFO,IAAM,0BAAN,cAAsC,eAI3C;AAAA,EACA,YAAY,EAAE,WAAW,MAAM,GAAgC;AAC7D,UAAM;AAAA,MACJ;AAAA,MACA,UAAU;AAAA,QACR,YAAY,EAAE,SAAS,OAAO,WAAW,MAAM;AAAA,MACjD;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,YAAY,CAAC,GAAG,GAAG,MAAM;AAAA,IACpC,CAAC;AASH;AAAA;AAAA;AAAA;AAAA;AAyHA;AAAA;AAAA;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AO;AAAA,EACnE;AAEA,QAAM,sBAAK,0DAAL;AACN,mBAAiB,SAAS,sBAAK,0CAAmB,KAAK,IAAI,CAAC;AAC9D","sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n MaybeUpdateState,\n TestOrigin,\n} from '@metamask/phishing-controller';\nimport type {\n InterfaceState,\n SnapId,\n ComponentOrElement,\n} from '@metamask/snaps-sdk';\nimport type { JSXElement } from '@metamask/snaps-sdk/jsx';\nimport { getJsonSizeUnsafe, validateJsxLinks } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport { constructState, getJsxInterface } from './utils';\n\nconst MAX_UI_CONTENT_SIZE = 10_000_000; // 10 mb\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | MaybeUpdateState;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState;\n\nexport type SnapInterfaceControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n never,\n SnapInterfaceControllerAllowedActions['type'],\n never\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: JSXElement;\n state: InterfaceState;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @returns The newly interface id.\n */\n async createInterface(snapId: SnapId, content: ComponentOrElement) {\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n\n const id = nanoid();\n const componentState = constructState({}, element);\n\n this.update((draftState) => {\n // @ts-expect-error - TS2589: Type instantiation is excessively deep and\n // possibly infinite.\n draftState.interfaces[id] = {\n snapId,\n content: element,\n state: componentState,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n */\n async updateInterface(\n snapId: SnapId,\n id: string,\n content: ComponentOrElement,\n ) {\n this.#validateArgs(snapId, id);\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n\n const oldState = this.state.interfaces[id].state;\n const newState = constructState(oldState, element);\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = element;\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Trigger a Phishing list update if needed.\n */\n async #triggerPhishingListUpdate() {\n await this.messagingSystem.call('PhishingController:maybeUpdateState');\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * @param element - The JSX element to verify.\n */\n async #validateContent(element: JSXElement) {\n // We assume the validity of this JSON to be validated by the caller.\n // E.g., in the RPC method implementation.\n const size = getJsonSizeUnsafe(element);\n assert(\n size <= MAX_UI_CONTENT_SIZE,\n `A Snap UI may not be larger than ${MAX_UI_CONTENT_SIZE / 1000000} MB.`,\n );\n\n await this.#triggerPhishingListUpdate();\n validateJsxLinks(element, this.#checkPhishingList.bind(this));\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils.ts"],"names":[],"mappings":";;;;;AAEA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,eAAe;AAmBf,SAAS,QAGd,SAAkB,SAA0C;AAC5D,SAAO,OAAO,QAAQ,OAAO,EAAE;AAAA,IAC7B,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,UAAI,EAAE,OAAO,UAAU;AACrB,YAAI,GAAG,IAAI;AAAA,MACb;AACA,aAAO;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EACH;AACF;AAYO,SAAS,gBAId,cACA,cACkC;AAClC,SAAO,OAAO,QAAQ,YAAY,EAAE,OAElC,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACvB,UAAM,aAAa,OAAO;AAC1B,QACE,CAAC,cACA,cACC,CAAC,UAAU,MAAM,WAAW,CAAC,GAAG,aAAa,GAAG,EAAE,WAAW,CAAC,CAAC,GACjE;AACA,UAAI,GAAG,IAAI;AAAA,IACb;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AACP;AAUO,SAAS,MACd,IACA,QAC0C;AAC1C,SAAO,eAAe,IAAI,MAAM,EAAE,GAAG,MAAM;AAC7C;AAUO,SAAS,eACd,OACA,QAC0C;AAC1C,MAAI;AACJ,QAAM,UAAe,IAAI,QAAgB,CAAC,SAAc,WAAW;AACjE,UAAM,MAAM,MAAM;AAChB,iBAAW,SAAY,QAAQ,IAAI,QAAQ,MAAM;AAAA,IACnD,CAAC;AACD,iBAAa;AAAA,EACf,CAAC;AAED,UAAQ,SAAS,MAAM;AACrB,QAAI,MAAM,WAAW,YAAY;AAC/B,YAAM,OAAO;AACb,iBAAW,IAAI,MA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,IACrB;AAEA,UAAM,oBAAoB,KAAK;AAE/B,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,yBAAyB,MAAM,MAAM,gBAAgB,KAAK,CAAC;AAAA,IAC7D;AAAA,EACF;AACF","sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n encodeBase64,\n getValidatedLocalizationFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport deepEqual from 'fast-deep-equal';\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 * Calculate a difference between two permissions objects.\n *\n * Similar to `setDiff` except for one additional condition:\n * Permissions in B should be removed from A if they exist in both and have differing caveats.\n *\n * @param permissionsA - An object containing one or more partial permissions.\n * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.\n * @returns The permissions set A without properties from B.\n */\nexport function permissionsDiff<\n PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n>(\n permissionsA: PermissionsA,\n permissionsB: PermissionsB,\n): Diff<PermissionsA, PermissionsB> {\n return Object.entries(permissionsA).reduce<\n Record<string, Pick<PermissionConstraint, 'caveats'>>\n >((acc, [key, value]) => {\n const isIncluded = key in permissionsB;\n if (\n !isIncluded ||\n (isIncluded &&\n !deepEqual(value.caveats ?? [], permissionsB[key].caveats ?? []))\n ) {\n acc[key] = value;\n }\n return acc;\n }, {}) as Diff<PermissionsA, PermissionsB>;\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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n encodeBase64,\n getValidatedLocalizationFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport deepEqual from 'fast-deep-equal';\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 * Calculate a difference between two permissions objects.\n *\n * Similar to `setDiff` except for one additional condition:\n * Permissions in B should be removed from A if they exist in both and have differing caveats.\n *\n * @param permissionsA - An object containing one or more partial permissions.\n * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.\n * @returns The permissions set A without properties from B.\n */\nexport function permissionsDiff<\n PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n>(\n permissionsA: PermissionsA,\n permissionsB: PermissionsB,\n): Diff<PermissionsA, PermissionsB> {\n return Object.entries(permissionsA).reduce<\n Record<string, Pick<PermissionConstraint, 'caveats'>>\n >((acc, [key, value]) => {\n const isIncluded = key in permissionsB;\n if (\n !isIncluded ||\n (isIncluded &&\n !deepEqual(value.caveats ?? [], permissionsB[key].caveats ?? []))\n ) {\n acc[key] = value;\n }\n return acc;\n }, {}) as Diff<PermissionsA, PermissionsB>;\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"],"mappings":";;;;;AAEA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,eAAe;AAmBf,SAAS,QAGd,SAAkB,SAA0C;AAC5D,SAAO,OAAO,QAAQ,OAAO,EAAE;AAAA,IAC7B,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,UAAI,EAAE,OAAO,UAAU;AACrB,YAAI,GAAG,IAAI;AAAA,MACb;AACA,aAAO;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EACH;AACF;AAYO,SAAS,gBAId,cACA,cACkC;AAClC,SAAO,OAAO,QAAQ,YAAY,EAAE,OAElC,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACvB,UAAM,aAAa,OAAO;AAC1B,QACE,CAAC,cACA,cACC,CAAC,UAAU,MAAM,WAAW,CAAC,GAAG,aAAa,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