@metamask/snaps-controllers 4.1.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/dist/cjs/cronjob/CronjobController.js +3 -3
- package/dist/cjs/cronjob/CronjobController.js.map +1 -1
- package/dist/cjs/index.js +1 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/interface/SnapInterfaceController.js +166 -0
- package/dist/cjs/interface/SnapInterfaceController.js.map +1 -0
- package/dist/cjs/interface/index.js +20 -0
- package/dist/cjs/interface/index.js.map +1 -0
- package/dist/cjs/interface/utils.js +59 -0
- package/dist/cjs/interface/utils.js.map +1 -0
- package/dist/cjs/services/browser.js +1 -0
- package/dist/cjs/services/browser.js.map +1 -1
- package/dist/cjs/services/index.js +1 -0
- package/dist/cjs/services/index.js.map +1 -1
- package/dist/cjs/services/webview/WebViewExecutionService.js +99 -0
- package/dist/cjs/services/webview/WebViewExecutionService.js.map +1 -0
- package/dist/cjs/services/webview/WebViewMessageStream.js +127 -0
- package/dist/cjs/services/webview/WebViewMessageStream.js.map +1 -0
- package/dist/cjs/services/webview/index.js +20 -0
- package/dist/cjs/services/webview/index.js.map +1 -0
- package/dist/cjs/snaps/SnapController.js +111 -51
- package/dist/cjs/snaps/SnapController.js.map +1 -1
- package/dist/cjs/snaps/constants.js +25 -0
- package/dist/cjs/snaps/constants.js.map +1 -0
- package/dist/cjs/snaps/index.js +0 -2
- package/dist/cjs/snaps/index.js.map +1 -1
- package/dist/cjs/snaps/location/npm.js +13 -2
- package/dist/cjs/snaps/location/npm.js.map +1 -1
- package/dist/esm/cronjob/CronjobController.js +2 -2
- package/dist/esm/cronjob/CronjobController.js.map +1 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/interface/SnapInterfaceController.js +158 -0
- package/dist/esm/interface/SnapInterfaceController.js.map +1 -0
- package/dist/esm/interface/index.js +3 -0
- package/dist/esm/interface/index.js.map +1 -0
- package/dist/esm/interface/utils.js +62 -0
- package/dist/esm/interface/utils.js.map +1 -0
- package/dist/esm/services/browser.js +1 -0
- package/dist/esm/services/browser.js.map +1 -1
- package/dist/esm/services/index.js +1 -0
- package/dist/esm/services/index.js.map +1 -1
- package/dist/esm/services/webview/WebViewExecutionService.js +89 -0
- package/dist/esm/services/webview/WebViewExecutionService.js.map +1 -0
- package/dist/esm/services/webview/WebViewMessageStream.js +119 -0
- package/dist/esm/services/webview/WebViewMessageStream.js.map +1 -0
- package/dist/esm/services/webview/index.js +3 -0
- package/dist/esm/services/webview/index.js.map +1 -0
- package/dist/esm/snaps/SnapController.js +105 -45
- package/dist/esm/snaps/SnapController.js.map +1 -1
- package/dist/esm/snaps/constants.js +16 -0
- package/dist/esm/snaps/constants.js.map +1 -0
- package/dist/esm/snaps/index.js +0 -2
- package/dist/esm/snaps/index.js.map +1 -1
- package/dist/esm/snaps/location/npm.js +13 -2
- package/dist/esm/snaps/location/npm.js.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/interface/SnapInterfaceController.d.ts +85 -0
- package/dist/types/interface/index.d.ts +1 -0
- package/dist/types/interface/utils.d.ts +36 -0
- package/dist/types/services/browser.d.ts +1 -0
- package/dist/types/services/index.d.ts +1 -0
- package/dist/types/services/webview/WebViewExecutionService.d.ts +20 -0
- package/dist/types/services/webview/WebViewMessageStream.d.ts +32 -0
- package/dist/types/services/webview/index.d.ts +1 -0
- package/dist/types/snaps/SnapController.d.ts +7 -4
- package/dist/types/snaps/constants.d.ts +1 -0
- package/dist/types/snaps/index.d.ts +0 -2
- package/dist/types/utils.d.ts +33 -13
- package/package.json +11 -11
- package/dist/cjs/snaps/endowments/cronjob.js +0 -100
- package/dist/cjs/snaps/endowments/cronjob.js.map +0 -1
- package/dist/cjs/snaps/endowments/enum.js +0 -26
- package/dist/cjs/snaps/endowments/enum.js.map +0 -1
- package/dist/cjs/snaps/endowments/ethereum-provider.js +0 -43
- package/dist/cjs/snaps/endowments/ethereum-provider.js.map +0 -1
- package/dist/cjs/snaps/endowments/home-page.js +0 -37
- package/dist/cjs/snaps/endowments/home-page.js.map +0 -1
- package/dist/cjs/snaps/endowments/index.js +0 -107
- package/dist/cjs/snaps/endowments/index.js.map +0 -1
- package/dist/cjs/snaps/endowments/keyring.js +0 -100
- package/dist/cjs/snaps/endowments/keyring.js.map +0 -1
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js +0 -37
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +0 -1
- package/dist/cjs/snaps/endowments/name-lookup.js +0 -106
- package/dist/cjs/snaps/endowments/name-lookup.js.map +0 -1
- package/dist/cjs/snaps/endowments/network-access.js +0 -44
- package/dist/cjs/snaps/endowments/network-access.js.map +0 -1
- package/dist/cjs/snaps/endowments/rpc.js +0 -99
- package/dist/cjs/snaps/endowments/rpc.js.map +0 -1
- package/dist/cjs/snaps/endowments/signature-insight.js +0 -106
- package/dist/cjs/snaps/endowments/signature-insight.js.map +0 -1
- package/dist/cjs/snaps/endowments/transaction-insight.js +0 -106
- package/dist/cjs/snaps/endowments/transaction-insight.js.map +0 -1
- package/dist/cjs/snaps/endowments/web-assembly.js +0 -42
- package/dist/cjs/snaps/endowments/web-assembly.js.map +0 -1
- package/dist/cjs/snaps/permissions.js +0 -61
- package/dist/cjs/snaps/permissions.js.map +0 -1
- package/dist/esm/snaps/endowments/cronjob.js +0 -99
- package/dist/esm/snaps/endowments/cronjob.js.map +0 -1
- package/dist/esm/snaps/endowments/enum.js +0 -16
- package/dist/esm/snaps/endowments/enum.js.map +0 -1
- package/dist/esm/snaps/endowments/ethereum-provider.js +0 -33
- package/dist/esm/snaps/endowments/ethereum-provider.js.map +0 -1
- package/dist/esm/snaps/endowments/home-page.js +0 -27
- package/dist/esm/snaps/endowments/home-page.js.map +0 -1
- package/dist/esm/snaps/endowments/index.js +0 -60
- package/dist/esm/snaps/endowments/index.js.map +0 -1
- package/dist/esm/snaps/endowments/keyring.js +0 -91
- package/dist/esm/snaps/endowments/keyring.js.map +0 -1
- package/dist/esm/snaps/endowments/lifecycle-hooks.js +0 -27
- package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +0 -1
- package/dist/esm/snaps/endowments/name-lookup.js +0 -98
- package/dist/esm/snaps/endowments/name-lookup.js.map +0 -1
- package/dist/esm/snaps/endowments/network-access.js +0 -34
- package/dist/esm/snaps/endowments/network-access.js.map +0 -1
- package/dist/esm/snaps/endowments/rpc.js +0 -88
- package/dist/esm/snaps/endowments/rpc.js.map +0 -1
- package/dist/esm/snaps/endowments/signature-insight.js +0 -99
- package/dist/esm/snaps/endowments/signature-insight.js.map +0 -1
- package/dist/esm/snaps/endowments/transaction-insight.js +0 -99
- package/dist/esm/snaps/endowments/transaction-insight.js.map +0 -1
- package/dist/esm/snaps/endowments/web-assembly.js +0 -32
- package/dist/esm/snaps/endowments/web-assembly.js.map +0 -1
- package/dist/esm/snaps/permissions.js +0 -50
- package/dist/esm/snaps/permissions.js.map +0 -1
- package/dist/types/snaps/endowments/cronjob.d.ts +0 -51
- package/dist/types/snaps/endowments/enum.d.ts +0 -13
- package/dist/types/snaps/endowments/ethereum-provider.d.ts +0 -14
- package/dist/types/snaps/endowments/home-page.d.ts +0 -15
- package/dist/types/snaps/endowments/index.d.ts +0 -127
- package/dist/types/snaps/endowments/keyring.d.ts +0 -39
- package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +0 -15
- package/dist/types/snaps/endowments/name-lookup.d.ts +0 -38
- package/dist/types/snaps/endowments/network-access.d.ts +0 -14
- package/dist/types/snaps/endowments/rpc.d.ts +0 -38
- package/dist/types/snaps/endowments/signature-insight.d.ts +0 -39
- package/dist/types/snaps/endowments/transaction-insight.d.ts +0 -39
- package/dist/types/snaps/endowments/web-assembly.d.ts +0 -14
- package/dist/types/snaps/permissions.d.ts +0 -16
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [5.0.0]
|
|
10
|
+
### Added
|
|
11
|
+
- Add support for dynamic user interfaces ([#1465](https://github.com/MetaMask/snaps/pull/1465), [#2126](https://github.com/MetaMask/snaps/pull/2126), [#2144](https://github.com/MetaMask/snaps/pull/2144), [#2152](https://github.com/MetaMask/snaps/pull/2152), [#2143](https://github.com/MetaMask/snaps/pull/2143))
|
|
12
|
+
- Add support for Snap defined execution timeouts ([#2098](https://github.com/MetaMask/snaps/pull/2098))
|
|
13
|
+
- A Snap can now define `maxRequestTime` to extend or shorten its execution timeout.
|
|
14
|
+
- Add `WebViewExecutionService` for mobile execution ([#2005](https://github.com/MetaMask/snaps/pull/2005))
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
- Loosen allowlist requirements ([#1672](https://github.com/MetaMask/snaps/pull/1672))
|
|
18
|
+
- Snaps with certain permissions can now be installed without being allowlisted.
|
|
19
|
+
- Reintroduce `DecompressionStream` for improved installation performance ([#2110](https://github.com/MetaMask/snaps/pull/2110))
|
|
20
|
+
- Bump `tar-stream` ([#2116](https://github.com/MetaMask/snaps/pull/2116))
|
|
21
|
+
- This fixes a problem where Snaps would sometimes fail to download from NPM.
|
|
22
|
+
- Bump several MetaMask dependencies ([#2129](https://github.com/MetaMask/snaps/pull/2129), [#2132](https://github.com/MetaMask/snaps/pull/2132), [#2130](https://github.com/MetaMask/snaps/pull/2130), [#2139](https://github.com/MetaMask/snaps/pull/2139), [#2142](https://github.com/MetaMask/snaps/pull/2142))
|
|
23
|
+
- Pass localized snap name to SubjectMetadataController ([#2157](https://github.com/MetaMask/snaps/pull/2157))
|
|
24
|
+
|
|
25
|
+
### Removed
|
|
26
|
+
- **BREAKING:** Remove endowment permission specifications from this package ([#2155](https://github.com/MetaMask/snaps/pull/2155))
|
|
27
|
+
- They can now be found in `snaps-rpc-methods`.
|
|
28
|
+
|
|
9
29
|
## [4.1.0]
|
|
10
30
|
### Added
|
|
11
31
|
- Add support for signature insights ([#2074](https://github.com/MetaMask/snaps/pull/2074))
|
|
@@ -168,7 +188,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
168
188
|
- The version of the package no longer needs to match the version of all other
|
|
169
189
|
MetaMask Snaps packages.
|
|
170
190
|
|
|
171
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@
|
|
191
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@5.0.0...HEAD
|
|
192
|
+
[5.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@4.1.0...@metamask/snaps-controllers@5.0.0
|
|
172
193
|
[4.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@4.0.0...@metamask/snaps-controllers@4.1.0
|
|
173
194
|
[4.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.6.0...@metamask/snaps-controllers@4.0.0
|
|
174
195
|
[3.6.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.5.1...@metamask/snaps-controllers@3.6.0
|
|
@@ -17,10 +17,10 @@ _export(exports, {
|
|
|
17
17
|
}
|
|
18
18
|
});
|
|
19
19
|
const _basecontroller = require("@metamask/base-controller");
|
|
20
|
+
const _snapsrpcmethods = require("@metamask/snaps-rpc-methods");
|
|
20
21
|
const _snapsutils = require("@metamask/snaps-utils");
|
|
21
22
|
const _utils = require("@metamask/utils");
|
|
22
23
|
const _ = require("..");
|
|
23
|
-
const _cronjob = require("../snaps/endowments/cronjob");
|
|
24
24
|
const _Timer = require("../snaps/Timer");
|
|
25
25
|
function _check_private_redeclaration(obj, privateCollection) {
|
|
26
26
|
if (privateCollection.has(obj)) {
|
|
@@ -85,8 +85,8 @@ class CronjobController extends _basecontroller.BaseController {
|
|
|
85
85
|
* @returns Array of Cronjob specifications.
|
|
86
86
|
*/ getSnapJobs(snapId) {
|
|
87
87
|
const permissions = _class_private_field_get(this, _messenger).call('PermissionController:getPermissions', snapId);
|
|
88
|
-
const permission = permissions?.[
|
|
89
|
-
const definitions = (0,
|
|
88
|
+
const permission = permissions?.[_snapsrpcmethods.SnapEndowments.Cronjob];
|
|
89
|
+
const definitions = (0, _snapsrpcmethods.getCronjobCaveatJobs)(permission);
|
|
90
90
|
return definitions?.map((definition, idx)=>{
|
|
91
91
|
return {
|
|
92
92
|
...definition,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: string) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["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","state","lastRun","updateJobLastRunState","set","snapIds","origin","handler","HandlerType","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","update","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","const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A;;mBAAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;QAGA,gCAAA;;mBAAA,KAAA;;uCAcQlB,SAAS,IAAImD;uCACb7B,UAAU,IAAI6B;uCACd9D,YAAYA;QAElB,IAAI,CAACsD,wBAAwB,GAAG,IAAI,CAACA,wBAAwB,CAACS,IAAI,CAAC,IAAI;QACvE,IAAI,CAACR,0BAA0B,GAC7B,IAAI,CAACA,0BAA0B,CAACQ,IAAI,CAAC,IAAI;QAC3C,IAAI,CAACP,uBAAuB,GAAG,IAAI,CAACA,uBAAuB,CAACO,IAAI,CAAC,IAAI;QAErE,2BAA2B;QAC3B,oDAAoD,GACpD,IAAI,CAAC9E,eAAe,CAAC+E,SAAS,CAC5B,gCACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAACrE,eAAe,CAAC+E,SAAS,CAC5B,kCACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAACtE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAACrE,eAAe,CAAC+E,SAAS,CAC5B,+BACA,IAAI,CAACT,0BAA0B;QAGjC,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;AAiPF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps } from '..';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: string) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["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","state","lastRun","updateJobLastRunState","set","snapIds","origin","handler","HandlerType","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","update","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;IAmDaA,aAAa;eAAbA;;IA8BAC,iBAAiB;eAAjBA;;;gCAhFkB;iCAKxB;4BAUA;uBACkC;kBAWR;uBACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBf,MAAMD,gBAAgBE,IAAAA,qBAAc,EAAC,IAAIC,eAAQ,CAACC,IAAI;AAwB7D,MAAMC,iBAAiB;IAWrB,0CAEA,2CAEA,uCAEA,+BAA+B;AAC/B;AAZK,MAAMJ,0BAA0BK,8BAAc;IAoEnD;;;;GAIC,GACD,AAAQC,aAAwB;QAC9B,MAAMC,QAAQ,IAAI,CAACC,eAAe,CAACC,IAAI,CAAC;QACxC,MAAMC,gBAAgBC,IAAAA,kBAAgB,EAACJ;QAEvC,MAAMK,OAAOF,cAAcG,GAAG,CAAC,CAACC,OAAS,IAAI,CAACC,WAAW,CAACD,KAAKE,E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ACtE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAACrE,eAAe,CAAC+E,SAAS,CAC5B,+BACA,IAAI,CAACT,0BAA0B;QAGjC,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;AAiPF"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -6,6 +6,7 @@ _export_star(require("./services"), exports);
|
|
|
6
6
|
_export_star(require("./snaps"), exports);
|
|
7
7
|
_export_star(require("./utils"), exports);
|
|
8
8
|
_export_star(require("./cronjob"), exports);
|
|
9
|
+
_export_star(require("./interface"), exports);
|
|
9
10
|
function _export_star(from, to) {
|
|
10
11
|
Object.keys(from).forEach(function(k) {
|
|
11
12
|
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export type { Json } from '@metamask/utils';\nexport * from './services';\nexport * from './snaps';\nexport * from './utils';\nexport * from './cronjob';\n"],"names":[],"mappings":";;;;qBACc;qBACA;qBACA;qBACA"}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export type { Json } from '@metamask/utils';\nexport * from './services';\nexport * from './snaps';\nexport * from './utils';\nexport * from './cronjob';\nexport * from './interface';\n"],"names":[],"mappings":";;;;qBACc;qBACA;qBACA;qBACA;qBACA"}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "SnapInterfaceController", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return SnapInterfaceController;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _basecontroller = require("@metamask/base-controller");
|
|
12
|
+
const _snapsutils = require("@metamask/snaps-utils");
|
|
13
|
+
const _utils = require("@metamask/utils");
|
|
14
|
+
const _nanoid = require("nanoid");
|
|
15
|
+
const _utils1 = require("./utils");
|
|
16
|
+
function _check_private_redeclaration(obj, privateCollection) {
|
|
17
|
+
if (privateCollection.has(obj)) {
|
|
18
|
+
throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function _class_private_method_get(receiver, privateSet, fn) {
|
|
22
|
+
if (!privateSet.has(receiver)) {
|
|
23
|
+
throw new TypeError("attempted to get private field on non-instance");
|
|
24
|
+
}
|
|
25
|
+
return fn;
|
|
26
|
+
}
|
|
27
|
+
function _class_private_method_init(obj, privateSet) {
|
|
28
|
+
_check_private_redeclaration(obj, privateSet);
|
|
29
|
+
privateSet.add(obj);
|
|
30
|
+
}
|
|
31
|
+
const controllerName = 'SnapInterfaceController';
|
|
32
|
+
var /**
|
|
33
|
+
* Constructor helper for registering this controller's messaging system
|
|
34
|
+
* actions.
|
|
35
|
+
*/ _registerMessageHandlers = /*#__PURE__*/ new WeakSet(), /**
|
|
36
|
+
* Utility function to validate the args passed to the other methods.
|
|
37
|
+
*
|
|
38
|
+
* @param snapId - The snap id.
|
|
39
|
+
* @param id - The interface id.
|
|
40
|
+
*/ _validateArgs = /*#__PURE__*/ new WeakSet(), _triggerPhishingListUpdate = /*#__PURE__*/ new WeakSet(), /**
|
|
41
|
+
* Check an origin against the phishing list.
|
|
42
|
+
*
|
|
43
|
+
* @param origin - The origin to check.
|
|
44
|
+
* @returns True if the origin is on the phishing list, otherwise false.
|
|
45
|
+
*/ _checkPhishingList = /*#__PURE__*/ new WeakSet(), _validateContent = /*#__PURE__*/ new WeakSet();
|
|
46
|
+
class SnapInterfaceController extends _basecontroller.BaseController {
|
|
47
|
+
/**
|
|
48
|
+
* Create an interface in the controller state with the associated data.
|
|
49
|
+
*
|
|
50
|
+
* @param snapId - The snap id that created the interface.
|
|
51
|
+
* @param content - The interface content.
|
|
52
|
+
* @returns The newly interface id.
|
|
53
|
+
*/ async createInterface(snapId, content) {
|
|
54
|
+
await _class_private_method_get(this, _validateContent, validateContent).call(this, content);
|
|
55
|
+
const id = (0, _nanoid.nanoid)();
|
|
56
|
+
const componentState = (0, _utils1.constructState)({}, content);
|
|
57
|
+
this.update((draftState)=>{
|
|
58
|
+
draftState.interfaces[id] = {
|
|
59
|
+
snapId,
|
|
60
|
+
content,
|
|
61
|
+
state: componentState
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
return id;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Get the data of a given interface id.
|
|
68
|
+
*
|
|
69
|
+
* @param snapId - The snap id requesting the interface data.
|
|
70
|
+
* @param id - The interface id.
|
|
71
|
+
* @returns The interface state.
|
|
72
|
+
*/ getInterface(snapId, id) {
|
|
73
|
+
_class_private_method_get(this, _validateArgs, validateArgs).call(this, snapId, id);
|
|
74
|
+
return this.state.interfaces[id];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Update the interface with the given content.
|
|
78
|
+
*
|
|
79
|
+
* @param snapId - The snap id requesting the update.
|
|
80
|
+
* @param id - The interface id.
|
|
81
|
+
* @param content - The new content.
|
|
82
|
+
*/ async updateInterface(snapId, id, content) {
|
|
83
|
+
_class_private_method_get(this, _validateArgs, validateArgs).call(this, snapId, id);
|
|
84
|
+
await _class_private_method_get(this, _validateContent, validateContent).call(this, content);
|
|
85
|
+
const oldState = this.state.interfaces[id].state;
|
|
86
|
+
const newState = (0, _utils1.constructState)(oldState, content);
|
|
87
|
+
this.update((draftState)=>{
|
|
88
|
+
draftState.interfaces[id].state = newState;
|
|
89
|
+
draftState.interfaces[id].content = content;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Delete an interface from state.
|
|
94
|
+
*
|
|
95
|
+
* @param id - The interface id.
|
|
96
|
+
*/ deleteInterface(id) {
|
|
97
|
+
this.update((draftState)=>{
|
|
98
|
+
delete draftState.interfaces[id];
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Update the interface state.
|
|
103
|
+
*
|
|
104
|
+
* @param id - The interface id.
|
|
105
|
+
* @param state - The new state.
|
|
106
|
+
*/ updateInterfaceState(id, state) {
|
|
107
|
+
this.update((draftState)=>{
|
|
108
|
+
draftState.interfaces[id].state = state;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
constructor({ messenger, state }){
|
|
112
|
+
super({
|
|
113
|
+
messenger,
|
|
114
|
+
metadata: {
|
|
115
|
+
interfaces: {
|
|
116
|
+
persist: false,
|
|
117
|
+
anonymous: false
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
name: controllerName,
|
|
121
|
+
state: {
|
|
122
|
+
interfaces: {},
|
|
123
|
+
...state
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
_class_private_method_init(this, _registerMessageHandlers);
|
|
127
|
+
_class_private_method_init(this, _validateArgs);
|
|
128
|
+
/**
|
|
129
|
+
* Trigger a Phishing list update if needed.
|
|
130
|
+
*/ _class_private_method_init(this, _triggerPhishingListUpdate);
|
|
131
|
+
_class_private_method_init(this, _checkPhishingList);
|
|
132
|
+
/**
|
|
133
|
+
* Utility function to validate the components of an interface.
|
|
134
|
+
* Throws if something is invalid.
|
|
135
|
+
*
|
|
136
|
+
* Right now this only checks links against the phighing list.
|
|
137
|
+
*
|
|
138
|
+
* @param content - The components to verify.
|
|
139
|
+
*/ _class_private_method_init(this, _validateContent);
|
|
140
|
+
_class_private_method_get(this, _registerMessageHandlers, registerMessageHandlers).call(this);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function registerMessageHandlers() {
|
|
144
|
+
this.messagingSystem.registerActionHandler(`${controllerName}:createInterface`, this.createInterface.bind(this));
|
|
145
|
+
this.messagingSystem.registerActionHandler(`${controllerName}:getInterface`, this.getInterface.bind(this));
|
|
146
|
+
this.messagingSystem.registerActionHandler(`${controllerName}:updateInterface`, this.updateInterface.bind(this));
|
|
147
|
+
this.messagingSystem.registerActionHandler(`${controllerName}:deleteInterface`, this.deleteInterface.bind(this));
|
|
148
|
+
this.messagingSystem.registerActionHandler(`${controllerName}:updateInterfaceState`, this.updateInterfaceState.bind(this));
|
|
149
|
+
}
|
|
150
|
+
function validateArgs(snapId, id) {
|
|
151
|
+
const existingInterface = this.state.interfaces[id];
|
|
152
|
+
(0, _utils.assert)(existingInterface !== undefined, `Interface with id '${id}' not found.`);
|
|
153
|
+
(0, _utils.assert)(existingInterface.snapId === snapId, `Interface not created by ${snapId}.`);
|
|
154
|
+
}
|
|
155
|
+
async function triggerPhishingListUpdate() {
|
|
156
|
+
await this.messagingSystem.call('PhishingController:maybeUpdateState');
|
|
157
|
+
}
|
|
158
|
+
function checkPhishingList(origin) {
|
|
159
|
+
return this.messagingSystem.call('PhishingController:testOrigin', origin).result;
|
|
160
|
+
}
|
|
161
|
+
async function validateContent(content) {
|
|
162
|
+
await _class_private_method_get(this, _triggerPhishingListUpdate, triggerPhishingListUpdate).call(this);
|
|
163
|
+
(0, _snapsutils.validateComponentLinks)(content, _class_private_method_get(this, _checkPhishingList, checkPhishingList).bind(this));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
//# sourceMappingURL=SnapInterfaceController.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/interface/SnapInterfaceController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n MaybeUpdateState,\n TestOrigin,\n} from '@metamask/phishing-controller';\nimport type { Component, InterfaceState, SnapId } from '@metamask/snaps-sdk';\nimport { validateComponentLinks } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport { constructState } from './utils';\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | MaybeUpdateState;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState;\n\nexport type SnapInterfaceControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n never,\n SnapInterfaceControllerAllowedActions['type'],\n never\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: Component;\n state: InterfaceState;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @returns The newly interface id.\n */\n async createInterface(snapId: SnapId, content: Component) {\n await this.#validateContent(content);\n\n const id = nanoid();\n\n const componentState = constructState({}, content);\n\n this.update((draftState) => {\n draftState.interfaces[id] = {\n snapId,\n content,\n state: componentState,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n */\n async updateInterface(snapId: SnapId, id: string, content: Component) {\n this.#validateArgs(snapId, id);\n await this.#validateContent(content);\n\n const oldState = this.state.interfaces[id].state;\n\n const newState = constructState(oldState, content);\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = content;\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Trigger a Phishing list update if needed.\n */\n async #triggerPhishingListUpdate() {\n await this.messagingSystem.call('PhishingController:maybeUpdateState');\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * Right now this only checks links against the phighing list.\n *\n * @param content - The components to verify.\n */\n async #validateContent(content: Component) {\n await this.#triggerPhishingListUpdate();\n\n validateComponentLinks(content, this.#checkPhishingList.bind(this));\n }\n}\n"],"names":["SnapInterfaceController","controllerName","BaseController","createInterface","snapId","content","validateContent","id","nanoid","componentState","constructState","update","draftState","interfaces","state","getInterface","validateArgs","updateInterface","oldState","newState","deleteInterface","updateInterfaceState","constructor","messenger","metadata","persist","anonymous","name","registerMessageHandlers","messagingSystem","registerActionHandler","bind","existingInterface","assert","undefined","call","origin","result","triggerPhishingListUpdate","validateComponentLinks","checkPhishingList"],"mappings":";;;;+BA6EaA;;;eAAAA;;;gCA5EkB;4BAMQ;uBAChB;wBACA;wBAEQ;;;;;;;;;;;;;;;;AAE/B,MAAMC,iBAAiB;IAkFrB;;;GAGC,GACD,wDA6GA;;;;;GAKC,GACD,6CAgBM,0DAIN;;;;;GAKC,GACD,kDAaM;AAhLD,MAAMD,gCAAgCE,8BAAc;IAiDzD;;;;;;GAMC,GACD,MAAMC,gBAAgBC,MAAc,EAAEC,OAAkB,EAAE;QACxD,MAAM,0BAAA,IAAI,EAA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A,aAAM,EACJD,kBAAkB5B,MAAM,KAAKA,QAC7B,CAAC,yBAAyB,EAAEA,OAAO,CAAC,CAAC;AAEzC;AAKA,eAAA;IACE,MAAM,IAAI,CAACyB,eAAe,CAACM,IAAI,CAAC;AAClC;AAQA,SAAA,kBAAmBC,MAAc;IAC/B,OAAO,IAAI,CAACP,eAAe,CAACM,IAAI,CAAC,iCAAiCC,QAC/DC,MAAM;AACX;AAUA,eAAA,gBAAuBhC,OAAkB;IACvC,MAAM,0BAAA,IAAI,EAAEiC,4BAAAA,gCAAN,IAAI;IAEVC,IAAAA,kCAAsB,EAAClC,SAAS,0BAAA,IAAI,EAAEmC,oBAAAA,mBAAkBT,IAAI,CAAC,IAAI;AACnE"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
_export_star(require("./SnapInterfaceController"), exports);
|
|
6
|
+
function _export_star(from, to) {
|
|
7
|
+
Object.keys(from).forEach(function(k) {
|
|
8
|
+
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
|
|
9
|
+
Object.defineProperty(to, k, {
|
|
10
|
+
enumerable: true,
|
|
11
|
+
get: function() {
|
|
12
|
+
return from[k];
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
return from;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/interface/index.ts"],"sourcesContent":["export * from './SnapInterfaceController';\n"],"names":[],"mappings":";;;;qBAAc"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
constructInputState: function() {
|
|
13
|
+
return constructInputState;
|
|
14
|
+
},
|
|
15
|
+
constructFormInputState: function() {
|
|
16
|
+
return constructFormInputState;
|
|
17
|
+
},
|
|
18
|
+
assertNameIsUnique: function() {
|
|
19
|
+
return assertNameIsUnique;
|
|
20
|
+
},
|
|
21
|
+
constructState: function() {
|
|
22
|
+
return constructState;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
const _snapssdk = require("@metamask/snaps-sdk");
|
|
26
|
+
const constructInputState = (state, component)=>{
|
|
27
|
+
return component.value ?? state[component.name] ?? null;
|
|
28
|
+
};
|
|
29
|
+
const constructFormInputState = (state, component, form)=>{
|
|
30
|
+
const oldFormState = state[form];
|
|
31
|
+
const oldInputState = oldFormState?.[component.name];
|
|
32
|
+
return component.value ?? oldInputState ?? null;
|
|
33
|
+
};
|
|
34
|
+
const assertNameIsUnique = (state, name)=>{
|
|
35
|
+
(0, _snapssdk.assert)(state[name] === undefined, `Duplicate component names are not allowed, found multiple instances of: "${name}".`);
|
|
36
|
+
};
|
|
37
|
+
const constructState = (oldState, component, newState = {})=>{
|
|
38
|
+
const { type } = component;
|
|
39
|
+
if (type === _snapssdk.NodeType.Panel) {
|
|
40
|
+
return component.children.reduce((acc, node)=>constructState(oldState, node, acc), newState);
|
|
41
|
+
}
|
|
42
|
+
if (type === _snapssdk.NodeType.Form) {
|
|
43
|
+
assertNameIsUnique(newState, component.name);
|
|
44
|
+
newState[component.name] = component.children.reduce((acc, node)=>{
|
|
45
|
+
if (node.type === _snapssdk.NodeType.Input) {
|
|
46
|
+
assertNameIsUnique(acc, node.name);
|
|
47
|
+
acc[node.name] = constructFormInputState(oldState, node, component.name);
|
|
48
|
+
}
|
|
49
|
+
return acc;
|
|
50
|
+
}, {});
|
|
51
|
+
}
|
|
52
|
+
if (type === _snapssdk.NodeType.Input) {
|
|
53
|
+
assertNameIsUnique(newState, component.name);
|
|
54
|
+
newState[component.name] = constructInputState(oldState, component);
|
|
55
|
+
}
|
|
56
|
+
return newState;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/interface/utils.ts"],"sourcesContent":["import { NodeType, assert } from '@metamask/snaps-sdk';\nimport type {\n Component,\n Input,\n FormState,\n InterfaceState,\n} from '@metamask/snaps-sdk';\n\n/**\n * Construct the state for a stray input (not enclosed in a form).\n *\n * @param state - The interface state.\n * @param component - The Input component.\n * @returns The input state.\n */\nexport const constructInputState = (\n state: InterfaceState,\n component: Input,\n) => {\n return component.value ?? state[component.name] ?? null;\n};\n\n/**\n * Construct the state for a form input.\n *\n * Sets the state to either the specified component value, the previous value from the old state or null.\n *\n * @param state - The interface state.\n * @param component - The Input component.\n * @param form - The parent form name of the input.\n * @returns The input state.\n */\nexport const constructFormInputState = (\n state: InterfaceState,\n component: Input,\n form: string,\n) => {\n const oldFormState = state[form] as FormState;\n const oldInputState = oldFormState?.[component.name];\n return component.value ?? oldInputState ?? null;\n};\n\n/**\n * Assert that the component name is unique in state.\n *\n * @param state - The interface state to verify against.\n * @param name - The component name to verify.\n */\nexport const assertNameIsUnique = (state: InterfaceState, name: string) => {\n assert(\n state[name] === undefined,\n `Duplicate component names are not allowed, found multiple instances of: \"${name}\".`,\n );\n};\n\n/**\n * Construct the interface state for a given component tree while preserving values for matching stateful components in the old state.\n *\n * @param oldState - The previous state.\n * @param component - The UI component to construct state from.\n * @param newState - The state that is being constructed.\n * @returns The interface state of the passed component.\n */\nexport const constructState = (\n oldState: InterfaceState,\n component: Component,\n newState: InterfaceState = {},\n): InterfaceState => {\n const { type } = component;\n if (type === NodeType.Panel) {\n return component.children.reduce(\n (acc, node) => constructState(oldState, node, acc),\n newState,\n );\n }\n\n if (type === NodeType.Form) {\n assertNameIsUnique(newState, component.name);\n newState[component.name] = component.children.reduce<FormState>(\n (acc, node) => {\n if (node.type === NodeType.Input) {\n assertNameIsUnique(acc, node.name);\n acc[node.name] = constructFormInputState(\n oldState,\n node,\n component.name,\n );\n }\n\n return acc;\n },\n {},\n );\n }\n\n if (type === NodeType.Input) {\n assertNameIsUnique(newState, component.name);\n newState[component.name] = constructInputState(oldState, component);\n }\n\n return newState;\n};\n"],"names":["constructInputState","constructFormInputState","assertNameIsUnique","constructState","state","component","value","name","form","oldFormState","oldInputState","assert","undefined","oldState","newState","type","NodeType","Panel","children","reduce","acc","node","Form","Input"],"mappings":";;;;;;;;;;;IAeaA,mBAAmB;eAAnBA;;IAiBAC,uBAAuB;eAAvBA;;IAgBAC,kBAAkB;eAAlBA;;IAeAC,cAAc;eAAdA;;;0BA/DoB;AAe1B,MAAMH,sBAAsB,CACjCI,OACAC;IAEA,OAAOA,UAAUC,KAAK,IAAIF,KAAK,CAACC,UAAUE,IAAI,CAAC,IAAI;AACrD;AAYO,MAAMN,0BAA0B,CACrCG,OACAC,WACAG;IAEA,MAAMC,eAAeL,KAAK,CAACI,KAAK;IAChC,MAAME,gBAAgBD,cAAc,CAACJ,UAAUE,IAAI,CAAC;IACpD,OAAOF,UAAUC,KAAK,IAAII,iBAAiB;AAC7C;AAQO,MAAMR,qBAAqB,CAACE,OAAuBG;IACxDI,IAAAA,gBAAM,EACJP,KAAK,CAACG,KAAK,KAAKK,WAChB,CAAC,yEAAyE,EAAEL,KAAK,EAAE,CAAC;AAExF;AAUO,MAAMJ,iBAAiB,CAC5BU,UACAR,WACAS,WAA2B,CAAC,CAAC;IAE7B,MAAM,EAAEC,IAAI,EAAE,GAAGV;IACjB,IAAIU,SAASC,kBAAQ,CAACC,KAAK,EAAE;QAC3B,OAAOZ,UAAUa,QAAQ,CAACC,MAAM,CAC9B,CAACC,KAAKC,OAASlB,eAAeU,UAAUQ,MAAMD,MAC9CN;IAEJ;IAEA,IAAIC,SAASC,kBAAQ,CAACM,IAAI,EAAE;QAC1BpB,mBAAmBY,UAAUT,UAAUE,IAAI;QAC3CO,QAAQ,CAACT,UAAUE,IAAI,CAAC,GAAGF,UAAUa,QAAQ,CAACC,MAAM,CAClD,CAACC,KAAKC;YACJ,IAAIA,KAAKN,IAAI,KAAKC,kBAAQ,CAACO,KAAK,EAAE;gBAChCrB,mBAAmBkB,KAAKC,KAAKd,IAAI;gBACjCa,GAAG,CAACC,KAAKd,IAAI,CAAC,GAAGN,wBACfY,UACAQ,MACAhB,UAAUE,IAAI;YAElB;YAEA,OAAOa;QACT,GACA,CAAC;IAEL;IAEA,IAAIL,SAASC,kBAAQ,CAACO,KAAK,EAAE;QAC3BrB,mBAAmBY,UAAUT,UAAUE,IAAI;QAC3CO,QAAQ,CAACT,UAAUE,IAAI,CAAC,GAAGP,oBAAoBa,UAAUR;IAC3D;IAEA,OAAOS;AACT"}
|
|
@@ -14,6 +14,7 @@ _export_star(require("./ExecutionService"), exports);
|
|
|
14
14
|
_export_star(require("./ProxyPostMessageStream"), exports);
|
|
15
15
|
_export_star(require("./iframe"), exports);
|
|
16
16
|
_export_star(require("./offscreen"), exports);
|
|
17
|
+
_export_star(require("./webview"), exports);
|
|
17
18
|
const _webworker = require("./webworker");
|
|
18
19
|
function _export_star(from, to) {
|
|
19
20
|
Object.keys(from).forEach(function(k) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/browser.ts"],"sourcesContent":["// Subset of exports meant for browser environments, omits Node.js services\nexport * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './offscreen';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":"AAAA,2EAA2E;;;;;+
|
|
1
|
+
{"version":3,"sources":["../../../src/services/browser.ts"],"sourcesContent":["// Subset of exports meant for browser environments, omits Node.js services\nexport * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './offscreen';\nexport * from './webview';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":"AAAA,2EAA2E;;;;;+BAOlEA;;;eAAAA,oCAAyB;;;qBANpB;qBACA;qBACA;qBACA;qBACA;qBACA;2BAC4B"}
|
|
@@ -14,6 +14,7 @@ _export_star(require("./ProxyPostMessageStream"), exports);
|
|
|
14
14
|
_export_star(require("./iframe"), exports);
|
|
15
15
|
_export_star(require("./node"), exports);
|
|
16
16
|
_export_star(require("./offscreen"), exports);
|
|
17
|
+
_export_star(require("./webview"), exports);
|
|
17
18
|
const _webworker = require("./webworker");
|
|
18
19
|
function _export_star(from, to) {
|
|
19
20
|
Object.keys(from).forEach(function(k) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/index.ts"],"sourcesContent":["export * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './node';\nexport * from './offscreen';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":";;;;+
|
|
1
|
+
{"version":3,"sources":["../../../src/services/index.ts"],"sourcesContent":["export * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './node';\nexport * from './offscreen';\nexport * from './webview';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":";;;;+BAOSA;;;eAAAA,oCAAyB;;;qBAPpB;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;2BAC4B"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "WebViewExecutionService", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return WebViewExecutionService;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _ProxyExecutionService = require("../proxy/ProxyExecutionService");
|
|
12
|
+
const _WebViewMessageStream = require("./WebViewMessageStream");
|
|
13
|
+
function _check_private_redeclaration(obj, privateCollection) {
|
|
14
|
+
if (privateCollection.has(obj)) {
|
|
15
|
+
throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function _class_apply_descriptor_get(receiver, descriptor) {
|
|
19
|
+
if (descriptor.get) {
|
|
20
|
+
return descriptor.get.call(receiver);
|
|
21
|
+
}
|
|
22
|
+
return descriptor.value;
|
|
23
|
+
}
|
|
24
|
+
function _class_apply_descriptor_set(receiver, descriptor, value) {
|
|
25
|
+
if (descriptor.set) {
|
|
26
|
+
descriptor.set.call(receiver, value);
|
|
27
|
+
} else {
|
|
28
|
+
if (!descriptor.writable) {
|
|
29
|
+
throw new TypeError("attempted to set read only private field");
|
|
30
|
+
}
|
|
31
|
+
descriptor.value = value;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function _class_extract_field_descriptor(receiver, privateMap, action) {
|
|
35
|
+
if (!privateMap.has(receiver)) {
|
|
36
|
+
throw new TypeError("attempted to " + action + " private field on non-instance");
|
|
37
|
+
}
|
|
38
|
+
return privateMap.get(receiver);
|
|
39
|
+
}
|
|
40
|
+
function _class_private_field_get(receiver, privateMap) {
|
|
41
|
+
var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
|
|
42
|
+
return _class_apply_descriptor_get(receiver, descriptor);
|
|
43
|
+
}
|
|
44
|
+
function _class_private_field_init(obj, privateMap, value) {
|
|
45
|
+
_check_private_redeclaration(obj, privateMap);
|
|
46
|
+
privateMap.set(obj, value);
|
|
47
|
+
}
|
|
48
|
+
function _class_private_field_set(receiver, privateMap, value) {
|
|
49
|
+
var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
|
|
50
|
+
_class_apply_descriptor_set(receiver, descriptor, value);
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
function _class_private_method_get(receiver, privateSet, fn) {
|
|
54
|
+
if (!privateSet.has(receiver)) {
|
|
55
|
+
throw new TypeError("attempted to get private field on non-instance");
|
|
56
|
+
}
|
|
57
|
+
return fn;
|
|
58
|
+
}
|
|
59
|
+
function _class_private_method_init(obj, privateSet) {
|
|
60
|
+
_check_private_redeclaration(obj, privateSet);
|
|
61
|
+
privateSet.add(obj);
|
|
62
|
+
}
|
|
63
|
+
var _getWebView = /*#__PURE__*/ new WeakMap(), _ensureWebViewLoaded = /*#__PURE__*/ new WeakSet();
|
|
64
|
+
class WebViewExecutionService extends _ProxyExecutionService.ProxyExecutionService {
|
|
65
|
+
/**
|
|
66
|
+
* Create a new stream for the specified job. This wraps the runtime stream
|
|
67
|
+
* in a stream specific to the job.
|
|
68
|
+
*
|
|
69
|
+
* @param jobId - The job ID.
|
|
70
|
+
*/ async initEnvStream(jobId) {
|
|
71
|
+
// Ensure that the WebView has been loaded before we proceed.
|
|
72
|
+
await _class_private_method_get(this, _ensureWebViewLoaded, ensureWebViewLoaded).call(this);
|
|
73
|
+
return super.initEnvStream(jobId);
|
|
74
|
+
}
|
|
75
|
+
constructor({ messenger, setupSnapProvider, getWebView }){
|
|
76
|
+
super({
|
|
77
|
+
messenger,
|
|
78
|
+
setupSnapProvider,
|
|
79
|
+
stream: new _WebViewMessageStream.WebViewMessageStream({
|
|
80
|
+
name: 'parent',
|
|
81
|
+
target: 'child',
|
|
82
|
+
getWebView
|
|
83
|
+
})
|
|
84
|
+
});
|
|
85
|
+
/**
|
|
86
|
+
* Ensure that the WebView has been loaded by awaiting the getWebView promise.
|
|
87
|
+
*/ _class_private_method_init(this, _ensureWebViewLoaded);
|
|
88
|
+
_class_private_field_init(this, _getWebView, {
|
|
89
|
+
writable: true,
|
|
90
|
+
value: void 0
|
|
91
|
+
});
|
|
92
|
+
_class_private_field_set(this, _getWebView, getWebView);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async function ensureWebViewLoaded() {
|
|
96
|
+
await _class_private_field_get(this, _getWebView).call(this);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
//# sourceMappingURL=WebViewExecutionService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/services/webview/WebViewExecutionService.ts"],"sourcesContent":["import type { ExecutionServiceArgs } from '../AbstractExecutionService';\nimport { ProxyExecutionService } from '../proxy/ProxyExecutionService';\nimport type { WebViewInterface } from './WebViewMessageStream';\nimport { WebViewMessageStream } from './WebViewMessageStream';\n\nexport type WebViewExecutionServiceArgs = ExecutionServiceArgs & {\n getWebView: () => Promise<WebViewInterface>;\n};\n\nexport class WebViewExecutionService extends ProxyExecutionService {\n #getWebView;\n\n constructor({\n messenger,\n setupSnapProvider,\n getWebView,\n }: WebViewExecutionServiceArgs) {\n super({\n messenger,\n setupSnapProvider,\n stream: new WebViewMessageStream({\n name: 'parent',\n target: 'child',\n getWebView,\n }),\n });\n this.#getWebView = getWebView;\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 // Ensure that the WebView has been loaded before we proceed.\n await this.#ensureWebViewLoaded();\n\n return super.initEnvStream(jobId);\n }\n\n /**\n * Ensure that the WebView has been loaded by awaiting the getWebView promise.\n */\n async #ensureWebViewLoaded() {\n await this.#getWebView();\n }\n}\n"],"names":["WebViewExecutionService","ProxyExecutionService","initEnvStream","jobId","ensureWebViewLoaded","constructor","messenger","setupSnapProvider","getWebView","stream","WebViewMessageStream","name","target"],"mappings":";;;;+BASaA;;;eAAAA;;;uCARyB;sCAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAOnC,2CAmCM;AApCD,MAAMA,gCAAgCC,4CAAqB;IAoBhE;;;;;GAKC,GACD,MAAgBC,cAAcC,KAAa,EAAE;QAC3C,6DAA6D;QAC7D,MAAM,0BAAA,IAAI,EAAEC,sBAAAA,0BAAN,IAAI;QAEV,OAAO,KAAK,CAACF,cAAcC;IAC7B;IA5BAE,YAAY,EACVC,SAAS,EACTC,iBAAiB,EACjBC,UAAU,EACkB,CAAE;QAC9B,KAAK,CAAC;YACJF;YACAC;YACAE,QAAQ,IAAIC,0CAAoB,CAAC;gBAC/BC,MAAM;gBACNC,QAAQ;gBACRJ;YACF;QACF;QAiBF;;GAEC,GACD,iCAAM;QAnCN,gCAAA;;mBAAA,KAAA;;uCAgBQA,aAAaA;IACrB;AAqBF;AAHE,eAAA;IACE,MAAM,yBAAA,IAAI,EAAEA,kBAAN,IAAI;AACZ"}
|