@metamask/snaps-controllers 11.1.0 → 11.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -1
- package/dist/cronjob/CronjobController.cjs +2 -2
- package/dist/cronjob/CronjobController.cjs.map +1 -1
- package/dist/cronjob/CronjobController.mjs +2 -2
- package/dist/cronjob/CronjobController.mjs.map +1 -1
- package/dist/insights/SnapInsightsController.cjs +1 -1
- package/dist/insights/SnapInsightsController.cjs.map +1 -1
- package/dist/insights/SnapInsightsController.mjs +1 -1
- package/dist/insights/SnapInsightsController.mjs.map +1 -1
- package/dist/interface/SnapInterfaceController.cjs +1 -8
- package/dist/interface/SnapInterfaceController.cjs.map +1 -1
- package/dist/interface/SnapInterfaceController.d.cts +2 -2
- package/dist/interface/SnapInterfaceController.d.cts.map +1 -1
- package/dist/interface/SnapInterfaceController.d.mts +2 -2
- package/dist/interface/SnapInterfaceController.d.mts.map +1 -1
- package/dist/interface/SnapInterfaceController.mjs +1 -8
- package/dist/interface/SnapInterfaceController.mjs.map +1 -1
- package/dist/interface/utils.cjs +2 -2
- package/dist/interface/utils.cjs.map +1 -1
- package/dist/interface/utils.d.cts +2 -2
- package/dist/interface/utils.d.mts +2 -2
- package/dist/interface/utils.mjs +2 -2
- package/dist/interface/utils.mjs.map +1 -1
- package/dist/multichain/MultichainRouter.cjs +7 -3
- package/dist/multichain/MultichainRouter.cjs.map +1 -1
- package/dist/multichain/MultichainRouter.d.cts +3 -0
- package/dist/multichain/MultichainRouter.d.cts.map +1 -1
- package/dist/multichain/MultichainRouter.d.mts +3 -0
- package/dist/multichain/MultichainRouter.d.mts.map +1 -1
- package/dist/multichain/MultichainRouter.mjs +7 -3
- package/dist/multichain/MultichainRouter.mjs.map +1 -1
- package/dist/snaps/SnapController.cjs +69 -54
- package/dist/snaps/SnapController.cjs.map +1 -1
- package/dist/snaps/SnapController.d.cts +2 -1
- package/dist/snaps/SnapController.d.cts.map +1 -1
- package/dist/snaps/SnapController.d.mts +2 -1
- package/dist/snaps/SnapController.d.mts.map +1 -1
- package/dist/snaps/SnapController.mjs +72 -57
- package/dist/snaps/SnapController.mjs.map +1 -1
- package/dist/snaps/constants.cjs +5 -1
- package/dist/snaps/constants.cjs.map +1 -1
- package/dist/snaps/constants.d.cts +4 -0
- package/dist/snaps/constants.d.cts.map +1 -1
- package/dist/snaps/constants.d.mts +4 -0
- package/dist/snaps/constants.d.mts.map +1 -1
- package/dist/snaps/constants.mjs +4 -0
- package/dist/snaps/constants.mjs.map +1 -1
- package/dist/utils.cjs +29 -1
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +20 -4
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +20 -4
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +27 -0
- package/dist/utils.mjs.map +1 -1
- package/package.json +14 -23
package/dist/snaps/constants.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS = exports.ALLOWED_PERMISSIONS = void 0;
|
|
3
|
+
exports.STATE_DEBOUNCE_TIMEOUT = exports.LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS = exports.ALLOWED_PERMISSIONS = void 0;
|
|
4
4
|
const snaps_rpc_methods_1 = require("@metamask/snaps-rpc-methods");
|
|
5
5
|
// These permissions are allowed without being on the allowlist.
|
|
6
6
|
exports.ALLOWED_PERMISSIONS = Object.freeze([
|
|
@@ -21,4 +21,8 @@ exports.LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS = {
|
|
|
21
21
|
iterations: 10000,
|
|
22
22
|
},
|
|
23
23
|
};
|
|
24
|
+
/**
|
|
25
|
+
* The timeout for debouncing state updates.
|
|
26
|
+
*/
|
|
27
|
+
exports.STATE_DEBOUNCE_TIMEOUT = 500;
|
|
24
28
|
//# sourceMappingURL=constants.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":";;;AAAA,mEAA6D;AAE7D,gEAAgE;AACnD,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,aAAa;IACb,kBAAkB;IAClB,aAAa;IACb,gBAAgB;IAChB,kCAAc,CAAC,OAAO;IACtB,kCAAc,CAAC,QAAQ;IACvB,kCAAc,CAAC,cAAc;IAC7B,kCAAc,CAAC,gBAAgB;IAC/B,kCAAc,CAAC,kBAAkB;IACjC,kCAAc,CAAC,gBAAgB;CAChC,CAAC,CAAC;AAEU,QAAA,wCAAwC,GAAG;IACtD,SAAS,EAAE,QAAiB;IAC5B,MAAM,EAAE;QACN,UAAU,EAAE,KAAM;KACnB;CACF,CAAC","sourcesContent":["import { SnapEndowments } from '@metamask/snaps-rpc-methods';\n\n// These permissions are allowed without being on the allowlist.\nexport const ALLOWED_PERMISSIONS = Object.freeze([\n 'snap_dialog',\n 'snap_manageState',\n 'snap_notify',\n 'snap_getLocale',\n SnapEndowments.Cronjob,\n SnapEndowments.HomePage,\n SnapEndowments.LifecycleHooks,\n SnapEndowments.EthereumProvider,\n SnapEndowments.TransactionInsight,\n SnapEndowments.SignatureInsight,\n]);\n\nexport const LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS = {\n algorithm: 'PBKDF2' as const,\n params: {\n iterations: 10_000,\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":";;;AAAA,mEAA6D;AAE7D,gEAAgE;AACnD,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,aAAa;IACb,kBAAkB;IAClB,aAAa;IACb,gBAAgB;IAChB,kCAAc,CAAC,OAAO;IACtB,kCAAc,CAAC,QAAQ;IACvB,kCAAc,CAAC,cAAc;IAC7B,kCAAc,CAAC,gBAAgB;IAC/B,kCAAc,CAAC,kBAAkB;IACjC,kCAAc,CAAC,gBAAgB;CAChC,CAAC,CAAC;AAEU,QAAA,wCAAwC,GAAG;IACtD,SAAS,EAAE,QAAiB;IAC5B,MAAM,EAAE;QACN,UAAU,EAAE,KAAM;KACnB;CACF,CAAC;AAEF;;GAEG;AACU,QAAA,sBAAsB,GAAG,GAAG,CAAC","sourcesContent":["import { SnapEndowments } from '@metamask/snaps-rpc-methods';\n\n// These permissions are allowed without being on the allowlist.\nexport const ALLOWED_PERMISSIONS = Object.freeze([\n 'snap_dialog',\n 'snap_manageState',\n 'snap_notify',\n 'snap_getLocale',\n SnapEndowments.Cronjob,\n SnapEndowments.HomePage,\n SnapEndowments.LifecycleHooks,\n SnapEndowments.EthereumProvider,\n SnapEndowments.TransactionInsight,\n SnapEndowments.SignatureInsight,\n]);\n\nexport const LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS = {\n algorithm: 'PBKDF2' as const,\n params: {\n iterations: 10_000,\n },\n};\n\n/**\n * The timeout for debouncing state updates.\n */\nexport const STATE_DEBOUNCE_TIMEOUT = 500;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,mBAAmB,mBAW9B,CAAC;AAEH,eAAO,MAAM,wCAAwC;;;;;CAKpD,CAAC"}
|
|
1
|
+
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,mBAAmB,mBAW9B,CAAC;AAEH,eAAO,MAAM,wCAAwC;;;;;CAKpD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,MAAM,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,mBAAmB,mBAW9B,CAAC;AAEH,eAAO,MAAM,wCAAwC;;;;;CAKpD,CAAC"}
|
|
1
|
+
{"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,mBAAmB,mBAW9B,CAAC;AAEH,eAAO,MAAM,wCAAwC;;;;;CAKpD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,MAAM,CAAC"}
|
package/dist/snaps/constants.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,oCAAoC;AAE7D,gEAAgE;AAChE,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,aAAa;IACb,kBAAkB;IAClB,aAAa;IACb,gBAAgB;IAChB,cAAc,CAAC,OAAO;IACtB,cAAc,CAAC,QAAQ;IACvB,cAAc,CAAC,cAAc;IAC7B,cAAc,CAAC,gBAAgB;IAC/B,cAAc,CAAC,kBAAkB;IACjC,cAAc,CAAC,gBAAgB;CAChC,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,wCAAwC,GAAG;IACtD,SAAS,EAAE,QAAiB;IAC5B,MAAM,EAAE;QACN,UAAU,EAAE,KAAM;KACnB;CACF,CAAC","sourcesContent":["import { SnapEndowments } from '@metamask/snaps-rpc-methods';\n\n// These permissions are allowed without being on the allowlist.\nexport const ALLOWED_PERMISSIONS = Object.freeze([\n 'snap_dialog',\n 'snap_manageState',\n 'snap_notify',\n 'snap_getLocale',\n SnapEndowments.Cronjob,\n SnapEndowments.HomePage,\n SnapEndowments.LifecycleHooks,\n SnapEndowments.EthereumProvider,\n SnapEndowments.TransactionInsight,\n SnapEndowments.SignatureInsight,\n]);\n\nexport const LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS = {\n algorithm: 'PBKDF2' as const,\n params: {\n iterations: 10_000,\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../../src/snaps/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,oCAAoC;AAE7D,gEAAgE;AAChE,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,aAAa;IACb,kBAAkB;IAClB,aAAa;IACb,gBAAgB;IAChB,cAAc,CAAC,OAAO;IACtB,cAAc,CAAC,QAAQ;IACvB,cAAc,CAAC,cAAc;IAC7B,cAAc,CAAC,gBAAgB;IAC/B,cAAc,CAAC,kBAAkB;IACjC,cAAc,CAAC,gBAAgB;CAChC,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,wCAAwC,GAAG;IACtD,SAAS,EAAE,QAAiB;IAC5B,MAAM,EAAE;QACN,UAAU,EAAE,KAAM;KACnB;CACF,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,GAAG,CAAC","sourcesContent":["import { SnapEndowments } from '@metamask/snaps-rpc-methods';\n\n// These permissions are allowed without being on the allowlist.\nexport const ALLOWED_PERMISSIONS = Object.freeze([\n 'snap_dialog',\n 'snap_manageState',\n 'snap_notify',\n 'snap_getLocale',\n SnapEndowments.Cronjob,\n SnapEndowments.HomePage,\n SnapEndowments.LifecycleHooks,\n SnapEndowments.EthereumProvider,\n SnapEndowments.TransactionInsight,\n SnapEndowments.SignatureInsight,\n]);\n\nexport const LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS = {\n algorithm: 'PBKDF2' as const,\n params: {\n iterations: 10_000,\n },\n};\n\n/**\n * The timeout for debouncing state updates.\n */\nexport const STATE_DEBOUNCE_TIMEOUT = 500;\n"]}
|
package/dist/utils.cjs
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.fetchSnap = exports.getSnapFiles = exports.withTimeout = exports.hasTimedOut = exports.delayWithTimer = exports.delay = exports.permissionsDiff = exports.setDiff = void 0;
|
|
6
|
+
exports.debouncePersistState = exports.fetchSnap = exports.getSnapFiles = exports.withTimeout = exports.hasTimedOut = exports.delayWithTimer = exports.delay = exports.permissionsDiff = exports.setDiff = void 0;
|
|
7
7
|
const snaps_sdk_1 = require("@metamask/snaps-sdk");
|
|
8
8
|
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
9
9
|
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
|
|
@@ -171,4 +171,32 @@ async function fetchSnap(snapId, location) {
|
|
|
171
171
|
}
|
|
172
172
|
}
|
|
173
173
|
exports.fetchSnap = fetchSnap;
|
|
174
|
+
/**
|
|
175
|
+
* Debounce persisting Snap state changes.
|
|
176
|
+
*
|
|
177
|
+
* @param fn - The function to debounce.
|
|
178
|
+
* @param timeout - The timeout in milliseconds. Defaults to 1000.
|
|
179
|
+
* @returns The debounced function.
|
|
180
|
+
* @example
|
|
181
|
+
* const originalUpdate = (snapId, newSnapState, encrypted) => {
|
|
182
|
+
* console.log(`Called with Snap ID: ${snapId} and state: ${newSnapState}`);
|
|
183
|
+
* };
|
|
184
|
+
*
|
|
185
|
+
* const debouncedUpdate = debounce(originalUpdate);
|
|
186
|
+
* debouncedFunction('npm:foo-snap', { foo: 'bar' }, false);
|
|
187
|
+
*/
|
|
188
|
+
function debouncePersistState(fn, timeout = 1000) {
|
|
189
|
+
const timeouts = new Map();
|
|
190
|
+
return (snapId, newSnapState, encrypted) => {
|
|
191
|
+
const key = `${snapId}-${encrypted}`;
|
|
192
|
+
if (timeouts.has(key)) {
|
|
193
|
+
clearTimeout(timeouts.get(key));
|
|
194
|
+
}
|
|
195
|
+
timeouts.set(key, setTimeout(() => {
|
|
196
|
+
fn(snapId, newSnapState, encrypted);
|
|
197
|
+
timeouts.delete(key);
|
|
198
|
+
}, timeout));
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
exports.debouncePersistState = debouncePersistState;
|
|
174
202
|
//# sourceMappingURL=utils.cjs.map
|
package/dist/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAEA,mDAA8D;AAC9D,uDAM+B;AAC/B,sEAAwC;AAGxC,6CAAsC;AAEtC;;;;;;;;;;;;;GAaG;AACH,SAAgB,OAAO,CAGrB,OAAgB,EAAE,OAAgB;IAClC,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CACnC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QACpB,IAAI,CAAC,CAAC,GAAG,IAAI,OAAO,CAAC,EAAE,CAAC;YACtB,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACnB,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAE,CACuB,CAAC;AAC9B,CAAC;AAbD,0BAaC;AAED;;;;;;;;;GASG;AACH,SAAgB,eAAe,CAI7B,YAA0B,EAC1B,YAA0B;IAE1B,OAAO,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,MAAM,CAExC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QACtB,MAAM,UAAU,GAAG,GAAG,IAAI,YAAY,CAAC;QACvC,IACE,CAAC,UAAU;YACX,CAAC,UAAU;gBACT,CAAC,IAAA,yBAAS,EAAC,KAAK,CAAC,OAAO,IAAI,EAAE,EAAE,YAAY,CAAC,GAAG,CAAC,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,EACnE,CAAC;YACD,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAA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Q,EACR,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAC7B,CAAC;QAEF,IAAA,oCAAsB,EAAC,cAAc,CAAC,CAAC;QAEvC,MAAM,OAAO,CAAC,GAAG,CACf,cAAc,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;YAChC,4BAA4B;YAC5B,kDAAkD;YAClD,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,MAAM,IAAA,0BAAY,EAAC,IAAI,CAAC,CAAC;QAC9C,CAAC,CAAC,CACH,CAAC;QAEF,MAAM,iBAAiB,GAAG,MAAM,YAAY,CAC1C,QAAQ,EACR,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAC/B,CAAC;QAEF,MAAM,0BAA0B,GAC9B,IAAA,2CAA6B,EAAC,iBAAiB,CAAC,CAAC;QAEnD,MAAM,KAAK,GAAG;YACZ,QAAQ;YACR,UAAU;YACV,OAAO;YACP,cAAc;YACd,iBAAiB,EAAE,0BAA0B;SAC9C,CAAC;QAEF,MAAM,IAAA,iCAAmB,EAAC,KAAK,CAAC,CAAC;QAEjC,OAAO,KAAK,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CACb,yBAAyB,MAAM,MAAM,IAAA,2BAAe,EAAC,KAAK,CAAC,GAAG,CAC/D,CAAC;IACJ,CAAC;AACH,CAAC;AAvDD,8BAuDC","sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { assert, getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n MAX_FILE_SIZE,\n encodeBase64,\n getValidatedLocalizationFiles,\n validateAuxiliaryFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport deepEqual from 'fast-deep-equal';\n\nimport type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * Calculate a difference between two permissions objects.\n *\n * Similar to `setDiff` except for one additional condition:\n * Permissions in B should be removed from A if they exist in both and have differing caveats.\n *\n * @param permissionsA - An object containing one or more partial permissions.\n * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.\n * @returns The permissions set A without properties from B.\n */\nexport function permissionsDiff<\n PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n>(\n permissionsA: PermissionsA,\n permissionsB: PermissionsB,\n): Diff<PermissionsA, PermissionsB> {\n return Object.entries(permissionsA).reduce<\n Record<string, Pick<PermissionConstraint, 'caveats'>>\n >((acc, [key, value]) => {\n const isIncluded = key in permissionsB;\n if (\n !isIncluded ||\n (isIncluded &&\n !deepEqual(value.caveats ?? [], permissionsB[key].caveats ?? []))\n ) {\n acc[key] = value;\n }\n return acc;\n }, {}) as Diff<PermissionsA, PermissionsB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n\n assert(\n sourceCode.size < MAX_FILE_SIZE,\n 'Snap source code must be smaller than 64 MB.',\n );\n\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n validateAuxiliaryFiles(auxiliaryFiles);\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${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ACpC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,CAAC,EAAE,OAAO,CAAC,CACZ,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AA7BD,oDA6BC","sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { assert, getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n MAX_FILE_SIZE,\n encodeBase64,\n getValidatedLocalizationFiles,\n validateAuxiliaryFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\n\nimport type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * Calculate a difference between two permissions objects.\n *\n * Similar to `setDiff` except for one additional condition:\n * Permissions in B should be removed from A if they exist in both and have differing caveats.\n *\n * @param permissionsA - An object containing one or more partial permissions.\n * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.\n * @returns The permissions set A without properties from B.\n */\nexport function permissionsDiff<\n PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n>(\n permissionsA: PermissionsA,\n permissionsB: PermissionsB,\n): Diff<PermissionsA, PermissionsB> {\n return Object.entries(permissionsA).reduce<\n Record<string, Pick<PermissionConstraint, 'caveats'>>\n >((acc, [key, value]) => {\n const isIncluded = key in permissionsB;\n if (\n !isIncluded ||\n (isIncluded &&\n !deepEqual(value.caveats ?? [], permissionsB[key].caveats ?? []))\n ) {\n acc[key] = value;\n }\n return acc;\n }, {}) as Diff<PermissionsA, PermissionsB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n\n assert(\n sourceCode.size < MAX_FILE_SIZE,\n 'Snap source code must be smaller than 64 MB.',\n );\n\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n validateAuxiliaryFiles(auxiliaryFiles);\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${snapId}\": ${getErrorMessage(error)}.`,\n );\n }\n}\n\n/**\n * Debounce persisting Snap state changes.\n *\n * @param fn - The function to debounce.\n * @param timeout - The timeout in milliseconds. Defaults to 1000.\n * @returns The debounced function.\n * @example\n * const originalUpdate = (snapId, newSnapState, encrypted) => {\n * console.log(`Called with Snap ID: ${snapId} and state: ${newSnapState}`);\n * };\n *\n * const debouncedUpdate = debounce(originalUpdate);\n * debouncedFunction('npm:foo-snap', { foo: 'bar' }, false);\n */\nexport function debouncePersistState(\n fn: (\n snapId: SnapId,\n newSnapState: Record<string, Json> | null,\n encrypted: boolean,\n ) => void,\n timeout = 1000,\n) {\n const timeouts = new Map<string, NodeJS.Timeout>();\n\n return (\n snapId: SnapId,\n newSnapState: Record<string, Json> | null,\n encrypted: boolean,\n ): void => {\n const key = `${snapId}-${encrypted}`;\n\n if (timeouts.has(key)) {\n clearTimeout(timeouts.get(key));\n }\n\n timeouts.set(\n key,\n setTimeout(() => {\n fn(snapId, newSnapState, encrypted);\n timeouts.delete(key);\n }, timeout),\n );\n };\n}\n"]}
|
package/dist/utils.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { PermissionConstraint } from "@metamask/permission-controller";
|
|
2
2
|
import type { SnapId } from "@metamask/snaps-sdk";
|
|
3
|
+
import type { Json } from "@metamask/utils";
|
|
3
4
|
import type { SnapLocation } from "./snaps/index.cjs";
|
|
4
5
|
import { Timer } from "./snaps/Timer.cjs";
|
|
5
6
|
/**
|
|
@@ -158,20 +159,20 @@ export declare function getSnapFiles(location: SnapLocation, files?: string[] |
|
|
|
158
159
|
*/
|
|
159
160
|
export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promise<{
|
|
160
161
|
manifest: import("@metamask/snaps-utils").VirtualFile<{
|
|
162
|
+
description: string;
|
|
161
163
|
source: {
|
|
164
|
+
shasum: string;
|
|
162
165
|
location: {
|
|
163
166
|
npm: {
|
|
164
|
-
registry: "https://registry.npmjs.org" | "https://registry.npmjs.org/";
|
|
165
167
|
filePath: string;
|
|
166
168
|
packageName: string;
|
|
169
|
+
registry: "https://registry.npmjs.org" | "https://registry.npmjs.org/";
|
|
167
170
|
iconPath?: string | undefined;
|
|
168
171
|
};
|
|
169
172
|
};
|
|
170
|
-
shasum: string;
|
|
171
173
|
files?: string[] | undefined;
|
|
172
174
|
locales?: string[] | undefined;
|
|
173
175
|
};
|
|
174
|
-
description: string;
|
|
175
176
|
version: import("@metamask/utils").SemVerVersion;
|
|
176
177
|
proposedName: string;
|
|
177
178
|
initialPermissions: Partial<{
|
|
@@ -238,12 +239,27 @@ export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promi
|
|
|
238
239
|
svgIcon: import("@metamask/snaps-utils").VirtualFile<unknown> | undefined;
|
|
239
240
|
auxiliaryFiles: import("@metamask/snaps-utils").VirtualFile<unknown>[];
|
|
240
241
|
localizationFiles: import("@metamask/snaps-utils").VirtualFile<{
|
|
242
|
+
locale: string;
|
|
241
243
|
messages: Record<string, {
|
|
242
244
|
message: string;
|
|
243
245
|
description?: string | undefined;
|
|
244
246
|
}>;
|
|
245
|
-
locale: string;
|
|
246
247
|
}>[];
|
|
247
248
|
}>;
|
|
249
|
+
/**
|
|
250
|
+
* Debounce persisting Snap state changes.
|
|
251
|
+
*
|
|
252
|
+
* @param fn - The function to debounce.
|
|
253
|
+
* @param timeout - The timeout in milliseconds. Defaults to 1000.
|
|
254
|
+
* @returns The debounced function.
|
|
255
|
+
* @example
|
|
256
|
+
* const originalUpdate = (snapId, newSnapState, encrypted) => {
|
|
257
|
+
* console.log(`Called with Snap ID: ${snapId} and state: ${newSnapState}`);
|
|
258
|
+
* };
|
|
259
|
+
*
|
|
260
|
+
* const debouncedUpdate = debounce(originalUpdate);
|
|
261
|
+
* debouncedFunction('npm:foo-snap', { foo: 'bar' }, false);
|
|
262
|
+
*/
|
|
263
|
+
export declare function debouncePersistState(fn: (snapId: SnapId, newSnapState: Record<string, Json> | null, encrypted: boolean) => void, timeout?: number): (snapId: SnapId, newSnapState: Record<string, Json> | null, encrypted: boolean) => void;
|
|
248
264
|
export {};
|
|
249
265
|
//# sourceMappingURL=utils.d.cts.map
|
package/dist/utils.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,wCAAwC;AAC5E,OAAO,KAAK,EAAE,MAAM,EAAE,4BAA4B;
|
|
1
|
+
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,wCAAwC;AAC5E,OAAO,KAAK,EAAE,MAAM,EAAE,4BAA4B;AASlD,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAG5C,OAAO,KAAK,EAAE,YAAY,EAAE,0BAAgB;AAC5C,OAAO,EAAE,KAAK,EAAE,0BAAsB;AAEtC;;;;;;;;;;;;;GAaG;AACH,wBAAgB,OAAO,CACrB,OAAO,SAAS,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,EACpC,OAAO,SAAS,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AAED;;;;;;;;GAQG;AACH,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDrE;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,CACF,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,EACzC,SAAS,EAAE,OAAO,KACf,IAAI,EACT,OAAO,SAAO,YAKJ,MAAM,gBACA,OAAO,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,aAC9B,OAAO,KACjB,IAAI,CAeR"}
|
package/dist/utils.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { PermissionConstraint } from "@metamask/permission-controller";
|
|
2
2
|
import type { SnapId } from "@metamask/snaps-sdk";
|
|
3
|
+
import type { Json } from "@metamask/utils";
|
|
3
4
|
import type { SnapLocation } from "./snaps/index.mjs";
|
|
4
5
|
import { Timer } from "./snaps/Timer.mjs";
|
|
5
6
|
/**
|
|
@@ -158,20 +159,20 @@ export declare function getSnapFiles(location: SnapLocation, files?: string[] |
|
|
|
158
159
|
*/
|
|
159
160
|
export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promise<{
|
|
160
161
|
manifest: import("@metamask/snaps-utils").VirtualFile<{
|
|
162
|
+
description: string;
|
|
161
163
|
source: {
|
|
164
|
+
shasum: string;
|
|
162
165
|
location: {
|
|
163
166
|
npm: {
|
|
164
|
-
registry: "https://registry.npmjs.org" | "https://registry.npmjs.org/";
|
|
165
167
|
filePath: string;
|
|
166
168
|
packageName: string;
|
|
169
|
+
registry: "https://registry.npmjs.org" | "https://registry.npmjs.org/";
|
|
167
170
|
iconPath?: string | undefined;
|
|
168
171
|
};
|
|
169
172
|
};
|
|
170
|
-
shasum: string;
|
|
171
173
|
files?: string[] | undefined;
|
|
172
174
|
locales?: string[] | undefined;
|
|
173
175
|
};
|
|
174
|
-
description: string;
|
|
175
176
|
version: import("@metamask/utils").SemVerVersion;
|
|
176
177
|
proposedName: string;
|
|
177
178
|
initialPermissions: Partial<{
|
|
@@ -238,12 +239,27 @@ export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promi
|
|
|
238
239
|
svgIcon: import("@metamask/snaps-utils").VirtualFile<unknown> | undefined;
|
|
239
240
|
auxiliaryFiles: import("@metamask/snaps-utils").VirtualFile<unknown>[];
|
|
240
241
|
localizationFiles: import("@metamask/snaps-utils").VirtualFile<{
|
|
242
|
+
locale: string;
|
|
241
243
|
messages: Record<string, {
|
|
242
244
|
message: string;
|
|
243
245
|
description?: string | undefined;
|
|
244
246
|
}>;
|
|
245
|
-
locale: string;
|
|
246
247
|
}>[];
|
|
247
248
|
}>;
|
|
249
|
+
/**
|
|
250
|
+
* Debounce persisting Snap state changes.
|
|
251
|
+
*
|
|
252
|
+
* @param fn - The function to debounce.
|
|
253
|
+
* @param timeout - The timeout in milliseconds. Defaults to 1000.
|
|
254
|
+
* @returns The debounced function.
|
|
255
|
+
* @example
|
|
256
|
+
* const originalUpdate = (snapId, newSnapState, encrypted) => {
|
|
257
|
+
* console.log(`Called with Snap ID: ${snapId} and state: ${newSnapState}`);
|
|
258
|
+
* };
|
|
259
|
+
*
|
|
260
|
+
* const debouncedUpdate = debounce(originalUpdate);
|
|
261
|
+
* debouncedFunction('npm:foo-snap', { foo: 'bar' }, false);
|
|
262
|
+
*/
|
|
263
|
+
export declare function debouncePersistState(fn: (snapId: SnapId, newSnapState: Record<string, Json> | null, encrypted: boolean) => void, timeout?: number): (snapId: SnapId, newSnapState: Record<string, Json> | null, encrypted: boolean) => void;
|
|
248
264
|
export {};
|
|
249
265
|
//# sourceMappingURL=utils.d.mts.map
|
package/dist/utils.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,wCAAwC;AAC5E,OAAO,KAAK,EAAE,MAAM,EAAE,4BAA4B;
|
|
1
|
+
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,wCAAwC;AAC5E,OAAO,KAAK,EAAE,MAAM,EAAE,4BAA4B;AASlD,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAG5C,OAAO,KAAK,EAAE,YAAY,EAAE,0BAAgB;AAC5C,OAAO,EAAE,KAAK,EAAE,0BAAsB;AAEtC;;;;;;;;;;;;;GAaG;AACH,wBAAgB,OAAO,CACrB,OAAO,SAAS,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,EACpC,OAAO,SAAS,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,EACpC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAU5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,YAAY,SAAS,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,CAAC,EAC1E,YAAY,SAAS,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,CAAC,EAE1E,YAAY,EAAE,YAAY,EAC1B,YAAY,EAAE,YAAY,GACzB,IAAI,CAAC,YAAY,EAAE,YAAY,CAAC,CAclC;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,MAAM,GAAG,IAAI,EACjC,EAAE,EAAE,MAAM,EACV,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,MAAM,CAAC,GAAG;IAAE,MAAM,EAAE,MAAM,IAAI,CAAA;CAAE,CAE1C;AAED;;;;;;;G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,OAAO,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,EAAE,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAErE;;;;;GAKG;AACH,MAAM,MAAM,OAAO,CACjB,IAAI,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACpC,SAAS,SAAS,MAAM,IACtB;IACF,CAAC,UAAU,GAAG,IAAI,MAAM,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;CAC1D,GAAG;KACD,GAAG,IAAI,MAAM,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;CAChD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,YAAY,EACtB,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,mEAS7B;AAED;;;;;;;;GAQG;AACH,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDrE;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,CACF,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,EACzC,SAAS,EAAE,OAAO,KACf,IAAI,EACT,OAAO,SAAO,YAKJ,MAAM,gBACA,OAAO,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,aAC9B,OAAO,KACjB,IAAI,CAeR"}
|
package/dist/utils.mjs
CHANGED
|
@@ -165,4 +165,31 @@ export async function fetchSnap(snapId, location) {
|
|
|
165
165
|
throw new Error(`Failed to fetch snap "${snapId}": ${getErrorMessage(error)}.`);
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* Debounce persisting Snap state changes.
|
|
170
|
+
*
|
|
171
|
+
* @param fn - The function to debounce.
|
|
172
|
+
* @param timeout - The timeout in milliseconds. Defaults to 1000.
|
|
173
|
+
* @returns The debounced function.
|
|
174
|
+
* @example
|
|
175
|
+
* const originalUpdate = (snapId, newSnapState, encrypted) => {
|
|
176
|
+
* console.log(`Called with Snap ID: ${snapId} and state: ${newSnapState}`);
|
|
177
|
+
* };
|
|
178
|
+
*
|
|
179
|
+
* const debouncedUpdate = debounce(originalUpdate);
|
|
180
|
+
* debouncedFunction('npm:foo-snap', { foo: 'bar' }, false);
|
|
181
|
+
*/
|
|
182
|
+
export function debouncePersistState(fn, timeout = 1000) {
|
|
183
|
+
const timeouts = new Map();
|
|
184
|
+
return (snapId, newSnapState, encrypted) => {
|
|
185
|
+
const key = `${snapId}-${encrypted}`;
|
|
186
|
+
if (timeouts.has(key)) {
|
|
187
|
+
clearTimeout(timeouts.get(key));
|
|
188
|
+
}
|
|
189
|
+
timeouts.set(key, setTimeout(() => {
|
|
190
|
+
fn(snapId, newSnapState, encrypted);
|
|
191
|
+
timeouts.delete(key);
|
|
192
|
+
}, timeout));
|
|
193
|
+
};
|
|
194
|
+
}
|
|
168
195
|
//# sourceMappingURL=utils.mjs.map
|
package/dist/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,4BAA4B;AAC9D,OAAO,EACL,aAAa,EACb,YAAY,EACZ,6BAA6B,EAC7B,sBAAsB,EACtB,mBAAmB,EACpB,8BAA8B;AAC/B,OAAO,UAAS,wBAAwB;;AAGxC,OAAO,EAAE,KAAK,EAAE,0BAAsB;AAEtC;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,OAAO,CAGrB,OAAgB,EAAE,OAAgB;IAClC,OA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,CAAC,iBAAiB,CAAC,CAAC;QAEnD,MAAM,KAAK,GAAG;YACZ,QAAQ;YACR,UAAU;YACV,OAAO;YACP,cAAc;YACd,iBAAiB,EAAE,0BAA0B;SAC9C,CAAC;QAEF,MAAM,mBAAmB,CAAC,KAAK,CAAC,CAAC;QAEjC,OAAO,KAAK,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CACb,yBAAyB,MAAM,MAAM,eAAe,CAAC,KAAK,CAAC,GAAG,CAC/D,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { assert, getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n MAX_FILE_SIZE,\n encodeBase64,\n getValidatedLocalizationFiles,\n validateAuxiliaryFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport deepEqual from 'fast-deep-equal';\n\nimport type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * Calculate a difference between two permissions objects.\n *\n * Similar to `setDiff` except for one additional condition:\n * Permissions in B should be removed from A if they exist in both and have differing caveats.\n *\n * @param permissionsA - An object containing one or more partial permissions.\n * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.\n * @returns The permissions set A without properties from B.\n */\nexport function permissionsDiff<\n PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n>(\n permissionsA: PermissionsA,\n permissionsB: PermissionsB,\n): Diff<PermissionsA, PermissionsB> {\n return Object.entries(permissionsA).reduce<\n Record<string, Pick<PermissionConstraint, 'caveats'>>\n >((acc, [key, value]) => {\n const isIncluded = key in permissionsB;\n if (\n !isIncluded ||\n (isIncluded &&\n !deepEqual(value.caveats ?? [], permissionsB[key].caveats ?? []))\n ) {\n acc[key] = value;\n }\n return acc;\n }, {}) as Diff<PermissionsA, PermissionsB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n\n assert(\n sourceCode.size < MAX_FILE_SIZE,\n 'Snap source code must be smaller than 64 MB.',\n );\n\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n validateAuxiliaryFiles(auxiliaryFiles);\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${snapId}\": ${getErrorMessage(error)}.`,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,4BAA4B;AAC9D,OAAO,EACL,aAAa,EACb,YAAY,EACZ,6BAA6B,EAC7B,sBAAsB,EACtB,mBAAmB,EACpB,8BAA8B;AAE/B,OAAO,UAAS,wBAAwB;;AAGxC,OAAO,EAAE,KAAK,EAAE,0BAAsB;AAEtC;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,OAAO,CAGrB,OAAgB,EAAE,OAAgB;IAClC,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CACnC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,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AAiB,EAAE,0BAA0B;SAC9C,CAAC;QAEF,MAAM,mBAAmB,CAAC,KAAK,CAAC,CAAC;QAEjC,OAAO,KAAK,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CACb,yBAAyB,MAAM,MAAM,eAAe,CAAC,KAAK,CAAC,GAAG,CAC/D,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,oBAAoB,CAClC,EAIS,EACT,OAAO,GAAG,IAAI;IAEd,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA0B,CAAC;IAEnD,OAAO,CACL,MAAc,EACd,YAAyC,EACzC,SAAkB,EACZ,EAAE;QACR,MAAM,GAAG,GAAG,GAAG,MAAM,IAAI,SAAS,EAAE,CAAC;QAErC,IAAI,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YACtB,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;QAClC,CAAC;QAED,QAAQ,CAAC,GAAG,CACV,GAAG,EACH,UAAU,CAAC,GAAG,EAAE;YACd,EAAE,CAAC,MAAM,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;YACpC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,CAAC,EAAE,OAAO,CAAC,CACZ,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { assert, getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n MAX_FILE_SIZE,\n encodeBase64,\n getValidatedLocalizationFiles,\n validateAuxiliaryFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\n\nimport type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * Calculate a difference between two permissions objects.\n *\n * Similar to `setDiff` except for one additional condition:\n * Permissions in B should be removed from A if they exist in both and have differing caveats.\n *\n * @param permissionsA - An object containing one or more partial permissions.\n * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.\n * @returns The permissions set A without properties from B.\n */\nexport function permissionsDiff<\n PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n>(\n permissionsA: PermissionsA,\n permissionsB: PermissionsB,\n): Diff<PermissionsA, PermissionsB> {\n return Object.entries(permissionsA).reduce<\n Record<string, Pick<PermissionConstraint, 'caveats'>>\n >((acc, [key, value]) => {\n const isIncluded = key in permissionsB;\n if (\n !isIncluded ||\n (isIncluded &&\n !deepEqual(value.caveats ?? [], permissionsB[key].caveats ?? []))\n ) {\n acc[key] = value;\n }\n return acc;\n }, {}) as Diff<PermissionsA, PermissionsB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n\n assert(\n sourceCode.size < MAX_FILE_SIZE,\n 'Snap source code must be smaller than 64 MB.',\n );\n\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n validateAuxiliaryFiles(auxiliaryFiles);\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${snapId}\": ${getErrorMessage(error)}.`,\n );\n }\n}\n\n/**\n * Debounce persisting Snap state changes.\n *\n * @param fn - The function to debounce.\n * @param timeout - The timeout in milliseconds. Defaults to 1000.\n * @returns The debounced function.\n * @example\n * const originalUpdate = (snapId, newSnapState, encrypted) => {\n * console.log(`Called with Snap ID: ${snapId} and state: ${newSnapState}`);\n * };\n *\n * const debouncedUpdate = debounce(originalUpdate);\n * debouncedFunction('npm:foo-snap', { foo: 'bar' }, false);\n */\nexport function debouncePersistState(\n fn: (\n snapId: SnapId,\n newSnapState: Record<string, Json> | null,\n encrypted: boolean,\n ) => void,\n timeout = 1000,\n) {\n const timeouts = new Map<string, NodeJS.Timeout>();\n\n return (\n snapId: SnapId,\n newSnapState: Record<string, Json> | null,\n encrypted: boolean,\n ): void => {\n const key = `${snapId}-${encrypted}`;\n\n if (timeouts.has(key)) {\n clearTimeout(timeouts.get(key));\n }\n\n timeouts.set(\n key,\n setTimeout(() => {\n fn(snapId, newSnapState, encrypted);\n timeouts.delete(key);\n }, timeout),\n );\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-controllers",
|
|
3
|
-
"version": "11.1
|
|
3
|
+
"version": "11.2.1",
|
|
4
4
|
"description": "Controllers for MetaMask Snaps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -71,9 +71,10 @@
|
|
|
71
71
|
"publish:preview": "yarn npm publish --tag preview",
|
|
72
72
|
"since-latest-release": "../../scripts/since-latest-release.sh",
|
|
73
73
|
"test": "jest --reporters=jest-silent-reporter && yarn test:browser",
|
|
74
|
-
"test:browser": "
|
|
74
|
+
"test:browser": "vitest",
|
|
75
|
+
"test:browser:firefox": "vitest --config ./vitest.config.firefox.mts",
|
|
75
76
|
"test:clean": "jest --clearCache",
|
|
76
|
-
"test:post": "ts-node scripts/coverage.ts && rimraf coverage/jest coverage/
|
|
77
|
+
"test:post": "ts-node scripts/coverage.ts && rimraf coverage/jest coverage/vite",
|
|
77
78
|
"test:pre": "yarn mkdirp test/fixtures && ./scripts/generate-fixtures.sh",
|
|
78
79
|
"test:verbose": "jest --verbose",
|
|
79
80
|
"test:watch": "jest --watch"
|
|
@@ -90,9 +91,9 @@
|
|
|
90
91
|
"@metamask/post-message-stream": "^9.0.0",
|
|
91
92
|
"@metamask/rpc-errors": "^7.0.2",
|
|
92
93
|
"@metamask/snaps-registry": "^3.2.3",
|
|
93
|
-
"@metamask/snaps-rpc-methods": "^12.
|
|
94
|
-
"@metamask/snaps-sdk": "^6.
|
|
95
|
-
"@metamask/snaps-utils": "^9.
|
|
94
|
+
"@metamask/snaps-rpc-methods": "^12.1.0",
|
|
95
|
+
"@metamask/snaps-sdk": "^6.22.0",
|
|
96
|
+
"@metamask/snaps-utils": "^9.2.0",
|
|
96
97
|
"@metamask/utils": "^11.2.0",
|
|
97
98
|
"@xstate/fsm": "^2.0.0",
|
|
98
99
|
"async-mutex": "^0.5.0",
|
|
@@ -109,37 +110,28 @@
|
|
|
109
110
|
"tar-stream": "^3.1.7"
|
|
110
111
|
},
|
|
111
112
|
"devDependencies": {
|
|
112
|
-
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
|
|
113
|
-
"@esbuild-plugins/node-modules-polyfill": "^0.2.2",
|
|
114
113
|
"@lavamoat/allow-scripts": "^3.0.4",
|
|
115
|
-
"@metamask/auto-changelog": "^
|
|
114
|
+
"@metamask/auto-changelog": "^5.0.1",
|
|
116
115
|
"@metamask/browser-passworder": "^6.0.0",
|
|
117
116
|
"@metamask/template-snap": "^0.7.0",
|
|
118
117
|
"@noble/hashes": "^1.7.1",
|
|
119
118
|
"@swc/core": "1.3.78",
|
|
120
119
|
"@swc/jest": "^0.2.26",
|
|
120
|
+
"@testing-library/dom": "^10.4.0",
|
|
121
121
|
"@ts-bridge/cli": "^0.6.1",
|
|
122
122
|
"@types/chrome": "^0.0.237",
|
|
123
123
|
"@types/concat-stream": "^2.0.0",
|
|
124
124
|
"@types/gunzip-maybe": "^1.4.0",
|
|
125
125
|
"@types/jest": "^27.5.1",
|
|
126
126
|
"@types/luxon": "^3",
|
|
127
|
-
"@types/mocha": "^10.0.1",
|
|
128
127
|
"@types/node": "18.14.2",
|
|
129
128
|
"@types/readable-stream": "^4.0.15",
|
|
130
129
|
"@types/semver": "^7.5.0",
|
|
131
130
|
"@types/tar-stream": "^3.1.1",
|
|
132
|
-
"@
|
|
133
|
-
"@wdio/cli": "^8.19.0",
|
|
134
|
-
"@wdio/globals": "^8.19.0",
|
|
135
|
-
"@wdio/mocha-framework": "^8.19.0",
|
|
136
|
-
"@wdio/spec-reporter": "^8.19.0",
|
|
137
|
-
"@wdio/static-server-service": "^8.19.0",
|
|
131
|
+
"@vitest/browser": "^3.0.8",
|
|
138
132
|
"deepmerge": "^4.2.2",
|
|
139
133
|
"depcheck": "^1.4.7",
|
|
140
|
-
"esbuild": "^0.25.1",
|
|
141
134
|
"eslint": "^9.11.0",
|
|
142
|
-
"expect-webdriverio": "^4.4.1",
|
|
143
135
|
"istanbul-lib-coverage": "^3.2.0",
|
|
144
136
|
"istanbul-lib-report": "^3.0.0",
|
|
145
137
|
"istanbul-reports": "^3.1.5",
|
|
@@ -151,14 +143,13 @@
|
|
|
151
143
|
"rimraf": "^4.1.2",
|
|
152
144
|
"ts-node": "^10.9.1",
|
|
153
145
|
"typescript": "~5.3.3",
|
|
154
|
-
"vite": "^6.2.
|
|
146
|
+
"vite": "^6.2.6",
|
|
147
|
+
"vite-plugin-node-polyfills": "^0.23.0",
|
|
155
148
|
"vite-tsconfig-paths": "^4.0.5",
|
|
156
|
-
"
|
|
157
|
-
"wdio-geckodriver-service": "^5.0.2",
|
|
158
|
-
"webdriverio": "^8.19.0"
|
|
149
|
+
"vitest": "^3.0.8"
|
|
159
150
|
},
|
|
160
151
|
"peerDependencies": {
|
|
161
|
-
"@metamask/snaps-execution-environments": "^7.
|
|
152
|
+
"@metamask/snaps-execution-environments": "^7.2.1"
|
|
162
153
|
},
|
|
163
154
|
"peerDependenciesMeta": {
|
|
164
155
|
"@metamask/snaps-execution-environments": {
|