@metamask/snaps-utils 1.0.2 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -221
- 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 +188 -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 +154 -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 -81
- 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 +67 -47
- 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
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
FORBIDDEN_COIN_TYPES: function() {
|
|
13
|
+
return FORBIDDEN_COIN_TYPES;
|
|
14
|
+
},
|
|
15
|
+
Bip32PathStruct: function() {
|
|
16
|
+
return Bip32PathStruct;
|
|
17
|
+
},
|
|
18
|
+
bip32entropy: function() {
|
|
19
|
+
return bip32entropy;
|
|
20
|
+
},
|
|
21
|
+
Bip32EntropyStruct: function() {
|
|
22
|
+
return Bip32EntropyStruct;
|
|
23
|
+
},
|
|
24
|
+
SnapGetBip32EntropyPermissionsStruct: function() {
|
|
25
|
+
return SnapGetBip32EntropyPermissionsStruct;
|
|
26
|
+
},
|
|
27
|
+
SemVerRangeStruct: function() {
|
|
28
|
+
return SemVerRangeStruct;
|
|
29
|
+
},
|
|
30
|
+
SnapIdsStruct: function() {
|
|
31
|
+
return SnapIdsStruct;
|
|
32
|
+
},
|
|
33
|
+
ChainIdsStruct: function() {
|
|
34
|
+
return ChainIdsStruct;
|
|
35
|
+
},
|
|
36
|
+
PermissionsStruct: function() {
|
|
37
|
+
return PermissionsStruct;
|
|
38
|
+
},
|
|
39
|
+
SnapManifestStruct: function() {
|
|
40
|
+
return SnapManifestStruct;
|
|
41
|
+
},
|
|
42
|
+
isSnapManifest: function() {
|
|
43
|
+
return isSnapManifest;
|
|
44
|
+
},
|
|
45
|
+
assertIsSnapManifest: function() {
|
|
46
|
+
return assertIsSnapManifest;
|
|
47
|
+
},
|
|
48
|
+
createSnapManifest: function() {
|
|
49
|
+
return createSnapManifest;
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
const _keytree = require("@metamask/key-tree");
|
|
53
|
+
const _utils = require("@metamask/utils");
|
|
54
|
+
const _superstruct = require("superstruct");
|
|
55
|
+
const _array = require("../array");
|
|
56
|
+
const _cronjob = require("../cronjob");
|
|
57
|
+
const _entropy = require("../entropy");
|
|
58
|
+
const _jsonrpc = require("../json-rpc");
|
|
59
|
+
const _namespace = require("../namespace");
|
|
60
|
+
const _snaps = require("../snaps");
|
|
61
|
+
const _types = require("../types");
|
|
62
|
+
// BIP-43 purposes that cannot be used for entropy derivation. These are in the
|
|
63
|
+
// string form, ending with `'`.
|
|
64
|
+
const FORBIDDEN_PURPOSES = [
|
|
65
|
+
_entropy.SIP_6_MAGIC_VALUE,
|
|
66
|
+
_entropy.STATE_ENCRYPTION_MAGIC_VALUE
|
|
67
|
+
];
|
|
68
|
+
const FORBIDDEN_COIN_TYPES = [
|
|
69
|
+
60
|
|
70
|
+
];
|
|
71
|
+
const FORBIDDEN_PATHS = FORBIDDEN_COIN_TYPES.map((coinType)=>[
|
|
72
|
+
'm',
|
|
73
|
+
"44'",
|
|
74
|
+
`${coinType}'`
|
|
75
|
+
]);
|
|
76
|
+
const Bip32PathStruct = (0, _superstruct.refine)((0, _superstruct.array)((0, _superstruct.string)()), 'BIP-32 path', (path)=>{
|
|
77
|
+
if (path.length === 0) {
|
|
78
|
+
return 'Path must be a non-empty BIP-32 derivation path array';
|
|
79
|
+
}
|
|
80
|
+
if (path[0] !== 'm') {
|
|
81
|
+
return 'Path must start with "m".';
|
|
82
|
+
}
|
|
83
|
+
if (path.length < 3) {
|
|
84
|
+
return 'Paths must have a length of at least three.';
|
|
85
|
+
}
|
|
86
|
+
if (path.slice(1).some((part)=>!(0, _keytree.isValidBIP32PathSegment)(part))) {
|
|
87
|
+
return 'Path must be a valid BIP-32 derivation path array.';
|
|
88
|
+
}
|
|
89
|
+
if (FORBIDDEN_PURPOSES.includes(path[1])) {
|
|
90
|
+
return `The purpose "${path[1]}" is not allowed for entropy derivation.`;
|
|
91
|
+
}
|
|
92
|
+
if (FORBIDDEN_PATHS.some((forbiddenPath)=>(0, _array.isEqual)(path.slice(0, forbiddenPath.length), forbiddenPath))) {
|
|
93
|
+
return `The path "${path.join('/')}" is not allowed for entropy derivation.`;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
});
|
|
97
|
+
const bip32entropy = (struct)=>(0, _superstruct.refine)(struct, 'BIP-32 entropy', (value)=>{
|
|
98
|
+
if (value.curve === 'ed25519' && value.path.slice(1).some((part)=>!part.endsWith("'"))) {
|
|
99
|
+
return 'Ed25519 does not support unhardened paths.';
|
|
100
|
+
}
|
|
101
|
+
return true;
|
|
102
|
+
});
|
|
103
|
+
const Bip32EntropyStruct = bip32entropy((0, _superstruct.type)({
|
|
104
|
+
path: Bip32PathStruct,
|
|
105
|
+
curve: (0, _superstruct.enums)([
|
|
106
|
+
'ed25519',
|
|
107
|
+
'secp256k1'
|
|
108
|
+
])
|
|
109
|
+
}));
|
|
110
|
+
const SnapGetBip32EntropyPermissionsStruct = (0, _superstruct.size)((0, _superstruct.array)(Bip32EntropyStruct), 1, Infinity);
|
|
111
|
+
const SemVerRangeStruct = (0, _superstruct.refine)((0, _superstruct.string)(), 'SemVer range', (value)=>{
|
|
112
|
+
if ((0, _utils.isValidSemVerRange)(value)) {
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
return 'Expected a valid SemVer range.';
|
|
116
|
+
});
|
|
117
|
+
const SnapIdsStruct = (0, _superstruct.refine)((0, _superstruct.record)(_snaps.SnapIdStruct, (0, _superstruct.object)({
|
|
118
|
+
version: (0, _superstruct.optional)(SemVerRangeStruct)
|
|
119
|
+
})), 'SnapIds', (value)=>{
|
|
120
|
+
if (Object.keys(value).length === 0) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
return true;
|
|
124
|
+
});
|
|
125
|
+
const ChainIdsStruct = (0, _superstruct.array)(_namespace.ChainIdStruct);
|
|
126
|
+
const PermissionsStruct = (0, _superstruct.type)({
|
|
127
|
+
'endowment:network-access': (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
128
|
+
'endowment:webassembly': (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
129
|
+
'endowment:transaction-insight': (0, _superstruct.optional)((0, _superstruct.object)({
|
|
130
|
+
allowTransactionOrigin: (0, _superstruct.optional)((0, _superstruct.boolean)())
|
|
131
|
+
})),
|
|
132
|
+
'endowment:cronjob': (0, _superstruct.optional)((0, _superstruct.object)({
|
|
133
|
+
jobs: _cronjob.CronjobSpecificationArrayStruct
|
|
134
|
+
})),
|
|
135
|
+
'endowment:rpc': (0, _superstruct.optional)(_jsonrpc.RpcOriginsStruct),
|
|
136
|
+
'endowment:name-lookup': (0, _superstruct.optional)(ChainIdsStruct),
|
|
137
|
+
snap_dialog: (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
138
|
+
// TODO: Remove
|
|
139
|
+
snap_confirm: (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
140
|
+
snap_manageState: (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
141
|
+
snap_manageAccounts: (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
142
|
+
snap_notify: (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
143
|
+
snap_getBip32Entropy: (0, _superstruct.optional)(SnapGetBip32EntropyPermissionsStruct),
|
|
144
|
+
snap_getBip32PublicKey: (0, _superstruct.optional)(SnapGetBip32EntropyPermissionsStruct),
|
|
145
|
+
snap_getBip44Entropy: (0, _superstruct.optional)((0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.object)({
|
|
146
|
+
coinType: (0, _superstruct.size)((0, _superstruct.integer)(), 0, 2 ** 32 - 1)
|
|
147
|
+
})), 1, Infinity)),
|
|
148
|
+
snap_getEntropy: (0, _superstruct.optional)((0, _superstruct.object)({})),
|
|
149
|
+
wallet_snap: (0, _superstruct.optional)(SnapIdsStruct)
|
|
150
|
+
});
|
|
151
|
+
const SnapManifestStruct = (0, _superstruct.object)({
|
|
152
|
+
version: _utils.VersionStruct,
|
|
153
|
+
description: (0, _superstruct.size)((0, _superstruct.string)(), 1, 280),
|
|
154
|
+
proposedName: (0, _superstruct.size)((0, _superstruct.pattern)((0, _superstruct.string)(), /^(?:[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), 1, 214),
|
|
155
|
+
repository: (0, _superstruct.optional)((0, _superstruct.object)({
|
|
156
|
+
type: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
|
|
157
|
+
url: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)
|
|
158
|
+
})),
|
|
159
|
+
source: (0, _superstruct.object)({
|
|
160
|
+
shasum: _utils.ChecksumStruct,
|
|
161
|
+
location: (0, _superstruct.object)({
|
|
162
|
+
npm: (0, _superstruct.object)({
|
|
163
|
+
filePath: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
|
|
164
|
+
iconPath: (0, _superstruct.optional)((0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)),
|
|
165
|
+
packageName: _types.NameStruct,
|
|
166
|
+
registry: (0, _superstruct.union)([
|
|
167
|
+
(0, _superstruct.literal)('https://registry.npmjs.org'),
|
|
168
|
+
(0, _superstruct.literal)('https://registry.npmjs.org/')
|
|
169
|
+
])
|
|
170
|
+
})
|
|
171
|
+
})
|
|
172
|
+
}),
|
|
173
|
+
initialPermissions: PermissionsStruct,
|
|
174
|
+
manifestVersion: (0, _superstruct.literal)('0.1'),
|
|
175
|
+
$schema: (0, _superstruct.optional)((0, _superstruct.string)())
|
|
176
|
+
});
|
|
177
|
+
function isSnapManifest(value) {
|
|
178
|
+
return (0, _superstruct.is)(value, SnapManifestStruct);
|
|
179
|
+
}
|
|
180
|
+
function assertIsSnapManifest(value) {
|
|
181
|
+
(0, _utils.assertStruct)(value, SnapManifestStruct, `"${_types.NpmSnapFileNames.Manifest}" is invalid`);
|
|
182
|
+
}
|
|
183
|
+
function createSnapManifest(value) {
|
|
184
|
+
// TODO: Add a utility to prefix these errors similar to assertStruct
|
|
185
|
+
return (0, _superstruct.create)(value, SnapManifestStruct);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
//# sourceMappingURL=validation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\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 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","pattern","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA0CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAGAC,iBAAiB;eAAjBA;;IAmCAC,kBAAkB;eAAlBA;;IA4CGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBA1PwB;uBAMjC;6BAmBA;uBAEiB;yBACwB;yBACgB;yBAC/B;2BACH;uBACD;uBACgB;AAE7C,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCC,0BAAiB;IACjBC,qCAA4B;CAC7B;AAEM,MAAMf,uBAAiC;IAAC;CAAG;AAClD,MAAMgB,kBAA8BhB,qBAAqBiB,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAEM,MAAMjB,kBAAkBkB,IAAAA,mBAAM,EACnCC,IAAAA,kBAAK,EAACC,IAAAA,mBAAM,MACZ,eACA,CAACC;IACC,IAAIA,KAAKC,MAAM,KAAK,GAAG;QACrB,OAAO;IACT;IAEA,IAAID,IAAI,CAAC,EAAE,KAAK,KAAK;QACnB,OAAO;IACT;IAEA,IAAIA,KAAKC,MAAM,GAAG,GAAG;QACnB,OAAO;IACT;IAEA,IAAID,KAAKE,KAAK,CAAC,GAAGC,IAAI,CAAC,CAACC,OAAS,CAACC,IAAAA,gCAAuB,EAACD,QAAQ;QAChE,OAAO;IACT;IAEA,IAAIb,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OyD,IAAAA,mBAAM,EAACzD,OAAOxB;AACvB"}
|
package/dist/cjs/mock.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
ALL_APIS: function() {
|
|
13
|
+
return ALL_APIS;
|
|
14
|
+
},
|
|
15
|
+
isConstructor: function() {
|
|
16
|
+
return isConstructor;
|
|
17
|
+
},
|
|
18
|
+
generateMockEndowments: function() {
|
|
19
|
+
return generateMockEndowments;
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto"));
|
|
23
|
+
const _events = /*#__PURE__*/ _interop_require_default(require("events"));
|
|
24
|
+
const _defaultendowments = require("./default-endowments");
|
|
25
|
+
function _interop_require_default(obj) {
|
|
26
|
+
return obj && obj.__esModule ? obj : {
|
|
27
|
+
default: obj
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const NETWORK_APIS = [
|
|
31
|
+
'fetch',
|
|
32
|
+
'Request',
|
|
33
|
+
'Headers',
|
|
34
|
+
'Response'
|
|
35
|
+
];
|
|
36
|
+
const ALL_APIS = [
|
|
37
|
+
..._defaultendowments.DEFAULT_ENDOWMENTS,
|
|
38
|
+
...NETWORK_APIS,
|
|
39
|
+
'WebAssembly'
|
|
40
|
+
];
|
|
41
|
+
/**
|
|
42
|
+
* Get a mock snap API, that always returns `true` for requests.
|
|
43
|
+
*
|
|
44
|
+
* @returns A mocked snap provider.
|
|
45
|
+
*/ function getMockSnapGlobal() {
|
|
46
|
+
// eslint-disable-next-line @typescript-eslint/require-await
|
|
47
|
+
return {
|
|
48
|
+
request: async ()=>true
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Get a mock Ethereum provider, that always returns `true` for requests.
|
|
53
|
+
*
|
|
54
|
+
* @returns A mocked ethereum provider.
|
|
55
|
+
*/ function getMockEthereumProvider() {
|
|
56
|
+
const mockProvider = new _events.default();
|
|
57
|
+
// eslint-disable-next-line @typescript-eslint/require-await
|
|
58
|
+
mockProvider.request = async ()=>true;
|
|
59
|
+
return mockProvider;
|
|
60
|
+
}
|
|
61
|
+
const isConstructor = (value)=>Boolean(typeof value?.prototype?.constructor?.name === 'string');
|
|
62
|
+
/**
|
|
63
|
+
* A function that always returns `true`.
|
|
64
|
+
*
|
|
65
|
+
* @returns `true`.
|
|
66
|
+
*/ const mockFunction = ()=>true;
|
|
67
|
+
class MockClass {
|
|
68
|
+
}
|
|
69
|
+
const handler = {
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
71
|
+
construct (Target, args) {
|
|
72
|
+
return new Proxy(new Target(...args), handler);
|
|
73
|
+
},
|
|
74
|
+
get (_target, _prop) {
|
|
75
|
+
return mockFunction;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Generate a mock class for a given value. The value is wrapped in a Proxy, and
|
|
80
|
+
* all methods are replaced with a mock function.
|
|
81
|
+
*
|
|
82
|
+
* @param value - The value to mock.
|
|
83
|
+
* @returns A mock class.
|
|
84
|
+
*/ const generateMockClass = (value)=>{
|
|
85
|
+
return new Proxy(value, handler);
|
|
86
|
+
};
|
|
87
|
+
// Things not currently auto-mocked because of NodeJS, by adding them here we
|
|
88
|
+
// have types for them and can use that to generate mocks if needed.
|
|
89
|
+
const mockWindow = {
|
|
90
|
+
crypto: _crypto.default,
|
|
91
|
+
SubtleCrypto: MockClass
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Generate a mock endowment for a certain class or function on the `globalThis`
|
|
95
|
+
* object.
|
|
96
|
+
*
|
|
97
|
+
* @param key - The key to generate the mock endowment for.
|
|
98
|
+
* @returns A mocked class or function. If the key is part of the default
|
|
99
|
+
* endowments, the original value is returned.
|
|
100
|
+
*/ const generateMockEndowment = (key)=>{
|
|
101
|
+
const globalValue = globalThis[key];
|
|
102
|
+
// Default exposed APIs don't need to be mocked
|
|
103
|
+
if (globalValue && _defaultendowments.DEFAULT_ENDOWMENTS.includes(key)) {
|
|
104
|
+
return globalValue;
|
|
105
|
+
}
|
|
106
|
+
// Fall back to mockWindow for certain APIs not exposed in global in Node.JS
|
|
107
|
+
const globalOrMocked = globalValue ?? mockWindow[key];
|
|
108
|
+
const type = typeof globalOrMocked;
|
|
109
|
+
const isFunction = type === 'function';
|
|
110
|
+
if (isFunction && isConstructor(globalOrMocked)) {
|
|
111
|
+
return generateMockClass(globalOrMocked);
|
|
112
|
+
} else if (isFunction || !globalOrMocked) {
|
|
113
|
+
// Fall back to function mock for now
|
|
114
|
+
return mockFunction;
|
|
115
|
+
}
|
|
116
|
+
return globalOrMocked;
|
|
117
|
+
};
|
|
118
|
+
const generateMockEndowments = ()=>{
|
|
119
|
+
return ALL_APIS.reduce((acc, cur)=>({
|
|
120
|
+
...acc,
|
|
121
|
+
[cur]: generateMockEndowment(cur)
|
|
122
|
+
}), {
|
|
123
|
+
snap: getMockSnapGlobal(),
|
|
124
|
+
ethereum: getMockEthereumProvider()
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
//# sourceMappingURL=mock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/mock.ts"],"sourcesContent":["import crypto from 'crypto';\nimport EventEmitter from 'events';\n\nimport { DEFAULT_ENDOWMENTS } from './default-endowments';\n\nconst NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];\n\nexport const ALL_APIS: string[] = [\n ...DEFAULT_ENDOWMENTS,\n ...NETWORK_APIS,\n 'WebAssembly',\n];\n\ntype MockSnapGlobal = {\n request: () => Promise<any>;\n};\n\ntype MockEthereumProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap API, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapGlobal(): MockSnapGlobal {\n // eslint-disable-next-line @typescript-eslint/require-await\n return { request: async () => true };\n}\n\n/**\n * Get a mock Ethereum provider, that always returns `true` for requests.\n *\n * @returns A mocked ethereum provider.\n */\nfunction getMockEthereumProvider(): MockEthereumProvider {\n const mockProvider = new EventEmitter() as Partial<MockEthereumProvider>;\n // eslint-disable-next-line @typescript-eslint/require-await\n mockProvider.request = async () => true;\n return mockProvider as MockEthereumProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we\n// have types for them and can use that to generate mocks if needed.\nconst mockWindow: Record<string, unknown> = {\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? mockWindow[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() },\n );\n};\n"],"names":["ALL_APIS","isConstructor","generateMockEndowments","NETWORK_APIS","DEFAULT_ENDOWMENTS","getMockSnapGlobal","request","getMockEthereumProvider","mockProvider","EventEmitter","value","Boolean","prototype","constructor","name","mockFunction","MockClass","handler","construct","Target","args","Proxy","get","_target","_prop","generateMockClass","mockWindow","crypto","SubtleCrypto","generateMockEndowment","key","globalValue","globalThis","includes","globalOrMocked","type","isFunction","reduce","acc","cur","snap","ethereum"],"mappings":";;;;;;;;;;;IAOaA,QAAQ;eAARA;;IA0CAC,aAAa;eAAbA;;IA0EAC,sBAAsB;eAAtBA;;;+DA3HM;+DACM;mCAEU;;;;;;AAEnC,MAAMC,eAAe;IAAC;IAAS;IAAW;IAAW;CAAW;AAEzD,MAAMH,WAAqB;OAC7BI,qCAAkB;OAClBD;IACH;CACD;AAUD;;;;CAIC,GACD,SAASE;IACP,4DAA4D;IAC5D,OAAO;QAAEC,SAAS,UAAY;IAAK;AACrC;AAEA;;;;CAIC,GACD,SAASC;IACP,MAAMC,eAAe,IAAIC,eAAY;IACrC,4DAA4D;IAC5DD,aAAaF,OAAO,GAAG,UAAY;IACnC,OAAOE;AACT;AAQO,MAAMP,gBAAgB,CAACS,QAC5BC,QAAQ,OAAOD,OAAOE,WAAWC,aAAaC,SAAS;AAEzD;;;;CAIC,GACD,MAAMC,eAAe,IAAM;AAC3B,MAAMC;AAAW;AAEjB,MAAMC,UAAU;IACd,gEAAgE;IAChEC,WAAUC,MAAW,EAAEC,IAAW;QAChC,OAAO,IAAIC,MAAM,IAAIF,UAAUC,OAAOH;IACxC;IACAK,KAAIC,OAAY,EAAEC,KAAU;QAC1B,OAAOT;IACT;AACF;AAEA;;;;;;CAMC,GACD,MAAMU,oBAAoB,CAACf;IACzB,OAAO,IAAIW,MAAMX,OAAOO;AAC1B;AAEA,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMS,aAAsC;IAC1CC,QAAAA,eAAM;IACNC,cAAcZ;AAChB;AAEA;;;;;;;CAOC,GACD,MAAMa,wBAAwB,CAACC;IAC7B,MAAMC,cAAc,AAACC,UAAkB,CAACF,IAAI;IAE5C,+CAA+C;IAC/C,IAAIC,eAAe3B,qCAAkB,CAAC6B,QAAQ,CAACH,MAAM;QACnD,OAAOC;IACT;IAEA,4EAA4E;IAC5E,MAAMG,iBAAiBH,eAAeL,UAAU,CAACI,IAAI;IAErD,MAAMK,OAAO,OAAOD;IACpB,MAAME,aAAaD,SAAS;IAC5B,IAAIC,cAAcnC,cAAciC,iBAAiB;QAC/C,OAAOT,kBAAkBS;IAC3B,OAAO,IAAIE,cAAc,CAACF,gBAAgB;QACxC,qCAAqC;QACrC,OAAOnB;IACT;IACA,OAAOmB;AACT;AAOO,MAAMhC,yBAAyB;IACpC,OAAOF,SAASqC,MAAM,CACpB,CAACC,KAAKC,MAAS,CAAA;YAAE,GAAGD,GAAG;YAAE,CAACC,IAAI,EAAEV,sBAAsBU;QAAK,CAAA,GAC3D;QAAEC,MAAMnC;QAAqBoC,UAAUlC;IAA0B;AAErE"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
CHAIN_ID_REGEX: function() {
|
|
13
|
+
return CHAIN_ID_REGEX;
|
|
14
|
+
},
|
|
15
|
+
ACCOUNT_ID_REGEX: function() {
|
|
16
|
+
return ACCOUNT_ID_REGEX;
|
|
17
|
+
},
|
|
18
|
+
ACCOUNT_ADDRESS_REGEX: function() {
|
|
19
|
+
return ACCOUNT_ADDRESS_REGEX;
|
|
20
|
+
},
|
|
21
|
+
parseChainId: function() {
|
|
22
|
+
return parseChainId;
|
|
23
|
+
},
|
|
24
|
+
parseAccountId: function() {
|
|
25
|
+
return parseAccountId;
|
|
26
|
+
},
|
|
27
|
+
LimitedString: function() {
|
|
28
|
+
return LimitedString;
|
|
29
|
+
},
|
|
30
|
+
ChainIdStruct: function() {
|
|
31
|
+
return ChainIdStruct;
|
|
32
|
+
},
|
|
33
|
+
AccountIdStruct: function() {
|
|
34
|
+
return AccountIdStruct;
|
|
35
|
+
},
|
|
36
|
+
AccountIdArrayStruct: function() {
|
|
37
|
+
return AccountIdArrayStruct;
|
|
38
|
+
},
|
|
39
|
+
AccountAddressStruct: function() {
|
|
40
|
+
return AccountAddressStruct;
|
|
41
|
+
},
|
|
42
|
+
ChainStruct: function() {
|
|
43
|
+
return ChainStruct;
|
|
44
|
+
},
|
|
45
|
+
NamespaceStruct: function() {
|
|
46
|
+
return NamespaceStruct;
|
|
47
|
+
},
|
|
48
|
+
NamespaceIdStruct: function() {
|
|
49
|
+
return NamespaceIdStruct;
|
|
50
|
+
},
|
|
51
|
+
isNamespaceId: function() {
|
|
52
|
+
return isNamespaceId;
|
|
53
|
+
},
|
|
54
|
+
isChainId: function() {
|
|
55
|
+
return isChainId;
|
|
56
|
+
},
|
|
57
|
+
isAccountId: function() {
|
|
58
|
+
return isAccountId;
|
|
59
|
+
},
|
|
60
|
+
isAccountIdArray: function() {
|
|
61
|
+
return isAccountIdArray;
|
|
62
|
+
},
|
|
63
|
+
isNamespace: function() {
|
|
64
|
+
return isNamespace;
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
const _superstruct = require("superstruct");
|
|
68
|
+
const CHAIN_ID_REGEX = RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u");
|
|
69
|
+
const ACCOUNT_ID_REGEX = RegExp("^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
|
|
70
|
+
const ACCOUNT_ADDRESS_REGEX = RegExp("^(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
|
|
71
|
+
function parseChainId(chainId) {
|
|
72
|
+
const match = CHAIN_ID_REGEX.exec(chainId);
|
|
73
|
+
if (!match?.groups) {
|
|
74
|
+
throw new Error('Invalid chain ID.');
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
namespace: match.groups.namespace,
|
|
78
|
+
reference: match.groups.reference
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function parseAccountId(accountId) {
|
|
82
|
+
const match = ACCOUNT_ID_REGEX.exec(accountId);
|
|
83
|
+
if (!match?.groups) {
|
|
84
|
+
throw new Error('Invalid account ID.');
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
address: match.groups.accountAddress,
|
|
88
|
+
chainId: match.groups.chainId,
|
|
89
|
+
chain: {
|
|
90
|
+
namespace: match.groups.namespace,
|
|
91
|
+
reference: match.groups.reference
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const LimitedString = (0, _superstruct.size)((0, _superstruct.string)(), 1, 40);
|
|
96
|
+
const ChainIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), CHAIN_ID_REGEX);
|
|
97
|
+
const AccountIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), ACCOUNT_ID_REGEX);
|
|
98
|
+
const AccountIdArrayStruct = (0, _superstruct.array)(AccountIdStruct);
|
|
99
|
+
const AccountAddressStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), ACCOUNT_ADDRESS_REGEX);
|
|
100
|
+
const ChainStruct = (0, _superstruct.object)({
|
|
101
|
+
id: ChainIdStruct,
|
|
102
|
+
name: LimitedString
|
|
103
|
+
});
|
|
104
|
+
const NamespaceStruct = (0, _superstruct.object)({
|
|
105
|
+
/**
|
|
106
|
+
* A list of supported chains in the namespace.
|
|
107
|
+
*/ chains: (0, _superstruct.array)(ChainStruct),
|
|
108
|
+
/**
|
|
109
|
+
* A list of supported RPC methods on the namespace, that a DApp can call.
|
|
110
|
+
*/ methods: (0, _superstruct.optional)((0, _superstruct.array)(LimitedString)),
|
|
111
|
+
/**
|
|
112
|
+
* A list of supported RPC events on the namespace, that a DApp can listen to.
|
|
113
|
+
*/ events: (0, _superstruct.optional)((0, _superstruct.array)(LimitedString))
|
|
114
|
+
});
|
|
115
|
+
const NamespaceIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), /^[-a-z0-9]{3,8}$/u);
|
|
116
|
+
function isNamespaceId(value) {
|
|
117
|
+
return (0, _superstruct.is)(value, NamespaceIdStruct);
|
|
118
|
+
}
|
|
119
|
+
function isChainId(value) {
|
|
120
|
+
return (0, _superstruct.is)(value, ChainIdStruct);
|
|
121
|
+
}
|
|
122
|
+
function isAccountId(value) {
|
|
123
|
+
return (0, _superstruct.is)(value, AccountIdStruct);
|
|
124
|
+
}
|
|
125
|
+
function isAccountIdArray(value) {
|
|
126
|
+
return (0, _superstruct.is)(value, AccountIdArrayStruct);
|
|
127
|
+
}
|
|
128
|
+
function isNamespace(value) {
|
|
129
|
+
return (0, _superstruct.is)(value, NamespaceStruct);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
//# sourceMappingURL=namespace.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n array,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\nexport type Caip2ChainId = Infer<typeof ChainIdStruct>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"names":["CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","ACCOUNT_ADDRESS_REGEX","parseChainId","parseAccountId","LimitedString","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","AccountAddressStruct","ChainStruct","NamespaceStruct","NamespaceIdStruct","isNamespaceId","isChainId","isAccountId","isAccountIdArray","isNamespace","chainId","match","exec","groups","Error","namespace","reference","accountId","address","accountAddress","chain","size","string","pattern","array","object","id","name","chains","methods","optional","events","value","is"],"mappings":";;;;;;;;;;;IAWaA,cAAc;eAAdA;;IAGAC,gBAAgB;eAAhBA;;IAGAC,qBAAqB;eAArBA;;IASGC,YAAY;eAAZA;;IAsBAC,cAAc;eAAdA;;IAwBHC,aAAa;eAAbA;;IAKAC,aAAa;eAAbA;;IAIAC,eAAe;eAAfA;;IAGAC,oBAAoB;eAApBA;;IACAC,oBAAoB;eAApBA;;IAMAC,WAAW;eAAXA;;IAMAC,eAAe;eAAfA;;IAqBAC,iBAAiB;eAAjBA;;IASGC,aAAa;eAAbA;;IAUAC,SAAS;eAATA;;IAUAC,WAAW;eAAXA;;IAUAC,gBAAgB;eAAhBA;;IAUAC,WAAW;eAAXA;;;6BA9JT;AAEA,MAAMjB,iBACX;AAEK,MAAMC,mBACX;AAEK,MAAMC,wBAAwB;AAS9B,SAASC,aAAae,OAAgB;IAI3C,MAAMC,QAAQnB,eAAeoB,IAAI,CAACF;IAClC,IAAI,CAACC,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLC,WAAWJ,MAAME,MAAM,CAACE,SAAS;QACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;IACnC;AACF;AASO,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A,eAAE,EAACD,OAAOjC;AACnB;AAQO,SAASS,iBAAiBwB,KAAc;IAC7C,OAAOC,IAAAA,eAAE,EAACD,OAAOhC;AACnB;AAQO,SAASS,YAAYuB,KAAc;IACxC,OAAOC,IAAAA,eAAE,EAACD,OAAO7B;AACnB"}
|
package/dist/cjs/npm.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
EXPECTED_SNAP_FILES: function() {
|
|
13
|
+
return EXPECTED_SNAP_FILES;
|
|
14
|
+
},
|
|
15
|
+
SnapFileNameFromKey: function() {
|
|
16
|
+
return SnapFileNameFromKey;
|
|
17
|
+
},
|
|
18
|
+
validateNpmSnap: function() {
|
|
19
|
+
return validateNpmSnap;
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
const _icon = require("./icon");
|
|
23
|
+
const _manifest = require("./manifest/manifest");
|
|
24
|
+
const _validation = require("./manifest/validation");
|
|
25
|
+
const _types = require("./types");
|
|
26
|
+
const EXPECTED_SNAP_FILES = [
|
|
27
|
+
'manifest',
|
|
28
|
+
'packageJson',
|
|
29
|
+
'sourceCode'
|
|
30
|
+
];
|
|
31
|
+
const SnapFileNameFromKey = {
|
|
32
|
+
manifest: _types.NpmSnapFileNames.Manifest,
|
|
33
|
+
packageJson: _types.NpmSnapFileNames.PackageJson,
|
|
34
|
+
sourceCode: 'source code bundle'
|
|
35
|
+
};
|
|
36
|
+
function validateNpmSnap(snapFiles, errorPrefix) {
|
|
37
|
+
EXPECTED_SNAP_FILES.forEach((key)=>{
|
|
38
|
+
if (!snapFiles[key]) {
|
|
39
|
+
throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
// Typecast: We are assured that the required files exist if we get here.
|
|
43
|
+
const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
|
|
44
|
+
try {
|
|
45
|
+
(0, _validation.assertIsSnapManifest)(manifest.result);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
48
|
+
}
|
|
49
|
+
const validatedManifest = manifest;
|
|
50
|
+
const { iconPath } = validatedManifest.result.source.location.npm;
|
|
51
|
+
if (iconPath && !svgIcon) {
|
|
52
|
+
throw new Error(`Missing file "${iconPath}".`);
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
(0, _types.assertIsNpmSnapPackageJson)(packageJson.result);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
58
|
+
}
|
|
59
|
+
const validatedPackageJson = packageJson;
|
|
60
|
+
(0, _manifest.validateNpmSnapManifest)({
|
|
61
|
+
manifest: validatedManifest,
|
|
62
|
+
packageJson: validatedPackageJson,
|
|
63
|
+
sourceCode,
|
|
64
|
+
svgIcon
|
|
65
|
+
});
|
|
66
|
+
if (svgIcon) {
|
|
67
|
+
try {
|
|
68
|
+
(0, _icon.assertIsSnapIcon)(svgIcon);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
manifest: validatedManifest,
|
|
75
|
+
packageJson: validatedPackageJson,
|
|
76
|
+
sourceCode,
|
|
77
|
+
svgIcon
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=npm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\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// TODO: Refactor this to be more shared with other validation.\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 try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"],"names":["EXPECTED_SNAP_FILES","SnapFileNameFromKey","validateNpmSnap","manifest","NpmSnapFileNames","Manifest","packageJson","PackageJson","sourceCode","snapFiles","errorPrefix","forEach","key","Error","svgIcon","assertIsSnapManifest","result","error","message","validatedManifest","iconPath","source","location","npm","assertIsNpmSnapPackageJson","validatedPackageJson","validateNpmSnapManifest","assertIsSnapIcon"],"mappings":";;;;;;;;;;;IAMaA,mBAAmB;eAAnBA;;IAMAC,mBAAmB;eAAnBA;;IAkBGC,eAAe;eAAfA;;;sBA9BiB;0BACO;4BACH;uBAEwB;AAEtD,MAAMF,sBAAsB;IACjC;IACA;IACA;CACD;AAEM,MAAMC,sBAAsB;IACjCE,UAAUC,uBAAgB,CAACC,QAAQ;IACnCC,aAAaF,uBAAgB,CAACG,WAAW;IACzCC,YAAY;AACd;AAcO,SAASN,gBACdO,SAA+B,EAC/BC,WAA2B;IAE3BV,oBAAoBW,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAET,mBAAmB,CAACW,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;IAEA,yEAAyE;IACzE,MAAM,EAAET,QAAQ,EAAEG,WAAW,EAAEE,UAAU,EAAEM,OAAO,EAAE,GAAGL;IACvD,IAAI;QACFM,IAAAA,gCAAoB,EAACZ,SAASa,MAAM;IACtC,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMC,oBAAoBhB;IAE1B,MAAM,EAAEiB,QAAQ,EAAE,GAAGD,kBAAkBH,MAAM,CAACK,MAAM,CAACC,QAAQ,CAACC,GAAG;IACjE,IAAIH,YAAY,CAACN,SAAS;QACxB,MAAM,IAAID,MAAM,CAAC,cAAc,EAAEO,SAAS,EAAE,CAAC;IAC/C;IAEA,IAAI;QACFI,IAAAA,iCAA0B,EAAClB,YAAYU,MAAM;IAC/C,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMO,uBAAuBnB;IAE7BoB,IAAAA,iCAAuB,EAAC;QACtBvB,UAAUgB;QACVb,aAAamB;QACbjB;QACAM;IACF;IAEA,IAAIA,SAAS;QACX,IAAI;YACFa,IAAAA,sBAAgB,EAACb;QACnB,EAAE,OAAOG,OAAO;YACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLf,UAAUgB;QACVb,aAAamB;QACbjB;QACAM;IACF;AACF"}
|
package/dist/cjs/path.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "normalizeRelative", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return normalizeRelative;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _utils = require("@metamask/utils");
|
|
12
|
+
function normalizeRelative(path) {
|
|
13
|
+
(0, _utils.assert)(!path.startsWith('/'));
|
|
14
|
+
(0, _utils.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
|
+
|
|
21
|
+
//# sourceMappingURL=path.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/path.ts"],"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"],"names":["normalizeRelative","path","assert","startsWith","search","slice"],"mappings":";;;;+BASgBA;;;eAAAA;;;uBATO;AAShB,SAASA,kBAAkBC,IAAY;IAC5CC,IAAAA,aAAM,EAAC,CAACD,KAAKE,UAAU,CAAC;IACxBD,IAAAA,aAAM,EACJD,KAAKG,MAAM,CAAC,eAAe,CAAC,GAC5B,CAAC,MAAM,EAAEH,KAAK,8CAA8C,CAAC;IAG/D,IAAIA,KAAKE,UAAU,CAAC,OAAO;QACzB,OAAOF,KAAKI,KAAK,CAAC;IACpB;IACA,OAAOJ;AACT"}
|