@metamask/snaps-controllers 0.24.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/LICENSE +18 -0
- package/README.md +3 -0
- package/dist/cronjob/CronjobController.d.ts +115 -0
- package/dist/cronjob/CronjobController.js +231 -0
- package/dist/cronjob/CronjobController.js.map +1 -0
- package/dist/cronjob/index.d.ts +1 -0
- package/dist/cronjob/index.js +18 -0
- package/dist/cronjob/index.js.map +1 -0
- package/dist/fsm.d.ts +24 -0
- package/dist/fsm.js +75 -0
- package/dist/fsm.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/multichain/MultiChainController.d.ts +135 -0
- package/dist/multichain/MultiChainController.js +348 -0
- package/dist/multichain/MultiChainController.js.map +1 -0
- package/dist/multichain/index.d.ts +3 -0
- package/dist/multichain/index.js +20 -0
- package/dist/multichain/index.js.map +1 -0
- package/dist/multichain/matching.d.ts +9 -0
- package/dist/multichain/matching.js +58 -0
- package/dist/multichain/matching.js.map +1 -0
- package/dist/multichain/middleware.d.ts +14 -0
- package/dist/multichain/middleware.js +42 -0
- package/dist/multichain/middleware.js.map +1 -0
- package/dist/services/AbstractExecutionService.d.ts +124 -0
- package/dist/services/AbstractExecutionService.js +316 -0
- package/dist/services/AbstractExecutionService.js.map +1 -0
- package/dist/services/ExecutionService.d.ts +68 -0
- package/dist/services/ExecutionService.js +4 -0
- package/dist/services/ExecutionService.js.map +1 -0
- package/dist/services/browser.d.ts +3 -0
- package/dist/services/browser.js +21 -0
- package/dist/services/browser.js.map +1 -0
- package/dist/services/iframe/IframeExecutionService.d.ts +25 -0
- package/dist/services/iframe/IframeExecutionService.js +82 -0
- package/dist/services/iframe/IframeExecutionService.js.map +1 -0
- package/dist/services/iframe/index.d.ts +1 -0
- package/dist/services/iframe/index.js +18 -0
- package/dist/services/iframe/index.js.map +1 -0
- package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.d.ts +3 -0
- package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js +74 -0
- package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js.map +1 -0
- package/dist/services/iframe/test/server.d.ts +11 -0
- package/dist/services/iframe/test/server.js +71 -0
- package/dist/services/iframe/test/server.js.map +1 -0
- package/dist/services/index.d.ts +4 -0
- package/dist/services/index.js +21 -0
- package/dist/services/index.js.map +1 -0
- package/dist/services/node/NodeProcessExecutionService.d.ts +11 -0
- package/dist/services/node/NodeProcessExecutionService.js +18 -0
- package/dist/services/node/NodeProcessExecutionService.js.map +1 -0
- package/dist/services/node/NodeThreadExecutionService.d.ts +11 -0
- package/dist/services/node/NodeThreadExecutionService.js +18 -0
- package/dist/services/node/NodeThreadExecutionService.js.map +1 -0
- package/dist/services/node/index.d.ts +2 -0
- package/dist/services/node/index.js +19 -0
- package/dist/services/node/index.js.map +1 -0
- package/dist/snaps/RequestQueue.d.ts +24 -0
- package/dist/snaps/RequestQueue.js +47 -0
- package/dist/snaps/RequestQueue.js.map +1 -0
- package/dist/snaps/SnapController.d.ts +600 -0
- package/dist/snaps/SnapController.js +1314 -0
- package/dist/snaps/SnapController.js.map +1 -0
- package/dist/snaps/Timer.d.ts +39 -0
- package/dist/snaps/Timer.js +86 -0
- package/dist/snaps/Timer.js.map +1 -0
- package/dist/snaps/endowments/cronjob.d.ts +49 -0
- package/dist/snaps/endowments/cronjob.js +105 -0
- package/dist/snaps/endowments/cronjob.js.map +1 -0
- package/dist/snaps/endowments/enum.d.ts +8 -0
- package/dist/snaps/endowments/enum.js +13 -0
- package/dist/snaps/endowments/enum.js.map +1 -0
- package/dist/snaps/endowments/ethereum-provider.d.ts +13 -0
- package/dist/snaps/endowments/ethereum-provider.js +31 -0
- package/dist/snaps/endowments/ethereum-provider.js.map +1 -0
- package/dist/snaps/endowments/index.d.ts +67 -0
- package/dist/snaps/endowments/index.js +39 -0
- package/dist/snaps/endowments/index.js.map +1 -0
- package/dist/snaps/endowments/keyring.d.ts +39 -0
- package/dist/snaps/endowments/keyring.js +103 -0
- package/dist/snaps/endowments/keyring.js.map +1 -0
- package/dist/snaps/endowments/long-running.d.ts +13 -0
- package/dist/snaps/endowments/long-running.js +28 -0
- package/dist/snaps/endowments/long-running.js.map +1 -0
- package/dist/snaps/endowments/network-access.d.ts +13 -0
- package/dist/snaps/endowments/network-access.js +29 -0
- package/dist/snaps/endowments/network-access.js.map +1 -0
- package/dist/snaps/endowments/transaction-insight.d.ts +38 -0
- package/dist/snaps/endowments/transaction-insight.js +106 -0
- package/dist/snaps/endowments/transaction-insight.js.map +1 -0
- package/dist/snaps/index.d.ts +4 -0
- package/dist/snaps/index.js +21 -0
- package/dist/snaps/index.js.map +1 -0
- package/dist/snaps/selectors.d.ts +2 -0
- package/dist/snaps/selectors.js +6 -0
- package/dist/snaps/selectors.js.map +1 -0
- package/dist/snaps/utils/index.d.ts +2 -0
- package/dist/snaps/utils/index.js +19 -0
- package/dist/snaps/utils/index.js.map +1 -0
- package/dist/snaps/utils/npm.d.ts +14 -0
- package/dist/snaps/utils/npm.js +81 -0
- package/dist/snaps/utils/npm.js.map +1 -0
- package/dist/snaps/utils/stream.d.ts +30 -0
- package/dist/snaps/utils/stream.js +124 -0
- package/dist/snaps/utils/stream.js.map +1 -0
- package/dist/utils.d.ts +128 -0
- package/dist/utils.js +92 -0
- package/dist/utils.js.map +1 -0
- package/package.json +99 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Copyright ConsenSys Software Inc. 2021. All rights reserved.
|
|
2
|
+
|
|
3
|
+
You acknowledge and agree that ConsenSys Software Inc. (“ConsenSys”) (or ConsenSys’s licensors) own all legal right, title and interest in and to the work, software, application, source code, documentation and any other documents in this repository (collectively, the “Program”), including any intellectual property rights which subsist in the Program (whether those rights happen to be registered or not, and wherever in the world those rights may exist), whether in source code or any other form.
|
|
4
|
+
|
|
5
|
+
Subject to the limited license below, you may not (and you may not permit anyone else to) distribute, publish, copy, modify, merge, combine with another program, create derivative works of, reverse engineer, decompile or otherwise attempt to extract the source code of, the Program or any part thereof, except that you may contribute to this repository.
|
|
6
|
+
|
|
7
|
+
You are granted a non-exclusive, non-transferable, non-sublicensable license to distribute, publish, copy, modify, merge, combine with another program or create derivative works of the Program (such resulting program, collectively, the “Resulting Program”) solely for Non-Commercial Use as long as you:
|
|
8
|
+
1. give prominent notice (“Notice”) with each copy of the Resulting Program that the Program is used in the Resulting Program and that the Program is the copyright of ConsenSys; and
|
|
9
|
+
2. subject the Resulting Program and any distribution, publication, copy, modification, merger therewith, combination with another program or derivative works thereof to the same Notice requirement and Non-Commercial Use restriction set forth herein.
|
|
10
|
+
|
|
11
|
+
“Non-Commercial Use” means each use as described in clauses (1)-(3) below, as reasonably determined by ConsenSys in its sole discretion:
|
|
12
|
+
1. personal use for research, personal study, private entertainment, hobby projects or amateur pursuits, in each case without any anticipated commercial application;
|
|
13
|
+
2. use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization or government institution; or
|
|
14
|
+
3. the number of monthly active users of the Resulting Program across all versions thereof and platforms globally do not exceed 10,000 at any time.
|
|
15
|
+
|
|
16
|
+
You will not use any trade mark, service mark, trade name, logo of ConsenSys or any other company or organization in a way that is likely or intended to cause confusion about the owner or authorized user of such marks, names or logos.
|
|
17
|
+
|
|
18
|
+
If you have any questions, comments or interest in pursuing any other use cases, please reach out to us at metamask.license@consensys.net.
|
package/README.md
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { BaseControllerV2 as BaseController, RestrictedControllerMessenger, GetPermissions } from '@metamask/controllers';
|
|
2
|
+
import { SnapId, CronjobSpecification } from '@metamask/snaps-utils';
|
|
3
|
+
import { GetAllSnaps, HandleSnapRequest, SnapInstalled, SnapRemoved, SnapUpdated } from '..';
|
|
4
|
+
import { Timer } from '../snaps/Timer';
|
|
5
|
+
export declare type CronjobControllerActions = GetAllSnaps | HandleSnapRequest | GetPermissions;
|
|
6
|
+
export declare type CronjobControllerEvents = SnapInstalled | SnapRemoved | SnapUpdated;
|
|
7
|
+
export declare type CronjobControllerMessenger = RestrictedControllerMessenger<'CronjobController', CronjobControllerActions, CronjobControllerEvents, CronjobControllerActions['type'], CronjobControllerEvents['type']>;
|
|
8
|
+
export declare const DAILY_TIMEOUT: number;
|
|
9
|
+
export declare type CronjobControllerArgs = {
|
|
10
|
+
messenger: CronjobControllerMessenger;
|
|
11
|
+
/**
|
|
12
|
+
* Persisted state that will be used for rehydration.
|
|
13
|
+
*/
|
|
14
|
+
state?: CronjobControllerState;
|
|
15
|
+
};
|
|
16
|
+
export declare type Cronjob = {
|
|
17
|
+
timer?: Timer;
|
|
18
|
+
id: string;
|
|
19
|
+
snapId: SnapId;
|
|
20
|
+
} & CronjobSpecification;
|
|
21
|
+
export declare type StoredJobInformation = {
|
|
22
|
+
lastRun: number;
|
|
23
|
+
};
|
|
24
|
+
export declare type CronjobControllerState = {
|
|
25
|
+
jobs: Record<string, StoredJobInformation>;
|
|
26
|
+
};
|
|
27
|
+
declare const controllerName = "CronjobController";
|
|
28
|
+
/**
|
|
29
|
+
* Use this controller to register and schedule periodically executed jobs
|
|
30
|
+
* using RPC method hooks.
|
|
31
|
+
*/
|
|
32
|
+
export declare class CronjobController extends BaseController<typeof controllerName, CronjobControllerState, CronjobControllerMessenger> {
|
|
33
|
+
#private;
|
|
34
|
+
constructor({ messenger, state }: CronjobControllerArgs);
|
|
35
|
+
/**
|
|
36
|
+
* Retrieve all cronjob specifications for all runnable snaps.
|
|
37
|
+
*
|
|
38
|
+
* @returns Array of Cronjob specifications.
|
|
39
|
+
*/
|
|
40
|
+
private getAllJobs;
|
|
41
|
+
/**
|
|
42
|
+
* Retrieve all Cronjob specifications for a Snap.
|
|
43
|
+
*
|
|
44
|
+
* @param snapId - ID of a Snap.
|
|
45
|
+
* @returns Array of Cronjob specifications.
|
|
46
|
+
*/
|
|
47
|
+
private getSnapJobs;
|
|
48
|
+
/**
|
|
49
|
+
* Register cron jobs for a given snap by getting specification from a permission caveats.
|
|
50
|
+
* Once registered, each job will be scheduled.
|
|
51
|
+
*
|
|
52
|
+
* @param snapId - ID of a snap.
|
|
53
|
+
*/
|
|
54
|
+
register(snapId: SnapId): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* Schedule a new job.
|
|
57
|
+
* This will interpret the cron expression and tell the timer to execute the job
|
|
58
|
+
* at the next suitable point in time.
|
|
59
|
+
* Job last run state will be initialized afterwards.
|
|
60
|
+
*
|
|
61
|
+
* Note: Schedule will be skipped if the job's execution time is too far in the future and
|
|
62
|
+
* will be revisited on a daily check.
|
|
63
|
+
*
|
|
64
|
+
* @param job - Cronjob specification.
|
|
65
|
+
*/
|
|
66
|
+
private schedule;
|
|
67
|
+
/**
|
|
68
|
+
* Execute job.
|
|
69
|
+
*
|
|
70
|
+
* @param job - Cronjob specification.
|
|
71
|
+
*/
|
|
72
|
+
private executeCronjob;
|
|
73
|
+
/**
|
|
74
|
+
* Unregister all jobs related to the given snapId.
|
|
75
|
+
*
|
|
76
|
+
* @param snapId - ID of a snap.
|
|
77
|
+
*/
|
|
78
|
+
unregister(snapId: SnapId): void;
|
|
79
|
+
/**
|
|
80
|
+
* Update time of a last run for the Cronjob specified by ID.
|
|
81
|
+
*
|
|
82
|
+
* @param jobId - ID of a cron job.
|
|
83
|
+
* @param lastRun - Unix timestamp when the job was last ran.
|
|
84
|
+
*/
|
|
85
|
+
private updateJobLastRunState;
|
|
86
|
+
/**
|
|
87
|
+
* Runs every 24 hours to check if new jobs need to be scheduled.
|
|
88
|
+
*
|
|
89
|
+
* This is necesary for longer running jobs that execute with more than 24 hours between them.
|
|
90
|
+
*/
|
|
91
|
+
dailyCheckIn(): Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* Run controller teardown process and unsubscribe from Snap events.
|
|
94
|
+
*/
|
|
95
|
+
destroy(): void;
|
|
96
|
+
/**
|
|
97
|
+
* Handle cron jobs on 'snapInstalled' event.
|
|
98
|
+
*
|
|
99
|
+
* @param snap - Basic Snap information.
|
|
100
|
+
*/
|
|
101
|
+
private _handleEventSnapInstalled;
|
|
102
|
+
/**
|
|
103
|
+
* Handle cron jobs on 'snapRemoved' event.
|
|
104
|
+
*
|
|
105
|
+
* @param snap - Basic Snap information.
|
|
106
|
+
*/
|
|
107
|
+
private _handleEventSnapRemoved;
|
|
108
|
+
/**
|
|
109
|
+
* Handle cron jobs on 'snapUpdated' event.
|
|
110
|
+
*
|
|
111
|
+
* @param snap - Basic Snap information.
|
|
112
|
+
*/
|
|
113
|
+
private _handleEventSnapUpdated;
|
|
114
|
+
}
|
|
115
|
+
export {};
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _CronjobController_messenger, _CronjobController_dailyTimer, _CronjobController_timers, _CronjobController_snapIds;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.CronjobController = exports.DAILY_TIMEOUT = void 0;
|
|
16
|
+
const controllers_1 = require("@metamask/controllers");
|
|
17
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
18
|
+
const utils_1 = require("@metamask/utils");
|
|
19
|
+
const __1 = require("..");
|
|
20
|
+
const cronjob_1 = require("../snaps/endowments/cronjob");
|
|
21
|
+
const Timer_1 = require("../snaps/Timer");
|
|
22
|
+
exports.DAILY_TIMEOUT = (0, utils_1.inMilliseconds)(24, utils_1.Duration.Hour);
|
|
23
|
+
const controllerName = 'CronjobController';
|
|
24
|
+
/**
|
|
25
|
+
* Use this controller to register and schedule periodically executed jobs
|
|
26
|
+
* using RPC method hooks.
|
|
27
|
+
*/
|
|
28
|
+
class CronjobController extends controllers_1.BaseControllerV2 {
|
|
29
|
+
constructor({ messenger, state }) {
|
|
30
|
+
super({
|
|
31
|
+
messenger,
|
|
32
|
+
metadata: {
|
|
33
|
+
jobs: { persist: true, anonymous: false },
|
|
34
|
+
},
|
|
35
|
+
name: controllerName,
|
|
36
|
+
state: Object.assign({ jobs: {} }, state),
|
|
37
|
+
});
|
|
38
|
+
_CronjobController_messenger.set(this, void 0);
|
|
39
|
+
_CronjobController_dailyTimer.set(this, void 0);
|
|
40
|
+
_CronjobController_timers.set(this, void 0);
|
|
41
|
+
// Mapping from jobId to snapId
|
|
42
|
+
_CronjobController_snapIds.set(this, void 0);
|
|
43
|
+
__classPrivateFieldSet(this, _CronjobController_timers, new Map(), "f");
|
|
44
|
+
__classPrivateFieldSet(this, _CronjobController_snapIds, new Map(), "f");
|
|
45
|
+
__classPrivateFieldSet(this, _CronjobController_messenger, messenger, "f");
|
|
46
|
+
this.dailyCheckIn();
|
|
47
|
+
this._handleEventSnapInstalled = this._handleEventSnapInstalled.bind(this);
|
|
48
|
+
this._handleEventSnapRemoved = this._handleEventSnapRemoved.bind(this);
|
|
49
|
+
this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);
|
|
50
|
+
// Subscribe to Snap events
|
|
51
|
+
this.messagingSystem.subscribe('SnapController:snapInstalled', this._handleEventSnapInstalled);
|
|
52
|
+
this.messagingSystem.subscribe('SnapController:snapRemoved', this._handleEventSnapRemoved);
|
|
53
|
+
this.messagingSystem.subscribe('SnapController:snapUpdated', this._handleEventSnapUpdated);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Retrieve all cronjob specifications for all runnable snaps.
|
|
57
|
+
*
|
|
58
|
+
* @returns Array of Cronjob specifications.
|
|
59
|
+
*/
|
|
60
|
+
async getAllJobs() {
|
|
61
|
+
const snaps = await this.messagingSystem.call('SnapController:getAll');
|
|
62
|
+
const filteredSnaps = (0, __1.getRunnableSnaps)(snaps);
|
|
63
|
+
const jobs = await Promise.all(filteredSnaps.map((snap) => this.getSnapJobs(snap.id)));
|
|
64
|
+
return (0, snaps_utils_1.flatten)(jobs).filter((job) => job !== undefined);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Retrieve all Cronjob specifications for a Snap.
|
|
68
|
+
*
|
|
69
|
+
* @param snapId - ID of a Snap.
|
|
70
|
+
* @returns Array of Cronjob specifications.
|
|
71
|
+
*/
|
|
72
|
+
async getSnapJobs(snapId) {
|
|
73
|
+
const permissions = await __classPrivateFieldGet(this, _CronjobController_messenger, "f").call('PermissionController:getPermissions', snapId);
|
|
74
|
+
const permission = permissions === null || permissions === void 0 ? void 0 : permissions[__1.SnapEndowments.Cronjob];
|
|
75
|
+
const definitions = (0, cronjob_1.getCronjobCaveatJobs)(permission);
|
|
76
|
+
return definitions === null || definitions === void 0 ? void 0 : definitions.map((definition, idx) => {
|
|
77
|
+
return Object.assign(Object.assign({}, definition), { id: `${snapId}-${idx}`, snapId });
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Register cron jobs for a given snap by getting specification from a permission caveats.
|
|
82
|
+
* Once registered, each job will be scheduled.
|
|
83
|
+
*
|
|
84
|
+
* @param snapId - ID of a snap.
|
|
85
|
+
*/
|
|
86
|
+
async register(snapId) {
|
|
87
|
+
const jobs = await this.getSnapJobs(snapId);
|
|
88
|
+
jobs === null || jobs === void 0 ? void 0 : jobs.forEach((job) => this.schedule(job));
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Schedule a new job.
|
|
92
|
+
* This will interpret the cron expression and tell the timer to execute the job
|
|
93
|
+
* at the next suitable point in time.
|
|
94
|
+
* Job last run state will be initialized afterwards.
|
|
95
|
+
*
|
|
96
|
+
* Note: Schedule will be skipped if the job's execution time is too far in the future and
|
|
97
|
+
* will be revisited on a daily check.
|
|
98
|
+
*
|
|
99
|
+
* @param job - Cronjob specification.
|
|
100
|
+
*/
|
|
101
|
+
schedule(job) {
|
|
102
|
+
if (__classPrivateFieldGet(this, _CronjobController_timers, "f").has(job.id)) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const parsed = (0, snaps_utils_1.parseCronExpression)(job.expression);
|
|
106
|
+
const next = parsed.next();
|
|
107
|
+
const now = new Date();
|
|
108
|
+
const ms = next.getTime() - now.getTime();
|
|
109
|
+
// Don't schedule this job yet as it is too far in the future
|
|
110
|
+
if (ms > exports.DAILY_TIMEOUT) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const timer = new Timer_1.Timer(ms);
|
|
114
|
+
timer.start(() => {
|
|
115
|
+
this.executeCronjob(job);
|
|
116
|
+
__classPrivateFieldGet(this, _CronjobController_timers, "f").delete(job.id);
|
|
117
|
+
this.schedule(job);
|
|
118
|
+
});
|
|
119
|
+
this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually
|
|
120
|
+
__classPrivateFieldGet(this, _CronjobController_timers, "f").set(job.id, timer);
|
|
121
|
+
__classPrivateFieldGet(this, _CronjobController_snapIds, "f").set(job.id, job.snapId);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Execute job.
|
|
125
|
+
*
|
|
126
|
+
* @param job - Cronjob specification.
|
|
127
|
+
*/
|
|
128
|
+
executeCronjob(job) {
|
|
129
|
+
this.updateJobLastRunState(job.id, Date.now());
|
|
130
|
+
__classPrivateFieldGet(this, _CronjobController_messenger, "f").call('SnapController:handleRequest', {
|
|
131
|
+
snapId: job.snapId,
|
|
132
|
+
origin: '',
|
|
133
|
+
handler: snaps_utils_1.HandlerType.OnCronjob,
|
|
134
|
+
request: job.request,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Unregister all jobs related to the given snapId.
|
|
139
|
+
*
|
|
140
|
+
* @param snapId - ID of a snap.
|
|
141
|
+
*/
|
|
142
|
+
unregister(snapId) {
|
|
143
|
+
const jobs = [...__classPrivateFieldGet(this, _CronjobController_snapIds, "f").entries()].filter(([_, jobSnapId]) => jobSnapId === snapId);
|
|
144
|
+
if (jobs.length) {
|
|
145
|
+
jobs.forEach(([id]) => {
|
|
146
|
+
const timer = __classPrivateFieldGet(this, _CronjobController_timers, "f").get(id);
|
|
147
|
+
if (timer) {
|
|
148
|
+
timer.cancel();
|
|
149
|
+
__classPrivateFieldGet(this, _CronjobController_timers, "f").delete(id);
|
|
150
|
+
__classPrivateFieldGet(this, _CronjobController_snapIds, "f").delete(id);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Update time of a last run for the Cronjob specified by ID.
|
|
157
|
+
*
|
|
158
|
+
* @param jobId - ID of a cron job.
|
|
159
|
+
* @param lastRun - Unix timestamp when the job was last ran.
|
|
160
|
+
*/
|
|
161
|
+
updateJobLastRunState(jobId, lastRun) {
|
|
162
|
+
this.update((state) => {
|
|
163
|
+
state.jobs[jobId] = {
|
|
164
|
+
lastRun,
|
|
165
|
+
};
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Runs every 24 hours to check if new jobs need to be scheduled.
|
|
170
|
+
*
|
|
171
|
+
* This is necesary for longer running jobs that execute with more than 24 hours between them.
|
|
172
|
+
*/
|
|
173
|
+
async dailyCheckIn() {
|
|
174
|
+
const jobs = await this.getAllJobs();
|
|
175
|
+
jobs.forEach((job) => {
|
|
176
|
+
var _a;
|
|
177
|
+
const parsed = (0, snaps_utils_1.parseCronExpression)(job.expression);
|
|
178
|
+
const lastRun = (_a = this.state.jobs[job.id]) === null || _a === void 0 ? void 0 : _a.lastRun;
|
|
179
|
+
// If a job was supposed to run while we were shut down but wasn't we run it now
|
|
180
|
+
if (lastRun !== undefined &&
|
|
181
|
+
parsed.hasPrev() &&
|
|
182
|
+
parsed.prev().getTime() > lastRun) {
|
|
183
|
+
this.executeCronjob(job);
|
|
184
|
+
}
|
|
185
|
+
// Try scheduling, will fail if an existing scheduled job is found
|
|
186
|
+
this.schedule(job);
|
|
187
|
+
});
|
|
188
|
+
__classPrivateFieldSet(this, _CronjobController_dailyTimer, new Timer_1.Timer(exports.DAILY_TIMEOUT), "f");
|
|
189
|
+
__classPrivateFieldGet(this, _CronjobController_dailyTimer, "f").start(() => this.dailyCheckIn());
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Run controller teardown process and unsubscribe from Snap events.
|
|
193
|
+
*/
|
|
194
|
+
destroy() {
|
|
195
|
+
super.destroy();
|
|
196
|
+
this.messagingSystem.unsubscribe('SnapController:snapInstalled', this._handleEventSnapInstalled);
|
|
197
|
+
this.messagingSystem.unsubscribe('SnapController:snapRemoved', this._handleEventSnapRemoved);
|
|
198
|
+
this.messagingSystem.unsubscribe('SnapController:snapUpdated', this._handleEventSnapUpdated);
|
|
199
|
+
__classPrivateFieldGet(this, _CronjobController_snapIds, "f").forEach((snapId) => {
|
|
200
|
+
this.unregister(snapId);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Handle cron jobs on 'snapInstalled' event.
|
|
205
|
+
*
|
|
206
|
+
* @param snap - Basic Snap information.
|
|
207
|
+
*/
|
|
208
|
+
async _handleEventSnapInstalled(snap) {
|
|
209
|
+
await this.register(snap.id);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Handle cron jobs on 'snapRemoved' event.
|
|
213
|
+
*
|
|
214
|
+
* @param snap - Basic Snap information.
|
|
215
|
+
*/
|
|
216
|
+
_handleEventSnapRemoved(snap) {
|
|
217
|
+
this.unregister(snap.id);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Handle cron jobs on 'snapUpdated' event.
|
|
221
|
+
*
|
|
222
|
+
* @param snap - Basic Snap information.
|
|
223
|
+
*/
|
|
224
|
+
async _handleEventSnapUpdated(snap) {
|
|
225
|
+
this.unregister(snap.id);
|
|
226
|
+
await this.register(snap.id);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
exports.CronjobController = CronjobController;
|
|
230
|
+
_CronjobController_messenger = new WeakMap(), _CronjobController_dailyTimer = new WeakMap(), _CronjobController_timers = new WeakMap(), _CronjobController_snapIds = new WeakMap();
|
|
231
|
+
//# sourceMappingURL=CronjobController.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CronjobController.js","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uDAI+B;AAC/B,uDAO+B;AAC/B,2CAA2D;AAC3D,0BAQY;AACZ,yDAAmE;AACnE,0CAAuC;AAiB1B,QAAA,aAAa,GAAG,IAAA,sBAAc,EAAC,EAAE,EAAE,gBAAQ,CAAC,IAAI,CAAC,CAAC;AAwB/D,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAE3C;;;GAGG;AACH,MAAa,iBAAkB,SAAQ,8BAItC;IAUC,YAAY,EAAE,SAAS,EAAE,KAAK,EAAyB;QACrD,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,IAAI,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;aAC1C;YACD,IAAI,EAAE,cAAc;YACpB,KAAK,kBACH,IAAI,EAAE,EAAE,IACL,KAAK,CACT;SACF,CAAC,CAAC;QApBL,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AzQD,8CAyQC","sourcesContent":["import {\n BaseControllerV2 as BaseController,\n RestrictedControllerMessenger,\n GetPermissions,\n} from '@metamask/controllers';\nimport {\n HandlerType,\n SnapId,\n TruncatedSnap,\n CronjobSpecification,\n flatten,\n parseCronExpression,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\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: 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 this.dailyCheckIn();\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 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 }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private async getAllJobs(): Promise<Cronjob[]> {\n const snaps = await this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = await Promise.all(\n filteredSnaps.map((snap) => this.getSnapJobs(snap.id)),\n );\n return flatten(jobs).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 async getSnapJobs(snapId: SnapId): Promise<Cronjob[] | undefined> {\n const permissions = await 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 async register(snapId: SnapId) {\n const jobs = await 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 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);\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 executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n 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 = await this.getAllJobs();\n jobs.forEach((job) => {\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 this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n });\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => this.dailyCheckIn());\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\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\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 async _handleEventSnapInstalled(snap: TruncatedSnap) {\n await 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 async _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n await this.register(snap.id);\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './CronjobController';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./CronjobController"), exports);
|
|
18
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cronjob/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC","sourcesContent":["export * from './CronjobController';\n"]}
|
package/dist/fsm.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { EventObject, StateMachine, Typestate } from '@xstate/fsm';
|
|
2
|
+
/**
|
|
3
|
+
* Validates the set-up of a @xstate/fsm machine.
|
|
4
|
+
*
|
|
5
|
+
* 1. Ensures that all named actions in the config have a provided implementation.
|
|
6
|
+
*
|
|
7
|
+
* @param machine - The machine to validate.
|
|
8
|
+
* @throws {@link AssertionError}. If the validation fails.
|
|
9
|
+
*/
|
|
10
|
+
export declare function validateMachine<TContext extends object, TEvent extends EventObject, TState extends Typestate<TContext>>(machine: StateMachine.Machine<TContext, TEvent, TState>): void;
|
|
11
|
+
/**
|
|
12
|
+
* Ensure that the interpreter is strict.
|
|
13
|
+
* Strict means that the transition must occur.
|
|
14
|
+
* The event must exist in .on {} state config and it's guard must succeed.
|
|
15
|
+
*
|
|
16
|
+
* The error will be thrown when an invalid `interpreter.send()` is called
|
|
17
|
+
* and will be bubbled there.
|
|
18
|
+
*
|
|
19
|
+
* TODO(ritave): Doesn't support self transitions.
|
|
20
|
+
*
|
|
21
|
+
* @param interpreter - The interpreter that will be force into strict mode.
|
|
22
|
+
* @throws {@link Error} Thrown when the transition is invalid.
|
|
23
|
+
*/
|
|
24
|
+
export declare function forceStrict(interpreter: StateMachine.Service<any, any, any>): void;
|
package/dist/fsm.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.forceStrict = exports.validateMachine = void 0;
|
|
4
|
+
const utils_1 = require("@metamask/utils");
|
|
5
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
6
|
+
const fsm_1 = require("@xstate/fsm");
|
|
7
|
+
/**
|
|
8
|
+
* Validates the set-up of a @xstate/fsm machine.
|
|
9
|
+
*
|
|
10
|
+
* 1. Ensures that all named actions in the config have a provided implementation.
|
|
11
|
+
*
|
|
12
|
+
* @param machine - The machine to validate.
|
|
13
|
+
* @throws {@link AssertionError}. If the validation fails.
|
|
14
|
+
*/
|
|
15
|
+
function validateMachine(machine) {
|
|
16
|
+
var _a;
|
|
17
|
+
(0, utils_1.assert)('_options' in machine, 'The machine is not an @xstate/fsm machine');
|
|
18
|
+
const typed = machine;
|
|
19
|
+
// 1.
|
|
20
|
+
const toArray = (obj) => {
|
|
21
|
+
if (Array.isArray(obj)) {
|
|
22
|
+
return obj;
|
|
23
|
+
}
|
|
24
|
+
else if (obj === undefined || obj === null) {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
return [obj];
|
|
28
|
+
};
|
|
29
|
+
const allActions = new Set();
|
|
30
|
+
const addActions = (actions) => (0, snaps_utils_1.flatMap)(toArray(actions), (action) => {
|
|
31
|
+
if (typeof action === 'string') {
|
|
32
|
+
return [action];
|
|
33
|
+
}
|
|
34
|
+
(0, utils_1.assert)(typeof action === 'function');
|
|
35
|
+
return [];
|
|
36
|
+
}).forEach(allActions.add.bind(allActions));
|
|
37
|
+
for (const state of Object.values(typed.config.states)) {
|
|
38
|
+
addActions(state.entry);
|
|
39
|
+
addActions(state.exit);
|
|
40
|
+
for (const transition of Object.values((_a = state.on) !== null && _a !== void 0 ? _a : {})) {
|
|
41
|
+
addActions(transition.actions);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
allActions.forEach((action) => (0, utils_1.assert)(typed._options.actions !== undefined && action in typed._options.actions, `Action "${action}" doesn't have an implementation`));
|
|
45
|
+
}
|
|
46
|
+
exports.validateMachine = validateMachine;
|
|
47
|
+
/**
|
|
48
|
+
* Ensure that the interpreter is strict.
|
|
49
|
+
* Strict means that the transition must occur.
|
|
50
|
+
* The event must exist in .on {} state config and it's guard must succeed.
|
|
51
|
+
*
|
|
52
|
+
* The error will be thrown when an invalid `interpreter.send()` is called
|
|
53
|
+
* and will be bubbled there.
|
|
54
|
+
*
|
|
55
|
+
* TODO(ritave): Doesn't support self transitions.
|
|
56
|
+
*
|
|
57
|
+
* @param interpreter - The interpreter that will be force into strict mode.
|
|
58
|
+
* @throws {@link Error} Thrown when the transition is invalid.
|
|
59
|
+
*/
|
|
60
|
+
function forceStrict(interpreter) {
|
|
61
|
+
// As soon as a listener subscribes, it is called. It might be called in
|
|
62
|
+
// an initial state which doesn't have the .changed property
|
|
63
|
+
let onInitialCalled = false;
|
|
64
|
+
interpreter.subscribe((state) => {
|
|
65
|
+
(0, utils_1.assert)(!onInitialCalled || state.changed, 'Invalid state transition');
|
|
66
|
+
onInitialCalled = true;
|
|
67
|
+
});
|
|
68
|
+
const ogSend = interpreter.send.bind(interpreter);
|
|
69
|
+
interpreter.send = (...args) => {
|
|
70
|
+
(0, utils_1.assert)(interpreter.status === fsm_1.InterpreterStatus.Running, 'Interpreter is stopped');
|
|
71
|
+
return ogSend(...args);
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
exports.forceStrict = forceStrict;
|
|
75
|
+
//# sourceMappingURL=fsm.js.map
|
package/dist/fsm.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vB,KAAK,MAAM,UAAU,IAAI,MAAM,CAAC,MAAM,CAAM,MAAA,KAAK,CAAC,EAAE,mCAAI,EAAE,CAAC,EAAE;YAC3D,UAAU,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;SAChC;KACF;IAED,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CAC5B,IAAA,cAAM,EACJ,KAAK,CAAC,QAAQ,CAAC,OAAO,KAAK,SAAS,IAAI,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,EACxE,WAAW,MAAM,kCAAkC,CACpD,CACF,CAAC;AACJ,CAAC;AA7CD,0CA6CC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CAAC,WAAgD;IAC1E,wEAAwE;IACxE,4DAA4D;IAC5D,IAAI,eAAe,GAAG,KAAK,CAAC;IAC5B,WAAW,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;QAC9B,IAAA,cAAM,EAAC,CAAC,eAAe,IAAI,KAAK,CAAC,OAAO,EAAE,0BAA0B,CAAC,CAAC;QACtE,eAAe,GAAG,IAAI,CAAC;IACzB,CAAC,CAAC,CAAC;IAEH,MAAM,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,WAAW,CAAC,IAAI,GAAG,CAAC,GAAG,IAAI,EAAE,EAAE;QAC7B,IAAA,cAAM,EACJ,WAAW,CAAC,MAAM,KAAK,uBAAiB,CAAC,OAAO,EAChD,wBAAwB,CACzB,CAAC;QACF,OAAO,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC;AAjBD,kCAiBC","sourcesContent":["import { assert } from '@metamask/utils';\nimport { flatMap } from '@metamask/snaps-utils';\nimport {\n EventObject,\n InterpreterStatus,\n StateMachine,\n Typestate,\n} 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 = <T>(obj: T | T[]): T[] => {\n if (Array.isArray(obj)) {\n return obj;\n } else if (obj === undefined || obj === null) {\n return [];\n }\n return [obj];\n };\n const allActions = new Set<string>();\n const addActions = (actions: any) =>\n flatMap(toArray(actions), (action) => {\n if (typeof action === 'string') {\n return [action];\n }\n assert(typeof action === 'function');\n return [];\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"]}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./services"), exports);
|
|
18
|
+
__exportStar(require("./snaps"), exports);
|
|
19
|
+
__exportStar(require("./utils"), exports);
|
|
20
|
+
__exportStar(require("./multichain"), exports);
|
|
21
|
+
__exportStar(require("./cronjob"), exports);
|
|
22
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,6CAA2B;AAC3B,0CAAwB;AACxB,0CAAwB;AACxB,+CAA6B;AAC7B,4CAA0B","sourcesContent":["export type { Json } from '@metamask/controllers';\nexport * from './services';\nexport * from './snaps';\nexport * from './utils';\nexport * from './multichain';\nexport * from './cronjob';\n"]}
|