@metamask/snaps-controllers 14.0.2 → 14.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -1
- package/dist/cronjob/CronjobController.cjs +13 -6
- package/dist/cronjob/CronjobController.cjs.map +1 -1
- package/dist/cronjob/CronjobController.d.cts +12 -1
- package/dist/cronjob/CronjobController.d.cts.map +1 -1
- package/dist/cronjob/CronjobController.d.mts +12 -1
- package/dist/cronjob/CronjobController.d.mts.map +1 -1
- package/dist/cronjob/CronjobController.mjs +13 -6
- package/dist/cronjob/CronjobController.mjs.map +1 -1
- package/dist/snaps/SnapController.cjs +44 -11
- package/dist/snaps/SnapController.cjs.map +1 -1
- package/dist/snaps/SnapController.d.cts +20 -2
- package/dist/snaps/SnapController.d.cts.map +1 -1
- package/dist/snaps/SnapController.d.mts +20 -2
- package/dist/snaps/SnapController.d.mts.map +1 -1
- package/dist/snaps/SnapController.mjs +45 -12
- package/dist/snaps/SnapController.mjs.map +1 -1
- package/dist/utils.cjs +12 -1
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +9 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +9 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +10 -0
- package/dist/utils.mjs.map +1 -1
- package/package.json +8 -8
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.isTrackableHandler = exports.throttleTracking = exports.TRACKABLE_HANDLERS = exports.debouncePersistState = exports.fetchSnap = exports.getSnapFiles = exports.withTimeout = exports.hasTimedOut = exports.delayWithTimer = exports.delay = exports.permissionsDiff = exports.setDiff = void 0;
|
|
6
|
+
exports.isLocalSnapId = exports.isTrackableHandler = exports.throttleTracking = exports.TRACKABLE_HANDLERS = 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"));
|
|
@@ -261,4 +261,15 @@ function isTrackableHandler(handler) {
|
|
|
261
261
|
return exports.TRACKABLE_HANDLERS.includes(handler);
|
|
262
262
|
}
|
|
263
263
|
exports.isTrackableHandler = isTrackableHandler;
|
|
264
|
+
/**
|
|
265
|
+
* Checks if the given Snap ID is a local Snap ID. This assumes the Snap ID is
|
|
266
|
+
* validated before calling this function, as it only checks the prefix.
|
|
267
|
+
*
|
|
268
|
+
* @param snapId - The Snap ID to check.
|
|
269
|
+
* @returns True if the Snap ID is a local Snap ID, false otherwise.
|
|
270
|
+
*/
|
|
271
|
+
function isLocalSnapId(snapId) {
|
|
272
|
+
return snapId.startsWith('local:');
|
|
273
|
+
}
|
|
274
|
+
exports.isLocalSnapId = isLocalSnapId;
|
|
264
275
|
//# 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,uDAO+B;AAE/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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CAChC,OAAoB;IAEpB,OAAO,0BAAkB,CAAC,QAAQ,CAAC,OAA2B,CAAC,CAAC;AAClE,CAAC;AAJD,gDAIC","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 HandlerType,\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\n/**\n * Handlers allowed for tracking.\n */\nexport const TRACKABLE_HANDLERS = Object.freeze([\n HandlerType.OnHomePage,\n HandlerType.OnInstall,\n HandlerType.OnNameLookup,\n HandlerType.OnRpcRequest,\n HandlerType.OnSignature,\n HandlerType.OnTransaction,\n HandlerType.OnUpdate,\n] as const);\n\n/**\n * A union type representing all possible trackable handler types.\n */\nexport type TrackableHandler = (typeof TRACKABLE_HANDLERS)[number];\n\n/**\n * Throttles event tracking calls per unique combination of parameters.\n *\n * @param fn - The tracking function to throttle.\n * @param timeout - The timeout in milliseconds. Defaults to 60000 (1 minute).\n * @returns The throttled function.\n */\nexport function throttleTracking(\n fn: (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ) => void,\n timeout = 60000,\n) {\n const previousCalls = new Map<string, number>();\n const pendingCalls = new Map<\n string,\n {\n args: [SnapId, TrackableHandler, boolean, string];\n timer: ReturnType<typeof setTimeout> | null;\n }\n >();\n\n return (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ): void => {\n const key = `${snapId}${handler}${success}${origin}`;\n const now = Date.now();\n const lastCall = previousCalls.get(key) ?? 0;\n const args: [SnapId, TrackableHandler, boolean, string] = [\n snapId,\n handler,\n success,\n origin,\n ];\n\n if (now - lastCall >= timeout) {\n previousCalls.set(key, now);\n fn(...args);\n return;\n }\n\n const pending = pendingCalls.get(key);\n if (pending?.timer) {\n clearTimeout(pending.timer);\n }\n\n previousCalls.set(key, now);\n\n pendingCalls.set(key, {\n args,\n timer: setTimeout(() => {\n fn(...args);\n pendingCalls.delete(key);\n }, timeout),\n });\n };\n}\n\n/**\n * Whether the handler type if allowed for tracking.\n *\n * @param handler Type of a handler.\n * @returns True if handler is allowed for tracking, false otherwise.\n */\nexport function isTrackableHandler(\n handler: HandlerType,\n): handler is TrackableHandler {\n return TRACKABLE_HANDLERS.includes(handler as TrackableHandler);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAEA,mDAA8D;AAC9D,uDAO+B;AAE/B,sEAAwC;AAGxC,6CAAsC;AAEt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,UAAU,CAAC,GAAG,EAAE;gBACrB,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;gBACZ,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC3B,CAAC,EAAE,OAAO,CAAC;SACZ,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC;AAvDD,4CAuDC;AAED;;;;;GAKG;AACH,SAAgB,kBAAkB,CAChC,OAAoB;IAEpB,OAAO,0BAAkB,CAAC,QAAQ,CAAC,OAA2B,CAAC,CAAC;AAClE,CAAC;AAJD,gDAIC;AAED;;;;;;GAMG;AACH,SAAgB,aAAa,CAAC,MAAc;IAC1C,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;AACrC,CAAC;AAFD,sCAEC","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 HandlerType,\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\n/**\n * Handlers allowed for tracking.\n */\nexport const TRACKABLE_HANDLERS = Object.freeze([\n HandlerType.OnHomePage,\n HandlerType.OnInstall,\n HandlerType.OnNameLookup,\n HandlerType.OnRpcRequest,\n HandlerType.OnSignature,\n HandlerType.OnTransaction,\n HandlerType.OnUpdate,\n] as const);\n\n/**\n * A union type representing all possible trackable handler types.\n */\nexport type TrackableHandler = (typeof TRACKABLE_HANDLERS)[number];\n\n/**\n * Throttles event tracking calls per unique combination of parameters.\n *\n * @param fn - The tracking function to throttle.\n * @param timeout - The timeout in milliseconds. Defaults to 60000 (1 minute).\n * @returns The throttled function.\n */\nexport function throttleTracking(\n fn: (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ) => void,\n timeout = 60000,\n) {\n const previousCalls = new Map<string, number>();\n const pendingCalls = new Map<\n string,\n {\n args: [SnapId, TrackableHandler, boolean, string];\n timer: ReturnType<typeof setTimeout> | null;\n }\n >();\n\n return (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ): void => {\n const key = `${snapId}${handler}${success}${origin}`;\n const now = Date.now();\n const lastCall = previousCalls.get(key) ?? 0;\n const args: [SnapId, TrackableHandler, boolean, string] = [\n snapId,\n handler,\n success,\n origin,\n ];\n\n if (now - lastCall >= timeout) {\n previousCalls.set(key, now);\n fn(...args);\n return;\n }\n\n const pending = pendingCalls.get(key);\n if (pending?.timer) {\n clearTimeout(pending.timer);\n }\n\n previousCalls.set(key, now);\n\n pendingCalls.set(key, {\n args,\n timer: setTimeout(() => {\n fn(...args);\n pendingCalls.delete(key);\n }, timeout),\n });\n };\n}\n\n/**\n * Whether the handler type if allowed for tracking.\n *\n * @param handler Type of a handler.\n * @returns True if handler is allowed for tracking, false otherwise.\n */\nexport function isTrackableHandler(\n handler: HandlerType,\n): handler is TrackableHandler {\n return TRACKABLE_HANDLERS.includes(handler as TrackableHandler);\n}\n\n/**\n * Checks if the given Snap ID is a local Snap ID. This assumes the Snap ID is\n * validated before calling this function, as it only checks the prefix.\n *\n * @param snapId - The Snap ID to check.\n * @returns True if the Snap ID is a local Snap ID, false otherwise.\n */\nexport function isLocalSnapId(snapId: SnapId): boolean {\n return snapId.startsWith('local:');\n}\n"]}
|
package/dist/utils.d.cts
CHANGED
|
@@ -160,7 +160,6 @@ export declare function getSnapFiles(location: SnapLocation, files?: string[] |
|
|
|
160
160
|
*/
|
|
161
161
|
export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promise<{
|
|
162
162
|
manifest: import("@metamask/snaps-utils").VirtualFile<{
|
|
163
|
-
description: string;
|
|
164
163
|
source: {
|
|
165
164
|
shasum: string;
|
|
166
165
|
location: {
|
|
@@ -174,6 +173,7 @@ export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promi
|
|
|
174
173
|
files?: string[] | undefined;
|
|
175
174
|
locales?: string[] | undefined;
|
|
176
175
|
};
|
|
176
|
+
description: string;
|
|
177
177
|
version: import("@metamask/utils").SemVerVersion;
|
|
178
178
|
proposedName: string;
|
|
179
179
|
initialPermissions: Partial<{
|
|
@@ -285,5 +285,13 @@ export declare function throttleTracking(fn: (snapId: SnapId, handler: Trackable
|
|
|
285
285
|
* @returns True if handler is allowed for tracking, false otherwise.
|
|
286
286
|
*/
|
|
287
287
|
export declare function isTrackableHandler(handler: HandlerType): handler is TrackableHandler;
|
|
288
|
+
/**
|
|
289
|
+
* Checks if the given Snap ID is a local Snap ID. This assumes the Snap ID is
|
|
290
|
+
* validated before calling this function, as it only checks the prefix.
|
|
291
|
+
*
|
|
292
|
+
* @param snapId - The Snap ID to check.
|
|
293
|
+
* @returns True if the Snap ID is a local Snap ID, false otherwise.
|
|
294
|
+
*/
|
|
295
|
+
export declare function isLocalSnapId(snapId: SnapId): boolean;
|
|
288
296
|
export {};
|
|
289
297
|
//# 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;AAElD,OAAO,EAML,WAAW,EACZ,8BAA8B;AAC/B,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,CA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E,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;AAED;;GAEG;AACH,eAAO,MAAM,kBAAkB,wLAQpB,CAAC;AAEZ;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEnE;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,CACF,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,EACzB,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,KACX,IAAI,EACT,OAAO,SAAQ,YAYL,MAAM,WACL,gBAAgB,WAChB,OAAO,UACR,MAAM,KACb,IAAI,CAgCR;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,WAAW,GACnB,OAAO,IAAI,gBAAgB,CAE7B;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAErD"}
|
package/dist/utils.d.mts
CHANGED
|
@@ -160,7 +160,6 @@ export declare function getSnapFiles(location: SnapLocation, files?: string[] |
|
|
|
160
160
|
*/
|
|
161
161
|
export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promise<{
|
|
162
162
|
manifest: import("@metamask/snaps-utils").VirtualFile<{
|
|
163
|
-
description: string;
|
|
164
163
|
source: {
|
|
165
164
|
shasum: string;
|
|
166
165
|
location: {
|
|
@@ -174,6 +173,7 @@ export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promi
|
|
|
174
173
|
files?: string[] | undefined;
|
|
175
174
|
locales?: string[] | undefined;
|
|
176
175
|
};
|
|
176
|
+
description: string;
|
|
177
177
|
version: import("@metamask/utils").SemVerVersion;
|
|
178
178
|
proposedName: string;
|
|
179
179
|
initialPermissions: Partial<{
|
|
@@ -285,5 +285,13 @@ export declare function throttleTracking(fn: (snapId: SnapId, handler: Trackable
|
|
|
285
285
|
* @returns True if handler is allowed for tracking, false otherwise.
|
|
286
286
|
*/
|
|
287
287
|
export declare function isTrackableHandler(handler: HandlerType): handler is TrackableHandler;
|
|
288
|
+
/**
|
|
289
|
+
* Checks if the given Snap ID is a local Snap ID. This assumes the Snap ID is
|
|
290
|
+
* validated before calling this function, as it only checks the prefix.
|
|
291
|
+
*
|
|
292
|
+
* @param snapId - The Snap ID to check.
|
|
293
|
+
* @returns True if the Snap ID is a local Snap ID, false otherwise.
|
|
294
|
+
*/
|
|
295
|
+
export declare function isLocalSnapId(snapId: SnapId): boolean;
|
|
288
296
|
export {};
|
|
289
297
|
//# 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;AAElD,OAAO,EAML,WAAW,EACZ,8BAA8B;AAC/B,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,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;;;;;;;;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;AAED;;GAEG;AACH,eAAO,MAAM,kBAAkB,wLAQpB,CAAC;AAEZ;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEnE;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,CACF,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,EACzB,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,KACX,IAAI,EACT,OAAO,SAAQ,YAYL,MAAM,WACL,gBAAgB,WAChB,OAAO,UACR,MAAM,KACb,IAAI,CAgCR;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,WAAW,GACnB,OAAO,IAAI,gBAAgB,CAE7B;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAErD"}
|
package/dist/utils.mjs
CHANGED
|
@@ -252,4 +252,14 @@ export function throttleTracking(fn, timeout = 60000) {
|
|
|
252
252
|
export function isTrackableHandler(handler) {
|
|
253
253
|
return TRACKABLE_HANDLERS.includes(handler);
|
|
254
254
|
}
|
|
255
|
+
/**
|
|
256
|
+
* Checks if the given Snap ID is a local Snap ID. This assumes the Snap ID is
|
|
257
|
+
* validated before calling this function, as it only checks the prefix.
|
|
258
|
+
*
|
|
259
|
+
* @param snapId - The Snap ID to check.
|
|
260
|
+
* @returns True if the Snap ID is a local Snap ID, false otherwise.
|
|
261
|
+
*/
|
|
262
|
+
export function isLocalSnapId(snapId) {
|
|
263
|
+
return snapId.startsWith('local:');
|
|
264
|
+
}
|
|
255
265
|
//# 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,EACnB,WAAW,EACZ,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,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;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,eAAe,CAI7B,YAA0B,EAC1B,YAA0B;IAE1B,OAAO,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,MAAM,CAExC,CAAC,GAAG,EAAE,CAAC,GAA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GAAG,CAAC,IAAI,CAAC,CAAC;QAC7C,MAAM,IAAI,GAAgD;YACxD,MAAM;YACN,OAAO;YACP,OAAO;YACP,MAAM;SACP,CAAC;QAEF,IAAI,GAAG,GAAG,QAAQ,IAAI,OAAO,EAAE,CAAC;YAC9B,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;YAC5B,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACZ,OAAO;QACT,CAAC;QAED,MAAM,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACtC,IAAI,OAAO,EAAE,KAAK,EAAE,CAAC;YACnB,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC;QAED,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QAE5B,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE;YACpB,IAAI;YACJ,KAAK,EAAE,UAAU,CAAC,GAAG,EAAE;gBACrB,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;gBACZ,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC3B,CAAC,EAAE,OAAO,CAAC;SACZ,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAoB;IAEpB,OAAO,kBAAkB,CAAC,QAAQ,CAAC,OAA2B,CAAC,CAAC;AAClE,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 HandlerType,\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\n/**\n * Handlers allowed for tracking.\n */\nexport const TRACKABLE_HANDLERS = Object.freeze([\n HandlerType.OnHomePage,\n HandlerType.OnInstall,\n HandlerType.OnNameLookup,\n HandlerType.OnRpcRequest,\n HandlerType.OnSignature,\n HandlerType.OnTransaction,\n HandlerType.OnUpdate,\n] as const);\n\n/**\n * A union type representing all possible trackable handler types.\n */\nexport type TrackableHandler = (typeof TRACKABLE_HANDLERS)[number];\n\n/**\n * Throttles event tracking calls per unique combination of parameters.\n *\n * @param fn - The tracking function to throttle.\n * @param timeout - The timeout in milliseconds. Defaults to 60000 (1 minute).\n * @returns The throttled function.\n */\nexport function throttleTracking(\n fn: (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ) => void,\n timeout = 60000,\n) {\n const previousCalls = new Map<string, number>();\n const pendingCalls = new Map<\n string,\n {\n args: [SnapId, TrackableHandler, boolean, string];\n timer: ReturnType<typeof setTimeout> | null;\n }\n >();\n\n return (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ): void => {\n const key = `${snapId}${handler}${success}${origin}`;\n const now = Date.now();\n const lastCall = previousCalls.get(key) ?? 0;\n const args: [SnapId, TrackableHandler, boolean, string] = [\n snapId,\n handler,\n success,\n origin,\n ];\n\n if (now - lastCall >= timeout) {\n previousCalls.set(key, now);\n fn(...args);\n return;\n }\n\n const pending = pendingCalls.get(key);\n if (pending?.timer) {\n clearTimeout(pending.timer);\n }\n\n previousCalls.set(key, now);\n\n pendingCalls.set(key, {\n args,\n timer: setTimeout(() => {\n fn(...args);\n pendingCalls.delete(key);\n }, timeout),\n });\n };\n}\n\n/**\n * Whether the handler type if allowed for tracking.\n *\n * @param handler Type of a handler.\n * @returns True if handler is allowed for tracking, false otherwise.\n */\nexport function isTrackableHandler(\n handler: HandlerType,\n): handler is TrackableHandler {\n return TRACKABLE_HANDLERS.includes(handler as TrackableHandler);\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,EACnB,WAAW,EACZ,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,EAAE,EAAE;QACpB,IAAI,CAAC,CAAC,GAAG,IAAI,OAAO,CAAC,EA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;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,MAAc;IAC1C,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;AACrC,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 HandlerType,\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\n/**\n * Handlers allowed for tracking.\n */\nexport const TRACKABLE_HANDLERS = Object.freeze([\n HandlerType.OnHomePage,\n HandlerType.OnInstall,\n HandlerType.OnNameLookup,\n HandlerType.OnRpcRequest,\n HandlerType.OnSignature,\n HandlerType.OnTransaction,\n HandlerType.OnUpdate,\n] as const);\n\n/**\n * A union type representing all possible trackable handler types.\n */\nexport type TrackableHandler = (typeof TRACKABLE_HANDLERS)[number];\n\n/**\n * Throttles event tracking calls per unique combination of parameters.\n *\n * @param fn - The tracking function to throttle.\n * @param timeout - The timeout in milliseconds. Defaults to 60000 (1 minute).\n * @returns The throttled function.\n */\nexport function throttleTracking(\n fn: (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ) => void,\n timeout = 60000,\n) {\n const previousCalls = new Map<string, number>();\n const pendingCalls = new Map<\n string,\n {\n args: [SnapId, TrackableHandler, boolean, string];\n timer: ReturnType<typeof setTimeout> | null;\n }\n >();\n\n return (\n snapId: SnapId,\n handler: TrackableHandler,\n success: boolean,\n origin: string,\n ): void => {\n const key = `${snapId}${handler}${success}${origin}`;\n const now = Date.now();\n const lastCall = previousCalls.get(key) ?? 0;\n const args: [SnapId, TrackableHandler, boolean, string] = [\n snapId,\n handler,\n success,\n origin,\n ];\n\n if (now - lastCall >= timeout) {\n previousCalls.set(key, now);\n fn(...args);\n return;\n }\n\n const pending = pendingCalls.get(key);\n if (pending?.timer) {\n clearTimeout(pending.timer);\n }\n\n previousCalls.set(key, now);\n\n pendingCalls.set(key, {\n args,\n timer: setTimeout(() => {\n fn(...args);\n pendingCalls.delete(key);\n }, timeout),\n });\n };\n}\n\n/**\n * Whether the handler type if allowed for tracking.\n *\n * @param handler Type of a handler.\n * @returns True if handler is allowed for tracking, false otherwise.\n */\nexport function isTrackableHandler(\n handler: HandlerType,\n): handler is TrackableHandler {\n return TRACKABLE_HANDLERS.includes(handler as TrackableHandler);\n}\n\n/**\n * Checks if the given Snap ID is a local Snap ID. This assumes the Snap ID is\n * validated before calling this function, as it only checks the prefix.\n *\n * @param snapId - The Snap ID to check.\n * @returns True if the Snap ID is a local Snap ID, false otherwise.\n */\nexport function isLocalSnapId(snapId: SnapId): boolean {\n return snapId.startsWith('local:');\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-controllers",
|
|
3
|
-
"version": "14.0
|
|
3
|
+
"version": "14.2.0",
|
|
4
4
|
"description": "Controllers for MetaMask Snaps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -86,14 +86,14 @@
|
|
|
86
86
|
"@metamask/key-tree": "^10.1.1",
|
|
87
87
|
"@metamask/object-multiplex": "^2.1.0",
|
|
88
88
|
"@metamask/permission-controller": "^11.0.6",
|
|
89
|
-
"@metamask/phishing-controller": "^
|
|
89
|
+
"@metamask/phishing-controller": "^13.1.0",
|
|
90
90
|
"@metamask/post-message-stream": "^10.0.0",
|
|
91
|
-
"@metamask/rpc-errors": "^7.0.
|
|
91
|
+
"@metamask/rpc-errors": "^7.0.3",
|
|
92
92
|
"@metamask/snaps-registry": "^3.2.3",
|
|
93
|
-
"@metamask/snaps-rpc-methods": "^13.
|
|
94
|
-
"@metamask/snaps-sdk": "^9.
|
|
95
|
-
"@metamask/snaps-utils": "^11.
|
|
96
|
-
"@metamask/utils": "^11.4.
|
|
93
|
+
"@metamask/snaps-rpc-methods": "^13.4.0",
|
|
94
|
+
"@metamask/snaps-sdk": "^9.3.0",
|
|
95
|
+
"@metamask/snaps-utils": "^11.2.0",
|
|
96
|
+
"@metamask/utils": "^11.4.2",
|
|
97
97
|
"@xstate/fsm": "^2.0.0",
|
|
98
98
|
"async-mutex": "^0.5.0",
|
|
99
99
|
"concat-stream": "^2.0.0",
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
"vitest": "^3.1.1"
|
|
146
146
|
},
|
|
147
147
|
"peerDependencies": {
|
|
148
|
-
"@metamask/snaps-execution-environments": "^10.
|
|
148
|
+
"@metamask/snaps-execution-environments": "^10.2.0"
|
|
149
149
|
},
|
|
150
150
|
"peerDependenciesMeta": {
|
|
151
151
|
"@metamask/snaps-execution-environments": {
|