@metamask/snaps-controllers 0.36.0-flask.1 → 0.37.0-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/dist/cjs/cronjob/CronjobController.js.map +1 -1
- package/dist/cjs/fsm.js.map +1 -1
- package/dist/cjs/services/AbstractExecutionService.js.map +1 -1
- package/dist/cjs/services/ExecutionService.js.map +1 -1
- package/dist/cjs/services/ProxyPostMessageStream.js.map +1 -1
- package/dist/cjs/services/iframe/IframeExecutionService.js.map +1 -1
- package/dist/cjs/services/node/NodeProcessExecutionService.js.map +1 -1
- package/dist/cjs/services/node/NodeThreadExecutionService.js.map +1 -1
- package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +1 -1
- package/dist/cjs/services/webworker/WebWorkerExecutionService.js.map +1 -1
- package/dist/cjs/snaps/SnapController.js.map +1 -1
- package/dist/cjs/snaps/endowments/cronjob.js.map +1 -1
- package/dist/cjs/snaps/endowments/ethereum-provider.js.map +1 -1
- package/dist/cjs/snaps/endowments/index.js.map +1 -1
- package/dist/cjs/snaps/endowments/long-running.js.map +1 -1
- package/dist/cjs/snaps/endowments/network-access.js.map +1 -1
- package/dist/cjs/snaps/endowments/rpc.js.map +1 -1
- package/dist/cjs/snaps/endowments/transaction-insight.js.map +1 -1
- package/dist/cjs/snaps/endowments/web-assembly.js.map +1 -1
- package/dist/cjs/snaps/location/http.js.map +1 -1
- package/dist/cjs/snaps/location/local.js.map +1 -1
- package/dist/cjs/snaps/location/location.js.map +1 -1
- package/dist/cjs/snaps/location/npm.js.map +1 -1
- package/dist/cjs/snaps/permissions.js.map +1 -1
- package/dist/cjs/snaps/registry/json.js.map +1 -1
- package/dist/cjs/snaps/registry/registry.js.map +1 -1
- package/dist/cjs/snaps/selectors.js.map +1 -1
- package/dist/cjs/utils.js.map +1 -1
- package/dist/esm/cronjob/CronjobController.js.map +1 -1
- package/dist/esm/fsm.js.map +1 -1
- package/dist/esm/services/AbstractExecutionService.js.map +1 -1
- package/dist/esm/services/ExecutionService.js.map +1 -1
- package/dist/esm/services/ProxyPostMessageStream.js.map +1 -1
- package/dist/esm/services/iframe/IframeExecutionService.js.map +1 -1
- package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -1
- package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -1
- package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -1
- package/dist/esm/services/webworker/WebWorkerExecutionService.js.map +1 -1
- package/dist/esm/snaps/SnapController.js.map +1 -1
- package/dist/esm/snaps/endowments/cronjob.js.map +1 -1
- package/dist/esm/snaps/endowments/ethereum-provider.js.map +1 -1
- package/dist/esm/snaps/endowments/index.js.map +1 -1
- package/dist/esm/snaps/endowments/long-running.js.map +1 -1
- package/dist/esm/snaps/endowments/network-access.js.map +1 -1
- package/dist/esm/snaps/endowments/rpc.js.map +1 -1
- package/dist/esm/snaps/endowments/transaction-insight.js.map +1 -1
- package/dist/esm/snaps/endowments/web-assembly.js.map +1 -1
- package/dist/esm/snaps/location/http.js.map +1 -1
- package/dist/esm/snaps/location/local.js.map +1 -1
- package/dist/esm/snaps/location/location.js.map +1 -1
- package/dist/esm/snaps/location/npm.js.map +1 -1
- package/dist/esm/snaps/permissions.js.map +1 -1
- package/dist/esm/snaps/registry/json.js.map +1 -1
- package/dist/esm/snaps/registry/registry.js.map +1 -1
- package/dist/esm/snaps/selectors.js.map +1 -1
- package/dist/esm/utils.js +2 -2
- package/dist/esm/utils.js.map +1 -1
- package/dist/types/cronjob/CronjobController.d.ts +5 -4
- package/dist/types/fsm.d.ts +1 -1
- package/dist/types/services/AbstractExecutionService.d.ts +4 -4
- package/dist/types/services/ExecutionService.d.ts +3 -3
- package/dist/types/services/ProxyPostMessageStream.d.ts +1 -1
- package/dist/types/services/iframe/IframeExecutionService.d.ts +3 -2
- package/dist/types/services/node/NodeProcessExecutionService.d.ts +4 -3
- package/dist/types/services/node/NodeThreadExecutionService.d.ts +3 -2
- package/dist/types/services/offscreen/OffscreenExecutionService.d.ts +2 -1
- package/dist/types/services/webworker/WebWorkerExecutionService.d.ts +2 -1
- package/dist/types/snaps/SnapController.d.ts +13 -10
- package/dist/types/snaps/endowments/cronjob.d.ts +5 -3
- package/dist/types/snaps/endowments/ethereum-provider.d.ts +2 -1
- package/dist/types/snaps/endowments/index.d.ts +2 -2
- package/dist/types/snaps/endowments/long-running.d.ts +2 -1
- package/dist/types/snaps/endowments/network-access.d.ts +2 -1
- package/dist/types/snaps/endowments/rpc.d.ts +5 -3
- package/dist/types/snaps/endowments/transaction-insight.d.ts +3 -2
- package/dist/types/snaps/endowments/web-assembly.d.ts +2 -1
- package/dist/types/snaps/location/http.d.ts +3 -2
- package/dist/types/snaps/location/local.d.ts +3 -3
- package/dist/types/snaps/location/location.d.ts +2 -2
- package/dist/types/snaps/location/npm.d.ts +4 -3
- package/dist/types/snaps/permissions.d.ts +2 -2
- package/dist/types/snaps/registry/json.d.ts +5 -4
- package/dist/types/snaps/registry/registry.d.ts +3 -3
- package/dist/types/snaps/selectors.d.ts +2 -2
- package/dist/types/utils.d.ts +14 -14
- package/package.json +10 -9
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.37.0-flask.1]
|
|
10
|
+
### Changed
|
|
11
|
+
- No changes this release.
|
|
12
|
+
|
|
13
|
+
## [0.36.1-flask.1]
|
|
14
|
+
### Changed
|
|
15
|
+
- No changes this release.
|
|
16
|
+
|
|
9
17
|
## [0.36.0-flask.1]
|
|
10
18
|
### Changed
|
|
11
19
|
- Allow omitting `jsonrpc` and `id` in `handleRequest` ([#1556](https://github.com/MetaMask/snaps/pull/1556))
|
|
@@ -547,7 +555,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
547
555
|
### Added
|
|
548
556
|
- First semi-stable release.
|
|
549
557
|
|
|
550
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/v0.
|
|
558
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/v0.37.0-flask.1...HEAD
|
|
559
|
+
[0.37.0-flask.1]: https://github.com/MetaMask/snaps/compare/v0.36.1-flask.1...v0.37.0-flask.1
|
|
560
|
+
[0.36.1-flask.1]: https://github.com/MetaMask/snaps/compare/v0.36.0-flask.1...v0.36.1-flask.1
|
|
551
561
|
[0.36.0-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.2-flask.1...v0.36.0-flask.1
|
|
552
562
|
[0.35.2-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.1-flask.1...v0.35.2-flask.1
|
|
553
563
|
[0.35.1-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.0-flask.1...v0.35.1-flask.1
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import {\n BaseControllerV2 as BaseController,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { GetPermissions } from '@metamask/permission-controller';\nimport {\n HandlerType,\n SnapId,\n ValidatedSnapId,\n TruncatedSnap,\n CronjobSpecification,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport {\n GetAllSnaps,\n getRunnableSnaps,\n HandleSnapRequest,\n SnapEndowments,\n SnapInstalled,\n SnapRemoved,\n SnapUpdated,\n} from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents = SnapInstalled | SnapRemoved | SnapUpdated;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: ValidatedSnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleEventSnapInstalled = this._handleEventSnapInstalled.bind(this);\n this._handleEventSnapRemoved = this._handleEventSnapRemoved.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleEventSnapInstalled,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapRemoved',\n this._handleEventSnapRemoved,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: ValidatedSnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: ValidatedSnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necesary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleEventSnapInstalled,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapRemoved',\n this._handleEventSnapRemoved,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle cron jobs on 'snapInstalled' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapInstalled(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapRemoved' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapRemoved(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["DAILY_TIMEOUT","CronjobController","inMilliseconds","Duration","Hour","controllerName","BaseController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","getRunnableSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","SnapEndowments","Cronjob","definitions","getCronjobCaveatJobs","definition","idx","register","forEach","schedule","timers","has","parsed","parseCronExpression","expression","next","now","Date","ms","getTime","timer","Timer","start","executeCronjob","catch","error","logError","delete","updateJobLastRunState","set","snapIds","origin","handler","HandlerType","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","lastRun","update","state","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleEventSnapInstalled","_handleEventSnapRemoved","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;IA2CaA,aAAa;eAAbA;;IA8BAC,iBAAiB;eAAjBA;;;gCAtEN;4BAUA;uBACkC;kBAUlC;yBAC8B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O,IAAI,CAAC,IAAI;QAErE,2BAA2B;QAC3B,oDAAoD,GACpD,IAAI,CAAC9E,eAAe,CAAC+E,SAAS,CAC5B,gCACA,IAAI,CAACV,yBAAyB;QAGhC,IAAI,CAACrE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACT,uBAAuB;QAG9B,IAAI,CAACtE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGvB,KAAK,CAAC,CAACC;YACzBC,IAAAA,oBAAQ,EAACD;QACX;IACF;AAoOF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type {\n SnapId,\n ValidatedSnapId,\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapInstalled,\n SnapRemoved,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents = SnapInstalled | SnapRemoved | SnapUpdated;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: ValidatedSnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleEventSnapInstalled = this._handleEventSnapInstalled.bind(this);\n this._handleEventSnapRemoved = this._handleEventSnapRemoved.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleEventSnapInstalled,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapRemoved',\n this._handleEventSnapRemoved,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: ValidatedSnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: ValidatedSnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necesary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleEventSnapInstalled,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapRemoved',\n this._handleEventSnapRemoved,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle cron jobs on 'snapInstalled' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapInstalled(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapRemoved' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapRemoved(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["DAILY_TIMEOUT","CronjobController","inMilliseconds","Duration","Hour","controllerName","BaseController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","getRunnableSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","SnapEndowments","Cronjob","definitions","getCronjobCaveatJobs","definition","idx","register","forEach","schedule","timers","has","parsed","parseCronExpression","expression","next","now","Date","ms","getTime","timer","Timer","start","executeCronjob","catch","error","logError","delete","updateJobLastRunState","set","snapIds","origin","handler","HandlerType","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","lastRun","update","state","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleEventSnapInstalled","_handleEventSnapRemoved","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;IA0CaA,aAAa;eAAbA;;IA8BAC,iBAAiB;eAAjBA;;;gCAvEsC;4BAY5C;uBACkC;kBASQ;yBACZ;uBACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBf,MAAMD,gBAAgBE,IAAAA,qBAAc,EAAC,IAAIC,eAAQ,CAACC,IA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B;QAGhC,IAAI,CAACrE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACT,uBAAuB;QAG9B,IAAI,CAACtE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGvB,KAAK,CAAC,CAACC;YACzBC,IAAAA,oBAAQ,EAACD;QACX;IACF;AAoOF"}
|
package/dist/cjs/fsm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/fsm.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/fsm.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport type { EventObject, StateMachine, Typestate } from '@xstate/fsm';\nimport { InterpreterStatus } from '@xstate/fsm';\n\n/**\n * Validates the set-up of a @xstate/fsm machine.\n *\n * 1. Ensures that all named actions in the config have a provided implementation.\n *\n * @param machine - The machine to validate.\n * @throws {@link AssertionError}. If the validation fails.\n */\nexport function validateMachine<\n TContext extends object,\n TEvent extends EventObject,\n TState extends Typestate<TContext>,\n>(machine: StateMachine.Machine<TContext, TEvent, TState>) {\n assert('_options' in machine, 'The machine is not an @xstate/fsm machine');\n const typed = machine as StateMachine.Machine<TContext, TEvent, TState> & {\n _options: { actions?: StateMachine.ActionMap<TContext, TEvent> };\n };\n\n // 1.\n const toArray = <Type>(obj: Type | Type[]): Type[] => {\n if (Array.isArray(obj)) {\n return obj;\n } else if (obj === undefined || obj === null) {\n return [];\n }\n return [obj];\n };\n\n const allActions = new Set<string>();\n const addActions = (actions: any) =>\n toArray(actions)\n .flatMap((action) => {\n if (typeof action === 'string') {\n return [action];\n }\n assert(typeof action === 'function');\n return [];\n })\n .forEach(allActions.add.bind(allActions));\n\n for (const state of Object.values<typeof typed.config.states[string]>(\n typed.config.states,\n )) {\n addActions(state.entry);\n addActions(state.exit);\n for (const transition of Object.values<any>(state.on ?? {})) {\n addActions(transition.actions);\n }\n }\n\n allActions.forEach((action) =>\n assert(\n typed._options.actions !== undefined && action in typed._options.actions,\n `Action \"${action}\" doesn't have an implementation`,\n ),\n );\n}\n\n/**\n * Ensure that the interpreter is strict.\n * Strict means that the transition must occur.\n * The event must exist in .on {} state config and it's guard must succeed.\n *\n * The error will be thrown when an invalid `interpreter.send()` is called\n * and will be bubbled there.\n *\n * TODO(ritave): Doesn't support self transitions.\n *\n * @param interpreter - The interpreter that will be force into strict mode.\n * @throws {@link Error} Thrown when the transition is invalid.\n */\nexport function forceStrict(interpreter: StateMachine.Service<any, any, any>) {\n // As soon as a listener subscribes, it is called. It might be called in\n // an initial state which doesn't have the .changed property\n let onInitialCalled = false;\n interpreter.subscribe((state) => {\n assert(!onInitialCalled || state.changed, 'Invalid state transition');\n onInitialCalled = true;\n });\n\n const ogSend = interpreter.send.bind(interpreter);\n interpreter.send = (...args) => {\n assert(\n interpreter.status === InterpreterStatus.Running,\n 'Interpreter is stopped',\n );\n return ogSend(...args);\n };\n}\n"],"names":["validateMachine","forceStrict","machine","assert","typed","toArray","obj","Array","isArray","undefined","allActions","Set","addActions","actions","flatMap","action","forEach","add","bind","state","Object","values","config","states","entry","exit","transition","on","_options","interpreter","onInitialCalled","subscribe","changed","ogSend","send","args","status","InterpreterStatus","Running"],"mappings":";;;;;;;;;;;IAYgBA,eAAe;eAAfA;;IA+DAC,WAAW;eAAXA;;;uBA3EO;qBAEW;AAU3B,SAASD,gBAIdE,OAAuD;IACvDC,IAAAA,aAAM,EAAC,cAAcD,SAAS;IAC9B,MAAME,QAAQF;IAId,KAAK;IACL,MAAMG,UAAU,CAAOC;QACrB,IAAIC,MAAMC,OAAO,CAACF,MAAM;YACtB,OAAOA;QACT,OAAO,IAAIA,QAAQG,aAAaH,QAAQ,MAAM;YAC5C,OAAO,EAAE;QACX;QACA,OAAO;YAACA;SAAI;IACd;IAEA,MAAMI,aAAa,IAAIC;IACvB,MAAMC,aAAa,CAACC,UAClBR,QAAQQ,SACLC,OAAO,CAAC,CAACC;YACR,IAAI,OAAOA,WAAW,UAAU;gBAC9B,OAAO;oBAACA;iBAAO;YACjB;YACAZ,IAAAA,aAAM,EAAC,OAAOY,WAAW;YACzB,OAAO,EAAE;QACX,GACCC,OAAO,CAACN,WAAWO,GAAG,CAACC,IAAI,CAACR;IAEjC,KAAK,MAAMS,SAASC,OAAOC,MAAM,CAC/BjB,MAAMkB,MAAM,CAACC,MAAM,EAClB;QACDX,WAAWO,MAAMK,KAAK;QACtBZ,WAAWO,MAAMM,IAAI;QACrB,KAAK,MAAMC,cAAcN,OAAOC,MAAM,CAAMF,MAAMQ,EAAE,IAAI,CAAC,GAAI;YAC3Df,WAAWc,WAAWb,OAAO;QAC/B;IACF;IAEAH,WAAWM,OAAO,CAAC,CAACD,SAClBZ,IAAAA,aAAM,EACJC,MAAMwB,QAAQ,CAACf,OAAO,KAAKJ,aAAaM,UAAUX,MAAMwB,QAAQ,CAACf,OAAO,EACxE,CAAC,QAAQ,EAAEE,OAAO,gCAAgC,CAAC;AAGzD;AAeO,SAASd,YAAY4B,WAAgD;IAC1E,wEAAwE;IACxE,4DAA4D;IAC5D,IAAIC,kBAAkB;IACtBD,YAAYE,SAAS,CAAC,CAACZ;QACrBhB,IAAAA,aAAM,EAAC,CAAC2B,mBAAmBX,MAAMa,OAAO,EAAE;QAC1CF,kBAAkB;IACpB;IAEA,MAAMG,SAASJ,YAAYK,IAAI,CAAChB,IAAI,CAACW;IACrCA,YAAYK,IAAI,GAAG,CAAC,GAAGC;QACrBhC,IAAAA,aAAM,EACJ0B,YAAYO,MAAM,KAAKC,sBAAiB,CAACC,OAAO,EAChD;QAEF,OAAOL,UAAUE;IACnB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/AbstractExecutionService.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport { BasePostMessageStream } from '@metamask/post-message-stream';\nimport {\n SnapRpcHook,\n SnapRpcHookArgs,\n SNAP_STREAM_NAMES,\n logError,\n} from '@metamask/snaps-utils';\nimport {\n Duration,\n isJsonRpcNotification,\n isObject,\n Json,\n JsonRpcNotification,\n} from '@metamask/utils';\nimport {\n JsonRpcEngine,\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport pump from 'pump';\nimport { Duplex } from 'stream';\n\nimport { log } from '../logging';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport {\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 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 #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = 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.#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 pump(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream);\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 // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\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<unknown>\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 as unknown as Duplex,\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 const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\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<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\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<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\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,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n /**\n * Gets the job id for a given snap.\n *\n * @param snapId - A given snap id.\n * @returns The ID of the snap's job.\n */\n #getJobForSnap(snapId: string): string | undefined {\n return this.#snapToJobMap.get(snapId);\n }\n\n /**\n * Gets the snap id for a given job.\n *\n * @param jobId - A given job id.\n * @returns The ID of the snap that is running the job.\n */\n #getSnapForJob(jobId: string): string | undefined {\n return this.#jobToSnapMap.get(jobId);\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 = await 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 pump(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"],"names":["AbstractExecutionService","setupMultiplex","controllerName","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","withTimeout","command","jsonrpc","method","params","id","nanoid","terminationTimeout","hasTimedOut","logError","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","log","initJob","worker","initStreams","rpcEngine","JsonRpcEngine","jsonRpcConnection","createStreamMiddleware","pump","push","middleware","envMetadata","set","envStream","initEnvStream","mux","commandStream","createStream","SNAP_STREAM_NAMES","COMMAND","notificationHandler","message","isJsonRpcNotification","jobToSnapMap","publish","isObject","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","rpcRequestHandler","constructor","Duration","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName","ObjectMultiplex"],"mappings":";;;;;;;;;;;IA0DsBA,wBAAwB;eAAxBA;;IAgaNC,cAAc;eAAdA;;;wEA1dY;4BAOrB;uBAOA;+BAMA;yCACgC;wBAChB;6DACN;yBAGG;wBACqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQzC,MAAMC,iBAAiB;IA0BrB,6CAQA,6CAEA,6CAEA,0CAEA,mDAuTA,gDAIA,gDAkBA;;;;;GAKC,GACD,8CAIA;;;;;GAKC,GACD,8CAIA,8CAKA;AAvXK,MAAeF;IAmCpB;;;GAGC,GACD,AAAQG,0BAAgC;QACtC,yBAAA,IAAI,EAAEC,YAAUC,qBAAqB,CACnC,CAAC,EAAEH,eAAe,iBAAiB,CAAC,EACpC,OAAOI,QAAgBC,UACrB,IAAI,CAACC,gBAAgB,CAACF,QAAQC;QAGlC,yBAAA,IAAI,EAAEH,YAAUC,qBAAqB,CACnC,CAAC,EAAEH,eAAe,YAAY,CAAC,EAC/B,OAAOO,WAAgC,IAAI,CAACC,WAAW,CAACD;QAG1D,yBAAA,IAAI,EAAEL,YAAUC,qBAAqB,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stractExecutionService.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcNotification } from '@metamask/utils';\nimport { Duration, isJsonRpcNotification, isObject } from '@metamask/utils';\nimport type {\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { JsonRpcEngine } from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport pump from 'pump';\nimport type { Duplex } from '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 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 #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = 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.#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 pump(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream);\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 // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\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<unknown>\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 as unknown as Duplex,\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 const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\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<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\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<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\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,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n /**\n * Gets the job id for a given snap.\n *\n * @param snapId - A given snap id.\n * @returns The ID of the snap's job.\n */\n #getJobForSnap(snapId: string): string | undefined {\n return this.#snapToJobMap.get(snapId);\n }\n\n /**\n * Gets the snap id for a given job.\n *\n * @param jobId - A given job id.\n * @returns The ID of the snap that is running the job.\n */\n #getSnapForJob(jobId: string): string | undefined {\n return this.#jobToSnapMap.get(jobId);\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 = await 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 pump(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"],"names":["AbstractExecutionService","setupMultiplex","controllerName","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","withTimeout","command","jsonrpc","method","params","id","nanoid","terminationTimeout","hasTimedOut","logError","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","log","initJob","worker","initStreams","rpcEngine","JsonRpcEngine","jsonRpcConnection","createStreamMiddleware","pump","push","middleware","envMetadata","set","envStream","initEnvStream","mux","commandStream","createStream","SNAP_STREAM_NAMES","COMMAND","notificationHandler","message","isJsonRpcNotification","jobToSnapMap","publish","isObject","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","rpcRequestHandler","constructor","Duration","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName","ObjectMultiplex"],"mappings":";;;;;;;;;;;IAiDsBA,wBAAwB;eAAxBA;;IAgaNC,cAAc;eAAdA;;;wEAjdY;4BAGgB;uBAEc;+BAM5B;yCACS;wBAChB;6DACN;yBAGG;wBACqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQzC,MAAMC,iBAAiB;IA0BrB,6CAQA,6CAEA,6CAEA,0CAEA,mDAuTA,gDAIA,gDAkBA;;;;;GAKC,GACD,8CAIA;;;;;GAKC,GACD,8CAIA,8CAKA;AAvXK,MAAeF;IAmCpB;;;GAGC,GACD,AAAQG,0BAAgC;QACtC,yBAAA,IAAI,EAAEC,YAAUC,qBAAqB,CACnC,CAAC,EAAEH,eAAe,iBAAiB,CAAC,EACpC,OAAOI,QAAgBC,UACrB,IAAI,CAACC,gBAAgB,CAACF,QAAQC;QAGlC,yBAAA,IAAI,E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,CAAC,CAAC,EAAEyE,WAAW,iBAAiB,CAAC,EAAEhE,SAC5CT,IAAAA,oBAAQ,EAACS;QACf;IACF;IAEF,OAAOmB;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/ExecutionService.ts"],"sourcesContent":["import { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { SnapId, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { Json } from '@metamask/types';\n\ntype TerminateSnap = (snapId: string) => Promise<void>;\ntype TerminateAll = () => Promise<void>;\ntype ExecuteSnap = (snapData: SnapExecutionData) => Promise<unknown>;\n\ntype HandleRpcRequest = (\n snapId: string,\n options: SnapRpcHookArgs,\n) => Promise<unknown>;\n\nexport interface ExecutionService {\n terminateSnap: TerminateSnap;\n terminateAllSnaps: TerminateAll;\n executeSnap: ExecuteSnap;\n handleRpcRequest: HandleRpcRequest;\n}\n\nexport type SnapExecutionData = {\n snapId: string;\n sourceCode: string;\n endowments?: Json;\n};\n\nexport type SnapErrorJson = {\n message: string;\n code: number;\n data?: Json;\n};\n\nconst controllerName = 'ExecutionService';\n\nexport type ErrorMessageEvent = {\n type: 'ExecutionService:unhandledError';\n payload: [SnapId, SnapErrorJson];\n};\n\nexport type OutboundRequest = {\n type: 'ExecutionService:outboundRequest';\n payload: [SnapId];\n};\n\nexport type OutboundResponse = {\n type: 'ExecutionService:outboundResponse';\n payload: [SnapId];\n};\n\nexport type ExecutionServiceEvents =\n | ErrorMessageEvent\n | OutboundRequest\n | OutboundResponse;\n\n/**\n * Handles RPC request.\n */\nexport type HandleRpcRequestAction = {\n type: `${typeof controllerName}:handleRpcRequest`;\n handler: ExecutionService['handleRpcRequest'];\n};\n\n/**\n * Executes a given snap.\n */\nexport type ExecuteSnapAction = {\n type: `${typeof controllerName}:executeSnap`;\n handler: ExecutionService['executeSnap'];\n};\n\n/**\n * Terminates a given snap.\n */\nexport type TerminateSnapAction = {\n type: `${typeof controllerName}:terminateSnap`;\n handler: ExecutionService['terminateSnap'];\n};\n\n/**\n * Terminates all snaps.\n */\nexport type TerminateAllSnapsAction = {\n type: `${typeof controllerName}:terminateAllSnaps`;\n handler: ExecutionService['terminateAllSnaps'];\n};\n\nexport type ExecutionServiceActions =\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateSnapAction\n | TerminateAllSnapsAction;\n\nexport type ExecutionServiceMessenger = RestrictedControllerMessenger<\n 'ExecutionService',\n ExecutionServiceActions,\n ExecutionServiceEvents,\n ExecutionServiceActions['type'],\n ExecutionServiceEvents['type']\n>;\n"],"names":["controllerName"],"mappings":";;;;AAgCA,MAAMA,iBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/ExecutionService.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport type { SnapId, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/types';\n\ntype TerminateSnap = (snapId: string) => Promise<void>;\ntype TerminateAll = () => Promise<void>;\ntype ExecuteSnap = (snapData: SnapExecutionData) => Promise<unknown>;\n\ntype HandleRpcRequest = (\n snapId: string,\n options: SnapRpcHookArgs,\n) => Promise<unknown>;\n\nexport interface ExecutionService {\n terminateSnap: TerminateSnap;\n terminateAllSnaps: TerminateAll;\n executeSnap: ExecuteSnap;\n handleRpcRequest: HandleRpcRequest;\n}\n\nexport type SnapExecutionData = {\n snapId: string;\n sourceCode: string;\n endowments?: Json;\n};\n\nexport type SnapErrorJson = {\n message: string;\n code: number;\n data?: Json;\n};\n\nconst controllerName = 'ExecutionService';\n\nexport type ErrorMessageEvent = {\n type: 'ExecutionService:unhandledError';\n payload: [SnapId, SnapErrorJson];\n};\n\nexport type OutboundRequest = {\n type: 'ExecutionService:outboundRequest';\n payload: [SnapId];\n};\n\nexport type OutboundResponse = {\n type: 'ExecutionService:outboundResponse';\n payload: [SnapId];\n};\n\nexport type ExecutionServiceEvents =\n | ErrorMessageEvent\n | OutboundRequest\n | OutboundResponse;\n\n/**\n * Handles RPC request.\n */\nexport type HandleRpcRequestAction = {\n type: `${typeof controllerName}:handleRpcRequest`;\n handler: ExecutionService['handleRpcRequest'];\n};\n\n/**\n * Executes a given snap.\n */\nexport type ExecuteSnapAction = {\n type: `${typeof controllerName}:executeSnap`;\n handler: ExecutionService['executeSnap'];\n};\n\n/**\n * Terminates a given snap.\n */\nexport type TerminateSnapAction = {\n type: `${typeof controllerName}:terminateSnap`;\n handler: ExecutionService['terminateSnap'];\n};\n\n/**\n * Terminates all snaps.\n */\nexport type TerminateAllSnapsAction = {\n type: `${typeof controllerName}:terminateAllSnaps`;\n handler: ExecutionService['terminateAllSnaps'];\n};\n\nexport type ExecutionServiceActions =\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateSnapAction\n | TerminateAllSnapsAction;\n\nexport type ExecutionServiceMessenger = RestrictedControllerMessenger<\n 'ExecutionService',\n ExecutionServiceActions,\n ExecutionServiceEvents,\n ExecutionServiceActions['type'],\n ExecutionServiceEvents['type']\n>;\n"],"names":["controllerName"],"mappings":";;;;AAgCA,MAAMA,iBAAiB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/ProxyPostMessageStream.ts"],"sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n readonly #extra?: Record<string, unknown>;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n * @param args.extra - Extra data to include in the post message.\n */\n constructor({ stream, jobId, extra }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n this.#extra = extra;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n extra: this.#extra,\n });\n }\n}\n"],"names":["ProxyPostMessageStream","BasePostMessageStream","_postMessage","data","stream","write","jobId","extra","constructor","on","onData","bind","push"],"mappings":";;;;+BAmBaA;;;eAAAA;;;mCAnByB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoB3B,uCAEA,sCAEA,sCAoBT;;;;;GAKC,GACD;AA/BK,MAAMA,+BAA+BC,wCAAqB;IAuC/D;;;;;GAKC,GACDC,aAAaC,IAAsB,EAAE;QACnC,yBAAA,IAAI,EAAEC,SAAOC,KAAK,CAAC;YACjBC,KAAK,2BAAE,IAAI,EAAEA;YACbH;YACAI,KAAK,2BAAE,IAAI,EAAEA;QACf;IACF;IA5CA;;;;;;;GAOC,GACDC,YAAY,EAAEJ,MAAM,EAAEE,KAAK,EAAEC,KAAK,EAA8B,CAAE;QAChE,KAAK;QAeP,iCAAA;QA9BA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;uCAaQH,SAASA;uCACTE,QAAQA;uCACRC,QAAQA;QAEd,yBAAA,IAAI,EAAEH,SAAOK,EAAE,CAAC,QAAQ,0BAAA,IAAI,EAAEC,SAAAA,QAAOC,IAAI,CAAC,IAAI;IAChD;AA6BF;AArBE,SAAA,OAAQR,IAAsB;IAC5B,IAAIA,KAAKG,KAAK,8BAAK,IAAI,EAAEA,SAAO;QAC9B;IACF;IAEA,IAAI,CAACM,IAAI,CAACT,KAAKA,IAAI;AACrB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/ProxyPostMessageStream.ts"],"sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n readonly #extra?: Record<string, unknown>;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n * @param args.extra - Extra data to include in the post message.\n */\n constructor({ stream, jobId, extra }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n this.#extra = extra;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n extra: this.#extra,\n });\n }\n}\n"],"names":["ProxyPostMessageStream","BasePostMessageStream","_postMessage","data","stream","write","jobId","extra","constructor","on","onData","bind","push"],"mappings":";;;;+BAmBaA;;;eAAAA;;;mCAnByB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoB3B,uCAEA,sCAEA,sCAoBT;;;;;GAKC,GACD;AA/BK,MAAMA,+BAA+BC,wCAAqB;IAuC/D;;;;;GAKC,GACDC,aAAaC,IAAsB,EAAE;QACnC,yBAAA,IAAI,EAAEC,SAAOC,KAAK,CAAC;YACjBC,KAAK,2BAAE,IAAI,EAAEA;YACbH;YACAI,KAAK,2BAAE,IAAI,EAAEA;QACf;IACF;IA5CA;;;;;;;GAOC,GACDC,YAAY,EAAEJ,MAAM,EAAEE,KAAK,EAAEC,KAAK,EAA8B,CAAE;QAChE,KAAK;QAeP,iCAAA;QA9BA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;uCAaQH,SAASA;uCACTE,QAAQA;uCACRC,QAAQA;QAEd,yBAAA,IAAI,EAAEH,SAAOK,EAAE,CAAC,QAAQ,0BAAA,IAAI,EAAEC,SAAAA,QAAOC,IAAI,CAAC,IAAI;IAChD;AA6BF;AArBE,SAAA,OAAQR,IAAsB;IAC5B,IAAIA,KAAKG,KAAK,8BAAK,IAAI,EAAEA,SAAO;QAC9B;IACF;IAEA,IAAI,CAACM,IAAI,CAACT,KAAKA,IAAI;AACrB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/services/iframe/IframeExecutionService.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../src/services/iframe/IframeExecutionService.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\nimport { createWindow } from '@metamask/snaps-utils';\n\nimport type { Job, ExecutionServiceArgs } from '../AbstractExecutionService';\nimport { AbstractExecutionService } from '../AbstractExecutionService';\n\ntype IframeExecutionEnvironmentServiceArgs = {\n iframeUrl: URL;\n} & ExecutionServiceArgs;\n\nexport class IframeExecutionService extends AbstractExecutionService<Window> {\n public iframeUrl: URL;\n\n constructor({\n iframeUrl,\n messenger,\n setupSnapProvider,\n }: IframeExecutionEnvironmentServiceArgs) {\n super({\n messenger,\n setupSnapProvider,\n });\n this.iframeUrl = iframeUrl;\n }\n\n protected terminateJob(jobWrapper: Job<Window>): void {\n document.getElementById(jobWrapper.id)?.remove();\n }\n\n protected async initEnvStream(jobId: string): Promise<{\n worker: Window;\n stream: BasePostMessageStream;\n }> {\n const iframeWindow = await createWindow(this.iframeUrl.toString(), jobId);\n\n const stream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: iframeWindow,\n targetOrigin: '*',\n });\n\n return { worker: iframeWindow, stream };\n }\n}\n"],"names":["IframeExecutionService","AbstractExecutionService","terminateJob","jobWrapper","document","getElementById","id","remove","initEnvStream","jobId","iframeWindow","createWindow","iframeUrl","toString","stream","WindowPostMessageStream","name","target","targetWindow","targetOrigin","worker","constructor","messenger","setupSnapProvider"],"mappings":";;;;+BAWaA;;;eAAAA;;;mCAV2B;4BACX;0CAGY;;;;;;;;;;;;;;AAMlC,MAAMA,+BAA+BC,kDAAwB;IAexDC,aAAaC,UAAuB,EAAQ;QACpDC,SAASC,cAAc,CAACF,WAAWG,EAAE,GAAGC;IAC1C;IAEA,MAAgBC,cAAcC,KAAa,EAGxC;QACD,MAAMC,eAAe,MAAMC,IAAAA,wBAAY,EAAC,IAAI,CAACC,SAAS,CAACC,QAAQ,IAAIJ;QAEnE,MAAMK,SAAS,IAAIC,0CAAuB,CAAC;YACzCC,MAAM;YACNC,QAAQ;YACRC,cAAcR;YACdS,cAAc;QAChB;QAEA,OAAO;YAAEC,QAAQV;YAAcI;QAAO;IACxC;IA9BAO,YAAY,EACVT,SAAS,EACTU,SAAS,EACTC,iBAAiB,EACqB,CAAE;QACxC,KAAK,CAAC;YACJD;YACAC;QACF;QAVF,uBAAOX,aAAP,KAAA;QAWE,IAAI,CAACA,SAAS,GAAGA;IACnB;AAqBF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/services/node/NodeProcessExecutionService.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../src/services/node/NodeProcessExecutionService.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { ProcessParentMessageStream } from '@metamask/post-message-stream';\nimport type { ChildProcess } from 'child_process';\nimport { fork } from 'child_process';\n\nimport type { Job } from '..';\nimport { AbstractExecutionService } from '..';\n\nexport class NodeProcessExecutionService extends AbstractExecutionService<ChildProcess> {\n protected async initEnvStream(): Promise<{\n worker: ChildProcess;\n stream: BasePostMessageStream;\n }> {\n const worker = fork(\n require.resolve(\n '@metamask/snaps-execution-environments/dist/browserify/node-process/bundle.js',\n ),\n );\n\n const stream = new ProcessParentMessageStream({ process: worker });\n return Promise.resolve({ worker, stream });\n }\n\n protected terminateJob(jobWrapper: Job<ChildProcess>): void {\n jobWrapper.worker.kill();\n }\n}\n"],"names":["NodeProcessExecutionService","AbstractExecutionService","initEnvStream","worker","fork","require","resolve","stream","ProcessParentMessageStream","process","Promise","terminateJob","jobWrapper","kill"],"mappings":";;;;+BAQaA;;;eAAAA;;;mCAP8B;+BAEtB;kBAGoB;AAElC,MAAMA,oCAAoCC,0BAAwB;IACvE,MAAgBC,gBAGb;QACD,MAAMC,SAASC,IAAAA,mBAAI,EACjBC,QAAQC,OAAO,CACb;QAIJ,MAAMC,SAAS,IAAIC,6CAA0B,CAAC;YAAEC,SAASN;QAAO;QAChE,OAAOO,QAAQJ,OAAO,CAAC;YAAEH;YAAQI;QAAO;IAC1C;IAEUI,aAAaC,UAA6B,EAAQ;QAC1DA,WAAWT,MAAM,CAACU,IAAI;IACxB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/services/node/NodeThreadExecutionService.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../src/services/node/NodeThreadExecutionService.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { ThreadParentMessageStream } from '@metamask/post-message-stream';\n// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { Worker } from 'worker_threads';\n\nimport type { Job } from '..';\nimport { AbstractExecutionService } from '..';\n\nexport class NodeThreadExecutionService extends AbstractExecutionService<Worker> {\n protected async initEnvStream(): Promise<{\n worker: Worker;\n stream: BasePostMessageStream;\n }> {\n const worker = new Worker(\n require.resolve(\n '@metamask/snaps-execution-environments/dist/browserify/node-thread/bundle.js',\n ),\n );\n const stream = new ThreadParentMessageStream({ thread: worker });\n return Promise.resolve({ worker, stream });\n }\n\n protected async terminateJob(jobWrapper: Job<Worker>): Promise<void> {\n await jobWrapper.worker.terminate();\n }\n}\n"],"names":["NodeThreadExecutionService","AbstractExecutionService","initEnvStream","worker","Worker","require","resolve","stream","ThreadParentMessageStream","thread","Promise","terminateJob","jobWrapper","terminate"],"mappings":";;;;+BAQaA;;;eAAAA;;;mCAP6B;gCAEnB;kBAGkB;AAElC,MAAMA,mCAAmCC,0BAAwB;IACtE,MAAgBC,gBAGb;QACD,MAAMC,SAAS,IAAIC,sBAAM,CACvBC,QAAQC,OAAO,CACb;QAGJ,MAAMC,SAAS,IAAIC,4CAAyB,CAAC;YAAEC,QAAQN;QAAO;QAC9D,OAAOO,QAAQJ,OAAO,CAAC;YAAEH;YAAQI;QAAO;IAC1C;IAEA,MAAgBI,aAAaC,UAAuB,EAAiB;QACnE,MAAMA,WAAWT,MAAM,CAACU,SAAS;IACnC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/services/offscreen/OffscreenExecutionService.ts"],"sourcesContent":["import { BrowserRuntimePostMessageStream } from '@metamask/post-message-stream';\nimport { nanoid } from 'nanoid';\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../src/services/offscreen/OffscreenExecutionService.ts"],"sourcesContent":["import { BrowserRuntimePostMessageStream } from '@metamask/post-message-stream';\nimport { nanoid } from 'nanoid';\n\nimport type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';\nimport { AbstractExecutionService } from '../AbstractExecutionService';\nimport { ProxyPostMessageStream } from '../ProxyPostMessageStream';\n\ntype OffscreenExecutionEnvironmentServiceArgs = {\n documentUrl: URL;\n frameUrl: URL;\n} & ExecutionServiceArgs;\n\nexport class OffscreenExecutionService extends AbstractExecutionService<string> {\n public readonly documentUrl: URL;\n\n public readonly frameUrl: URL;\n\n readonly #runtimeStream: BrowserRuntimePostMessageStream;\n\n /**\n * Create a new offscreen execution service.\n *\n * @param args - The constructor arguments.\n * @param args.documentUrl - The URL of the offscreen document to use as the\n * execution environment. This must be a URL relative to the location where\n * this is called. This cannot be a public (http(s)) URL.\n * @param args.frameUrl - The URL of the iframe to load inside the offscreen\n * document.\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 frameUrl,\n messenger,\n setupSnapProvider,\n }: OffscreenExecutionEnvironmentServiceArgs) {\n super({\n messenger,\n setupSnapProvider,\n });\n\n this.documentUrl = documentUrl;\n this.frameUrl = frameUrl;\n this.#runtimeStream = new BrowserRuntimePostMessageStream({\n name: 'parent',\n target: 'child',\n });\n }\n\n /**\n * Send a termination command to the offscreen 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 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 offscreen document.\n await this.createDocument();\n\n const stream = new ProxyPostMessageStream({\n stream: this.#runtimeStream,\n extra: {\n // TODO: Rather than injecting the frame URL here, we should come up\n // with a better way to do this. The frame URL is needed to avoid hard\n // coding it in the offscreen execution environment.\n frameUrl: this.frameUrl.toString(),\n },\n jobId,\n });\n\n return { worker: jobId, stream };\n }\n\n /**\n * Creates the offscreen document to be used as the execution environment.\n *\n * If the document already exists, this does nothing.\n */\n private async createDocument() {\n // Extensions can only have a single offscreen document.\n if (await chrome.offscreen.hasDocument()) {\n return;\n }\n\n await chrome.offscreen.createDocument({\n justification: 'MetaMask Snaps Execution Environment',\n reasons: ['IFRAME_SCRIPTING' as chrome.offscreen.Reason],\n url: this.documentUrl.toString(),\n });\n }\n}\n"],"names":["OffscreenExecutionService","AbstractExecutionService","terminateJob","job","runtimeStream","write","jobId","id","data","jsonrpc","method","nanoid","initEnvStream","createDocument","stream","ProxyPostMessageStream","extra","frameUrl","toString","worker","chrome","offscreen","hasDocument","justification","reasons","url","documentUrl","constructor","messenger","setupSnapProvider","BrowserRuntimePostMessageStream","name","target"],"mappings":";;;;+BAYaA;;;eAAAA;;;mCAZmC;wBACzB;0CAGkB;wCACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAY5B;AALJ,MAAMA,kCAAkCC,kDAAwB;IAwCrE;;;;GAIC,GACD,MAAgBC,aAAaC,GAAgB,EAAE;QAC7C,0EAA0E;QAC1E,8CAA8C;QAC9C,yBAAA,IAAI,EAAEC,gBAAcC,KAAK,CAAC;YACxBC,OAAOH,IAAII,EAAE;YACbC,MAAM;gBACJC,SAAS;gBACTC,QAAQ;gBACRH,IAAII,IAAAA,cAAM;YACZ;QACF;IACF;IAEA;;;;;GAKC,GACD,MAAgBC,cAAcN,KAAa,EAAE;QAC3C,wCAAwC;QACxC,MAAM,IAAI,CAACO,cAAc;QAEzB,MAAMC,SAAS,IAAIC,8CAAsB,CAAC;YACxCD,MAAM,2BAAE,IAAI,EAAEV;YACdY,OAAO;gBACL,oEAAoE;gBACpE,sEAAsE;gBACtE,oDAAoD;gBACpDC,UAAU,IAAI,CAACA,QAAQ,CAACC,QAAQ;YAClC;YACAZ;QACF;QAEA,OAAO;YAAEa,QAAQb;YAAOQ;QAAO;IACjC;IAEA;;;;GAIC,GACD,MAAcD,iBAAiB;QAC7B,wDAAwD;QACxD,IAAI,MAAMO,OAAOC,SAAS,CAACC,WAAW,IAAI;YACxC;QACF;QAEA,MAAMF,OAAOC,SAAS,CAACR,cAAc,CAAC;YACpCU,eAAe;YACfC,SAAS;gBAAC;aAA8C;YACxDC,KAAK,IAAI,CAACC,WAAW,CAACR,QAAQ;QAChC;IACF;IA3FA;;;;;;;;;;;;;GAaC,GACDS,YAAY,EACVD,WAAW,EACXT,QAAQ,EACRW,SAAS,EACTC,iBAAiB,EACwB,CAAE;QAC3C,KAAK,CAAC;YACJD;YACAC;QACF;QA7BF,uBAAgBH,eAAhB,KAAA;QAEA,uBAAgBT,YAAhB,KAAA;QAEA,gCAAS;;mBAAT,KAAA;;QA2BE,IAAI,CAACS,WAAW,GAAGA;QACnB,IAAI,CAACT,QAAQ,GAAGA;uCACVb,gBAAgB,IAAI0B,kDAA+B,CAAC;YACxDC,MAAM;YACNC,QAAQ;QACV;IACF;AA6DF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/services/webworker/WebWorkerExecutionService.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../src/services/webworker/WebWorkerExecutionService.ts"],"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"],"names":["WORKER_POOL_ID","WebWorkerExecutionService","AbstractExecutionService","terminateJob","job","assert","runtimeStream","write","jobId","id","data","jsonrpc","method","nanoid","initEnvStream","createDocument","stream","ProxyPostMessageStream","worker","document","getElementById","window","createWindow","documentUrl","href","WindowPostMessageStream","name","target","targetWindow","targetOrigin","constructor","messenger","setupSnapProvider"],"mappings":";;;;;;;;;;;IAcaA,cAAc;eAAdA;;IAEAC,yBAAyB;eAAzBA;;;mCAf2B;4BACX;uBACN;wBACA;0CAGkB;wCACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMhC,MAAMD,iBAAiB;IAG5B,4CAEA;AAHK,MAAMC,kCAAkCC,kDAAwB;IA6BrE;;;;GAIC,GACD,MAAgBC,aAAaC,GAAgB,EAAE;QAC7C,0EAA0E;QAC1E,8CAA8C;QAC9CC,IAAAA,aAAM,2BAAC,IAAI,EAAEC,iBAAe;QAC5B,yBAAA,IAAI,EAAEA,gBAAcC,KAAK,CAAC;YACxBC,OAAOJ,IAAIK,EAAE;YACbC,MAAM;gBACJC,SAAS;gBACTC,QAAQ;gBACRH,IAAII,IAAAA,cAAM;YACZ;QACF;IACF;IAEA;;;;;GAKC,GACD,MAAgBC,cAAcN,KAAa,EAAE;QAC3C,0CAA0C;QAC1C,MAAM,IAAI,CAACO,cAAc;QAEzB,+DAA+D;QAC/DV,IAAAA,aAAM,2BAAC,IAAI,EAAEC,iBAAe;QAE5B,MAAMU,SAAS,IAAIC,8CAAsB,CAAC;YACxCD,MAAM,2BAAE,IAAI,EAAEV;YACdE;QACF;QAEA,OAAO;YAAEU,QAAQV;YAAOQ;QAAO;IACjC;IAEA;;;;GAIC,GACD,MAAcD,iBAAiB;QAC7B,wCAAwC;QACxC,IAAII,SAASC,cAAc,CAACpB,iBAAiB;YAC3C;QACF;QAEA,MAAMqB,SAAS,MAAMC,IAAAA,wBAAY,EAC/B,yBAAA,IAAI,EAAEC,cAAY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