@metamask/snaps-utils 1.0.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -218
- package/dist/cjs/array.js +23 -0
- package/dist/cjs/array.js.map +1 -0
- package/dist/cjs/caveats.js +36 -0
- package/dist/cjs/caveats.js.map +1 -0
- package/dist/cjs/checksum.js +38 -0
- package/dist/cjs/checksum.js.map +1 -0
- package/dist/cjs/cronjob.js +84 -0
- package/dist/cjs/cronjob.js.map +1 -0
- package/dist/cjs/deep-clone.js +22 -0
- package/dist/cjs/deep-clone.js.map +1 -0
- package/dist/cjs/default-endowments.js +49 -0
- package/dist/cjs/default-endowments.js.map +1 -0
- package/dist/cjs/entropy.js +23 -0
- package/dist/cjs/entropy.js.map +1 -0
- package/dist/cjs/enum.js +16 -0
- package/dist/cjs/enum.js.map +1 -0
- package/dist/cjs/errors.js +19 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/{eval-worker.js → cjs/eval-worker.js} +22 -21
- package/dist/cjs/eval-worker.js.map +1 -0
- package/dist/cjs/eval.js +77 -0
- package/dist/cjs/eval.js.map +1 -0
- package/dist/cjs/fs.js +126 -0
- package/dist/cjs/fs.js.map +1 -0
- package/dist/cjs/handlers.js +80 -0
- package/dist/cjs/handlers.js.map +1 -0
- package/dist/cjs/icon.js +37 -0
- package/dist/cjs/icon.js.map +1 -0
- package/dist/cjs/iframe.js +59 -0
- package/dist/cjs/iframe.js.map +1 -0
- package/dist/cjs/index.browser.js +43 -0
- package/dist/cjs/index.browser.js.map +1 -0
- package/dist/cjs/index.executionenv.js +24 -0
- package/dist/cjs/index.executionenv.js.map +1 -0
- package/dist/cjs/index.js +48 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/json-rpc.js +46 -0
- package/dist/cjs/json-rpc.js.map +1 -0
- package/dist/cjs/json.js +16 -0
- package/dist/cjs/json.js.map +1 -0
- package/dist/cjs/logging.js +40 -0
- package/dist/cjs/logging.js.map +1 -0
- package/dist/cjs/manifest/index.browser.js +20 -0
- package/dist/cjs/manifest/index.browser.js.map +1 -0
- package/dist/cjs/manifest/index.js +21 -0
- package/dist/cjs/manifest/index.js.map +1 -0
- package/dist/cjs/manifest/manifest.js +239 -0
- package/dist/cjs/manifest/manifest.js.map +1 -0
- package/dist/cjs/manifest/validation.js +189 -0
- package/dist/cjs/manifest/validation.js.map +1 -0
- package/dist/cjs/mock.js +128 -0
- package/dist/cjs/mock.js.map +1 -0
- package/dist/cjs/namespace.js +132 -0
- package/dist/cjs/namespace.js.map +1 -0
- package/dist/cjs/npm.js +81 -0
- package/dist/cjs/npm.js.map +1 -0
- package/dist/cjs/path.js +21 -0
- package/dist/cjs/path.js.map +1 -0
- package/dist/cjs/post-process.js +328 -0
- package/dist/cjs/post-process.js.map +1 -0
- package/dist/cjs/snaps.js +230 -0
- package/dist/cjs/snaps.js.map +1 -0
- package/dist/cjs/strings.js +21 -0
- package/dist/cjs/strings.js.map +1 -0
- package/dist/cjs/structs.js +163 -0
- package/dist/cjs/structs.js.map +1 -0
- package/dist/cjs/types.js +109 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/cjs/validation.js +22 -0
- package/dist/cjs/validation.js.map +1 -0
- package/dist/cjs/versions.js +47 -0
- package/dist/cjs/versions.js.map +1 -0
- package/dist/cjs/virtual-file/VirtualFile.js +85 -0
- package/dist/cjs/virtual-file/VirtualFile.js.map +1 -0
- package/dist/cjs/virtual-file/index.browser.js +20 -0
- package/dist/cjs/virtual-file/index.browser.js.map +1 -0
- package/dist/cjs/virtual-file/index.js +21 -0
- package/dist/cjs/virtual-file/index.js.map +1 -0
- package/dist/cjs/virtual-file/toVirtualFile.js +33 -0
- package/dist/cjs/virtual-file/toVirtualFile.js.map +1 -0
- package/dist/{array.js → esm/array.js} +3 -7
- package/dist/esm/array.js.map +1 -0
- package/dist/esm/caveats.js +26 -0
- package/dist/esm/caveats.js.map +1 -0
- package/dist/esm/checksum.js +36 -0
- package/dist/esm/checksum.js.map +1 -0
- package/dist/esm/cronjob.js +66 -0
- package/dist/esm/cronjob.js.map +1 -0
- package/dist/esm/deep-clone.js +7 -0
- package/dist/esm/deep-clone.js.map +1 -0
- package/dist/{default-endowments.js → esm/default-endowments.js} +3 -6
- package/dist/esm/default-endowments.js.map +1 -0
- package/dist/esm/entropy.js +6 -0
- package/dist/esm/entropy.js.map +1 -0
- package/dist/esm/enum.js +12 -0
- package/dist/esm/enum.js.map +1 -0
- package/dist/esm/errors.js +17 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/eval-worker.js +47 -0
- package/dist/esm/eval-worker.js.map +1 -0
- package/dist/esm/eval.js +65 -0
- package/dist/esm/eval.js.map +1 -0
- package/dist/{fs.js → esm/fs.js} +33 -56
- package/dist/esm/fs.js.map +1 -0
- package/dist/esm/handlers.js +59 -0
- package/dist/esm/handlers.js.map +1 -0
- package/dist/esm/icon.js +11 -0
- package/dist/esm/icon.js.map +1 -0
- package/dist/{iframe.js → esm/iframe.js} +16 -18
- package/dist/esm/iframe.js.map +1 -0
- package/dist/esm/index.browser.js +26 -0
- package/dist/esm/index.browser.js.map +1 -0
- package/dist/esm/index.executionenv.js +7 -0
- package/dist/esm/index.executionenv.js.map +1 -0
- package/dist/esm/index.js +31 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/json-rpc.js +39 -0
- package/dist/esm/json-rpc.js.map +1 -0
- package/dist/esm/json.js +17 -0
- package/dist/esm/json.js.map +1 -0
- package/dist/{logging.js → esm/logging.js} +6 -14
- package/dist/esm/logging.js.map +1 -0
- package/dist/esm/manifest/index.browser.js +3 -0
- package/dist/esm/manifest/index.browser.js.map +1 -0
- package/dist/esm/manifest/index.js +4 -0
- package/dist/esm/manifest/index.js.map +1 -0
- package/dist/{manifest → esm/manifest}/manifest.js +101 -115
- package/dist/esm/manifest/manifest.js.map +1 -0
- package/dist/esm/manifest/validation.js +155 -0
- package/dist/esm/manifest/validation.js.map +1 -0
- package/dist/{mock.js → esm/mock.js} +42 -40
- package/dist/esm/mock.js.map +1 -0
- package/dist/esm/namespace.js +112 -0
- package/dist/esm/namespace.js.map +1 -0
- package/dist/esm/npm.js +70 -0
- package/dist/esm/npm.js.map +1 -0
- package/dist/esm/path.js +17 -0
- package/dist/esm/path.js.map +1 -0
- package/dist/{post-process.js → esm/post-process.js} +110 -99
- package/dist/esm/post-process.js.map +1 -0
- package/dist/esm/snaps.js +215 -0
- package/dist/esm/snaps.js.map +1 -0
- package/dist/esm/strings.js +11 -0
- package/dist/esm/strings.js.map +1 -0
- package/dist/esm/structs.js +230 -0
- package/dist/esm/structs.js.map +1 -0
- package/dist/esm/types.js +80 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/validation.js +17 -0
- package/dist/esm/validation.js.map +1 -0
- package/dist/{versions.js → esm/versions.js} +15 -18
- package/dist/esm/versions.js.map +1 -0
- package/dist/{virtual-file → esm/virtual-file}/VirtualFile.js +47 -33
- package/dist/esm/virtual-file/VirtualFile.js.map +1 -0
- package/dist/esm/virtual-file/index.browser.js +3 -0
- package/dist/esm/virtual-file/index.browser.js.map +1 -0
- package/dist/esm/virtual-file/index.js +4 -0
- package/dist/esm/virtual-file/index.js.map +1 -0
- package/dist/esm/virtual-file/toVirtualFile.js +26 -0
- package/dist/esm/virtual-file/toVirtualFile.js.map +1 -0
- package/dist/{caveats.d.ts → types/caveats.d.ts} +5 -5
- package/dist/{cronjob.d.ts → types/cronjob.d.ts} +1 -1
- package/dist/types/enum.d.ts +30 -0
- package/dist/types/errors.d.ts +10 -0
- package/dist/{eval.d.ts → types/eval.d.ts} +9 -1
- package/dist/{fs.d.ts → types/fs.d.ts} +2 -2
- package/dist/types/handlers.d.ts +196 -0
- package/dist/types/icon.d.ts +4 -0
- package/dist/{iframe.d.ts → types/iframe.d.ts} +3 -2
- package/dist/{index.browser.d.ts → types/index.browser.d.ts} +5 -1
- package/dist/{index.d.ts → types/index.d.ts} +5 -1
- package/dist/{json-rpc.d.ts → types/json-rpc.d.ts} +2 -2
- package/dist/types/json.d.ts +13 -0
- package/dist/{manifest → types/manifest}/manifest.d.ts +6 -4
- package/dist/{manifest → types/manifest}/validation.d.ts +40 -76
- package/dist/types/namespace.d.ts +128 -0
- package/dist/{npm.d.ts → types/npm.d.ts} +2 -3
- package/dist/{snaps.d.ts → types/snaps.d.ts} +17 -9
- package/dist/types/strings.d.ts +8 -0
- package/dist/types/structs.d.ts +158 -0
- package/dist/{types.d.ts → types/types.d.ts} +15 -22
- package/dist/types/validation.d.ts +8 -0
- package/dist/{versions.d.ts → types/versions.d.ts} +1 -1
- package/package.json +66 -46
- package/dist/array.js.map +0 -1
- package/dist/caveats.js +0 -35
- package/dist/caveats.js.map +0 -1
- package/dist/checksum.js +0 -42
- package/dist/checksum.js.map +0 -1
- package/dist/cronjob.js +0 -71
- package/dist/cronjob.js.map +0 -1
- package/dist/deep-clone.js +0 -9
- package/dist/deep-clone.js.map +0 -1
- package/dist/default-endowments.js.map +0 -1
- package/dist/entropy.js +0 -8
- package/dist/entropy.js.map +0 -1
- package/dist/eval-worker.js.map +0 -1
- package/dist/eval.js +0 -27
- package/dist/eval.js.map +0 -1
- package/dist/fs.js.map +0 -1
- package/dist/handlers.d.ts +0 -105
- package/dist/handlers.js +0 -3
- package/dist/handlers.js.map +0 -1
- package/dist/iframe.js.map +0 -1
- package/dist/iframe.test.browser.js +0 -15
- package/dist/iframe.test.browser.js.map +0 -1
- package/dist/index.browser.js +0 -37
- package/dist/index.browser.js.map +0 -1
- package/dist/index.executionenv.js +0 -22
- package/dist/index.executionenv.js.map +0 -1
- package/dist/index.js +0 -42
- package/dist/index.js.map +0 -1
- package/dist/json-rpc.js +0 -46
- package/dist/json-rpc.js.map +0 -1
- package/dist/json.d.ts +0 -9
- package/dist/json.js +0 -18
- package/dist/json.js.map +0 -1
- package/dist/logging.js.map +0 -1
- package/dist/manifest/index.browser.js +0 -18
- package/dist/manifest/index.browser.js.map +0 -1
- package/dist/manifest/index.js +0 -19
- package/dist/manifest/index.js.map +0 -1
- package/dist/manifest/manifest.js.map +0 -1
- package/dist/manifest/validation.js +0 -141
- package/dist/manifest/validation.js.map +0 -1
- package/dist/mock.js.map +0 -1
- package/dist/namespace.d.ts +0 -275
- package/dist/namespace.js +0 -225
- package/dist/namespace.js.map +0 -1
- package/dist/notification.d.ts +0 -66
- package/dist/notification.js +0 -58
- package/dist/notification.js.map +0 -1
- package/dist/npm.js +0 -74
- package/dist/npm.js.map +0 -1
- package/dist/path.js +0 -21
- package/dist/path.js.map +0 -1
- package/dist/post-process.js.map +0 -1
- package/dist/snaps.js +0 -202
- package/dist/snaps.js.map +0 -1
- package/dist/types.js +0 -103
- package/dist/types.js.map +0 -1
- package/dist/versions.js.map +0 -1
- package/dist/virtual-file/VirtualFile.js.map +0 -1
- package/dist/virtual-file/index.browser.js +0 -18
- package/dist/virtual-file/index.browser.js.map +0 -1
- package/dist/virtual-file/index.js +0 -19
- package/dist/virtual-file/index.js.map +0 -1
- package/dist/virtual-file/toVirtualFile.js +0 -30
- package/dist/virtual-file/toVirtualFile.js.map +0 -1
- /package/dist/{array.d.ts → types/array.d.ts} +0 -0
- /package/dist/{checksum.d.ts → types/checksum.d.ts} +0 -0
- /package/dist/{deep-clone.d.ts → types/deep-clone.d.ts} +0 -0
- /package/dist/{default-endowments.d.ts → types/default-endowments.d.ts} +0 -0
- /package/dist/{entropy.d.ts → types/entropy.d.ts} +0 -0
- /package/dist/{eval-worker.d.ts → types/eval-worker.d.ts} +0 -0
- /package/dist/{iframe.test.browser.d.ts → types/iframe.test.browser.d.ts} +0 -0
- /package/dist/{index.executionenv.d.ts → types/index.executionenv.d.ts} +0 -0
- /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
- /package/dist/{manifest → types/manifest}/index.browser.d.ts +0 -0
- /package/dist/{manifest → types/manifest}/index.d.ts +0 -0
- /package/dist/{mock.d.ts → types/mock.d.ts} +0 -0
- /package/dist/{path.d.ts → types/path.d.ts} +0 -0
- /package/dist/{post-process.d.ts → types/post-process.d.ts} +0 -0
- /package/dist/{virtual-file → types/virtual-file}/VirtualFile.d.ts +0 -0
- /package/dist/{virtual-file → types/virtual-file}/index.browser.d.ts +0 -0
- /package/dist/{virtual-file → types/virtual-file}/index.d.ts +0 -0
- /package/dist/{virtual-file → types/virtual-file}/toVirtualFile.d.ts +0 -0
package/dist/notification.js
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.assertIsMetaMaskNotification = exports.isMetaMaskNotification = exports.MetaMaskNotificationStruct = exports.assertIsEvent = exports.isEvent = exports.EventStruct = void 0;
|
|
4
|
-
const utils_1 = require("@metamask/utils");
|
|
5
|
-
const superstruct_1 = require("superstruct");
|
|
6
|
-
const namespace_1 = require("./namespace");
|
|
7
|
-
exports.EventStruct = (0, superstruct_1.object)({
|
|
8
|
-
name: (0, superstruct_1.string)(),
|
|
9
|
-
data: (0, superstruct_1.unknown)(),
|
|
10
|
-
});
|
|
11
|
-
/**
|
|
12
|
-
* Check if a value is a SIP-2 event.
|
|
13
|
-
*
|
|
14
|
-
* @param value - The value to check.
|
|
15
|
-
* @returns Whether the value is a SIP-2 event.
|
|
16
|
-
*/
|
|
17
|
-
function isEvent(value) {
|
|
18
|
-
return (0, superstruct_1.is)(value, exports.EventStruct);
|
|
19
|
-
}
|
|
20
|
-
exports.isEvent = isEvent;
|
|
21
|
-
/**
|
|
22
|
-
* Assert that a value is a SIP-2 event.
|
|
23
|
-
*
|
|
24
|
-
* @param value - The value to check.
|
|
25
|
-
* @throws If the value is not a SIP-2 event.
|
|
26
|
-
*/
|
|
27
|
-
function assertIsEvent(value) {
|
|
28
|
-
(0, utils_1.assertStruct)(value, exports.EventStruct, 'Invalid event');
|
|
29
|
-
}
|
|
30
|
-
exports.assertIsEvent = assertIsEvent;
|
|
31
|
-
exports.MetaMaskNotificationStruct = (0, superstruct_1.object)({
|
|
32
|
-
method: (0, superstruct_1.literal)('multichainHack_metamask_event'),
|
|
33
|
-
params: (0, superstruct_1.object)({
|
|
34
|
-
chainId: namespace_1.ChainIdStruct,
|
|
35
|
-
event: exports.EventStruct,
|
|
36
|
-
}),
|
|
37
|
-
});
|
|
38
|
-
/**
|
|
39
|
-
* Check if a value is a SIP-2 notification.
|
|
40
|
-
*
|
|
41
|
-
* @param value - The value to check.
|
|
42
|
-
* @returns Whether the value is a SIP-2 notification.
|
|
43
|
-
*/
|
|
44
|
-
function isMetaMaskNotification(value) {
|
|
45
|
-
return (0, superstruct_1.is)(value, exports.MetaMaskNotificationStruct);
|
|
46
|
-
}
|
|
47
|
-
exports.isMetaMaskNotification = isMetaMaskNotification;
|
|
48
|
-
/**
|
|
49
|
-
* Assert that a value is a SIP-2 notification.
|
|
50
|
-
*
|
|
51
|
-
* @param value - The value to check.
|
|
52
|
-
* @throws If the value is not a SIP-2 notification.
|
|
53
|
-
*/
|
|
54
|
-
function assertIsMetaMaskNotification(value) {
|
|
55
|
-
(0, utils_1.assertStruct)(value, exports.MetaMaskNotificationStruct, 'Invalid notification');
|
|
56
|
-
}
|
|
57
|
-
exports.assertIsMetaMaskNotification = assertIsMetaMaskNotification;
|
|
58
|
-
//# sourceMappingURL=notification.js.map
|
package/dist/notification.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"notification.js","sourceRoot":"","sources":["../src/notification.ts"],"names":[],"mappings":";;;AAAA,2CAA+C;AAC/C,6CAA0E;AAE1E,2CAA4C;AAE/B,QAAA,WAAW,GAAG,IAAA,oBAAM,EAAC;IAChC,IAAI,EAAE,IAAA,oBAAM,GAAE;IACd,IAAI,EAAE,IAAA,qBAAO,GAAE;CAChB,CAAC,CAAC;AAIH;;;;;GAKG;AACH,SAAgB,OAAO,CAAC,KAAc;IACpC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,mBAAW,CAAC,CAAC;AAChC,CAAC;AAFD,0BAEC;AAED;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,KAAc;IAC1C,IAAA,oBAAY,EAAC,KAAK,EAAE,mBAAW,EAAE,eAAe,CAAC,CAAC;AACpD,CAAC;AAFD,sCAEC;AAEY,QAAA,0BAA0B,GAAG,IAAA,oBAAM,EAAC;IAC/C,MAAM,EAAE,IAAA,qBAAO,EAAC,+BAA+B,CAAC;IAChD,MAAM,EAAE,IAAA,oBAAM,EAAC;QACb,OAAO,EAAE,yBAAa;QACtB,KAAK,EAAE,mBAAW;KACnB,CAAC;CACH,CAAC,CAAC;AAIH;;;;;GAKG;AACH,SAAgB,sBAAsB,CACpC,KAAc;IAEd,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,kCAA0B,CAAC,CAAC;AAC/C,CAAC;AAJD,wDAIC;AAED;;;;;GAKG;AACH,SAAgB,4BAA4B,CAC1C,KAAc;IAEd,IAAA,oBAAY,EAAC,KAAK,EAAE,kCAA0B,EAAE,sBAAsB,CAAC,CAAC;AAC1E,CAAC;AAJD,oEAIC","sourcesContent":["import { assertStruct } from '@metamask/utils';\nimport { Infer, is, literal, object, string, unknown } from 'superstruct';\n\nimport { ChainIdStruct } from './namespace';\n\nexport const EventStruct = object({\n name: string(),\n data: unknown(),\n});\n\nexport type Event = Infer<typeof EventStruct>;\n\n/**\n * Check if a value is a SIP-2 event.\n *\n * @param value - The value to check.\n * @returns Whether the value is a SIP-2 event.\n */\nexport function isEvent(value: unknown): value is Event {\n return is(value, EventStruct);\n}\n\n/**\n * Assert that a value is a SIP-2 event.\n *\n * @param value - The value to check.\n * @throws If the value is not a SIP-2 event.\n */\nexport function assertIsEvent(value: unknown): asserts value is Event {\n assertStruct(value, EventStruct, 'Invalid event');\n}\n\nexport const MetaMaskNotificationStruct = object({\n method: literal('multichainHack_metamask_event'),\n params: object({\n chainId: ChainIdStruct,\n event: EventStruct,\n }),\n});\n\nexport type MetaMaskNotification = Infer<typeof MetaMaskNotificationStruct>;\n\n/**\n * Check if a value is a SIP-2 notification.\n *\n * @param value - The value to check.\n * @returns Whether the value is a SIP-2 notification.\n */\nexport function isMetaMaskNotification(\n value: unknown,\n): value is MetaMaskNotification {\n return is(value, MetaMaskNotificationStruct);\n}\n\n/**\n * Assert that a value is a SIP-2 notification.\n *\n * @param value - The value to check.\n * @throws If the value is not a SIP-2 notification.\n */\nexport function assertIsMetaMaskNotification(\n value: unknown,\n): asserts value is MetaMaskNotification {\n assertStruct(value, MetaMaskNotificationStruct, 'Invalid notification');\n}\n"]}
|
package/dist/npm.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.validateNpmSnap = exports.SnapFileNameFromKey = exports.EXPECTED_SNAP_FILES = exports.SVG_MAX_BYTE_SIZE_TEXT = exports.SVG_MAX_BYTE_SIZE = void 0;
|
|
4
|
-
const manifest_1 = require("./manifest/manifest");
|
|
5
|
-
const validation_1 = require("./manifest/validation");
|
|
6
|
-
const types_1 = require("./types");
|
|
7
|
-
exports.SVG_MAX_BYTE_SIZE = 100000;
|
|
8
|
-
exports.SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(exports.SVG_MAX_BYTE_SIZE / 1000)}kb`;
|
|
9
|
-
exports.EXPECTED_SNAP_FILES = [
|
|
10
|
-
'manifest',
|
|
11
|
-
'packageJson',
|
|
12
|
-
'sourceCode',
|
|
13
|
-
];
|
|
14
|
-
exports.SnapFileNameFromKey = {
|
|
15
|
-
manifest: types_1.NpmSnapFileNames.Manifest,
|
|
16
|
-
packageJson: types_1.NpmSnapFileNames.PackageJson,
|
|
17
|
-
sourceCode: 'source code bundle',
|
|
18
|
-
};
|
|
19
|
-
/**
|
|
20
|
-
* Validates the files extracted from an npm Snap package tarball by ensuring
|
|
21
|
-
* that they're non-empty and that the Json files match their respective schemas
|
|
22
|
-
* and the Snaps publishing specification.
|
|
23
|
-
*
|
|
24
|
-
* @param snapFiles - The object containing the expected Snap file contents,
|
|
25
|
-
* if any.
|
|
26
|
-
* @param errorPrefix - The prefix of the error message.
|
|
27
|
-
* @returns A tuple of the Snap manifest object and the Snap source code.
|
|
28
|
-
*/
|
|
29
|
-
function validateNpmSnap(snapFiles, errorPrefix) {
|
|
30
|
-
exports.EXPECTED_SNAP_FILES.forEach((key) => {
|
|
31
|
-
if (!snapFiles[key]) {
|
|
32
|
-
throw new Error(`${errorPrefix ?? ''}Missing file "${exports.SnapFileNameFromKey[key]}".`);
|
|
33
|
-
}
|
|
34
|
-
});
|
|
35
|
-
// Typecast: We are assured that the required files exist if we get here.
|
|
36
|
-
const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
|
|
37
|
-
try {
|
|
38
|
-
(0, validation_1.assertIsSnapManifest)(manifest.result);
|
|
39
|
-
}
|
|
40
|
-
catch (error) {
|
|
41
|
-
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
42
|
-
}
|
|
43
|
-
const validatedManifest = manifest;
|
|
44
|
-
const { iconPath } = validatedManifest.result.source.location.npm;
|
|
45
|
-
if (iconPath && !svgIcon) {
|
|
46
|
-
throw new Error(`Missing file "${iconPath}".`);
|
|
47
|
-
}
|
|
48
|
-
try {
|
|
49
|
-
(0, types_1.assertIsNpmSnapPackageJson)(packageJson.result);
|
|
50
|
-
}
|
|
51
|
-
catch (error) {
|
|
52
|
-
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
53
|
-
}
|
|
54
|
-
const validatedPackageJson = packageJson;
|
|
55
|
-
(0, manifest_1.validateNpmSnapManifest)({
|
|
56
|
-
manifest: validatedManifest,
|
|
57
|
-
packageJson: validatedPackageJson,
|
|
58
|
-
sourceCode,
|
|
59
|
-
svgIcon,
|
|
60
|
-
});
|
|
61
|
-
if (svgIcon) {
|
|
62
|
-
if (Buffer.byteLength(svgIcon.value, 'utf8') > exports.SVG_MAX_BYTE_SIZE) {
|
|
63
|
-
throw new Error(`${errorPrefix ?? ''}The specified SVG icon exceeds the maximum size of ${exports.SVG_MAX_BYTE_SIZE_TEXT}.`);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
return {
|
|
67
|
-
manifest: validatedManifest,
|
|
68
|
-
packageJson: validatedPackageJson,
|
|
69
|
-
sourceCode,
|
|
70
|
-
svgIcon,
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
exports.validateNpmSnap = validateNpmSnap;
|
|
74
|
-
//# sourceMappingURL=npm.js.map
|
package/dist/npm.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../src/npm.ts"],"names":[],"mappings":";;;AAAA,kDAA8D;AAC9D,sDAA6D;AAC7D,mCAKiB;AAEJ,QAAA,iBAAiB,GAAG,MAAO,CAAC;AAC5B,QAAA,sBAAsB,GAAG,GAAG,IAAI,CAAC,KAAK,CACjD,yBAAiB,GAAG,IAAI,CACzB,IAAI,CAAC;AAEO,QAAA,mBAAmB,GAAG;IACjC,UAAU;IACV,aAAa;IACb,YAAY;CACJ,CAAC;AAEE,QAAA,mBAAmB,GAAG;IACjC,QAAQ,EAAE,wBAAgB,CAAC,QAAQ;IACnC,WAAW,EAAE,wBAAgB,CAAC,WAAW;IACzC,UAAU,EAAE,oBAAoB;CACxB,CAAC;AAEX;;;;;;;;;GASG;AACH,SAAgB,eAAe,CAC7B,SAA+B,EAC/B,WAA2B;IAE3B,2BAAmB,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QAClC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CACb,GAAG,WAAW,IAAI,EAAE,iBAAiB,2BAAmB,CAAC,GAAG,CAAC,IAAI,CAClE,CAAC;SACH;IACH,CAAC,CAAC,CAAC;IAEH,yEAAyE;IACzE,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,SAAsB,CAAC;IAC9E,IAAI;QACF,IAAA,iCAAoB,EAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;KACvC;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,GAAG,WAAW,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACzD;IACD,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IAEnC,MAAM,EAAE,QAAQ,EAAE,GAAG,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;IAClE,IAAI,QAAQ,IAAI,CAAC,OAAO,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,QAAQ,IAAI,CAAC,CAAC;KAChD;IAED,IAAI;QACF,IAAA,kCAA0B,EAAC,WAAW,CAAC,MAAM,CAAC,CAAC;KAChD;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,GAAG,WAAW,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACzD;IACD,MAAM,oBAAoB,GAAG,WAAW,CAAC;IAEzC,IAAA,kCAAuB,EAAC;QACtB,QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;QACV,OAAO;KACR,CAAC,CAAC;IAEH,IAAI,OAAO,EAAE;QACX,IAAI,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,yBAAiB,EAAE;YAChE,MAAM,IAAI,KAAK,CACb,GACE,WAAW,IAAI,EACjB,sDAAsD,8BAAsB,GAAG,CAChF,CAAC;SACH;KACF;IAED,OAAO;QACL,QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC;AAxDD,0CAwDC","sourcesContent":["import { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport {\n assertIsNpmSnapPackageJson,\n NpmSnapFileNames,\n SnapFiles,\n UnvalidatedSnapFiles,\n} from './types';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n });\n\n if (svgIcon) {\n if (Buffer.byteLength(svgIcon.value, 'utf8') > SVG_MAX_BYTE_SIZE) {\n throw new Error(\n `${\n errorPrefix ?? ''\n }The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"]}
|
package/dist/path.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.normalizeRelative = void 0;
|
|
4
|
-
const utils_1 = require("@metamask/utils");
|
|
5
|
-
/**
|
|
6
|
-
* Normalizes relative paths by optionally removing `./` prefix.
|
|
7
|
-
*
|
|
8
|
-
* @param path - Path to make normalize.
|
|
9
|
-
* @returns The same path, with `./` prefix remove.
|
|
10
|
-
*/
|
|
11
|
-
// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well
|
|
12
|
-
function normalizeRelative(path) {
|
|
13
|
-
(0, utils_1.assert)(!path.startsWith('/'));
|
|
14
|
-
(0, utils_1.assert)(path.search(/:|\/\//u) === -1, `Path "${path}" potentially an URI instead of local relative`);
|
|
15
|
-
if (path.startsWith('./')) {
|
|
16
|
-
return path.slice(2);
|
|
17
|
-
}
|
|
18
|
-
return path;
|
|
19
|
-
}
|
|
20
|
-
exports.normalizeRelative = normalizeRelative;
|
|
21
|
-
//# sourceMappingURL=path.js.map
|
package/dist/path.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"path.js","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AAEzC;;;;;GAKG;AACH,4EAA4E;AAC5E,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAA,cAAM,EAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9B,IAAA,cAAM,EACJ,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAC7B,SAAS,IAAI,gDAAgD,CAC9D,CAAC;IAEF,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QACzB,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KACtB;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAXD,8CAWC","sourcesContent":["import { assert } from '@metamask/utils';\n\n/**\n * Normalizes relative paths by optionally removing `./` prefix.\n *\n * @param path - Path to make normalize.\n * @returns The same path, with `./` prefix remove.\n */\n// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well\nexport function normalizeRelative(path: string): string {\n assert(!path.startsWith('/'));\n assert(\n path.search(/:|\\/\\//u) === -1,\n `Path \"${path}\" potentially an URI instead of local relative`,\n );\n\n if (path.startsWith('./')) {\n return path.slice(2);\n }\n return path;\n}\n"]}
|
package/dist/post-process.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"post-process.js","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AAAA,wDAAwD;AACxD,sCAAgF;AAChF,wCAQsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,+HAAyG,CAAA;AAC3G,CAAC,EAFW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,sCAAsC,CAAC;AAE3D,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,IAAA,uBAAe,EAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEtC,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAE5C,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEpD,CAAC,CAAC;AAEH;;;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,CAAC;YAEhC,mEAAmE;YACnE,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;gBACrD,MAAM,IAAI,KAAK,CACb,uFAAuF;oBACrF,oFAAoF;oBACpF,oFAAoF;oBACpF,kBAAkB,CACrB,CAAC;aACH;QACH,CAAC;KACF,CAAC;IAEF,IAAI;QACF,MAAM,IAAI,GAAG,IAAA,oBAAa,EAAC,IAAI,EAAE;YAC/B,kDAAkD;YAClD,UAAU,EAAE,KAAK;YAEjB,UAAU,EAAE;gBACV,sEAAsE;gBACtE,UAAU,EAAE,IAAI;gBAEhB,sEAAsE;gBACtE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC3C;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;KACH;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACnE;AACH,CAAC;AApQD,8CAoQC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\nimport {\n binaryExpression,\n Expression,\n Identifier,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const source = path.getSource();\n\n // Throw an error if HTML comments are used as a binary expression.\n if (source.includes('<!--') || source.includes('-->')) {\n throw new Error(\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.',\n );\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
|
package/dist/snaps.js
DELETED
|
@@ -1,202 +0,0 @@
|
|
|
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.verifyRequestedSnapPermissions = exports.isSnapPermitted = exports.isCaipChainId = exports.assertIsValidSnapId = exports.getSnapPrefix = exports.SnapIdStruct = exports.HttpSnapIdStruct = exports.NpmSnapIdStruct = exports.LocalSnapIdStruct = exports.BaseSnapIdStruct = exports.LOCALHOST_HOSTNAMES = exports.validateSnapShasum = exports.getSnapChecksum = exports.ProgrammaticallyFixableSnapError = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = void 0;
|
|
7
|
-
const utils_1 = require("@metamask/utils");
|
|
8
|
-
const base_1 = require("@scure/base");
|
|
9
|
-
const fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
|
|
10
|
-
const superstruct_1 = require("superstruct");
|
|
11
|
-
const validate_npm_package_name_1 = __importDefault(require("validate-npm-package-name"));
|
|
12
|
-
const caveats_1 = require("./caveats");
|
|
13
|
-
const checksum_1 = require("./checksum");
|
|
14
|
-
const types_1 = require("./types");
|
|
15
|
-
// This RegEx matches valid npm package names (with some exceptions) and space-
|
|
16
|
-
// separated alphanumerical words, optionally with dashes and underscores.
|
|
17
|
-
// The RegEx consists of two parts. The first part matches space-separated
|
|
18
|
-
// words. It is based on the following Stackoverflow answer:
|
|
19
|
-
// https://stackoverflow.com/a/34974982
|
|
20
|
-
// The second part, after the pipe operator, is the same RegEx used for the
|
|
21
|
-
// `name` field of the official package.json JSON Schema, except that we allow
|
|
22
|
-
// mixed-case letters. It was originally copied from:
|
|
23
|
-
// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138
|
|
24
|
-
exports.PROPOSED_NAME_REGEX = /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;
|
|
25
|
-
var SnapStatus;
|
|
26
|
-
(function (SnapStatus) {
|
|
27
|
-
SnapStatus["Installing"] = "installing";
|
|
28
|
-
SnapStatus["Updating"] = "updating";
|
|
29
|
-
SnapStatus["Running"] = "running";
|
|
30
|
-
SnapStatus["Stopped"] = "stopped";
|
|
31
|
-
SnapStatus["Crashed"] = "crashed";
|
|
32
|
-
})(SnapStatus = exports.SnapStatus || (exports.SnapStatus = {}));
|
|
33
|
-
var SnapStatusEvents;
|
|
34
|
-
(function (SnapStatusEvents) {
|
|
35
|
-
SnapStatusEvents["Start"] = "START";
|
|
36
|
-
SnapStatusEvents["Stop"] = "STOP";
|
|
37
|
-
SnapStatusEvents["Crash"] = "CRASH";
|
|
38
|
-
SnapStatusEvents["Update"] = "UPDATE";
|
|
39
|
-
})(SnapStatusEvents = exports.SnapStatusEvents || (exports.SnapStatusEvents = {}));
|
|
40
|
-
/**
|
|
41
|
-
* An error indicating that a Snap validation failure is programmatically
|
|
42
|
-
* fixable during development.
|
|
43
|
-
*/
|
|
44
|
-
class ProgrammaticallyFixableSnapError extends Error {
|
|
45
|
-
constructor(message, reason) {
|
|
46
|
-
super(message);
|
|
47
|
-
this.reason = reason;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
exports.ProgrammaticallyFixableSnapError = ProgrammaticallyFixableSnapError;
|
|
51
|
-
/**
|
|
52
|
-
* Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.
|
|
53
|
-
*
|
|
54
|
-
* @param manifest - The manifest itself.
|
|
55
|
-
* @returns A virtual file containing the checksummable manifest.
|
|
56
|
-
*/
|
|
57
|
-
function getChecksummableManifest(manifest) {
|
|
58
|
-
const manifestCopy = manifest.clone();
|
|
59
|
-
delete manifestCopy.result.source.shasum;
|
|
60
|
-
// We use fast-json-stable-stringify to deterministically serialize the JSON
|
|
61
|
-
// This is required before checksumming so we get reproducible checksums across platforms etc
|
|
62
|
-
manifestCopy.value = (0, fast_json_stable_stringify_1.default)(manifestCopy.result);
|
|
63
|
-
return manifestCopy;
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Calculates the Base64-encoded SHA-256 digest of all required Snap files.
|
|
67
|
-
*
|
|
68
|
-
* @param files - All required Snap files to be included in the checksum.
|
|
69
|
-
* @returns The Base64-encoded SHA-256 digest of the source code.
|
|
70
|
-
*/
|
|
71
|
-
function getSnapChecksum(files) {
|
|
72
|
-
const { manifest, sourceCode, svgIcon } = files;
|
|
73
|
-
const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter((file) => file !== undefined);
|
|
74
|
-
return base_1.base64.encode((0, checksum_1.checksumFiles)(all));
|
|
75
|
-
}
|
|
76
|
-
exports.getSnapChecksum = getSnapChecksum;
|
|
77
|
-
/**
|
|
78
|
-
* Checks whether the `source.shasum` property of a Snap manifest matches the
|
|
79
|
-
* shasum of the snap.
|
|
80
|
-
*
|
|
81
|
-
* @param files - All required Snap files to be included in the checksum.
|
|
82
|
-
* @param errorMessage - The error message to throw if validation fails.
|
|
83
|
-
*/
|
|
84
|
-
function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
|
|
85
|
-
if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {
|
|
86
|
-
throw new ProgrammaticallyFixableSnapError(errorMessage, types_1.SnapValidationFailureReason.ShasumMismatch);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
exports.validateSnapShasum = validateSnapShasum;
|
|
90
|
-
exports.LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
|
|
91
|
-
// Require snap ids to only consist of printable ASCII characters
|
|
92
|
-
exports.BaseSnapIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), /^[\x21-\x7E]*$/u);
|
|
93
|
-
const LocalSnapIdSubUrlStruct = (0, types_1.uri)({
|
|
94
|
-
protocol: (0, superstruct_1.enums)(['http:', 'https:']),
|
|
95
|
-
hostname: (0, superstruct_1.enums)(exports.LOCALHOST_HOSTNAMES),
|
|
96
|
-
hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
97
|
-
search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
98
|
-
});
|
|
99
|
-
exports.LocalSnapIdStruct = (0, superstruct_1.refine)(exports.BaseSnapIdStruct, 'local Snap Id', (value) => {
|
|
100
|
-
if (!value.startsWith(types_1.SnapIdPrefixes.local)) {
|
|
101
|
-
return `Expected local snap ID, got "${value}".`;
|
|
102
|
-
}
|
|
103
|
-
const [error] = (0, superstruct_1.validate)(value.slice(types_1.SnapIdPrefixes.local.length), LocalSnapIdSubUrlStruct);
|
|
104
|
-
return error ?? true;
|
|
105
|
-
});
|
|
106
|
-
exports.NpmSnapIdStruct = (0, superstruct_1.intersection)([
|
|
107
|
-
exports.BaseSnapIdStruct,
|
|
108
|
-
(0, types_1.uri)({
|
|
109
|
-
protocol: (0, superstruct_1.literal)(types_1.SnapIdPrefixes.npm),
|
|
110
|
-
pathname: (0, superstruct_1.refine)((0, superstruct_1.string)(), 'package name', function* (value) {
|
|
111
|
-
const normalized = value.startsWith('/') ? value.slice(1) : value;
|
|
112
|
-
const { errors, validForNewPackages, warnings } = (0, validate_npm_package_name_1.default)(normalized);
|
|
113
|
-
if (!validForNewPackages) {
|
|
114
|
-
if (errors === undefined) {
|
|
115
|
-
(0, utils_1.assert)(warnings !== undefined);
|
|
116
|
-
yield* warnings;
|
|
117
|
-
}
|
|
118
|
-
else {
|
|
119
|
-
yield* errors;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
return true;
|
|
123
|
-
}),
|
|
124
|
-
search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
125
|
-
hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
126
|
-
}),
|
|
127
|
-
]);
|
|
128
|
-
exports.HttpSnapIdStruct = (0, superstruct_1.intersection)([
|
|
129
|
-
exports.BaseSnapIdStruct,
|
|
130
|
-
(0, types_1.uri)({
|
|
131
|
-
protocol: (0, superstruct_1.enums)(['http:', 'https:']),
|
|
132
|
-
search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
133
|
-
hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
134
|
-
}),
|
|
135
|
-
]);
|
|
136
|
-
exports.SnapIdStruct = (0, superstruct_1.union)([exports.NpmSnapIdStruct, exports.LocalSnapIdStruct]);
|
|
137
|
-
/**
|
|
138
|
-
* Extracts the snap prefix from a snap ID.
|
|
139
|
-
*
|
|
140
|
-
* @param snapId - The snap ID to extract the prefix from.
|
|
141
|
-
* @returns The snap prefix from a snap id, e.g. `npm:`.
|
|
142
|
-
*/
|
|
143
|
-
function getSnapPrefix(snapId) {
|
|
144
|
-
const prefix = Object.values(types_1.SnapIdPrefixes).find((possiblePrefix) => snapId.startsWith(possiblePrefix));
|
|
145
|
-
if (prefix !== undefined) {
|
|
146
|
-
return prefix;
|
|
147
|
-
}
|
|
148
|
-
throw new Error(`Invalid or no prefix found for "${snapId}"`);
|
|
149
|
-
}
|
|
150
|
-
exports.getSnapPrefix = getSnapPrefix;
|
|
151
|
-
/**
|
|
152
|
-
* Assert that the given value is a valid snap ID.
|
|
153
|
-
*
|
|
154
|
-
* @param value - The value to check.
|
|
155
|
-
* @throws If the value is not a valid snap ID.
|
|
156
|
-
*/
|
|
157
|
-
function assertIsValidSnapId(value) {
|
|
158
|
-
(0, utils_1.assertStruct)(value, exports.SnapIdStruct, 'Invalid snap ID');
|
|
159
|
-
}
|
|
160
|
-
exports.assertIsValidSnapId = assertIsValidSnapId;
|
|
161
|
-
/**
|
|
162
|
-
* Typeguard to ensure a chainId follows the CAIP-2 standard.
|
|
163
|
-
*
|
|
164
|
-
* @param chainId - The chainId being tested.
|
|
165
|
-
* @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.
|
|
166
|
-
*/
|
|
167
|
-
function isCaipChainId(chainId) {
|
|
168
|
-
return (typeof chainId === 'string' &&
|
|
169
|
-
/^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(chainId));
|
|
170
|
-
}
|
|
171
|
-
exports.isCaipChainId = isCaipChainId;
|
|
172
|
-
/**
|
|
173
|
-
* Utility function to check if an origin has permission (and caveat) for a particular snap.
|
|
174
|
-
*
|
|
175
|
-
* @param permissions - An origin's permissions object.
|
|
176
|
-
* @param snapId - The id of the snap.
|
|
177
|
-
* @returns A boolean based on if an origin has the specified snap.
|
|
178
|
-
*/
|
|
179
|
-
function isSnapPermitted(permissions, snapId) {
|
|
180
|
-
return Boolean((permissions?.wallet_snap?.caveats?.find((caveat) => caveat.type === caveats_1.SnapCaveatType.SnapIds) ?? {}).value?.[snapId]);
|
|
181
|
-
}
|
|
182
|
-
exports.isSnapPermitted = isSnapPermitted;
|
|
183
|
-
/**
|
|
184
|
-
* Checks whether the passed in requestedPermissions is a valid
|
|
185
|
-
* permission request for a `wallet_snap` permission.
|
|
186
|
-
*
|
|
187
|
-
* @param requestedPermissions - The requested permissions.
|
|
188
|
-
* @throws If the criteria is not met.
|
|
189
|
-
*/
|
|
190
|
-
function verifyRequestedSnapPermissions(requestedPermissions) {
|
|
191
|
-
(0, utils_1.assert)((0, utils_1.isObject)(requestedPermissions), 'Requested permissions must be an object.');
|
|
192
|
-
const { wallet_snap: walletSnapPermission } = requestedPermissions;
|
|
193
|
-
(0, utils_1.assert)((0, utils_1.isObject)(walletSnapPermission), 'wallet_snap is missing from the requested permissions.');
|
|
194
|
-
const { caveats } = walletSnapPermission;
|
|
195
|
-
(0, utils_1.assert)(Array.isArray(caveats) && caveats.length === 1, 'wallet_snap must have a caveat property with a single-item array value.');
|
|
196
|
-
const [caveat] = caveats;
|
|
197
|
-
(0, utils_1.assert)((0, utils_1.isObject)(caveat) &&
|
|
198
|
-
caveat.type === caveats_1.SnapCaveatType.SnapIds &&
|
|
199
|
-
(0, utils_1.isObject)(caveat.value), `The requested permissions do not have a valid ${caveats_1.SnapCaveatType.SnapIds} caveat.`);
|
|
200
|
-
}
|
|
201
|
-
exports.verifyRequestedSnapPermissions = verifyRequestedSnapPermissions;
|
|
202
|
-
//# sourceMappingURL=snaps.js.map
|
package/dist/snaps.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.js","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,2CAOyB;AACzB,sCAAqC;AAErC,4FAAyD;AACzD,6CAWqB;AACrB,0FAA2D;AAE3D,uCAA2C;AAC3C,yCAA2C;AAE3C,mCAOiB;AAGjB,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAWrH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAMrB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAK3B;AA+FD;;;GAGG;AACH,MAAa,gCAAiC,SAAQ,KAAK;IAGzD,YAAY,OAAe,EAAE,MAAmC;QAC9D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAPD,4EAOC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAC/B,QAAmC;IAEnC,MAAM,YAAY,GAAG,QAAQ,CAAC,KAAK,EAAsB,CAAC;IAC1D,OAAO,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IA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ACR,CACF,CAAC;AACJ,CAAC;AAPD,sCAOC;AAED;;;;;;GAMG;AACH,SAAgB,eAAe,CAC7B,WAAqD,EACrD,MAAc;IAEd,OAAO,OAAO,CAGR,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CACtC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO,CACnD,IAAI,EAAE,CACR,CAAC,KACH,EAAE,CAAC,MAAM,CAAC,CACZ,CAAC;AACJ,CAAC;AAbD,0CAaC;AAED;;;;;;GAMG;AACH,SAAgB,8BAA8B,CAC5C,oBAA6B;IAE7B,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,IAAA,cAAM,EACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { BlockReason } from '@metamask/snaps-registry';\nimport {\n assert,\n Json,\n SemVerVersion,\n isObject,\n Opaque,\n assertStruct,\n} from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n Struct,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport {\n SnapFiles,\n SnapId,\n SnapIdPrefixes,\n SnapsPermissionRequest,\n SnapValidationFailureReason,\n uri,\n} from './types';\nimport { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: string };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: SnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"]}
|
package/dist/types.js
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WALLET_SNAP_PERMISSION_KEY = exports.isValidUrl = exports.uri = exports.SNAP_EXPORT_NAMES = exports.HandlerType = exports.SNAP_STREAM_NAMES = exports.SnapValidationFailureReason = exports.SnapIdPrefixes = exports.assertIsNpmSnapPackageJson = exports.isNpmSnapPackageJson = exports.NpmSnapPackageJsonStruct = exports.NameStruct = exports.NpmSnapFileNames = void 0;
|
|
4
|
-
const utils_1 = require("@metamask/utils");
|
|
5
|
-
const superstruct_1 = require("superstruct");
|
|
6
|
-
var NpmSnapFileNames;
|
|
7
|
-
(function (NpmSnapFileNames) {
|
|
8
|
-
NpmSnapFileNames["PackageJson"] = "package.json";
|
|
9
|
-
NpmSnapFileNames["Manifest"] = "snap.manifest.json";
|
|
10
|
-
})(NpmSnapFileNames = exports.NpmSnapFileNames || (exports.NpmSnapFileNames = {}));
|
|
11
|
-
exports.NameStruct = (0, superstruct_1.size)((0, superstruct_1.pattern)((0, superstruct_1.string)(), /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/u), 1, 214);
|
|
12
|
-
// Note we use `type` instead of `object` here, because the latter does not
|
|
13
|
-
// allow unknown keys.
|
|
14
|
-
exports.NpmSnapPackageJsonStruct = (0, superstruct_1.type)({
|
|
15
|
-
version: utils_1.VersionStruct,
|
|
16
|
-
name: exports.NameStruct,
|
|
17
|
-
main: (0, superstruct_1.optional)((0, superstruct_1.size)((0, superstruct_1.string)(), 1, Infinity)),
|
|
18
|
-
repository: (0, superstruct_1.optional)((0, superstruct_1.object)({
|
|
19
|
-
type: (0, superstruct_1.size)((0, superstruct_1.string)(), 1, Infinity),
|
|
20
|
-
url: (0, superstruct_1.size)((0, superstruct_1.string)(), 1, Infinity),
|
|
21
|
-
})),
|
|
22
|
-
});
|
|
23
|
-
/**
|
|
24
|
-
* Check if the given value is a valid {@link NpmSnapPackageJson} object.
|
|
25
|
-
*
|
|
26
|
-
* @param value - The value to check.
|
|
27
|
-
* @returns Whether the value is a valid {@link NpmSnapPackageJson} object.
|
|
28
|
-
*/
|
|
29
|
-
function isNpmSnapPackageJson(value) {
|
|
30
|
-
return (0, superstruct_1.is)(value, exports.NpmSnapPackageJsonStruct);
|
|
31
|
-
}
|
|
32
|
-
exports.isNpmSnapPackageJson = isNpmSnapPackageJson;
|
|
33
|
-
/**
|
|
34
|
-
* Asserts that the given value is a valid {@link NpmSnapPackageJson} object.
|
|
35
|
-
*
|
|
36
|
-
* @param value - The value to check.
|
|
37
|
-
* @throws If the value is not a valid {@link NpmSnapPackageJson} object.
|
|
38
|
-
*/
|
|
39
|
-
function assertIsNpmSnapPackageJson(value) {
|
|
40
|
-
(0, utils_1.assertStruct)(value, exports.NpmSnapPackageJsonStruct, `"${NpmSnapFileNames.PackageJson}" is invalid`);
|
|
41
|
-
}
|
|
42
|
-
exports.assertIsNpmSnapPackageJson = assertIsNpmSnapPackageJson;
|
|
43
|
-
/**
|
|
44
|
-
* The possible prefixes for snap ids.
|
|
45
|
-
*/
|
|
46
|
-
/* eslint-disable @typescript-eslint/naming-convention */
|
|
47
|
-
var SnapIdPrefixes;
|
|
48
|
-
(function (SnapIdPrefixes) {
|
|
49
|
-
SnapIdPrefixes["npm"] = "npm:";
|
|
50
|
-
SnapIdPrefixes["local"] = "local:";
|
|
51
|
-
})(SnapIdPrefixes = exports.SnapIdPrefixes || (exports.SnapIdPrefixes = {}));
|
|
52
|
-
/**
|
|
53
|
-
* Snap validation failure reason codes that are programmatically fixable
|
|
54
|
-
* if validation occurs during development.
|
|
55
|
-
*/
|
|
56
|
-
var SnapValidationFailureReason;
|
|
57
|
-
(function (SnapValidationFailureReason) {
|
|
58
|
-
SnapValidationFailureReason["NameMismatch"] = "\"name\" field mismatch";
|
|
59
|
-
SnapValidationFailureReason["VersionMismatch"] = "\"version\" field mismatch";
|
|
60
|
-
SnapValidationFailureReason["RepositoryMismatch"] = "\"repository\" field mismatch";
|
|
61
|
-
SnapValidationFailureReason["ShasumMismatch"] = "\"shasum\" field mismatch";
|
|
62
|
-
})(SnapValidationFailureReason = exports.SnapValidationFailureReason || (exports.SnapValidationFailureReason = {}));
|
|
63
|
-
/* eslint-disable @typescript-eslint/naming-convention */
|
|
64
|
-
var SNAP_STREAM_NAMES;
|
|
65
|
-
(function (SNAP_STREAM_NAMES) {
|
|
66
|
-
SNAP_STREAM_NAMES["JSON_RPC"] = "jsonRpc";
|
|
67
|
-
SNAP_STREAM_NAMES["COMMAND"] = "command";
|
|
68
|
-
})(SNAP_STREAM_NAMES = exports.SNAP_STREAM_NAMES || (exports.SNAP_STREAM_NAMES = {}));
|
|
69
|
-
/* eslint-enable @typescript-eslint/naming-convention */
|
|
70
|
-
var HandlerType;
|
|
71
|
-
(function (HandlerType) {
|
|
72
|
-
HandlerType["OnRpcRequest"] = "onRpcRequest";
|
|
73
|
-
HandlerType["OnTransaction"] = "onTransaction";
|
|
74
|
-
HandlerType["SnapKeyring"] = "keyring";
|
|
75
|
-
HandlerType["OnCronjob"] = "onCronjob";
|
|
76
|
-
})(HandlerType = exports.HandlerType || (exports.HandlerType = {}));
|
|
77
|
-
exports.SNAP_EXPORT_NAMES = Object.values(HandlerType);
|
|
78
|
-
const uri = (opts = {}) => (0, superstruct_1.refine)((0, superstruct_1.union)([(0, superstruct_1.string)(), (0, superstruct_1.instance)(URL)]), 'uri', (value) => {
|
|
79
|
-
try {
|
|
80
|
-
const url = new URL(value);
|
|
81
|
-
const UrlStruct = (0, superstruct_1.type)(opts);
|
|
82
|
-
(0, superstruct_1.assert)(url, UrlStruct);
|
|
83
|
-
return true;
|
|
84
|
-
}
|
|
85
|
-
catch {
|
|
86
|
-
return `Expected URL, got "${value.toString()}".`;
|
|
87
|
-
}
|
|
88
|
-
});
|
|
89
|
-
exports.uri = uri;
|
|
90
|
-
/**
|
|
91
|
-
* Returns whether a given value is a valid URL.
|
|
92
|
-
*
|
|
93
|
-
* @param url - The value to check.
|
|
94
|
-
* @param opts - Optional constraints for url checking.
|
|
95
|
-
* @returns Whether `url` is valid URL or not.
|
|
96
|
-
*/
|
|
97
|
-
function isValidUrl(url, opts = {}) {
|
|
98
|
-
return (0, superstruct_1.is)(url, (0, exports.uri)(opts));
|
|
99
|
-
}
|
|
100
|
-
exports.isValidUrl = isValidUrl;
|
|
101
|
-
// redefining here to avoid circular dependency
|
|
102
|
-
exports.WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';
|
|
103
|
-
//# sourceMappingURL=types.js.map
|
package/dist/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAAA,2CAAoE;AACpE,6CAcqB;AAOrB,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,gDAA4B,CAAA;IAC5B,mDAA+B,CAAA;AACjC,CAAC,EAHW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAG3B;AAEY,QAAA,UAAU,GAAG,IAAA,kBAAI,EAC5B,IAAA,qBAAO,EACL,IAAA,oBAAM,GAAE,EACR,6DAA6D,CAC9D,EACD,CAAC,EACD,GAAG,CACJ,CAAC;AAEF,2EAA2E;AAC3E,sBAAsB;AACT,QAAA,wBAAwB,GAAG,IAAA,kBAAI,EAAC;IAC3C,OAAO,EAAE,qBAAa;IACtB,IAAI,EAAE,kBAAU;IAChB,IAAI,EAAE,IAAA,sBAAQ,EAAC,IAAA,kBAAI,EAAC,IAAA,oBAAM,GAAE,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;IAC3C,UAAU,EAAE,IAAA,sBAAQ,EAClB,IAAA,oBAAM,EAAC;QACL,IAAI,EAAE,IAAA,kBAAI,EAAC,IAAA,oBAAM,GAAE,EAAE,CAAC,EAAE,QAAQ,CAAC;QACjC,GAAG,EAAE,IAAA,kBAAI,EAAC,IAAA,oBAAM,GAAE,EAAE,CAAC,EAAE,QAAQ,CAAC;KACjC,CAAC,CACH;CACF,CAAC,CAAC;AAKH;;;;;GAKG;AACH,SAAgB,oBAAoB,CAClC,KAAc;IAEd,OAAO,IAAA,g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AAE;IACxD,IAAI;QACF,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;QAE3B,MAAM,SAAS,GAAG,IAAA,kBAAI,EAAC,IAAI,CAAC,CAAC;QAC7B,IAAA,oBAAiB,EAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAClC,OAAO,IAAI,CAAC;KACb;IAAC,MAAM;QACN,OAAO,sBAAsB,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC;KACnD;AACH,CAAC,CAAC,CAAC;AAXQ,QAAA,GAAG,OAWX;AAEL;;;;;;GAMG;AACH,SAAgB,UAAU,CACxB,GAAY,EACZ,OAAwB,EAAE;IAE1B,OAAO,IAAA,gBAAE,EAAC,GAAG,EAAE,IAAA,WAAG,EAAC,IAAI,CAAC,CAAC,CAAC;AAC5B,CAAC;AALD,gCAKC;AAED,+CAA+C;AAClC,QAAA,0BAA0B,GAAG,aAAa,CAAC","sourcesContent":["import { assertStruct, Json, VersionStruct } from '@metamask/utils';\nimport {\n Infer,\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n Struct,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport { SnapCaveatType } from './caveats';\nimport { SnapFunctionExports, SnapKeyring as Keyring } from './handlers';\nimport { SnapManifest } from './manifest';\nimport { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n};\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapId = string;\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n SnapKeyring = 'keyring',\n OnCronjob = 'onCronjob',\n}\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\ntype KeyringParameter<Fn> = Fn extends (...args: any[]) => unknown\n ? Parameters<Fn>\n : never;\n\ntype KeyringParameters = KeyringParameter<Keyring[keyof Keyring]>;\n\nexport type SnapExportsParameters =\n | ObjectParameters<SnapFunctionExports>\n | KeyringParameters;\n\ntype UriOptions<T extends string> = {\n protocol?: Struct<T>;\n hash?: Struct<T>;\n port?: Struct<T>;\n hostname?: Struct<T>;\n pathname?: Struct<T>;\n search?: Struct<T>;\n};\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"]}
|
package/dist/versions.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":";;;AAAA,2CAKyB;AACzB,mCAA8D;AAC9D,6CAAuC;AAE1B,QAAA,8BAA8B,GAAG,GAAkB,CAAC;AAEjE;;;;;;;;;GASG;AACH,SAAgB,gBAAgB,CAC9B,QAAyB,EACzB,YAAyB;IAEzB,MAAM,0BAA0B,GAAG,IAAA,sBAAmB,EACpD,QAAQ,EACR,YAAY,CACb,CAAC;IAEF,4CAA4C;IAC5C,IAAI,0BAA0B,EAAE;QAC9B,OAAO,0BAA0B,CAAC;KACnC;IAED,iFAAiF;IACjF,OAAO,IAAA,sBAAmB,EAAC,QAAQ,EAAE,YAAY,EAAE;QACjD,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAlBD,4CAkBC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CACjC,OAAc;IAEd,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,QAAQ,EAAE;QACjD,OAAO,CAAC,SAAS,EAAE,sCAA8B,CAAC,CAAC;KACpD;IACD,OAAO,IAAA,sBAAQ,EAAC,OAAO,EAAE,0BAAkB,CAAC,CAAC;AAC/C,CAAC;AAPD,kDAOC","sourcesContent":["import {\n Json,\n SemVerVersion,\n SemVerRange,\n VersionRangeStruct,\n} from '@metamask/utils';\nimport { maxSatisfying as maxSatisfyingSemver } from 'semver';\nimport { validate } from 'superstruct';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"VirtualFile.js","sourceRoot":"","sources":["../../src/virtual-file/VirtualFile.ts"],"names":[],"mappings":";;;AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;AACtD,2CAAyC;AAEzC,8CAA0C;AA+B1C,MAAa,WAAW;IACtB,YAAY,KAA0B;QACpC,IAAI,OAA4B,CAAC;QACjC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,UAAU,EAAE;YAC5D,OAAO,GAAG,EAAE,KAAK,EAAE,CAAC;SACrB;aAAM;YACL,OAAO,GAAG,KAAK,CAAC;SACjB;QAED,IAAI,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC;QAClC,wDAAwD;QACxD,gEAAgE;QAChE,4DAA4D;QAC5D,EAAE;QACF,wEAAwE;QACxE,4EAA4E;QAC5E,8EAA8E;QAC9E,EAAE;QACF,iDAAiD;QACjD,IAAI,CAAC,MAAM,GAAG,OAAO,EAAE,MAAM,IAAK,SAAiB,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,OAAO,EAAE,IAAI,IAAI,EAAE,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,OAAO,EAAE,IAAI,IAAI,GAAG,CAAC;IACnC,CAAC;IAUD,QAAQ,CAAC,QAAiB;QACxB,IAAI,OAAO,IAAI,CAAC,KAAK,KAAK,QAAQ,EAAE;YAClC,IAAA,cAAM,EAAC,QAAQ,KAAK,SAAS,EAAE,yBAAyB,CAAC,CAAC;YAC1D,OAAO,IAAI,CAAC,KAAK,CAAC;SACnB;QACD,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC1C,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,KAAK;QACH,MAAM,KAAK,GAAG,IAAI,WAAW,EAAU,CAAC;QACxC,IAAI,OAAO,IAAI,CAAC,KAAK,KAAK,QAAQ,EAAE;YAClC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;SAC1B;aAAM;YACL,mFAAmF;YACnF,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;SACnC;QACD,KAAK,CAAC,MAAM,GAAG,IAAA,sBAAS,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACtC,KAAK,CAAC,IAAI,GAAG,IAAA,sBAAS,EAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAtDD,kCAsDC","sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert } from '@metamask/utils';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"]}
|