@metamask/snaps-controllers 7.0.1 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/dist/{chunk-XE5IWVNV.js → chunk-4DPX4O3T.js} +17 -6
  3. package/dist/chunk-4DPX4O3T.js.map +1 -0
  4. package/dist/{chunk-BJOQRBH2.mjs → chunk-6QZJC5I2.mjs} +2 -2
  5. package/dist/chunk-6QZJC5I2.mjs.map +1 -0
  6. package/dist/{chunk-2KCUVQFS.mjs → chunk-7DLODFQK.mjs} +2 -2
  7. package/dist/{chunk-Z6SOB3SY.js → chunk-ABKWEVW4.js} +3 -3
  8. package/dist/chunk-ABKWEVW4.js.map +1 -0
  9. package/dist/{chunk-NOLPMHXS.js → chunk-BOFPNIRX.js} +21 -3
  10. package/dist/chunk-BOFPNIRX.js.map +1 -0
  11. package/dist/{chunk-WQYMF7QP.js → chunk-CXT7XBMN.js} +3 -3
  12. package/dist/{chunk-63GNCRER.js → chunk-DQLRXCST.js} +4 -4
  13. package/dist/chunk-DQLRXCST.js.map +1 -0
  14. package/dist/{chunk-YVNRYLOC.js → chunk-DVTMXCTZ.js} +3 -3
  15. package/dist/{chunk-3ZC4LB7T.js → chunk-FOT4VRMQ.js} +3 -3
  16. package/dist/chunk-FOT4VRMQ.js.map +1 -0
  17. package/dist/{chunk-MYWDTEX2.js → chunk-GRBWVPLF.js} +4 -4
  18. package/dist/{chunk-36YC4Z3T.mjs → chunk-GTDDODNP.mjs} +13 -2
  19. package/dist/chunk-GTDDODNP.mjs.map +1 -0
  20. package/dist/{chunk-Q2ON6SMV.js → chunk-GZ3RVSUA.js} +5 -6
  21. package/dist/chunk-GZ3RVSUA.js.map +1 -0
  22. package/dist/{chunk-5MVIYRYL.mjs → chunk-HBNET6MY.mjs} +40 -26
  23. package/dist/chunk-HBNET6MY.mjs.map +1 -0
  24. package/dist/{chunk-SCERVW3B.mjs → chunk-HT7X5NPH.mjs} +2 -2
  25. package/dist/chunk-HT7X5NPH.mjs.map +1 -0
  26. package/dist/{chunk-WVGK5B5P.mjs → chunk-IRVUYBSV.mjs} +70 -41
  27. package/dist/chunk-IRVUYBSV.mjs.map +1 -0
  28. package/dist/{chunk-CJN25EXL.js → chunk-JMP6XYRL.js} +46 -32
  29. package/dist/chunk-JMP6XYRL.js.map +1 -0
  30. package/dist/{chunk-Y5KX5ICF.mjs → chunk-JQLPWQIR.mjs} +3 -3
  31. package/dist/chunk-JQLPWQIR.mjs.map +1 -0
  32. package/dist/{chunk-54TYYPAN.js → chunk-JZCXZEFV.js} +72 -43
  33. package/dist/chunk-JZCXZEFV.js.map +1 -0
  34. package/dist/{chunk-NSLYI2LS.js → chunk-M2NMZ4ER.js} +3 -3
  35. package/dist/chunk-M2NMZ4ER.js.map +1 -0
  36. package/dist/{chunk-Q4I5QTVC.mjs → chunk-MB23XAVD.mjs} +2 -2
  37. package/dist/chunk-MB23XAVD.mjs.map +1 -0
  38. package/dist/{chunk-75VM3O4K.mjs → chunk-MD2JCQBG.mjs} +2 -2
  39. package/dist/{chunk-25LS4KZK.mjs → chunk-PGQXTXAQ.mjs} +3 -3
  40. package/dist/chunk-PGQXTXAQ.mjs.map +1 -0
  41. package/dist/{chunk-N7WIJNHY.js → chunk-PRJADV7W.js} +4 -4
  42. package/dist/chunk-PRJADV7W.js.map +1 -0
  43. package/dist/{chunk-K276CM3B.mjs → chunk-SD6JM5ZU.mjs} +6 -7
  44. package/dist/chunk-SD6JM5ZU.mjs.map +1 -0
  45. package/dist/{chunk-VOZOZKRC.mjs → chunk-XO7KDFBY.mjs} +21 -3
  46. package/dist/chunk-XO7KDFBY.mjs.map +1 -0
  47. package/dist/{chunk-ZETJVFUS.mjs → chunk-XSFI32LB.mjs} +2 -2
  48. package/dist/cronjob/CronjobController.js +11 -11
  49. package/dist/cronjob/CronjobController.mjs +10 -10
  50. package/dist/cronjob/index.js +11 -11
  51. package/dist/cronjob/index.mjs +10 -10
  52. package/dist/index.js +13 -11
  53. package/dist/index.mjs +12 -10
  54. package/dist/interface/SnapInterfaceController.js +2 -2
  55. package/dist/interface/SnapInterfaceController.mjs +1 -1
  56. package/dist/interface/index.js +2 -2
  57. package/dist/interface/index.mjs +1 -1
  58. package/dist/node.js +15 -13
  59. package/dist/node.mjs +14 -12
  60. package/dist/react-native.js +14 -12
  61. package/dist/react-native.mjs +13 -11
  62. package/dist/services/AbstractExecutionService.js +4 -4
  63. package/dist/services/AbstractExecutionService.mjs +3 -3
  64. package/dist/services/browser.js +9 -9
  65. package/dist/services/browser.mjs +8 -8
  66. package/dist/services/iframe/IframeExecutionService.js +5 -5
  67. package/dist/services/iframe/IframeExecutionService.mjs +4 -4
  68. package/dist/services/iframe/index.js +5 -5
  69. package/dist/services/iframe/index.mjs +4 -4
  70. package/dist/services/index.js +8 -8
  71. package/dist/services/index.mjs +7 -7
  72. package/dist/services/node-js/NodeProcessExecutionService.js +9 -9
  73. package/dist/services/node-js/NodeProcessExecutionService.mjs +8 -8
  74. package/dist/services/node-js/NodeThreadExecutionService.js +9 -9
  75. package/dist/services/node-js/NodeThreadExecutionService.mjs +8 -8
  76. package/dist/services/node-js/index.js +10 -10
  77. package/dist/services/node-js/index.mjs +9 -9
  78. package/dist/services/node.js +10 -10
  79. package/dist/services/node.mjs +9 -9
  80. package/dist/services/offscreen/OffscreenExecutionService.js +6 -6
  81. package/dist/services/offscreen/OffscreenExecutionService.mjs +5 -5
  82. package/dist/services/offscreen/index.js +6 -6
  83. package/dist/services/offscreen/index.mjs +5 -5
  84. package/dist/services/proxy/ProxyExecutionService.js +5 -5
  85. package/dist/services/proxy/ProxyExecutionService.mjs +4 -4
  86. package/dist/services/react-native.js +9 -9
  87. package/dist/services/react-native.mjs +8 -8
  88. package/dist/services/webview/WebViewExecutionService.js +6 -6
  89. package/dist/services/webview/WebViewExecutionService.mjs +5 -5
  90. package/dist/services/webview/index.js +6 -6
  91. package/dist/services/webview/index.mjs +5 -5
  92. package/dist/services/webworker/WebWorkerExecutionService.js +5 -5
  93. package/dist/services/webworker/WebWorkerExecutionService.mjs +4 -4
  94. package/dist/services/webworker/index.js +5 -5
  95. package/dist/services/webworker/index.mjs +4 -4
  96. package/dist/snaps/SnapController.js +4 -4
  97. package/dist/snaps/SnapController.mjs +3 -3
  98. package/dist/snaps/Timer.js +2 -2
  99. package/dist/snaps/Timer.mjs +1 -1
  100. package/dist/snaps/index.js +4 -4
  101. package/dist/snaps/index.mjs +3 -3
  102. package/dist/tsconfig.build.tsbuildinfo +1 -1
  103. package/dist/types/services/AbstractExecutionService.d.ts +17 -12
  104. package/dist/types/services/ExecutionService.d.ts +1 -1
  105. package/dist/types/services/iframe/IframeExecutionService.d.ts +2 -2
  106. package/dist/types/services/node-js/NodeProcessExecutionService.d.ts +2 -2
  107. package/dist/types/services/node-js/NodeThreadExecutionService.d.ts +2 -2
  108. package/dist/types/services/proxy/ProxyExecutionService.d.ts +2 -2
  109. package/dist/types/services/webworker/WebWorkerExecutionService.d.ts +2 -2
  110. package/dist/types/snaps/SnapController.d.ts +5 -6
  111. package/dist/types/snaps/Timer.d.ts +7 -0
  112. package/dist/types/utils.d.ts +12 -0
  113. package/dist/utils.js +5 -3
  114. package/dist/utils.mjs +4 -2
  115. package/package.json +5 -4
  116. package/dist/chunk-25LS4KZK.mjs.map +0 -1
  117. package/dist/chunk-36YC4Z3T.mjs.map +0 -1
  118. package/dist/chunk-3ZC4LB7T.js.map +0 -1
  119. package/dist/chunk-54TYYPAN.js.map +0 -1
  120. package/dist/chunk-5MVIYRYL.mjs.map +0 -1
  121. package/dist/chunk-63GNCRER.js.map +0 -1
  122. package/dist/chunk-BJOQRBH2.mjs.map +0 -1
  123. package/dist/chunk-CJN25EXL.js.map +0 -1
  124. package/dist/chunk-K276CM3B.mjs.map +0 -1
  125. package/dist/chunk-N7WIJNHY.js.map +0 -1
  126. package/dist/chunk-NOLPMHXS.js.map +0 -1
  127. package/dist/chunk-NSLYI2LS.js.map +0 -1
  128. package/dist/chunk-Q2ON6SMV.js.map +0 -1
  129. package/dist/chunk-Q4I5QTVC.mjs.map +0 -1
  130. package/dist/chunk-SCERVW3B.mjs.map +0 -1
  131. package/dist/chunk-VOZOZKRC.mjs.map +0 -1
  132. package/dist/chunk-WVGK5B5P.mjs.map +0 -1
  133. package/dist/chunk-XE5IWVNV.js.map +0 -1
  134. package/dist/chunk-Y5KX5ICF.mjs.map +0 -1
  135. package/dist/chunk-Z6SOB3SY.js.map +0 -1
  136. /package/dist/{chunk-2KCUVQFS.mjs.map → chunk-7DLODFQK.mjs.map} +0 -0
  137. /package/dist/{chunk-WQYMF7QP.js.map → chunk-CXT7XBMN.js.map} +0 -0
  138. /package/dist/{chunk-YVNRYLOC.js.map → chunk-DVTMXCTZ.js.map} +0 -0
  139. /package/dist/{chunk-MYWDTEX2.js.map → chunk-GRBWVPLF.js.map} +0 -0
  140. /package/dist/{chunk-75VM3O4K.mjs.map → chunk-MD2JCQBG.mjs.map} +0 -0
  141. /package/dist/{chunk-ZETJVFUS.mjs.map → chunk-XSFI32LB.mjs.map} +0 -0
