@metamask/snaps-execution-environments 3.1.0 → 3.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.
@@ -23,6 +23,21 @@ const _globalEvents = require("./globalEvents");
23
23
  const _sortParams = require("./sortParams");
24
24
  const _utils1 = require("./utils");
25
25
  const _validation = require("./validation");
26
+ function _check_private_redeclaration(obj, privateCollection) {
27
+ if (privateCollection.has(obj)) {
28
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
29
+ }
30
+ }
31
+ function _class_private_method_get(receiver, privateSet, fn) {
32
+ if (!privateSet.has(receiver)) {
33
+ throw new TypeError("attempted to get private field on non-instance");
34
+ }
35
+ return fn;
36
+ }
37
+ function _class_private_method_init(obj, privateSet) {
38
+ _check_private_redeclaration(obj, privateSet);
39
+ privateSet.add(obj);
40
+ }
26
41
  function _define_property(obj, key, value) {
27
42
  if (key in obj) {
28
43
  Object.defineProperty(obj, key, {
@@ -74,6 +89,7 @@ const unhandledError = _rpcerrors.rpcErrors.internal({
74
89
  ]
75
90
  }
76
91
  };
92
+ var _write = /*#__PURE__*/ new WeakSet(), _notify = /*#__PURE__*/ new WeakSet(), _respond = /*#__PURE__*/ new WeakSet();
77
93
  class BaseSnapExecutor {
78
94
  errorHandler(error, data) {
79
95
  const serializedError = (0, _rpcerrors.serializeError)(error, {
@@ -81,7 +97,7 @@ class BaseSnapExecutor {
81
97
  shouldIncludeStack: false
82
98
  });
83
99
  const errorData = (0, _snapsutils.getErrorData)(serializedError);
84
- this.notify({
100
+ _class_private_method_get(this, _notify, notify).call(this, {
85
101
  method: 'UnhandledError',
86
102
  params: {
87
103
  error: {
@@ -92,6 +108,8 @@ class BaseSnapExecutor {
92
108
  }
93
109
  }
94
110
  }
111
+ }).catch((notifyError)=>{
112
+ (0, _snapsutils.logError)(notifyError);
95
113
  });
96
114
  }
97
115
  async onCommandRequest(message) {
@@ -103,7 +121,7 @@ class BaseSnapExecutor {
103
121
  }
104
122
  const { id, method, params } = message;
105
123
  if (!(0, _utils.hasProperty)(EXECUTION_ENVIRONMENT_METHODS, method)) {
106
- this.respond(id, {
124
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
107
125
  error: _rpcerrors.rpcErrors.methodNotFound({
108
126
  data: {
109
127
  method
@@ -117,7 +135,7 @@ class BaseSnapExecutor {
117
135
  const paramsAsArray = (0, _sortParams.sortParamKeys)(methodObject.params, params);
118
136
  const [error] = (0, _superstruct.validate)(paramsAsArray, methodObject.struct);
119
137
  if (error) {
120
- this.respond(id, {
138
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
121
139
  error: _rpcerrors.rpcErrors.invalidParams({
122
140
  message: `Invalid parameters for method "${method}": ${error.message}.`,
123
141
  data: {
@@ -130,43 +148,17 @@ class BaseSnapExecutor {
130
148
  }
131
149
  try {
132
150
  const result = await this.methods[method](...paramsAsArray);
133
- this.respond(id, {
151
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
134
152
  result
135
153
  });
136
154
  } catch (rpcError) {
137
- this.respond(id, {
155
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
138
156
  error: (0, _rpcerrors.serializeError)(rpcError, {
139
157
  fallbackError
140
158
  })
141
159
  });
142
160
  }
143
161
  }
144
- notify(requestObject) {
145
- if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
146
- throw _rpcerrors.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
147
- }
148
- this.commandStream.write({
149
- ...requestObject,
150
- jsonrpc: '2.0'
151
- });
152
- }
153
- respond(id, requestObject) {
154
- if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
155
- // Instead of throwing, we directly respond with an error.
156
- // This prevents an issue where we wouldn't respond when errors were non-serializable
157
- this.commandStream.write({
158
- error: (0, _rpcerrors.serializeError)(_rpcerrors.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
159
- id,
160
- jsonrpc: '2.0'
161
- });
162
- return;
163
- }
164
- this.commandStream.write({
165
- ...requestObject,
166
- id,
167
- jsonrpc: '2.0'
168
- });
169
- }
170
162
  /**
171
163
  * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
172
164
  * on errors.
@@ -282,16 +274,18 @@ class BaseSnapExecutor {
282
274
  const request = async (args)=>{
283
275
  const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
284
276
  (0, _utils1.assertSnapOutboundRequest)(sanitizedArgs);
285
- this.notify({
286
- method: 'OutboundRequest'
287
- });
288
- try {
289
- return await (0, _utils1.withTeardown)(originalRequest(sanitizedArgs), this);
290
- } finally{
291
- this.notify({
292
- method: 'OutboundResponse'
277
+ return await (0, _utils1.withTeardown)((async ()=>{
278
+ await _class_private_method_get(this, _notify, notify).call(this, {
279
+ method: 'OutboundRequest'
293
280
  });
294
- }
281
+ try {
282
+ return await originalRequest(sanitizedArgs);
283
+ } finally{
284
+ await _class_private_method_get(this, _notify, notify).call(this, {
285
+ method: 'OutboundResponse'
286
+ });
287
+ }
288
+ })(), this);
295
289
  };
296
290
  // Proxy target is intentionally set to be an empty object, to ensure
297
291
  // that access to the prototype chain is not possible.
@@ -320,16 +314,18 @@ class BaseSnapExecutor {
320
314
  const request = async (args)=>{
321
315
  const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
322
316
  (0, _utils1.assertEthereumOutboundRequest)(sanitizedArgs);
323
- this.notify({
324
- method: 'OutboundRequest'
325
- });
326
- try {
327
- return await (0, _utils1.withTeardown)(originalRequest(sanitizedArgs), this);
328
- } finally{
329
- this.notify({
330
- method: 'OutboundResponse'
317
+ return await (0, _utils1.withTeardown)((async ()=>{
318
+ await _class_private_method_get(this, _notify, notify).call(this, {
319
+ method: 'OutboundRequest'
331
320
  });
332
- }
321
+ try {
322
+ return await originalRequest(sanitizedArgs);
323
+ } finally{
324
+ await _class_private_method_get(this, _notify, notify).call(this, {
325
+ method: 'OutboundResponse'
326
+ });
327
+ }
328
+ })(), this);
333
329
  };
334
330
  const streamProviderProxy = (0, _utils1.proxyStreamProvider)(provider, request);
335
331
  return harden(streamProviderProxy);
@@ -383,6 +379,12 @@ class BaseSnapExecutor {
383
379
  }
384
380
  }
385
381
  constructor(commandStream, rpcStream){
382
+ // Awaitable function that writes back to the command stream
383
+ // To prevent snap execution from blocking writing we wrap in a promise
384
+ // and await it before continuing execution
385
+ _class_private_method_init(this, _write);
386
+ _class_private_method_init(this, _notify);
387
+ _class_private_method_init(this, _respond);
386
388
  _define_property(this, "snapData", void 0);
387
389
  _define_property(this, "commandStream", void 0);
388
390
  _define_property(this, "rpcStream", void 0);
@@ -426,5 +428,42 @@ class BaseSnapExecutor {
426
428
  }, this.onTerminate.bind(this));
427
429
  }
428
430
  }
431
+ async function write(chunk) {
432
+ return new Promise((resolve, reject)=>{
433
+ this.commandStream.write(chunk, (error)=>{
434
+ if (error) {
435
+ reject(error);
436
+ return;
437
+ }
438
+ resolve();
439
+ });
440
+ });
441
+ }
442
+ async function notify(requestObject) {
443
+ if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
444
+ throw _rpcerrors.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
445
+ }
446
+ await _class_private_method_get(this, _write, write).call(this, {
447
+ ...requestObject,
448
+ jsonrpc: '2.0'
449
+ });
450
+ }
451
+ async function respond(id, requestObject) {
452
+ if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
453
+ // Instead of throwing, we directly respond with an error.
454
+ // This prevents an issue where we wouldn't respond when errors were non-serializable
455
+ await _class_private_method_get(this, _write, write).call(this, {
456
+ error: (0, _rpcerrors.serializeError)(_rpcerrors.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
457
+ id,
458
+ jsonrpc: '2.0'
459
+ });
460
+ return;
461
+ }
462
+ await _class_private_method_get(this, _write, write).call(this, {
463
+ ...requestObject,
464
+ id,
465
+ jsonrpc: '2.0'
466
+ });
467
+ }
429
468
 
430
469
  //# sourceMappingURL=BaseSnapExecutor.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n getErrorData,\n unwrapError,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n this.commandStream.write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","unhandledError","rpcErrors","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","serializedError","serializeError","shouldIncludeStack","errorData","getErrorData","notify","method","onCommandRequest","isJsonRpcRequest","invalidRequest","id","hasProperty","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","Error","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","unwrapError","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","WrappedSnapError","size","lastTeardown","Map","on","catch","logError","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BA+GnDA;;;eAAAA;;;+BA9G2B;2BACT;2BAEuB;4BAc/C;uBAcA;6BAEkB;yBAEL;0BAE4B;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,qBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAEA,MAAMC,iBAAiBC,oBAAS,CAC7BH,QAAQ,CAAO;IACdC,SAAS;AACX,GACCG,SAAS;AAUZ;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IACAG,WAAW;QACTL,QAAQM,2CAA+B;QACvCJ,QAAQ,EAAE;IACZ;IACAK,SAAS;QACPP,QAAQQ,yCAA6B;QACrCN,QAAQ;YAAC;YAAU;YAAW;YAAU;SAAU;IACpD;AACF;AAIO,MAAMd;IAyEHqB,aAAaC,KAAc,EAAEC,IAA0B,EAAE;QAC/D,MAAMC,kBAAkBC,IAAAA,yBAAc,EAACH,OAA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IAE9B;AAmXF"}
1
+ {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n getErrorData,\n unwrapError,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n await this.#write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\n );\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","unhandledError","rpcErrors","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","serializedError","serializeError","shouldIncludeStack","errorData","getErrorData","notify","method","catch","notifyError","logError","onCommandRequest","isJsonRpcRequest","invalidRequest","id","hasProperty","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","Error","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","unwrapError","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","WrappedSnapError","size","lastTeardown","commandStream","Map","on","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace","chunk","resolve","write","requestObject","isValidJson","isObject","jsonrpc"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BA+GnDA;;;eAAAA;;;+BA9G2B;2BACT;2BAEuB;4BAc/C;uBAcA;6BAEkB;yBAEL;0BAE4B;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,qBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAEA,MAAMC,iBAAiBC,oBAAS,CAC7BH,QAAQ,CAAO;IACdC,SAAS;AACX,GACCG,SAAS;AAUZ;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;YAAC;YAAU;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AEiB,MAAMhB,OAAO,CAACgJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACvD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AA8YF;AAzTE,eAAA,MAAayC,KAAW;IACtB,OAAO,IAAIrB,QAAc,CAACsB,SAASpB;QACjC,IAAI,CAACO,aAAa,CAACc,KAAK,CAACF,OAAO,CAACjI;YAC/B,IAAIA,OAAO;gBACT8G,OAAO9G;gBACP;YACF;YACAkI;QACF;IACF;AACF;AAEA,eAAA,OAAcE,aAAmD;IAC/D,IAAI,CAACC,IAAAA,kBAAW,EAACD,kBAAkB,CAACE,IAAAA,eAAQ,EAACF,gBAAgB;QAC3D,MAAMlJ,oBAAS,CAACH,QAAQ,CACtB;IAEJ;IAEA,MAAM,0BAAA,IAAI,EAAEoJ,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBG,SAAS;IACX;AACF;AAEA,eAAA,QAAexH,EAAa,EAAEqH,aAAsC;IAClE,IAAI,CAACC,IAAAA,kBAAW,EAACD,kBAAkB,CAACE,IAAAA,eAAQ,EAACF,gBAAgB;QAC3D,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,0BAAA,IAAI,EAAED,QAAAA,YAAN,IAAI,EAAQ;YAChBnI,OAAOG,IAAAA,yBAAc,EACnBjB,oBAAS,CAACH,QAAQ,CAChB;YAGJgC;YACAwH,SAAS;QACX;QACA;IACF;IAEA,MAAM,0BAAA,IAAI,EAAEJ,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBrH;QACAwH,SAAS;IACX;AACF"}
@@ -58,6 +58,8 @@ function getHandlerArguments(origin, handler, request) {
58
58
  return {
59
59
  request
60
60
  };
61
+ case _snapsutils.HandlerType.OnHomePage:
62
+ return {};
61
63
  default:
62
64
  return (0, _utils.assertExhaustive)(handler);
63
65
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAgCgBA,mBAAmB;eAAnBA;;IA6DAC,+BAA+B;eAA/BA;;;4BA7FY;uBACK;4BAc1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACT,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEI,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQI,MAAM;gBAEhB,OAAOM,SACH;oBACEJ;oBACAI;gBACF,IACA;oBACEJ;oBACAK;gBACF;YACN;QACA,KAAKV,uBAAW,CAACW,YAAY;QAC7B,KAAKX,uBAAW,CAACY,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACa,SAAS;QAC1B,KAAKb,uBAAW,CAACc,SAAS;QAC1B,KAAKd,uBAAW,CAACe,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB;YACE,OAAOiB,IAAAA,uBAAgB,EAAClB;IAC5B;AACF;AAaO,SAASF,gCACdqB,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQ/B,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMmB,WACLW,QACA/B,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAgCgBA,mBAAmB;eAAnBA;;IAgEAC,+BAA+B;eAA/BA;;;4BAhGY;uBACK;4BAc1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACT,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEI,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQI,MAAM;gBAEhB,OAAOM,SACH;oBACEJ;oBACAI;gBACF,IACA;oBACEJ;oBACAK;gBACF;YACN;QACA,KAAKV,uBAAW,CAACW,YAAY;QAC7B,KAAKX,uBAAW,CAACY,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACa,SAAS;QAC1B,KAAKb,uBAAW,CAACc,SAAS;QAC1B,KAAKd,uBAAW,CAACe,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB,KAAKC,uBAAW,CAACgB,UAAU;YACzB,OAAO,CAAC;QAEV;YACE,OAAOC,IAAAA,uBAAgB,EAACnB;IAC5B;AACF;AAaO,SAASF,gCACdsB,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQhC,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMoB,WACLW,QACAhC,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
@@ -1,5 +1,20 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
2
  /// <reference path="../../../../node_modules/ses/types.d.ts" />
3
+ function _check_private_redeclaration(obj, privateCollection) {
4
+ if (privateCollection.has(obj)) {
5
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
6
+ }
7
+ }
8
+ function _class_private_method_get(receiver, privateSet, fn) {
9
+ if (!privateSet.has(receiver)) {
10
+ throw new TypeError("attempted to get private field on non-instance");
11
+ }
12
+ return fn;
13
+ }
14
+ function _class_private_method_init(obj, privateSet) {
15
+ _check_private_redeclaration(obj, privateSet);
16
+ privateSet.add(obj);
17
+ }
3
18
  function _define_property(obj, key, value) {
4
19
  if (key in obj) {
5
20
  Object.defineProperty(obj, key, {
@@ -64,6 +79,7 @@ const unhandledError = rpcErrors.internal({
64
79
  ]
65
80
  }
66
81
  };
82
+ var _write = /*#__PURE__*/ new WeakSet(), _notify = /*#__PURE__*/ new WeakSet(), _respond = /*#__PURE__*/ new WeakSet();
67
83
  export class BaseSnapExecutor {
68
84
  errorHandler(error, data) {
69
85
  const serializedError = serializeError(error, {
@@ -71,7 +87,7 @@ export class BaseSnapExecutor {
71
87
  shouldIncludeStack: false
72
88
  });
73
89
  const errorData = getErrorData(serializedError);
74
- this.notify({
90
+ _class_private_method_get(this, _notify, notify).call(this, {
75
91
  method: 'UnhandledError',
76
92
  params: {
77
93
  error: {
@@ -82,6 +98,8 @@ export class BaseSnapExecutor {
82
98
  }
83
99
  }
84
100
  }
101
+ }).catch((notifyError)=>{
102
+ logError(notifyError);
85
103
  });
86
104
  }
87
105
  async onCommandRequest(message) {
@@ -93,7 +111,7 @@ export class BaseSnapExecutor {
93
111
  }
94
112
  const { id, method, params } = message;
95
113
  if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {
96
- this.respond(id, {
114
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
97
115
  error: rpcErrors.methodNotFound({
98
116
  data: {
99
117
  method
@@ -107,7 +125,7 @@ export class BaseSnapExecutor {
107
125
  const paramsAsArray = sortParamKeys(methodObject.params, params);
108
126
  const [error] = validate(paramsAsArray, methodObject.struct);
109
127
  if (error) {
110
- this.respond(id, {
128
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
111
129
  error: rpcErrors.invalidParams({
112
130
  message: `Invalid parameters for method "${method}": ${error.message}.`,
113
131
  data: {
@@ -120,43 +138,17 @@ export class BaseSnapExecutor {
120
138
  }
121
139
  try {
122
140
  const result = await this.methods[method](...paramsAsArray);
123
- this.respond(id, {
141
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
124
142
  result
125
143
  });
126
144
  } catch (rpcError) {
127
- this.respond(id, {
145
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
128
146
  error: serializeError(rpcError, {
129
147
  fallbackError
130
148
  })
131
149
  });
132
150
  }
133
151
  }
134
- notify(requestObject) {
135
- if (!isValidJson(requestObject) || !isObject(requestObject)) {
136
- throw rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
137
- }
138
- this.commandStream.write({
139
- ...requestObject,
140
- jsonrpc: '2.0'
141
- });
142
- }
143
- respond(id, requestObject) {
144
- if (!isValidJson(requestObject) || !isObject(requestObject)) {
145
- // Instead of throwing, we directly respond with an error.
146
- // This prevents an issue where we wouldn't respond when errors were non-serializable
147
- this.commandStream.write({
148
- error: serializeError(rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
149
- id,
150
- jsonrpc: '2.0'
151
- });
152
- return;
153
- }
154
- this.commandStream.write({
155
- ...requestObject,
156
- id,
157
- jsonrpc: '2.0'
158
- });
159
- }
160
152
  /**
161
153
  * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
162
154
  * on errors.
@@ -272,16 +264,18 @@ export class BaseSnapExecutor {
272
264
  const request = async (args)=>{
273
265
  const sanitizedArgs = sanitizeRequestArguments(args);
274
266
  assertSnapOutboundRequest(sanitizedArgs);
275
- this.notify({
276
- method: 'OutboundRequest'
277
- });
278
- try {
279
- return await withTeardown(originalRequest(sanitizedArgs), this);
280
- } finally{
281
- this.notify({
282
- method: 'OutboundResponse'
267
+ return await withTeardown((async ()=>{
268
+ await _class_private_method_get(this, _notify, notify).call(this, {
269
+ method: 'OutboundRequest'
283
270
  });
284
- }
271
+ try {
272
+ return await originalRequest(sanitizedArgs);
273
+ } finally{
274
+ await _class_private_method_get(this, _notify, notify).call(this, {
275
+ method: 'OutboundResponse'
276
+ });
277
+ }
278
+ })(), this);
285
279
  };
286
280
  // Proxy target is intentionally set to be an empty object, to ensure
287
281
  // that access to the prototype chain is not possible.
@@ -310,16 +304,18 @@ export class BaseSnapExecutor {
310
304
  const request = async (args)=>{
311
305
  const sanitizedArgs = sanitizeRequestArguments(args);
312
306
  assertEthereumOutboundRequest(sanitizedArgs);
313
- this.notify({
314
- method: 'OutboundRequest'
315
- });
316
- try {
317
- return await withTeardown(originalRequest(sanitizedArgs), this);
318
- } finally{
319
- this.notify({
320
- method: 'OutboundResponse'
307
+ return await withTeardown((async ()=>{
308
+ await _class_private_method_get(this, _notify, notify).call(this, {
309
+ method: 'OutboundRequest'
321
310
  });
322
- }
311
+ try {
312
+ return await originalRequest(sanitizedArgs);
313
+ } finally{
314
+ await _class_private_method_get(this, _notify, notify).call(this, {
315
+ method: 'OutboundResponse'
316
+ });
317
+ }
318
+ })(), this);
323
319
  };
324
320
  const streamProviderProxy = proxyStreamProvider(provider, request);
325
321
  return harden(streamProviderProxy);
@@ -373,6 +369,12 @@ export class BaseSnapExecutor {
373
369
  }
374
370
  }
375
371
  constructor(commandStream, rpcStream){
372
+ // Awaitable function that writes back to the command stream
373
+ // To prevent snap execution from blocking writing we wrap in a promise
374
+ // and await it before continuing execution
375
+ _class_private_method_init(this, _write);
376
+ _class_private_method_init(this, _notify);
377
+ _class_private_method_init(this, _respond);
376
378
  _define_property(this, "snapData", void 0);
377
379
  _define_property(this, "commandStream", void 0);
378
380
  _define_property(this, "rpcStream", void 0);
@@ -416,5 +418,42 @@ export class BaseSnapExecutor {
416
418
  }, this.onTerminate.bind(this));
417
419
  }
418
420
  }
421
+ async function write(chunk) {
422
+ return new Promise((resolve, reject)=>{
423
+ this.commandStream.write(chunk, (error)=>{
424
+ if (error) {
425
+ reject(error);
426
+ return;
427
+ }
428
+ resolve();
429
+ });
430
+ });
431
+ }
432
+ async function notify(requestObject) {
433
+ if (!isValidJson(requestObject) || !isObject(requestObject)) {
434
+ throw rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
435
+ }
436
+ await _class_private_method_get(this, _write, write).call(this, {
437
+ ...requestObject,
438
+ jsonrpc: '2.0'
439
+ });
440
+ }
441
+ async function respond(id, requestObject) {
442
+ if (!isValidJson(requestObject) || !isObject(requestObject)) {
443
+ // Instead of throwing, we directly respond with an error.
444
+ // This prevents an issue where we wouldn't respond when errors were non-serializable
445
+ await _class_private_method_get(this, _write, write).call(this, {
446
+ error: serializeError(rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
447
+ id,
448
+ jsonrpc: '2.0'
449
+ });
450
+ return;
451
+ }
452
+ await _class_private_method_get(this, _write, write).call(this, {
453
+ ...requestObject,
454
+ id,
455
+ jsonrpc: '2.0'
456
+ });
457
+ }
419
458
 
420
459
  //# sourceMappingURL=BaseSnapExecutor.js.map