@metamask/snaps-controllers 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +18 -0
  2. package/README.md +3 -0
  3. package/dist/cronjob/CronjobController.d.ts +115 -0
  4. package/dist/cronjob/CronjobController.js +231 -0
  5. package/dist/cronjob/CronjobController.js.map +1 -0
  6. package/dist/cronjob/index.d.ts +1 -0
  7. package/dist/cronjob/index.js +18 -0
  8. package/dist/cronjob/index.js.map +1 -0
  9. package/dist/fsm.d.ts +24 -0
  10. package/dist/fsm.js +75 -0
  11. package/dist/fsm.js.map +1 -0
  12. package/dist/index.d.ts +6 -0
  13. package/dist/index.js +22 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/multichain/MultiChainController.d.ts +135 -0
  16. package/dist/multichain/MultiChainController.js +348 -0
  17. package/dist/multichain/MultiChainController.js.map +1 -0
  18. package/dist/multichain/index.d.ts +3 -0
  19. package/dist/multichain/index.js +20 -0
  20. package/dist/multichain/index.js.map +1 -0
  21. package/dist/multichain/matching.d.ts +9 -0
  22. package/dist/multichain/matching.js +58 -0
  23. package/dist/multichain/matching.js.map +1 -0
  24. package/dist/multichain/middleware.d.ts +14 -0
  25. package/dist/multichain/middleware.js +42 -0
  26. package/dist/multichain/middleware.js.map +1 -0
  27. package/dist/services/AbstractExecutionService.d.ts +124 -0
  28. package/dist/services/AbstractExecutionService.js +316 -0
  29. package/dist/services/AbstractExecutionService.js.map +1 -0
  30. package/dist/services/ExecutionService.d.ts +68 -0
  31. package/dist/services/ExecutionService.js +4 -0
  32. package/dist/services/ExecutionService.js.map +1 -0
  33. package/dist/services/browser.d.ts +3 -0
  34. package/dist/services/browser.js +21 -0
  35. package/dist/services/browser.js.map +1 -0
  36. package/dist/services/iframe/IframeExecutionService.d.ts +25 -0
  37. package/dist/services/iframe/IframeExecutionService.js +82 -0
  38. package/dist/services/iframe/IframeExecutionService.js.map +1 -0
  39. package/dist/services/iframe/index.d.ts +1 -0
  40. package/dist/services/iframe/index.js +18 -0
  41. package/dist/services/iframe/index.js.map +1 -0
  42. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.d.ts +3 -0
  43. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js +74 -0
  44. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js.map +1 -0
  45. package/dist/services/iframe/test/server.d.ts +11 -0
  46. package/dist/services/iframe/test/server.js +71 -0
  47. package/dist/services/iframe/test/server.js.map +1 -0
  48. package/dist/services/index.d.ts +4 -0
  49. package/dist/services/index.js +21 -0
  50. package/dist/services/index.js.map +1 -0
  51. package/dist/services/node/NodeProcessExecutionService.d.ts +11 -0
  52. package/dist/services/node/NodeProcessExecutionService.js +18 -0
  53. package/dist/services/node/NodeProcessExecutionService.js.map +1 -0
  54. package/dist/services/node/NodeThreadExecutionService.d.ts +11 -0
  55. package/dist/services/node/NodeThreadExecutionService.js +18 -0
  56. package/dist/services/node/NodeThreadExecutionService.js.map +1 -0
  57. package/dist/services/node/index.d.ts +2 -0
  58. package/dist/services/node/index.js +19 -0
  59. package/dist/services/node/index.js.map +1 -0
  60. package/dist/snaps/RequestQueue.d.ts +24 -0
  61. package/dist/snaps/RequestQueue.js +47 -0
  62. package/dist/snaps/RequestQueue.js.map +1 -0
  63. package/dist/snaps/SnapController.d.ts +600 -0
  64. package/dist/snaps/SnapController.js +1314 -0
  65. package/dist/snaps/SnapController.js.map +1 -0
  66. package/dist/snaps/Timer.d.ts +39 -0
  67. package/dist/snaps/Timer.js +86 -0
  68. package/dist/snaps/Timer.js.map +1 -0
  69. package/dist/snaps/endowments/cronjob.d.ts +49 -0
  70. package/dist/snaps/endowments/cronjob.js +105 -0
  71. package/dist/snaps/endowments/cronjob.js.map +1 -0
  72. package/dist/snaps/endowments/enum.d.ts +8 -0
  73. package/dist/snaps/endowments/enum.js +13 -0
  74. package/dist/snaps/endowments/enum.js.map +1 -0
  75. package/dist/snaps/endowments/ethereum-provider.d.ts +13 -0
  76. package/dist/snaps/endowments/ethereum-provider.js +31 -0
  77. package/dist/snaps/endowments/ethereum-provider.js.map +1 -0
  78. package/dist/snaps/endowments/index.d.ts +67 -0
  79. package/dist/snaps/endowments/index.js +39 -0
  80. package/dist/snaps/endowments/index.js.map +1 -0
  81. package/dist/snaps/endowments/keyring.d.ts +39 -0
  82. package/dist/snaps/endowments/keyring.js +103 -0
  83. package/dist/snaps/endowments/keyring.js.map +1 -0
  84. package/dist/snaps/endowments/long-running.d.ts +13 -0
  85. package/dist/snaps/endowments/long-running.js +28 -0
  86. package/dist/snaps/endowments/long-running.js.map +1 -0
  87. package/dist/snaps/endowments/network-access.d.ts +13 -0
  88. package/dist/snaps/endowments/network-access.js +29 -0
  89. package/dist/snaps/endowments/network-access.js.map +1 -0
  90. package/dist/snaps/endowments/transaction-insight.d.ts +38 -0
  91. package/dist/snaps/endowments/transaction-insight.js +106 -0
  92. package/dist/snaps/endowments/transaction-insight.js.map +1 -0
  93. package/dist/snaps/index.d.ts +4 -0
  94. package/dist/snaps/index.js +21 -0
  95. package/dist/snaps/index.js.map +1 -0
  96. package/dist/snaps/selectors.d.ts +2 -0
  97. package/dist/snaps/selectors.js +6 -0
  98. package/dist/snaps/selectors.js.map +1 -0
  99. package/dist/snaps/utils/index.d.ts +2 -0
  100. package/dist/snaps/utils/index.js +19 -0
  101. package/dist/snaps/utils/index.js.map +1 -0
  102. package/dist/snaps/utils/npm.d.ts +14 -0
  103. package/dist/snaps/utils/npm.js +81 -0
  104. package/dist/snaps/utils/npm.js.map +1 -0
  105. package/dist/snaps/utils/stream.d.ts +30 -0
  106. package/dist/snaps/utils/stream.js +124 -0
  107. package/dist/snaps/utils/stream.js.map +1 -0
  108. package/dist/utils.d.ts +128 -0
  109. package/dist/utils.js +92 -0
  110. package/dist/utils.js.map +1 -0
  111. package/package.json +99 -0
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./npm"), exports);
18
+ __exportStar(require("./stream"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/snaps/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wCAAsB;AACtB,2CAAyB","sourcesContent":["export * from './npm';\nexport * from './stream';\n"]}
@@ -0,0 +1,14 @@
1
+ import { SnapFiles } from '@metamask/snaps-utils';
2
+ export declare const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
3
+ /**
4
+ * Fetches a Snap from the public npm registry.
5
+ *
6
+ * @param packageName - The name of the package whose tarball to fetch.
7
+ * @param versionRange - The SemVer range of the package to fetch. The highest
8
+ * version satisfying the range will be fetched.
9
+ * @param registryUrl - The URL of the npm registry to fetch from.
10
+ * @param fetchFunction - The fetch function to use. Defaults to the global
11
+ * {@link fetch}. Useful for Node.js compatibility.
12
+ * @returns A tuple of the Snap manifest object and the Snap source code.
13
+ */
14
+ export declare function fetchNpmSnap(packageName: string, versionRange: string, registryUrl?: string, fetchFunction?: typeof fetch): Promise<SnapFiles>;
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.fetchNpmSnap = exports.DEFAULT_NPM_REGISTRY = void 0;
7
+ const utils_1 = require("@metamask/utils");
8
+ const pump_1 = __importDefault(require("pump"));
9
+ const gunzip_maybe_1 = __importDefault(require("gunzip-maybe"));
10
+ const snaps_utils_1 = require("@metamask/snaps-utils");
11
+ const stream_1 = require("./stream");
12
+ exports.DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
13
+ /**
14
+ * Fetches a Snap from the public npm registry.
15
+ *
16
+ * @param packageName - The name of the package whose tarball to fetch.
17
+ * @param versionRange - The SemVer range of the package to fetch. The highest
18
+ * version satisfying the range will be fetched.
19
+ * @param registryUrl - The URL of the npm registry to fetch from.
20
+ * @param fetchFunction - The fetch function to use. Defaults to the global
21
+ * {@link fetch}. Useful for Node.js compatibility.
22
+ * @returns A tuple of the Snap manifest object and the Snap source code.
23
+ */
24
+ async function fetchNpmSnap(packageName, versionRange, registryUrl = exports.DEFAULT_NPM_REGISTRY, fetchFunction = fetch) {
25
+ const [tarballResponse, actualVersion] = await fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction);
26
+ // Extract the tarball and get the necessary files from it.
27
+ const snapFiles = {};
28
+ await new Promise((resolve, reject) => {
29
+ (0, pump_1.default)((0, stream_1.getNodeStream)(tarballResponse),
30
+ // The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
31
+ // before we can actually grab any files from it.
32
+ (0, gunzip_maybe_1.default)(), (0, stream_1.createTarballExtractionStream)(snapFiles), (error) => {
33
+ error ? reject(error) : resolve();
34
+ });
35
+ });
36
+ // At this point, the necessary files will have been added to the snapFiles
37
+ // object if they exist.
38
+ return (0, snaps_utils_1.validateNpmSnap)(snapFiles, `npm Snap "${packageName}@${actualVersion}" validation error: `);
39
+ }
40
+ exports.fetchNpmSnap = fetchNpmSnap;
41
+ /**
42
+ * Fetches the tarball (`.tgz` file) of the specified package and version from
43
+ * the public npm registry. Throws an error if fetching fails.
44
+ *
45
+ * @param packageName - The name of the package whose tarball to fetch.
46
+ * @param versionRange - The SemVer range of the package to fetch. The highest
47
+ * version satisfying the range will be fetched.
48
+ * @param registryUrl - The URL of the npm registry to fetch the tarball from.
49
+ * @param fetchFunction - The fetch function to use. Defaults to the global
50
+ * {@link fetch}. Useful for Node.js compatibility.
51
+ * @returns A tuple of the {@link Response} for the package tarball and the
52
+ * actual version of the package.
53
+ */
54
+ async function fetchNpmTarball(packageName, versionRange, registryUrl = exports.DEFAULT_NPM_REGISTRY, fetchFunction = fetch) {
55
+ var _a, _b, _c, _d;
56
+ const packageMetadata = await (await fetchFunction(new URL(packageName, registryUrl).toString())).json();
57
+ if (!(0, utils_1.isObject)(packageMetadata)) {
58
+ throw new Error(`Failed to fetch package "${packageName}" metadata from npm.`);
59
+ }
60
+ const targetVersion = (0, snaps_utils_1.getTargetVersion)(Object.keys((_a = packageMetadata === null || packageMetadata === void 0 ? void 0 : packageMetadata.versions) !== null && _a !== void 0 ? _a : {}), versionRange);
61
+ if (targetVersion === null) {
62
+ throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}"`);
63
+ }
64
+ const tarballUrlString = (_d = (_c = (_b = packageMetadata.versions) === null || _b === void 0 ? void 0 : _b[targetVersion]) === null || _c === void 0 ? void 0 : _c.dist) === null || _d === void 0 ? void 0 : _d.tarball;
65
+ if (!(0, snaps_utils_1.isValidUrl)(tarballUrlString) || !tarballUrlString.endsWith('.tgz')) {
66
+ throw new Error(`Failed to find valid tarball URL in npm metadata for package "${packageName}".`);
67
+ }
68
+ // Override the tarball hostname/protocol with registryUrl hostname/protocol
69
+ const newRegistryUrl = new URL(registryUrl);
70
+ const newTarballUrl = new URL(tarballUrlString);
71
+ newTarballUrl.hostname = newRegistryUrl.hostname;
72
+ newTarballUrl.protocol = newRegistryUrl.protocol;
73
+ // Perform a raw fetch because we want the Response object itself.
74
+ const tarballResponse = await fetchFunction(newTarballUrl.toString());
75
+ if (!tarballResponse.ok) {
76
+ throw new Error(`Failed to fetch tarball for package "${packageName}".`);
77
+ }
78
+ const stream = await tarballResponse.blob().then((blob) => blob.stream());
79
+ return [stream, targetVersion];
80
+ }
81
+ //# sourceMappingURL=npm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/utils/npm.ts"],"names":[],"mappings":";;;;;;AAAA,2CAA2C;AAC3C,gDAAwB;AACxB,gEAA8C;AAC9C,uDAM+B;AAE/B,qCAAwE;AAE3D,QAAA,oBAAoB,GAAG,4BAA4B,CAAC;AAEjE;;;;;;;;;;GAUG;AACI,KAAK,UAAU,YAAY,CAChC,WAAmB,EACnB,YAAoB,EACpB,WAAW,GAAG,4BAAoB,EAClC,aAAa,GAAG,KAAK;IAErB,MAAM,CAAC,eAAe,EAAE,aAAa,CAAC,GAAG,MAAM,eAAe,CAC5D,WAAW,EACX,YAAY,EACZ,WAAW,EACX,aAAa,CACd,CAAC;IAEF,2DAA2D;IAC3D,MAAM,SAAS,GAAyB,EAAE,CAAC;IAC3C,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC1C,IAAA,cAAI,EACF,IAAA,sBAAa,EAAC,eAAe,CAAC;QAC9B,4EAA4E;QAC5E,iDAAiD;QACjD,IAAA,sBAAkB,GAAE,EACpB,IAAA,sCAA6B,EAAC,SAAS,CAAC,EACxC,CAAC,KAAK,EAAE,EAAE;YACR,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;QACpC,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,2EAA2E;IAC3E,wBAAwB;IACxB,OAAO,IAAA,6BAAe,EACpB,SAAS,EACT,aAAa,WAAW,IAAI,aAAa,sBAAsB,CAChE,CAAC;AACJ,CAAC;AAlCD,oCAkCC;AAED;;;;;;;;;;;;GAYG;AACH,KAA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AAG,MAAM,aAAa,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC,CAAC;IACtE,IAAI,CAAC,eAAe,CAAC,EAAE,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,wCAAwC,WAAW,IAAI,CAAC,CAAC;KAC1E;IACD,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAE1E,OAAO,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AACjC,CAAC","sourcesContent":["import { isObject } from '@metamask/utils';\nimport pump from 'pump';\nimport createGunzipStream from 'gunzip-maybe';\nimport {\n SnapFiles,\n UnvalidatedSnapFiles,\n isValidUrl,\n getTargetVersion,\n validateNpmSnap,\n} from '@metamask/snaps-utils';\n\nimport { createTarballExtractionStream, getNodeStream } from './stream';\n\nexport const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\n/**\n * Fetches a Snap from the public npm registry.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport async function fetchNpmSnap(\n packageName: string,\n versionRange: string,\n registryUrl = DEFAULT_NPM_REGISTRY,\n fetchFunction = fetch,\n): Promise<SnapFiles> {\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n packageName,\n versionRange,\n registryUrl,\n fetchFunction,\n );\n\n // Extract the tarball and get the necessary files from it.\n const snapFiles: UnvalidatedSnapFiles = {};\n await new Promise<void>((resolve, reject) => {\n pump(\n getNodeStream(tarballResponse),\n // The \"gz\" in \"tgz\" stands for \"gzip\". The tarball needs to be decompressed\n // before we can actually grab any files from it.\n createGunzipStream(),\n createTarballExtractionStream(snapFiles),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\n\n // At this point, the necessary files will have been added to the snapFiles\n // object if they exist.\n return validateNpmSnap(\n snapFiles,\n `npm Snap \"${packageName}@${actualVersion}\" validation error: `,\n );\n}\n\n/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry. Throws an error if fetching fails.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch the tarball from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the {@link Response} for the package tarball and the\n * actual version of the package.\n */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: string,\n registryUrl = DEFAULT_NPM_REGISTRY,\n fetchFunction = fetch,\n): Promise<[ReadableStream, string]> {\n const packageMetadata = await (\n await fetchFunction(new URL(packageName, registryUrl).toString())\n ).json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n const targetVersion = getTargetVersion(\n Object.keys((packageMetadata as any)?.versions ?? {}),\n versionRange,\n );\n\n if (targetVersion === null) {\n throw new Error(\n `Failed to find a matching version in npm metadata for package \"${packageName}\" and requested semver range \"${versionRange}\"`,\n );\n }\n\n const tarballUrlString = (packageMetadata as any).versions?.[targetVersion]\n ?.dist?.tarball;\n\n if (!isValidUrl(tarballUrlString) || !tarballUrlString.endsWith('.tgz')) {\n throw new Error(\n `Failed to find valid tarball URL in npm metadata for package \"${packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newRegistryUrl = new URL(registryUrl);\n const newTarballUrl = new URL(tarballUrlString);\n newTarballUrl.hostname = newRegistryUrl.hostname;\n newTarballUrl.protocol = newRegistryUrl.protocol;\n\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await fetchFunction(newTarballUrl.toString());\n if (!tarballResponse.ok) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n const stream = await tarballResponse.blob().then((blob) => blob.stream());\n\n return [stream, targetVersion];\n}\n"]}
@@ -0,0 +1,30 @@
1
+ /// <reference types="node" />
2
+ import { Readable, Writable } from 'stream';
3
+ import { UnvalidatedSnapFiles } from '@metamask/snaps-utils';
4
+ /**
5
+ * Strips the leading `./` from a string, or does nothing if no string is
6
+ * provided.
7
+ *
8
+ * @param pathString - The path string to normalize.
9
+ * @returns The specified path without a `./` prefix, or `undefined` if no
10
+ * string was provided.
11
+ */
12
+ export declare function stripDotSlash(pathString?: string): string | undefined;
13
+ /**
14
+ * Converts a {@link ReadableStream} to a Node.js {@link Readable}
15
+ * stream. Returns the stream directly if it is already a Node.js stream.
16
+ * We can't use the native Web {@link ReadableStream} directly because the
17
+ * other stream libraries we use expect Node.js streams.
18
+ *
19
+ * @param stream - The stream to convert.
20
+ * @returns The given stream as a Node.js Readable stream.
21
+ */
22
+ export declare function getNodeStream(stream: ReadableStream): Readable;
23
+ /**
24
+ * Creates a `tar-stream` that will get the necessary files from an npm Snap
25
+ * package tarball (`.tgz` file).
26
+ *
27
+ * @param snapFiles - An object to write target file contents to.
28
+ * @returns The {@link Writable} tarball extraction stream.
29
+ */
30
+ export declare function createTarballExtractionStream(snapFiles: UnvalidatedSnapFiles): Writable;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createTarballExtractionStream = exports.getNodeStream = exports.stripDotSlash = void 0;
7
+ const readable_web_to_node_stream_1 = require("readable-web-to-node-stream");
8
+ const tar_stream_1 = require("tar-stream");
9
+ const concat_stream_1 = __importDefault(require("concat-stream"));
10
+ const utils_1 = require("@metamask/utils");
11
+ const snaps_utils_1 = require("@metamask/snaps-utils");
12
+ // The paths of files within npm tarballs appear to always be prefixed with
13
+ // "package/".
14
+ const NPM_TARBALL_PATH_PREFIX = /^package\//u;
15
+ /**
16
+ * Strips the leading `./` from a string, or does nothing if no string is
17
+ * provided.
18
+ *
19
+ * @param pathString - The path string to normalize.
20
+ * @returns The specified path without a `./` prefix, or `undefined` if no
21
+ * string was provided.
22
+ */
23
+ function stripDotSlash(pathString) {
24
+ return pathString === null || pathString === void 0 ? void 0 : pathString.replace(/^\.\//u, '');
25
+ }
26
+ exports.stripDotSlash = stripDotSlash;
27
+ /**
28
+ * Converts a {@link ReadableStream} to a Node.js {@link Readable}
29
+ * stream. Returns the stream directly if it is already a Node.js stream.
30
+ * We can't use the native Web {@link ReadableStream} directly because the
31
+ * other stream libraries we use expect Node.js streams.
32
+ *
33
+ * @param stream - The stream to convert.
34
+ * @returns The given stream as a Node.js Readable stream.
35
+ */
36
+ function getNodeStream(stream) {
37
+ if (typeof stream.getReader !== 'function') {
38
+ return stream;
39
+ }
40
+ return new readable_web_to_node_stream_1.ReadableWebToNodeStream(stream);
41
+ }
42
+ exports.getNodeStream = getNodeStream;
43
+ /**
44
+ * Creates a `tar-stream` that will get the necessary files from an npm Snap
45
+ * package tarball (`.tgz` file).
46
+ *
47
+ * @param snapFiles - An object to write target file contents to.
48
+ * @returns The {@link Writable} tarball extraction stream.
49
+ */
50
+ function createTarballExtractionStream(snapFiles) {
51
+ // `tar-stream` is pretty old-school, so we create it first and then
52
+ // instrument it by adding event listeners.
53
+ const extractStream = (0, tar_stream_1.extract)();
54
+ // `tar-stream` reads every file in the tarball serially. We already know
55
+ // where to look for package.json and the Snap manifest, but we don't know
56
+ // where the source code is. Therefore, we cache the contents of each .js
57
+ // file in the tarball and pick out the correct one when the stream has ended.
58
+ const jsFileCache = new Map();
59
+ // "entry" is fired for every discreet entity in the tarball. This includes
60
+ // files and folders.
61
+ extractStream.on('entry', (header, entryStream, next) => {
62
+ const { name: headerName, type: headerType } = header;
63
+ if (headerType === 'file') {
64
+ // The name is a path if the header type is "file".
65
+ const filePath = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');
66
+ // Note the use of `concat-stream` since the data for each file may be
67
+ // chunked.
68
+ if (filePath === snaps_utils_1.NpmSnapFileNames.PackageJson) {
69
+ return entryStream.pipe((0, concat_stream_1.default)((data) => {
70
+ try {
71
+ snapFiles.packageJson = JSON.parse(data.toString());
72
+ }
73
+ catch (_error) {
74
+ return extractStream.destroy(new Error(`Failed to parse "${snaps_utils_1.NpmSnapFileNames.PackageJson}".`));
75
+ }
76
+ return next();
77
+ }));
78
+ }
79
+ else if (filePath === snaps_utils_1.NpmSnapFileNames.Manifest) {
80
+ return entryStream.pipe((0, concat_stream_1.default)((data) => {
81
+ try {
82
+ snapFiles.manifest = JSON.parse(data.toString());
83
+ }
84
+ catch (_error) {
85
+ return extractStream.destroy(new Error(`Failed to parse "${snaps_utils_1.NpmSnapFileNames.Manifest}".`));
86
+ }
87
+ return next();
88
+ }));
89
+ }
90
+ else if (/\w+\.(?:js|svg)$/u.test(filePath)) {
91
+ return entryStream.pipe((0, concat_stream_1.default)((data) => {
92
+ jsFileCache.set(filePath, data);
93
+ return next();
94
+ }));
95
+ }
96
+ }
97
+ // If we get here, the entry is not a file, and we want to ignore. The entry
98
+ // stream must be drained, or the extractStream will stop reading. This is
99
+ // effectively a no-op for the current entry.
100
+ entryStream.on('end', () => next());
101
+ return entryStream.resume();
102
+ });
103
+ // Once we've read the entire tarball, attempt to grab the bundle file
104
+ // contents from the .js file cache.
105
+ extractStream.once('finish', () => {
106
+ var _a, _b, _c, _d, _e;
107
+ if ((0, utils_1.isObject)(snapFiles.manifest)) {
108
+ /* istanbul ignore next: optional chaining */
109
+ const { filePath: _bundlePath, iconPath: _iconPath } = (_c = (_b = (_a = snapFiles.manifest.source) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.npm) !== null && _c !== void 0 ? _c : {};
110
+ const bundlePath = stripDotSlash(_bundlePath);
111
+ const iconPath = stripDotSlash(_iconPath);
112
+ if (bundlePath) {
113
+ snapFiles.sourceCode = (_d = jsFileCache.get(bundlePath)) === null || _d === void 0 ? void 0 : _d.toString('utf8');
114
+ }
115
+ if (typeof iconPath === 'string' && iconPath.endsWith('.svg')) {
116
+ snapFiles.svgIcon = (_e = jsFileCache.get(iconPath)) === null || _e === void 0 ? void 0 : _e.toString('utf8');
117
+ }
118
+ }
119
+ jsFileCache.clear();
120
+ });
121
+ return extractStream;
122
+ }
123
+ exports.createTarballExtractionStream = createTarballExtractionStream;
124
+ //# sourceMappingURL=stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/snaps/utils/stream.ts"],"names":[],"mappings":";;;;;;AACA,6EAAsE;AACtE,2CAAmD;AACnD,kEAAmC;AACnC,2CAA2C;AAC3C,uDAI+B;AAE/B,2EAA2E;AAC3E,cAAc;AACd,MAAM,uBAAuB,GAAG,aAAa,CAAC;AAE9C;;;;;;;GAOG;AACH,SAAgB,aAAa,CAAC,UAAmB;IAC/C,OAAO,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC;AAFD,sCAEC;AAED;;;;;;;;GAQG;AACH,SAAgB,aAAa,CAAC,MAAsB;IAClD,IAAI,OAAO,MAAM,CAAC,SAAS,KAAK,UAAU,EAAE;QAC1C,OAAO,MAA6B,CAAC;KACtC;IAED,OAAO,IAAI,qDAAuB,CAAC,MAAM,CAAC,CAAC;AAC7C,CAAC;AAND,sCAMC;AAED;;;;;;GAMG;AACH,SAAgB,6BAA6B,CAC3C,SAA+B;IAE/B,oEAAoE;IACpE,2CAA2C;IAC3C,MAAM,aAAa,GAAG,IAAA,oBAAU,GAAE,CAAC;IAEnC,yEAAyE;IACzE,0EAA0E;IAC1E,yEAAyE;IACzE,8EAA8E;IAC9E,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE9C,2EA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AC,QAAQ,CAAC,0CAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;aACjE;SACF;QACD,WAAW,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,OAAO,aAAa,CAAC;AACvB,CAAC;AA5FD,sEA4FC","sourcesContent":["import { Readable, Writable } from 'stream';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { extract as tarExtract } from 'tar-stream';\nimport concat from 'concat-stream';\nimport { isObject } from '@metamask/utils';\nimport {\n SnapManifest,\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n} from '@metamask/snaps-utils';\n\n// The paths of files within npm tarballs appear to always be prefixed with\n// \"package/\".\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\n\n/**\n * Strips the leading `./` from a string, or does nothing if no string is\n * provided.\n *\n * @param pathString - The path string to normalize.\n * @returns The specified path without a `./` prefix, or `undefined` if no\n * string was provided.\n */\nexport function stripDotSlash(pathString?: string): string | undefined {\n return pathString?.replace(/^\\.\\//u, '');\n}\n\n/**\n * Converts a {@link ReadableStream} to a Node.js {@link Readable}\n * stream. Returns the stream directly if it is already a Node.js stream.\n * We can't use the native Web {@link ReadableStream} directly because the\n * other stream libraries we use expect Node.js streams.\n *\n * @param stream - The stream to convert.\n * @returns The given stream as a Node.js Readable stream.\n */\nexport function getNodeStream(stream: ReadableStream): Readable {\n if (typeof stream.getReader !== 'function') {\n return stream as unknown as Readable;\n }\n\n return new ReadableWebToNodeStream(stream);\n}\n\n/**\n * Creates a `tar-stream` that will get the necessary files from an npm Snap\n * package tarball (`.tgz` file).\n *\n * @param snapFiles - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nexport function createTarballExtractionStream(\n snapFiles: UnvalidatedSnapFiles,\n): Writable {\n // `tar-stream` is pretty old-school, so we create it first and then\n // instrument it by adding event listeners.\n const extractStream = tarExtract();\n\n // `tar-stream` reads every file in the tarball serially. We already know\n // where to look for package.json and the Snap manifest, but we don't know\n // where the source code is. Therefore, we cache the contents of each .js\n // file in the tarball and pick out the correct one when the stream has ended.\n const jsFileCache = new Map<string, Buffer>();\n\n // \"entry\" is fired for every discreet entity in the tarball. This includes\n // files and folders.\n extractStream.on('entry', (header, entryStream, next) => {\n const { name: headerName, type: headerType } = header;\n if (headerType === 'file') {\n // The name is a path if the header type is \"file\".\n const filePath = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');\n\n // Note the use of `concat-stream` since the data for each file may be\n // chunked.\n if (filePath === NpmSnapFileNames.PackageJson) {\n return entryStream.pipe(\n concat((data) => {\n try {\n snapFiles.packageJson = JSON.parse(data.toString());\n } catch (_error) {\n return extractStream.destroy(\n new Error(`Failed to parse \"${NpmSnapFileNames.PackageJson}\".`),\n );\n }\n\n return next();\n }),\n );\n } else if (filePath === NpmSnapFileNames.Manifest) {\n return entryStream.pipe(\n concat((data) => {\n try {\n snapFiles.manifest = JSON.parse(data.toString());\n } catch (_error) {\n return extractStream.destroy(\n new Error(`Failed to parse \"${NpmSnapFileNames.Manifest}\".`),\n );\n }\n\n return next();\n }),\n );\n } else if (/\\w+\\.(?:js|svg)$/u.test(filePath)) {\n return entryStream.pipe(\n concat((data) => {\n jsFileCache.set(filePath, data);\n return next();\n }),\n );\n }\n }\n\n // If we get here, the entry is not a file, and we want to ignore. The entry\n // stream must be drained, or the extractStream will stop reading. This is\n // effectively a no-op for the current entry.\n entryStream.on('end', () => next());\n return entryStream.resume();\n });\n\n // Once we've read the entire tarball, attempt to grab the bundle file\n // contents from the .js file cache.\n extractStream.once('finish', () => {\n if (isObject(snapFiles.manifest)) {\n /* istanbul ignore next: optional chaining */\n const { filePath: _bundlePath, iconPath: _iconPath } =\n (snapFiles.manifest as unknown as Partial<SnapManifest>).source\n ?.location?.npm ?? {};\n\n const bundlePath = stripDotSlash(_bundlePath);\n const iconPath = stripDotSlash(_iconPath);\n\n if (bundlePath) {\n snapFiles.sourceCode = jsFileCache.get(bundlePath)?.toString('utf8');\n }\n\n if (typeof iconPath === 'string' && iconPath.endsWith('.svg')) {\n snapFiles.svgIcon = jsFileCache.get(iconPath)?.toString('utf8');\n }\n }\n jsFileCache.clear();\n });\n\n return extractStream;\n}\n"]}
@@ -0,0 +1,128 @@
1
+ import { Timer } from './snaps/Timer';
2
+ /**
3
+ * Takes two objects and does a Set Difference of them.
4
+ * Set Difference is generally defined as follows:
5
+ * ```
6
+ * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B
7
+ * ```
8
+ * Meaning that the returned object contains all properties of A expect those that also
9
+ * appear in B. Notice that properties that appear in B, but not in A, have no effect.
10
+ *
11
+ * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}
12
+ * @param objectA - The object on which the difference is being calculated.
13
+ * @param objectB - The object whose properties will be removed from objectA.
14
+ * @returns The objectA without properties from objectB.
15
+ */
16
+ export declare function setDiff<ObjectA extends Record<any, unknown>, ObjectB extends Record<any, unknown>>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB>;
17
+ /**
18
+ * A Promise that delays it's return for a given amount of milliseconds.
19
+ *
20
+ * @param ms - Milliseconds to delay the execution for.
21
+ * @param result - The result to return from the Promise after delay.
22
+ * @returns A promise that is void if no result provided, result otherwise.
23
+ * @template Result - The `result`.
24
+ */
25
+ export declare function delay<Result = void>(ms: number, result?: Result): Promise<Result> & {
26
+ cancel: () => void;
27
+ };
28
+ /**
29
+ * A Promise that delays it's return by using a pausable Timer.
30
+ *
31
+ * @param timer - Timer used to control the delay.
32
+ * @param result - The result to return from the Promise after delay.
33
+ * @returns A promise that is void if no result provided, result otherwise.
34
+ * @template Result - The `result`.
35
+ */
36
+ export declare function delayWithTimer<Result = void>(timer: Timer, result?: Result): Promise<Result> & {
37
+ cancel: () => void;
38
+ };
39
+ export declare const hasTimedOut: unique symbol;
40
+ /**
41
+ * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.
42
+ *
43
+ * 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.
44
+ *
45
+ * @param promise - The promise that you want to execute.
46
+ * @param timerOrMs - The timer controlling the timeout or a ms value.
47
+ * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if
48
+ * returning early.
49
+ * @template PromiseValue- - The value of the Promise.
50
+ */
51
+ export declare function withTimeout<PromiseValue = void>(promise: Promise<PromiseValue>, timerOrMs: Timer | number): Promise<PromiseValue | typeof hasTimedOut>;
52
+ /**
53
+ * Checks whether the type is composed of literal types
54
+ *
55
+ * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed
56
+ * @example
57
+ * ```
58
+ * type t1 = IsLiteral<1 | 2 | "asd" | true>;
59
+ * // t1 = true
60
+ *
61
+ * type t2 = IsLiteral<number | string>;
62
+ * // t2 = false
63
+ *
64
+ * type t3 = IsLiteral<1 | string>;
65
+ * // t3 = boolean
66
+ *
67
+ * const s = Symbol();
68
+ * type t4 = IsLiteral<typeof s>;
69
+ * // t4 = true
70
+ *
71
+ * type t5 = IsLiteral<symbol>
72
+ * // t5 = false;
73
+ * ```
74
+ */
75
+ declare type IsLiteral<T> = T extends string | number | boolean | symbol ? Extract<string | number | boolean | symbol, T> extends never ? true : false : false;
76
+ /**
77
+ * Returns all keys of an object, that are literal, as an union
78
+ *
79
+ * @example
80
+ * ```
81
+ * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>
82
+ * // t1 = 'b' | 'c'
83
+ * ```
84
+ * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}
85
+ */
86
+ declare type _LiteralKeys<T> = NonNullable<{
87
+ [Key in keyof T]: IsLiteral<Key> extends true ? Key : never;
88
+ }[keyof T]>;
89
+ /**
90
+ * Returns all keys of an object, that are not literal, as an union
91
+ *
92
+ * @example
93
+ * ```
94
+ * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>
95
+ * // t1 = 'a' | 'd'
96
+ * ```
97
+ * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}
98
+ */
99
+ declare type _NonLiteralKeys<T> = NonNullable<{
100
+ [Key in keyof T]: IsLiteral<Key> extends false ? Key : never;
101
+ }[keyof T]>;
102
+ /**
103
+ * A set difference of two objects based on their keys
104
+ *
105
+ * @example
106
+ * ```
107
+ * type t1 = Diff<{a: string, b: string}, {a: number}>
108
+ * // t1 = {b: string};
109
+ * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;
110
+ * // t2 = { a?: string, 0: string};
111
+ * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;
112
+ * // t3 = {a?: string, 0: string}
113
+ * ```
114
+ * @see {@link setDiff} for the main use-case
115
+ */
116
+ export declare type Diff<A, B> = Omit<A, _LiteralKeys<B>> & Partial<Pick<A, Extract<keyof A, _NonLiteralKeys<B>>>>;
117
+ /**
118
+ * Makes every specified property of the specified object type mutable.
119
+ *
120
+ * @template T - The object whose readonly properties to make mutable.
121
+ * @template TargetKey - The property key(s) to make mutable.
122
+ */
123
+ export declare type Mutable<T extends Record<string, unknown>, TargetKey extends string> = {
124
+ -readonly [Key in keyof Pick<T, TargetKey>]: T[Key];
125
+ } & {
126
+ [Key in keyof Omit<T, TargetKey>]: T[Key];
127
+ };
128
+ export {};
package/dist/utils.js ADDED
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withTimeout = exports.hasTimedOut = exports.delayWithTimer = exports.delay = exports.setDiff = void 0;
4
+ const Timer_1 = require("./snaps/Timer");
5
+ /**
6
+ * Takes two objects and does a Set Difference of them.
7
+ * Set Difference is generally defined as follows:
8
+ * ```
9
+ * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B
10
+ * ```
11
+ * Meaning that the returned object contains all properties of A expect those that also
12
+ * appear in B. Notice that properties that appear in B, but not in A, have no effect.
13
+ *
14
+ * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}
15
+ * @param objectA - The object on which the difference is being calculated.
16
+ * @param objectB - The object whose properties will be removed from objectA.
17
+ * @returns The objectA without properties from objectB.
18
+ */
19
+ function setDiff(objectA, objectB) {
20
+ return Object.entries(objectA).reduce((acc, [key, value]) => {
21
+ if (!(key in objectB)) {
22
+ acc[key] = value;
23
+ }
24
+ return acc;
25
+ }, {});
26
+ }
27
+ exports.setDiff = setDiff;
28
+ /**
29
+ * A Promise that delays it's return for a given amount of milliseconds.
30
+ *
31
+ * @param ms - Milliseconds to delay the execution for.
32
+ * @param result - The result to return from the Promise after delay.
33
+ * @returns A promise that is void if no result provided, result otherwise.
34
+ * @template Result - The `result`.
35
+ */
36
+ function delay(ms, result) {
37
+ return delayWithTimer(new Timer_1.Timer(ms), result);
38
+ }
39
+ exports.delay = delay;
40
+ /**
41
+ * A Promise that delays it's return by using a pausable Timer.
42
+ *
43
+ * @param timer - Timer used to control the delay.
44
+ * @param result - The result to return from the Promise after delay.
45
+ * @returns A promise that is void if no result provided, result otherwise.
46
+ * @template Result - The `result`.
47
+ */
48
+ function delayWithTimer(timer, result) {
49
+ let rejectFunc;
50
+ const promise = new Promise((resolve, reject) => {
51
+ timer.start(() => {
52
+ result === undefined ? resolve() : resolve(result);
53
+ });
54
+ rejectFunc = reject;
55
+ });
56
+ promise.cancel = () => {
57
+ if (timer.status !== 'finished') {
58
+ timer.cancel();
59
+ rejectFunc(new Error('The delay has been canceled.'));
60
+ }
61
+ };
62
+ return promise;
63
+ }
64
+ exports.delayWithTimer = delayWithTimer;
65
+ /*
66
+ * We use a Symbol instead of rejecting the promise so that Errors thrown
67
+ * by the main promise will propagate.
68
+ */
69
+ exports.hasTimedOut = Symbol('Used to check if the requested promise has timeout (see withTimeout)');
70
+ /**
71
+ * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.
72
+ *
73
+ * 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.
74
+ *
75
+ * @param promise - The promise that you want to execute.
76
+ * @param timerOrMs - The timer controlling the timeout or a ms value.
77
+ * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if
78
+ * returning early.
79
+ * @template PromiseValue- - The value of the Promise.
80
+ */
81
+ async function withTimeout(promise, timerOrMs) {
82
+ const timer = typeof timerOrMs === 'number' ? new Timer_1.Timer(timerOrMs) : timerOrMs;
83
+ const delayPromise = delayWithTimer(timer, exports.hasTimedOut);
84
+ try {
85
+ return await Promise.race([promise, delayPromise]);
86
+ }
87
+ finally {
88
+ delayPromise.cancel();
89
+ }
90
+ }
91
+ exports.withTimeout = withTimeout;
92
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,yCAAsC;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;YACrB,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;SAClB;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAE,CACuB,CAAC;AAC9B,CAAC;AAbD,0BAaC;AAED;;;;;;;GAOG;AACH,SAAgB,KAAK,CACnB,EAAU,EACV,MAAe;IAEf,OAAO,cAAc,CAAC,IAAI,aAAK,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;AAC/C,CAAC;AALD,sBAKC;AAED;;;;;;;GAOG;AACH,SAAgB,cAAc,CAC5B,KAAY,EACZ,MAAe;IAEf,IAAI,UAAmC,CAAC;IACxC,MAAM,OAAO,GAAQ,IAAI,OAAO,CAAS,CAAC,OAAY,EAAE,MAAM,EAAE,EAAE;QAChE,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE;YACf,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;QACH,UAAU,GAAG,MAAM,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,OAAO,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,IAAI,KAAK,CAAC,MAAM,KAAK,UAAU,EAAE;YAC/B,KAAK,CAAC,MAAM,EAAE,CAAC;YACf,UAAU,CAAC,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC,CAAC;SACvD;IACH,CAAC,CAAC;IACF,OAAO,OAAO,CAAC;AACjB,CAAC;AAnBD,wCAmBC;AAED;;;GAGG;AACU,QAAA,WAAW,GAAG,MAAM,CAC/B,sEAAsE,CACvE,CAAC;AAEF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,WAAW,CAC/B,OAA8B,EAC9B,SAAyB;IAEzB,MAAM,KAAK,GACT,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,aAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnE,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,EAAE,mBAAW,CAAC,CAAC;IACxD,IAAI;QACF,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;KACpD;YAAS;QACR,YAAY,CAAC,MAAM,EAAE,CAAC;KACvB;AACH,CAAC;AAZD,kCAYC","sourcesContent":["import { 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 * A Promise that delays it's 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<T> = T extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, T> 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<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends true ? Key : never;\n }[keyof T]\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<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends false ? Key : never;\n }[keyof T]\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<A, B> = Omit<A, _LiteralKeys<B>> &\n Partial<Pick<A, Extract<keyof A, _NonLiteralKeys<B>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template T - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n T extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<T, TargetKey>]: T[Key];\n} &\n {\n [Key in keyof Omit<T, TargetKey>]: T[Key];\n };\n"]}
package/package.json ADDED
@@ -0,0 +1,99 @@
1
+ {
2
+ "name": "@metamask/snaps-controllers",
3
+ "version": "0.24.0",
4
+ "description": "Controllers for MetaMask Snaps.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/MetaMask/snaps-monorepo.git"
8
+ },
9
+ "main": "dist/index.js",
10
+ "browser": {
11
+ "./dist/services": "./dist/services/browser.js"
12
+ },
13
+ "types": "dist/index.d.ts",
14
+ "files": [
15
+ "dist/"
16
+ ],
17
+ "scripts": {
18
+ "test:prepare": "yarn mkdirp test/fixtures && ./scripts/generate-fixtures.sh",
19
+ "test": "yarn test:prepare && jest && yarn posttest",
20
+ "posttest": "jest-it-up --margin 0.25",
21
+ "test:ci": "yarn test",
22
+ "build:tsc": "tsc --project tsconfig.build.json",
23
+ "build": "yarn build:tsc",
24
+ "build:clean": "yarn clean && yarn build",
25
+ "clean": "rimraf '*.tsbuildinfo' 'dist/*'",
26
+ "lint:eslint": "eslint . --cache --ext js,ts",
27
+ "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path ../../.gitignore",
28
+ "lint": "yarn lint:eslint && yarn lint:misc --check",
29
+ "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
30
+ "lint:changelog": "yarn auto-changelog validate",
31
+ "publish:package": "../../scripts/publish-package.sh"
32
+ },
33
+ "dependencies": {
34
+ "@metamask/browser-passworder": "^3.0.0",
35
+ "@metamask/controllers": "^32.0.2",
36
+ "@metamask/object-multiplex": "^1.1.0",
37
+ "@metamask/post-message-stream": "^6.0.0",
38
+ "@metamask/rpc-methods": "^0.24.0",
39
+ "@metamask/snaps-execution-environments": "^0.24.0",
40
+ "@metamask/snaps-types": "^0.24.0",
41
+ "@metamask/snaps-utils": "^0.24.0",
42
+ "@metamask/utils": "^3.3.1",
43
+ "@xstate/fsm": "^2.0.0",
44
+ "concat-stream": "^2.0.0",
45
+ "cron-parser": "^4.5.0",
46
+ "eth-rpc-errors": "^4.0.2",
47
+ "gunzip-maybe": "^1.4.2",
48
+ "immer": "^9.0.6",
49
+ "json-rpc-engine": "^6.1.0",
50
+ "json-rpc-middleware-stream": "^4.2.0",
51
+ "nanoid": "^3.1.31",
52
+ "pump": "^3.0.0",
53
+ "readable-web-to-node-stream": "^3.0.2",
54
+ "tar-stream": "^2.2.0"
55
+ },
56
+ "devDependencies": {
57
+ "@lavamoat/allow-scripts": "^2.0.3",
58
+ "@metamask/auto-changelog": "^2.6.0",
59
+ "@metamask/eslint-config": "^9.0.0",
60
+ "@metamask/eslint-config-jest": "^9.0.0",
61
+ "@metamask/eslint-config-nodejs": "^9.0.0",
62
+ "@metamask/eslint-config-typescript": "^9.0.1",
63
+ "@metamask/template-snap": "^0.7.0",
64
+ "@peculiar/webcrypto": "^1.3.3",
65
+ "@types/concat-stream": "^2.0.0",
66
+ "@types/gunzip-maybe": "^1.4.0",
67
+ "@types/jest": "^27.5.1",
68
+ "@types/pump": "^1.1.1",
69
+ "@types/readable-stream": "^2.3.9",
70
+ "@types/tar-stream": "^2.2.2",
71
+ "deepmerge": "^4.2.2",
72
+ "eslint": "^7.30.0",
73
+ "eslint-config-prettier": "^8.3.0",
74
+ "eslint-plugin-import": "^2.23.4",
75
+ "eslint-plugin-jest": "^24.4.0",
76
+ "eslint-plugin-jsdoc": "^36.1.0",
77
+ "eslint-plugin-node": "^11.1.0",
78
+ "eslint-plugin-prettier": "^3.4.0",
79
+ "jest": "^29.0.2",
80
+ "jest-environment-jsdom": "^29.0.2",
81
+ "jest-fetch-mock": "^3.0.3",
82
+ "jest-it-up": "^2.0.0",
83
+ "jsdom": "^19.0.0",
84
+ "mkdirp": "^1.0.4",
85
+ "prettier": "^2.3.2",
86
+ "prettier-plugin-packagejson": "^2.2.11",
87
+ "rimraf": "^3.0.2",
88
+ "serve-handler": "^6.1.5",
89
+ "ts-jest": "^29.0.0",
90
+ "typescript": "^4.4.0"
91
+ },
92
+ "engines": {
93
+ "node": ">=16.0.0"
94
+ },
95
+ "publishConfig": {
96
+ "access": "public",
97
+ "registry": "https://registry.npmjs.org/"
98
+ }
99
+ }