@@ -4,11 +4,13 @@ import ObjectMultiplex from '@metamask/object-multiplex';
4
4
  import type { BasePostMessageStream } from '@metamask/post-message-stream';
5
5
  import type { SnapRpcHookArgs } from '@metamask/snaps-utils';
6
6
  import type { Duplex } from 'readable-stream';
7
+ import { Timer } from '../snaps/Timer';
7
8
  import type { ExecutionService, ExecutionServiceMessenger, SnapExecutionData } from './ExecutionService';
8
9
  export declare type SetupSnapProvider = (snapId: string, stream: Duplex) => void;
9
10
  export declare type ExecutionServiceArgs = {
10
11
  setupSnapProvider: SetupSnapProvider;
11
12
  messenger: ExecutionServiceMessenger;
13
+ initTimeout?: number;
12
14
  pingTimeout?: number;
13
15
  terminationTimeout?: number;
14
16
  };
@@ -23,11 +25,12 @@ export declare type Job<WorkerType> = {
23
25
  rpcEngine: JsonRpcEngine;
24
26
  worker: WorkerType;
25
27
  };
28
+ export declare type TerminateJobArgs<WorkerType> = Partial<Job<WorkerType>> & Pick<Job<WorkerType>, 'id'>;
26
29
  export declare abstract class AbstractExecutionService<WorkerType> implements ExecutionService {
27
30
  #private;
28
31
  protected jobs: Map<string, Job<WorkerType>>;
29
32
  private readonly setupSnapProvider;
30
- constructor({ setupSnapProvider, messenger, pingTimeout, terminationTimeout, }: ExecutionServiceArgs);
33
+ constructor({ setupSnapProvider, messenger, initTimeout, pingTimeout, terminationTimeout, }: ExecutionServiceArgs);
31
34
  /**
32
35
  * Constructor helper for registering the controller's messaging system
33
36
  * actions.
@@ -40,7 +43,7 @@ export declare abstract class AbstractExecutionService<WorkerType> implements Ex
40
43
  *
41
44
  * @param job - The object corresponding to the job to be terminated.
42
45
  */
43
- protected abstract terminateJob(job: Job<WorkerType>): void;
46
+ protected abstract terminateJob(job: TerminateJobArgs<WorkerType>): void;
44
47
  /**
45
48
  * Terminates the job with the specified ID and deletes all its associated
46
49
  * data. Any subsequent messages targeting the job will fail with an error.
@@ -53,20 +56,21 @@ export declare abstract class AbstractExecutionService<WorkerType> implements Ex
53
56
  /**
54
57
  * Initiates a job for a snap.
55
58
  *
56
- * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.
57
- *
59
+ * @param jobId - The ID of the job to initiate.
60
+ * @param timer - The timer to use for timeouts.
58
61
  * @returns Information regarding the created job.
62
+ * @throws If the execution service returns an error or execution times out.
59
63
  */
60
- protected initJob(): Promise<Job<WorkerType>>;
64
+ protected initJob(jobId: string, timer: Timer): Promise<Job<WorkerType>>;
61
65
  /**
62
66
  * Sets up the streams for an initiated job.
63
67
  *
64
- * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.
65
- *
66
68
  * @param jobId - The id of the job.
69
+ * @param timer - The timer to use for timeouts.
67
70
  * @returns The streams to communicate with the worker and the worker itself.
71
+ * @throws If the execution service returns an error or execution times out.
68
72
  */
69
- protected initStreams(jobId: string): Promise<{
73
+ protected initStreams(jobId: string, timer: Timer): Promise<{
70
74
  streams: JobStreams;
71
75
  worker: WorkerType;
72
76
  }>;
@@ -98,13 +102,14 @@ export declare abstract class AbstractExecutionService<WorkerType> implements Ex
98
102
  /**
99
103
  * Initializes and executes a snap, setting up the communication channels to the snap etc.
100
104
  *
101
- * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.
102
- *
103
105
  * @param snapData - Data needed for Snap execution.
106
+ * @param snapData.snapId - The ID of the Snap to execute.
107
+ * @param snapData.sourceCode - The source code of the Snap to execute.
108
+ * @param snapData.endowments - The endowments available to the executing Snap.
104
109
  * @returns A string `OK` if execution succeeded.
105
- * @throws If the execution service returns an error.
110
+ * @throws If the execution service returns an error or execution times out.
106
111
  */
107
- executeSnap(snapData: SnapExecutionData): Promise<string>;
112
+ executeSnap({ snapId, sourceCode, endowments, }: SnapExecutionData): Promise<string>;
108
113
  private command;
109
114
  /**
110
115
  * Handle RPC request.
@@ -14,7 +14,7 @@ export interface ExecutionService {
14
14
  export declare type SnapExecutionData = {
15
15
  snapId: string;
16
16
  sourceCode: string;
17
- endowments?: Json;
17
+ endowments: Json;
18
18
  };
19
19
  export declare type SnapErrorJson = {
20
20
  message: string;
@@ -1,5 +1,5 @@
1
1
  import type { BasePostMessageStream } from '@metamask/post-message-stream';
2
- import type { Job, ExecutionServiceArgs } from '../AbstractExecutionService';
2
+ import type { ExecutionServiceArgs, TerminateJobArgs } from '../AbstractExecutionService';
3
3
  import { AbstractExecutionService } from '../AbstractExecutionService';
4
4
  declare type IframeExecutionEnvironmentServiceArgs = {
5
5
  iframeUrl: URL;
@@ -7,7 +7,7 @@ declare type IframeExecutionEnvironmentServiceArgs = {
7
7
  export declare class IframeExecutionService extends AbstractExecutionService<Window> {
8
8
  iframeUrl: URL;
9
9
  constructor({ iframeUrl, messenger, setupSnapProvider, }: IframeExecutionEnvironmentServiceArgs);
10
- protected terminateJob(jobWrapper: Job<Window>): void;
10
+ protected terminateJob(jobWrapper: TerminateJobArgs<Window>): void;
11
11
  protected initEnvStream(jobId: string): Promise<{
12
12
  worker: Window;
13
13
  stream: BasePostMessageStream;
@@ -1,12 +1,12 @@
1
1
  /// <reference types="node" />
2
2
  import type { BasePostMessageStream } from '@metamask/post-message-stream';
3
3
  import type { ChildProcess } from 'child_process';
4
- import type { Job } from '..';
4
+ import type { TerminateJobArgs } from '..';
5
5
  import { AbstractExecutionService } from '..';
6
6
  export declare class NodeProcessExecutionService extends AbstractExecutionService<ChildProcess> {
7
7
  protected initEnvStream(): Promise<{
8
8
  worker: ChildProcess;
9
9
  stream: BasePostMessageStream;
10
10
  }>;
11
- protected terminateJob(jobWrapper: Job<ChildProcess>): void;
11
+ protected terminateJob(jobWrapper: TerminateJobArgs<ChildProcess>): void;
12
12
  }
@@ -1,12 +1,12 @@
1
1
  /// <reference types="node" />
2
2
  import type { BasePostMessageStream } from '@metamask/post-message-stream';
3
3
  import { Worker } from 'worker_threads';
4
- import type { Job } from '..';
4
+ import type { TerminateJobArgs } from '..';
5
5
  import { AbstractExecutionService } from '..';
6
6
  export declare class NodeThreadExecutionService extends AbstractExecutionService<Worker> {
7
7
  protected initEnvStream(): Promise<{
8
8
  worker: Worker;
9
9
  stream: BasePostMessageStream;
10
10
  }>;
11
- protected terminateJob(jobWrapper: Job<Worker>): Promise<void>;
11
+ protected terminateJob(jobWrapper: TerminateJobArgs<Worker>): Promise<void>;
12
12
  }
@@ -1,5 +1,5 @@
1
1
  import type { BasePostMessageStream } from '@metamask/post-message-stream';
2
- import type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';
2
+ import type { ExecutionServiceArgs, TerminateJobArgs } from '../AbstractExecutionService';
3
3
  import { AbstractExecutionService } from '../AbstractExecutionService';
4
4
  import { ProxyPostMessageStream } from '../ProxyPostMessageStream';
5
5
  declare type ProxyExecutionEnvironmentServiceArgs = {
@@ -24,7 +24,7 @@ export declare class ProxyExecutionService extends AbstractExecutionService<stri
24
24
  *
25
25
  * @param job - The job to terminate.
26
26
  */
27
- protected terminateJob(job: Job<string>): Promise<void>;
27
+ protected terminateJob(job: TerminateJobArgs<string>): Promise<void>;
28
28
  /**
29
29
  * Create a new stream for the specified job. This wraps the root stream
30
30
  * in a stream specific to the job.
@@ -1,4 +1,4 @@
1
- import type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';
1
+ import type { ExecutionServiceArgs, TerminateJobArgs } from '../AbstractExecutionService';
2
2
  import { AbstractExecutionService } from '../AbstractExecutionService';
3
3
  import { ProxyPostMessageStream } from '../ProxyPostMessageStream';
4
4
  declare type WebWorkerExecutionEnvironmentServiceArgs = {
@@ -24,7 +24,7 @@ export declare class WebWorkerExecutionService extends AbstractExecutionService<
24
24
  *
25
25
  * @param job - The job to terminate.
26
26
  */
27
- protected terminateJob(job: Job<string>): Promise<void>;
27
+ protected terminateJob(job: TerminateJobArgs<string>): Promise<void>;
28
28
  /**
29
29
  * Create a new stream for the specified job. This wraps the runtime stream
30
30
  * in a stream specific to the job.
@@ -84,6 +84,10 @@ export interface SnapRuntimeData {
84
84
  * Cached encryption salt used for state encryption.
85
85
  */
86
86
  encryptionSalt: string | null;
87
+ /**
88
+ * A boolean flag to determine whether the Snap is currently being stopped.
89
+ */
90
+ stopping: boolean;
87
91
  }
88
92
  export declare type SnapError = {
89
93
  message: string;
@@ -337,11 +341,6 @@ declare type SnapControllerArgs = {
337
341
  * unless it is permitted to take longer.
338
342
  */
339
343
  maxRequestTime?: number;
340
- /**
341
- * The maximum amount of time a snap may take to initialize, including
342
- * the time it takes for the execution environment to start.
343
- */
344
- maxInitTime?: number;
345
344
  /**
346
345
  * The npm registry URL that will be used to fetch published snaps.
347
346
  */
@@ -374,7 +373,7 @@ declare type SnapControllerArgs = {
374
373
  export declare class SnapController extends BaseController<string, SnapControllerState, SnapControllerMessenger> {
375
374
  #private;
376
375
  private readonly maxRequestTime;
377
- constructor({ closeAllConnections, messenger, state, dynamicPermissions, environmentEndowmentPermissions, excludedPermissions, idleTimeCheckInterval, maxIdleTime, maxRequestTime, maxInitTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, preinstalledSnaps, encryptor, getMnemonic, }: SnapControllerArgs);
376
+ constructor({ closeAllConnections, messenger, state, dynamicPermissions, environmentEndowmentPermissions, excludedPermissions, idleTimeCheckInterval, maxIdleTime, maxRequestTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, preinstalledSnaps, encryptor, getMnemonic, }: SnapControllerArgs);
378
377
  /**
379
378
  * Checks all installed snaps against the block list and
380
379
  * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}
@@ -10,12 +10,19 @@ export declare class Timer {
10
10
  */
11
11
  constructor(ms: number);
12
12
  get status(): TimerStatus;
13
+ get remaining(): number;
13
14
  /**
14
15
  * Cancels the currently running timer and marks it finished.
15
16
  *
16
17
  * @throws {@link Error}. If it wasn't running or paused.
17
18
  */
18
19
  cancel(): void;
20
+ /**
21
+ * Marks the timer as finished prematurely and triggers the callback.
22
+ *
23
+ * @throws {@link Error}. If it wasn't running or paused.
24
+ */
25
+ finish(): void;
19
26
  /**
20
27
  * Pauses a currently running timer, allowing it to resume later.
21
28
  *
@@ -1,3 +1,4 @@
1
+ import type { PermissionConstraint } from '@metamask/permission-controller';
1
2
  import type { SnapId } from '@metamask/snaps-sdk';
2
3
  import type { SnapLocation } from './snaps';
3
4
  import { Timer } from './snaps/Timer';
@@ -16,6 +17,17 @@ import { Timer } from './snaps/Timer';
16
17
  * @returns The objectA without properties from objectB.
17
18
  */
18
19
  export declare function setDiff<ObjectA extends Record<any, unknown>, ObjectB extends Record<any, unknown>>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB>;
20
+ /**
21
+ * Calculate a difference between two permissions objects.
22
+ *
23
+ * Similar to `setDiff` except for one additional condition:
24
+ * Permissions in B should be removed from A if they exist in both and have differing caveats.
25
+ *
26
+ * @param permissionsA - An object containing one or more partial permissions.
27
+ * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.
28
+ * @returns The permissions set A without properties from B.
29
+ */
30
+ export declare function permissionsDiff<PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>, PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>>(permissionsA: PermissionsA, permissionsB: PermissionsB): Diff<PermissionsA, PermissionsB>;
19
31
  /**
20
32
  * A Promise that delays its return for a given amount of milliseconds.
21
33
  *
package/dist/utils.js CHANGED
@@ -6,8 +6,9 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkXE5IWVNVjs = require('./chunk-XE5IWVNV.js');
10
- require('./chunk-NOLPMHXS.js');
9
+
10
+ var _chunk4DPX4O3Tjs = require('./chunk-4DPX4O3T.js');
11
+ require('./chunk-BOFPNIRX.js');
11
12
  require('./chunk-EXN2TFDJ.js');
12
13
 
13
14
 
@@ -17,5 +18,6 @@ require('./chunk-EXN2TFDJ.js');
17
18
 
18
19
 
19
20
 
20
- exports.delay = _chunkXE5IWVNVjs.delay; exports.delayWithTimer = _chunkXE5IWVNVjs.delayWithTimer; exports.fetchSnap = _chunkXE5IWVNVjs.fetchSnap; exports.getSnapFiles = _chunkXE5IWVNVjs.getSnapFiles; exports.hasTimedOut = _chunkXE5IWVNVjs.hasTimedOut; exports.setDiff = _chunkXE5IWVNVjs.setDiff; exports.withTimeout = _chunkXE5IWVNVjs.withTimeout;
21
+
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;
21
23
  //# sourceMappingURL=utils.js.map
package/dist/utils.mjs CHANGED
@@ -4,10 +4,11 @@ import {
4
4
  fetchSnap,
5
5
  getSnapFiles,
6
6
  hasTimedOut,
7
+ permissionsDiff,
7
8
  setDiff,
8
9
  withTimeout
9
- } from "./chunk-36YC4Z3T.mjs";
10
- import "./chunk-VOZOZKRC.mjs";
10
+ } from "./chunk-GTDDODNP.mjs";
11
+ import "./chunk-XO7KDFBY.mjs";
11
12
  import "./chunk-YRZVIDCF.mjs";
12
13
  export {
13
14
  delay,
@@ -15,6 +16,7 @@ export {
15
16
  fetchSnap,
16
17
  getSnapFiles,
17
18
  hasTimedOut,
19
+ permissionsDiff,
18
20
  setDiff,
19
21
  withTimeout
20
22
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-controllers",
3
- "version": "7.0.1",
3
+ "version": "8.0.0",
4
4
  "description": "Controllers for MetaMask Snaps.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -62,12 +62,13 @@
62
62
  "@metamask/rpc-errors": "^6.2.1",
63
63
  "@metamask/snaps-registry": "^3.1.0",
64
64
  "@metamask/snaps-rpc-methods": "^8.0.0",
65
- "@metamask/snaps-sdk": "^4.0.0",
66
- "@metamask/snaps-utils": "^7.1.0",
65
+ "@metamask/snaps-sdk": "^4.0.1",
66
+ "@metamask/snaps-utils": "^7.2.0",
67
67
  "@metamask/utils": "^8.3.0",
68
68
  "@xstate/fsm": "^2.0.0",
69
69
  "browserify-zlib": "^0.2.0",
70
70
  "concat-stream": "^2.0.0",
71
+ "fast-deep-equal": "^3.1.3",
71
72
  "get-npm-tarball-url": "^2.0.3",
72
73
  "immer": "^9.0.6",
73
74
  "nanoid": "^3.1.31",
@@ -135,7 +136,7 @@
135
136
  "webdriverio": "^8.19.0"
136
137
  },
137
138
  "peerDependencies": {
138
- "@metamask/snaps-execution-environments": "^6.0.0"
139
+ "@metamask/snaps-execution-environments": "^6.0.2"
139
140
  },
140
141
  "peerDependenciesMeta": {
141
142
  "@metamask/snaps-execution-environments": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/services/node-js/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"],"mappings":";;;;;;;;AACA,SAAS,kCAAkC;AAE3C,SAAS,YAAY;AAKd,IAAM,8BAAN,cAA0C,yBAAuC;AAAA,EACtF,MAAgB,gBAGb;AACD,UAAM,SAAS;AAAA,MACb,UAAQ;AAAA,QACN;AAAA,MACF;AAAA,MACA;AAAA,QACE,OAAO;AAAA,MACT;AAAA,IACF;AAIA,WAAO,QAAQ,GAAG,QAAQ,CAAC,SAAS;AAElC,cAAQ,IAAI,KAAK,SAAS,CAAC;AAAA,IAC7B,CAAC;AAED,WAAO,QAAQ,GAAG,QAAQ,CAAC,SAAS;AAElC,cAAQ,MAAM,KAAK,SAAS,CAAC;AAAA,IAC/B,CAAC;AAED,UAAM,SAAS,IAAI,2BAA2B,EAAE,SAAS,OAAO,CAAC;AACjE,WAAO,QAAQ,QAAQ,EAAE,QAAQ,OAAO,CAAC;AAAA,EAC3C;AAAA,EAEU,aAAa,YAAqC;AAC1D,eAAW,OAAO,KAAK;AAAA,EACzB;AACF;","names":[]}
@@ -1 +0,0 @@
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"],"mappings":";;;;;AACA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAmBA,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;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ACxB,OAAO,IAAI;AAAA,MACX,MAAM;AAAA,QACJ,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,IAAI,OAAO;AAAA,MACb;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAgB,cAAc,OAAe;AAE3C,UAAM,KAAK,eAAe;AAG1B,WAAO,mBAAK,iBAAgB,iCAAiC;AAE7D,UAAM,SAAS,IAAI,uBAAuB;AAAA,MACxC,QAAQ,mBAAK;AAAA,MACb;AAAA,IACF,CAAC;AAED,WAAO,EAAE,QAAQ,OAAO,OAAO;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,iBAAiB;AAE7B,QAAI,SAAS,eAAe,cAAc,GAAG;AAC3C;AAAA,IACF;AAEA,UAAM,SAAS,MAAM;AAAA,MACnB,mBAAK,cAAa;AAAA,MAClB;AAAA,MACA;AAAA,IACF;AAEA,uBAAK,gBAAiB,IAAI,wBAAwB;AAAA,MAChD,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,cAAc;AAAA,MACd,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AA5FE;AAEA","sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\nimport { createWindow } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';\nimport { AbstractExecutionService } from '../AbstractExecutionService';\nimport { ProxyPostMessageStream } from '../ProxyPostMessageStream';\n\ntype WebWorkerExecutionEnvironmentServiceArgs = {\n documentUrl: URL;\n} & ExecutionServiceArgs;\n\nexport const WORKER_POOL_ID = 'snaps-worker-pool';\n\nexport class WebWorkerExecutionService extends AbstractExecutionService<string> {\n #documentUrl: URL;\n\n #runtimeStream?: BasePostMessageStream;\n\n /**\n * Create a new webworker execution service.\n *\n * @param args - The constructor arguments.\n * @param args.documentUrl - The URL of the worker pool document to use as the\n * execution environment.\n * @param args.messenger - The messenger to use for communication with the\n * `SnapController`.\n * @param args.setupSnapProvider - The function to use to set up the snap\n * provider.\n */\n constructor({\n documentUrl,\n messenger,\n setupSnapProvider,\n }: WebWorkerExecutionEnvironmentServiceArgs) {\n super({\n messenger,\n setupSnapProvider,\n });\n\n this.#documentUrl = documentUrl;\n }\n\n /**\n * Send a termination command to the worker pool document.\n *\n * @param job - The job to terminate.\n */\n protected async terminateJob(job: Job<string>) {\n // The `AbstractExecutionService` will have already closed the job stream,\n // so we write to the runtime stream directly.\n assert(this.#runtimeStream, 'Runtime stream not initialized.');\n this.#runtimeStream.write({\n jobId: job.id,\n data: {\n jsonrpc: '2.0',\n method: 'terminateJob',\n id: nanoid(),\n },\n });\n }\n\n /**\n * Create a new stream for the specified job. This wraps the runtime stream\n * in a stream specific to the job.\n *\n * @param jobId - The job ID.\n */\n protected async initEnvStream(jobId: string) {\n // Lazily create the worker pool document.\n await this.createDocument();\n\n // `createDocument` should have initialized the runtime stream.\n assert(this.#runtimeStream, 'Runtime stream not initialized.');\n\n const stream = new ProxyPostMessageStream({\n stream: this.#runtimeStream,\n jobId,\n });\n\n return { worker: jobId, stream };\n }\n\n /**\n * Creates the worker pool document to be used as the execution environment.\n *\n * If the document already exists, this does nothing.\n */\n private async createDocument() {\n // We only want to create a single pool.\n if (document.getElementById(WORKER_POOL_ID)) {\n return;\n }\n\n const window = await createWindow(\n this.#documentUrl.href,\n WORKER_POOL_ID,\n false,\n );\n\n this.#runtimeStream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: window,\n targetOrigin: '*',\n });\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/services/AbstractExecutionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,8BAA8B;AACvC,OAAO,qBAAqB;AAE5B,SAAS,oBAAoB;AA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AAI,QAAQ,KAAK;AACpC,qBAAK,eAAc,IAAI,OAAO,MAAM;AACtC;AAEA;AAAA,6BAAwB,SAAC,OAAqB;AAC5C,QAAM,SAAS,mBAAK,eAAc,IAAI,KAAK;AAC3C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,SAAS,KAAK,uBAAuB;AAAA,EACvD;AAEA,qBAAK,eAAc,OAAO,KAAK;AAC/B,qBAAK,eAAc,OAAO,MAAM;AAChC,wBAAK,sCAAL,WAAsB;AACxB;AAgCK,SAAS,eACd,kBACA,YACiB;AACjB,QAAM,MAAM,IAAI,gBAAgB;AAChC,WAAS,kBAAkB,KAAK,kBAAkB,CAAC,UAAU;AAC3D,QAAI,OAAO;AACT,mBACI,SAAS,IAAI,UAAU,qBAAqB,KAAK,IACjD,SAAS,KAAK;AAAA,IACpB;AAAA,EACF,CAAC;AACD,SAAO;AACT","sourcesContent":["import { JsonRpcEngine } from '@metamask/json-rpc-engine';\nimport { createStreamMiddleware } from '@metamask/json-rpc-middleware-stream';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type {\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport {\n Duration,\n assertIsJsonRpcRequest,\n inMilliseconds,\n isJsonRpcNotification,\n isObject,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'readable-stream';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n pingTimeout?: number;\n terminationTimeout?: number;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #pingTimeout: number;\n\n #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n pingTimeout = inMilliseconds(2, Duration.Second),\n terminationTimeout = inMilliseconds(1, Duration.Second),\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#pingTimeout = pingTimeout;\n this.#terminationTimeout = terminationTimeout;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (snapData: SnapExecutionData) => this.executeSnap(snapData),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: Job<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pipeline(\n jsonRpcConnection.stream,\n streams.command,\n jsonRpcConnection.stream,\n (error) => {\n if (error) {\n logError(`Command stream failure.`, error);\n }\n },\n );\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n const mux = setupMultiplex(envStream, `Job: \"${jobId}\"`);\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n // This may resolve even if the environment has failed to start up fully\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n const pingResult = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n }),\n this.#pingTimeout,\n );\n\n if (pingResult === hasTimedOut) {\n throw new Error('The Snaps execution environment failed to start.');\n }\n\n const rpcStream = job.streams.rpc;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n assertIsJsonRpcRequest(message);\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n const response: PendingJsonRpcResponse<Json> = await job.rpcEngine.handle(\n message,\n );\n\n if (response.error) {\n throw new JsonRpcError(\n response.error.code,\n response.error.message,\n response.error.data,\n );\n }\n\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request: request as JsonRpcRequest,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pipeline(connectionStream, mux, connectionStream, (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n });\n return mux;\n}\n"]}