@metamask/snaps-utils 0.35.1-flask.1 → 1.0.0-prerelease.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 +5 -46
- package/dist/{esm/array.js → array.js} +7 -3
- package/dist/array.js.map +1 -0
- package/dist/{types/caveats.d.ts → caveats.d.ts} +4 -0
- package/dist/caveats.js +35 -0
- package/dist/caveats.js.map +1 -0
- package/dist/checksum.js +42 -0
- package/dist/checksum.js.map +1 -0
- package/dist/cronjob.js +71 -0
- package/dist/cronjob.js.map +1 -0
- package/dist/deep-clone.js +9 -0
- package/dist/deep-clone.js.map +1 -0
- package/dist/{esm/default-endowments.js → default-endowments.js} +6 -3
- package/dist/default-endowments.js.map +1 -0
- package/dist/entropy.js +8 -0
- package/dist/entropy.js.map +1 -0
- package/dist/{cjs/eval-worker.js → eval-worker.js} +21 -22
- package/dist/eval-worker.js.map +1 -0
- package/dist/eval.js +27 -0
- package/dist/eval.js.map +1 -0
- package/dist/{esm/fs.js → fs.js} +56 -33
- package/dist/fs.js.map +1 -0
- package/dist/{types/handlers.d.ts → handlers.d.ts} +42 -5
- package/dist/handlers.js +3 -0
- package/dist/handlers.js.map +1 -0
- package/dist/{types/iframe.d.ts → iframe.d.ts} +2 -3
- package/dist/{esm/iframe.js → iframe.js} +18 -16
- package/dist/iframe.js.map +1 -0
- package/dist/iframe.test.browser.js +15 -0
- package/dist/iframe.test.browser.js.map +1 -0
- package/dist/{types/index.browser.d.ts → index.browser.d.ts} +1 -2
- package/dist/index.browser.js +37 -0
- package/dist/index.browser.js.map +1 -0
- package/dist/{types/index.d.ts → index.d.ts} +1 -2
- package/dist/index.executionenv.js +22 -0
- package/dist/index.executionenv.js.map +1 -0
- package/dist/index.js +42 -0
- package/dist/index.js.map +1 -0
- package/dist/json-rpc.js +46 -0
- package/dist/json-rpc.js.map +1 -0
- package/dist/json.d.ts +9 -0
- package/dist/json.js +18 -0
- package/dist/json.js.map +1 -0
- package/dist/{esm/logging.js → logging.js} +14 -6
- package/dist/logging.js.map +1 -0
- package/dist/manifest/index.browser.js +18 -0
- package/dist/manifest/index.browser.js.map +1 -0
- package/dist/manifest/index.js +19 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/{esm/manifest → manifest}/manifest.js +113 -98
- package/dist/manifest/manifest.js.map +1 -0
- package/dist/{types/manifest → manifest}/validation.d.ts +73 -31
- package/dist/manifest/validation.js +141 -0
- package/dist/manifest/validation.js.map +1 -0
- package/dist/{esm/mock.js → mock.js} +40 -42
- package/dist/mock.js.map +1 -0
- package/dist/namespace.d.ts +275 -0
- package/dist/namespace.js +225 -0
- package/dist/namespace.js.map +1 -0
- package/dist/notification.d.ts +66 -0
- package/dist/notification.js +58 -0
- package/dist/notification.js.map +1 -0
- package/dist/{types/npm.d.ts → npm.d.ts} +2 -0
- package/dist/npm.js +74 -0
- package/dist/npm.js.map +1 -0
- package/dist/path.js +21 -0
- package/dist/path.js.map +1 -0
- package/dist/{esm/post-process.js → post-process.js} +99 -110
- package/dist/post-process.js.map +1 -0
- package/dist/{types/snaps.d.ts → snaps.d.ts} +2 -9
- package/dist/snaps.js +202 -0
- package/dist/snaps.js.map +1 -0
- package/dist/{types/types.d.ts → types.d.ts} +5 -2
- package/dist/types.js +103 -0
- package/dist/types.js.map +1 -0
- package/dist/{esm/versions.js → versions.js} +18 -15
- package/dist/versions.js.map +1 -0
- package/dist/{esm/virtual-file → virtual-file}/VirtualFile.js +33 -47
- package/dist/virtual-file/VirtualFile.js.map +1 -0
- package/dist/virtual-file/index.browser.js +18 -0
- package/dist/virtual-file/index.browser.js.map +1 -0
- package/dist/virtual-file/index.js +19 -0
- package/dist/virtual-file/index.js.map +1 -0
- package/dist/virtual-file/toVirtualFile.js +30 -0
- package/dist/virtual-file/toVirtualFile.js.map +1 -0
- package/package.json +32 -61
- package/dist/cjs/array.js +0 -23
- package/dist/cjs/array.js.map +0 -1
- package/dist/cjs/caveats.js +0 -33
- package/dist/cjs/caveats.js.map +0 -1
- package/dist/cjs/checksum.js +0 -38
- package/dist/cjs/checksum.js.map +0 -1
- package/dist/cjs/cronjob.js +0 -84
- package/dist/cjs/cronjob.js.map +0 -1
- package/dist/cjs/deep-clone.js +0 -22
- package/dist/cjs/deep-clone.js.map +0 -1
- package/dist/cjs/default-endowments.js +0 -49
- package/dist/cjs/default-endowments.js.map +0 -1
- package/dist/cjs/entropy.js +0 -23
- package/dist/cjs/entropy.js.map +0 -1
- package/dist/cjs/enum.js +0 -16
- package/dist/cjs/enum.js.map +0 -1
- package/dist/cjs/eval-worker.js.map +0 -1
- package/dist/cjs/eval.js +0 -29
- package/dist/cjs/eval.js.map +0 -1
- package/dist/cjs/fs.js +0 -126
- package/dist/cjs/fs.js.map +0 -1
- package/dist/cjs/handlers.js +0 -6
- package/dist/cjs/handlers.js.map +0 -1
- package/dist/cjs/icon.js +0 -37
- package/dist/cjs/icon.js.map +0 -1
- package/dist/cjs/iframe.js +0 -59
- package/dist/cjs/iframe.js.map +0 -1
- package/dist/cjs/index.browser.js +0 -40
- package/dist/cjs/index.browser.js.map +0 -1
- package/dist/cjs/index.executionenv.js +0 -24
- package/dist/cjs/index.executionenv.js.map +0 -1
- package/dist/cjs/index.js +0 -45
- package/dist/cjs/index.js.map +0 -1
- package/dist/cjs/json-rpc.js +0 -46
- package/dist/cjs/json-rpc.js.map +0 -1
- package/dist/cjs/json.js +0 -16
- package/dist/cjs/json.js.map +0 -1
- package/dist/cjs/logging.js +0 -40
- package/dist/cjs/logging.js.map +0 -1
- package/dist/cjs/manifest/index.browser.js +0 -20
- package/dist/cjs/manifest/index.browser.js.map +0 -1
- package/dist/cjs/manifest/index.js +0 -21
- package/dist/cjs/manifest/index.js.map +0 -1
- package/dist/cjs/manifest/manifest.js +0 -239
- package/dist/cjs/manifest/manifest.js.map +0 -1
- package/dist/cjs/manifest/validation.js +0 -183
- package/dist/cjs/manifest/validation.js.map +0 -1
- package/dist/cjs/mock.js +0 -128
- package/dist/cjs/mock.js.map +0 -1
- package/dist/cjs/namespace.js +0 -124
- package/dist/cjs/namespace.js.map +0 -1
- package/dist/cjs/npm.js +0 -81
- package/dist/cjs/npm.js.map +0 -1
- package/dist/cjs/path.js +0 -21
- package/dist/cjs/path.js.map +0 -1
- package/dist/cjs/post-process.js +0 -328
- package/dist/cjs/post-process.js.map +0 -1
- package/dist/cjs/snaps.js +0 -230
- package/dist/cjs/snaps.js.map +0 -1
- package/dist/cjs/types.js +0 -117
- package/dist/cjs/types.js.map +0 -1
- package/dist/cjs/validation.js +0 -22
- package/dist/cjs/validation.js.map +0 -1
- package/dist/cjs/versions.js +0 -47
- package/dist/cjs/versions.js.map +0 -1
- package/dist/cjs/virtual-file/VirtualFile.js +0 -85
- package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
- package/dist/cjs/virtual-file/index.browser.js +0 -20
- package/dist/cjs/virtual-file/index.browser.js.map +0 -1
- package/dist/cjs/virtual-file/index.js +0 -21
- package/dist/cjs/virtual-file/index.js.map +0 -1
- package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
- package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
- package/dist/esm/array.js.map +0 -1
- package/dist/esm/caveats.js +0 -23
- package/dist/esm/caveats.js.map +0 -1
- package/dist/esm/checksum.js +0 -36
- package/dist/esm/checksum.js.map +0 -1
- package/dist/esm/cronjob.js +0 -66
- package/dist/esm/cronjob.js.map +0 -1
- package/dist/esm/deep-clone.js +0 -7
- package/dist/esm/deep-clone.js.map +0 -1
- package/dist/esm/default-endowments.js.map +0 -1
- package/dist/esm/entropy.js +0 -6
- package/dist/esm/entropy.js.map +0 -1
- package/dist/esm/enum.js +0 -12
- package/dist/esm/enum.js.map +0 -1
- package/dist/esm/eval-worker.js +0 -47
- package/dist/esm/eval-worker.js.map +0 -1
- package/dist/esm/eval.js +0 -25
- package/dist/esm/eval.js.map +0 -1
- package/dist/esm/fs.js.map +0 -1
- package/dist/esm/handlers.js +0 -3
- package/dist/esm/handlers.js.map +0 -1
- package/dist/esm/icon.js +0 -11
- package/dist/esm/icon.js.map +0 -1
- package/dist/esm/iframe.js.map +0 -1
- package/dist/esm/index.browser.js +0 -23
- package/dist/esm/index.browser.js.map +0 -1
- package/dist/esm/index.executionenv.js +0 -7
- package/dist/esm/index.executionenv.js.map +0 -1
- package/dist/esm/index.js +0 -28
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/json-rpc.js +0 -39
- package/dist/esm/json-rpc.js.map +0 -1
- package/dist/esm/json.js +0 -17
- package/dist/esm/json.js.map +0 -1
- package/dist/esm/logging.js.map +0 -1
- package/dist/esm/manifest/index.browser.js +0 -3
- package/dist/esm/manifest/index.browser.js.map +0 -1
- package/dist/esm/manifest/index.js +0 -4
- package/dist/esm/manifest/index.js.map +0 -1
- package/dist/esm/manifest/manifest.js.map +0 -1
- package/dist/esm/manifest/validation.js +0 -152
- package/dist/esm/manifest/validation.js.map +0 -1
- package/dist/esm/mock.js.map +0 -1
- package/dist/esm/namespace.js +0 -110
- package/dist/esm/namespace.js.map +0 -1
- package/dist/esm/npm.js +0 -70
- package/dist/esm/npm.js.map +0 -1
- package/dist/esm/path.js +0 -17
- package/dist/esm/path.js.map +0 -1
- package/dist/esm/post-process.js.map +0 -1
- package/dist/esm/snaps.js +0 -215
- package/dist/esm/snaps.js.map +0 -1
- package/dist/esm/types.js +0 -85
- package/dist/esm/types.js.map +0 -1
- package/dist/esm/validation.js +0 -17
- package/dist/esm/validation.js.map +0 -1
- package/dist/esm/versions.js.map +0 -1
- package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
- package/dist/esm/virtual-file/index.browser.js +0 -3
- package/dist/esm/virtual-file/index.browser.js.map +0 -1
- package/dist/esm/virtual-file/index.js +0 -4
- package/dist/esm/virtual-file/index.js.map +0 -1
- package/dist/esm/virtual-file/toVirtualFile.js +0 -26
- package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
- package/dist/types/enum.d.ts +0 -30
- package/dist/types/icon.d.ts +0 -4
- package/dist/types/json.d.ts +0 -13
- package/dist/types/namespace.d.ts +0 -124
- package/dist/types/validation.d.ts +0 -8
- /package/dist/{types/array.d.ts → array.d.ts} +0 -0
- /package/dist/{types/checksum.d.ts → checksum.d.ts} +0 -0
- /package/dist/{types/cronjob.d.ts → cronjob.d.ts} +0 -0
- /package/dist/{types/deep-clone.d.ts → deep-clone.d.ts} +0 -0
- /package/dist/{types/default-endowments.d.ts → default-endowments.d.ts} +0 -0
- /package/dist/{types/entropy.d.ts → entropy.d.ts} +0 -0
- /package/dist/{types/eval-worker.d.ts → eval-worker.d.ts} +0 -0
- /package/dist/{types/eval.d.ts → eval.d.ts} +0 -0
- /package/dist/{types/fs.d.ts → fs.d.ts} +0 -0
- /package/dist/{types/iframe.test.browser.d.ts → iframe.test.browser.d.ts} +0 -0
- /package/dist/{types/index.executionenv.d.ts → index.executionenv.d.ts} +0 -0
- /package/dist/{types/json-rpc.d.ts → json-rpc.d.ts} +0 -0
- /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
- /package/dist/{types/manifest → manifest}/index.browser.d.ts +0 -0
- /package/dist/{types/manifest → manifest}/index.d.ts +0 -0
- /package/dist/{types/manifest → manifest}/manifest.d.ts +0 -0
- /package/dist/{types/mock.d.ts → mock.d.ts} +0 -0
- /package/dist/{types/path.d.ts → path.d.ts} +0 -0
- /package/dist/{types/post-process.d.ts → post-process.d.ts} +0 -0
- /package/dist/{types/versions.d.ts → versions.d.ts} +0 -0
- /package/dist/{types/virtual-file → virtual-file}/VirtualFile.d.ts +0 -0
- /package/dist/{types/virtual-file → virtual-file}/index.browser.d.ts +0 -0
- /package/dist/{types/virtual-file → virtual-file}/index.d.ts +0 -0
- /package/dist/{types/virtual-file → virtual-file}/toVirtualFile.d.ts +0 -0
package/dist/esm/snaps.js
DELETED
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
function _define_property(obj, key, value) {
|
|
2
|
-
if (key in obj) {
|
|
3
|
-
Object.defineProperty(obj, key, {
|
|
4
|
-
value: value,
|
|
5
|
-
enumerable: true,
|
|
6
|
-
configurable: true,
|
|
7
|
-
writable: true
|
|
8
|
-
});
|
|
9
|
-
} else {
|
|
10
|
-
obj[key] = value;
|
|
11
|
-
}
|
|
12
|
-
return obj;
|
|
13
|
-
}
|
|
14
|
-
import { assert, isObject, assertStruct } from '@metamask/utils';
|
|
15
|
-
import { base64 } from '@scure/base';
|
|
16
|
-
import stableStringify from 'fast-json-stable-stringify';
|
|
17
|
-
import { empty, enums, intersection, literal, pattern, refine, string, union, validate } from 'superstruct';
|
|
18
|
-
import validateNPMPackage from 'validate-npm-package-name';
|
|
19
|
-
import { SnapCaveatType } from './caveats';
|
|
20
|
-
import { checksumFiles } from './checksum';
|
|
21
|
-
import { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';
|
|
22
|
-
// This RegEx matches valid npm package names (with some exceptions) and space-
|
|
23
|
-
// separated alphanumerical words, optionally with dashes and underscores.
|
|
24
|
-
// The RegEx consists of two parts. The first part matches space-separated
|
|
25
|
-
// words. It is based on the following Stackoverflow answer:
|
|
26
|
-
// https://stackoverflow.com/a/34974982
|
|
27
|
-
// The second part, after the pipe operator, is the same RegEx used for the
|
|
28
|
-
// `name` field of the official package.json JSON Schema, except that we allow
|
|
29
|
-
// mixed-case letters. It was originally copied from:
|
|
30
|
-
// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138
|
|
31
|
-
export const 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;
|
|
32
|
-
export var SnapStatus;
|
|
33
|
-
(function(SnapStatus) {
|
|
34
|
-
SnapStatus["Installing"] = 'installing';
|
|
35
|
-
SnapStatus["Updating"] = 'updating';
|
|
36
|
-
SnapStatus["Running"] = 'running';
|
|
37
|
-
SnapStatus["Stopped"] = 'stopped';
|
|
38
|
-
SnapStatus["Crashed"] = 'crashed';
|
|
39
|
-
})(SnapStatus || (SnapStatus = {}));
|
|
40
|
-
export var SnapStatusEvents;
|
|
41
|
-
(function(SnapStatusEvents) {
|
|
42
|
-
SnapStatusEvents["Start"] = 'START';
|
|
43
|
-
SnapStatusEvents["Stop"] = 'STOP';
|
|
44
|
-
SnapStatusEvents["Crash"] = 'CRASH';
|
|
45
|
-
SnapStatusEvents["Update"] = 'UPDATE';
|
|
46
|
-
})(SnapStatusEvents || (SnapStatusEvents = {}));
|
|
47
|
-
/**
|
|
48
|
-
* An error indicating that a Snap validation failure is programmatically
|
|
49
|
-
* fixable during development.
|
|
50
|
-
*/ export class ProgrammaticallyFixableSnapError extends Error {
|
|
51
|
-
constructor(message, reason){
|
|
52
|
-
super(message);
|
|
53
|
-
_define_property(this, "reason", void 0);
|
|
54
|
-
this.reason = reason;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.
|
|
59
|
-
*
|
|
60
|
-
* @param manifest - The manifest itself.
|
|
61
|
-
* @returns A virtual file containing the checksummable manifest.
|
|
62
|
-
*/ function getChecksummableManifest(manifest) {
|
|
63
|
-
const manifestCopy = manifest.clone();
|
|
64
|
-
delete manifestCopy.result.source.shasum;
|
|
65
|
-
// We use fast-json-stable-stringify to deterministically serialize the JSON
|
|
66
|
-
// This is required before checksumming so we get reproducible checksums across platforms etc
|
|
67
|
-
manifestCopy.value = stableStringify(manifestCopy.result);
|
|
68
|
-
return manifestCopy;
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Calculates the Base64-encoded SHA-256 digest of all required Snap files.
|
|
72
|
-
*
|
|
73
|
-
* @param files - All required Snap files to be included in the checksum.
|
|
74
|
-
* @returns The Base64-encoded SHA-256 digest of the source code.
|
|
75
|
-
*/ export function getSnapChecksum(files) {
|
|
76
|
-
const { manifest, sourceCode, svgIcon } = files;
|
|
77
|
-
const all = [
|
|
78
|
-
getChecksummableManifest(manifest),
|
|
79
|
-
sourceCode,
|
|
80
|
-
svgIcon
|
|
81
|
-
].filter((file)=>file !== undefined);
|
|
82
|
-
return base64.encode(checksumFiles(all));
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Checks whether the `source.shasum` property of a Snap manifest matches the
|
|
86
|
-
* shasum of the snap.
|
|
87
|
-
*
|
|
88
|
-
* @param files - All required Snap files to be included in the checksum.
|
|
89
|
-
* @param errorMessage - The error message to throw if validation fails.
|
|
90
|
-
*/ export function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
|
|
91
|
-
if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {
|
|
92
|
-
throw new ProgrammaticallyFixableSnapError(errorMessage, SnapValidationFailureReason.ShasumMismatch);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
export const LOCALHOST_HOSTNAMES = [
|
|
96
|
-
'localhost',
|
|
97
|
-
'127.0.0.1',
|
|
98
|
-
'[::1]'
|
|
99
|
-
];
|
|
100
|
-
// Require snap ids to only consist of printable ASCII characters
|
|
101
|
-
export const BaseSnapIdStruct = pattern(string(), /^[\x21-\x7E]*$/u);
|
|
102
|
-
const LocalSnapIdSubUrlStruct = uri({
|
|
103
|
-
protocol: enums([
|
|
104
|
-
'http:',
|
|
105
|
-
'https:'
|
|
106
|
-
]),
|
|
107
|
-
hostname: enums(LOCALHOST_HOSTNAMES),
|
|
108
|
-
hash: empty(string()),
|
|
109
|
-
search: empty(string())
|
|
110
|
-
});
|
|
111
|
-
export const LocalSnapIdStruct = refine(BaseSnapIdStruct, 'local Snap Id', (value)=>{
|
|
112
|
-
if (!value.startsWith(SnapIdPrefixes.local)) {
|
|
113
|
-
return `Expected local snap ID, got "${value}".`;
|
|
114
|
-
}
|
|
115
|
-
const [error] = validate(value.slice(SnapIdPrefixes.local.length), LocalSnapIdSubUrlStruct);
|
|
116
|
-
return error ?? true;
|
|
117
|
-
});
|
|
118
|
-
export const NpmSnapIdStruct = intersection([
|
|
119
|
-
BaseSnapIdStruct,
|
|
120
|
-
uri({
|
|
121
|
-
protocol: literal(SnapIdPrefixes.npm),
|
|
122
|
-
pathname: refine(string(), 'package name', function*(value) {
|
|
123
|
-
const normalized = value.startsWith('/') ? value.slice(1) : value;
|
|
124
|
-
const { errors, validForNewPackages, warnings } = validateNPMPackage(normalized);
|
|
125
|
-
if (!validForNewPackages) {
|
|
126
|
-
if (errors === undefined) {
|
|
127
|
-
assert(warnings !== undefined);
|
|
128
|
-
yield* warnings;
|
|
129
|
-
} else {
|
|
130
|
-
yield* errors;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return true;
|
|
134
|
-
}),
|
|
135
|
-
search: empty(string()),
|
|
136
|
-
hash: empty(string())
|
|
137
|
-
})
|
|
138
|
-
]);
|
|
139
|
-
export const HttpSnapIdStruct = intersection([
|
|
140
|
-
BaseSnapIdStruct,
|
|
141
|
-
uri({
|
|
142
|
-
protocol: enums([
|
|
143
|
-
'http:',
|
|
144
|
-
'https:'
|
|
145
|
-
]),
|
|
146
|
-
search: empty(string()),
|
|
147
|
-
hash: empty(string())
|
|
148
|
-
})
|
|
149
|
-
]);
|
|
150
|
-
export const SnapIdStruct = union([
|
|
151
|
-
NpmSnapIdStruct,
|
|
152
|
-
LocalSnapIdStruct
|
|
153
|
-
]);
|
|
154
|
-
/**
|
|
155
|
-
* Extracts the snap prefix from a snap ID.
|
|
156
|
-
*
|
|
157
|
-
* @param snapId - The snap ID to extract the prefix from.
|
|
158
|
-
* @returns The snap prefix from a snap id, e.g. `npm:`.
|
|
159
|
-
*/ export function getSnapPrefix(snapId) {
|
|
160
|
-
const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix)=>snapId.startsWith(possiblePrefix));
|
|
161
|
-
if (prefix !== undefined) {
|
|
162
|
-
return prefix;
|
|
163
|
-
}
|
|
164
|
-
throw new Error(`Invalid or no prefix found for "${snapId}"`);
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Strips snap prefix from a full snap ID.
|
|
168
|
-
*
|
|
169
|
-
* @param snapId - The snap ID to strip.
|
|
170
|
-
* @returns The stripped snap ID.
|
|
171
|
-
*/ export function stripSnapPrefix(snapId) {
|
|
172
|
-
return snapId.replace(getSnapPrefix(snapId), '');
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Assert that the given value is a valid snap ID.
|
|
176
|
-
*
|
|
177
|
-
* @param value - The value to check.
|
|
178
|
-
* @throws If the value is not a valid snap ID.
|
|
179
|
-
*/ export function assertIsValidSnapId(value) {
|
|
180
|
-
assertStruct(value, SnapIdStruct, 'Invalid snap ID');
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* Typeguard to ensure a chainId follows the CAIP-2 standard.
|
|
184
|
-
*
|
|
185
|
-
* @param chainId - The chainId being tested.
|
|
186
|
-
* @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.
|
|
187
|
-
*/ export function isCaipChainId(chainId) {
|
|
188
|
-
return typeof chainId === 'string' && RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u").test(chainId);
|
|
189
|
-
}
|
|
190
|
-
/**
|
|
191
|
-
* Utility function to check if an origin has permission (and caveat) for a particular snap.
|
|
192
|
-
*
|
|
193
|
-
* @param permissions - An origin's permissions object.
|
|
194
|
-
* @param snapId - The id of the snap.
|
|
195
|
-
* @returns A boolean based on if an origin has the specified snap.
|
|
196
|
-
*/ export function isSnapPermitted(permissions, snapId) {
|
|
197
|
-
return Boolean((permissions?.wallet_snap?.caveats?.find((caveat)=>caveat.type === SnapCaveatType.SnapIds) ?? {}).value?.[snapId]);
|
|
198
|
-
}
|
|
199
|
-
/**
|
|
200
|
-
* Checks whether the passed in requestedPermissions is a valid
|
|
201
|
-
* permission request for a `wallet_snap` permission.
|
|
202
|
-
*
|
|
203
|
-
* @param requestedPermissions - The requested permissions.
|
|
204
|
-
* @throws If the criteria is not met.
|
|
205
|
-
*/ export function verifyRequestedSnapPermissions(requestedPermissions) {
|
|
206
|
-
assert(isObject(requestedPermissions), 'Requested permissions must be an object.');
|
|
207
|
-
const { wallet_snap: walletSnapPermission } = requestedPermissions;
|
|
208
|
-
assert(isObject(walletSnapPermission), 'wallet_snap is missing from the requested permissions.');
|
|
209
|
-
const { caveats } = walletSnapPermission;
|
|
210
|
-
assert(Array.isArray(caveats) && caveats.length === 1, 'wallet_snap must have a caveat property with a single-item array value.');
|
|
211
|
-
const [caveat] = caveats;
|
|
212
|
-
assert(isObject(caveat) && caveat.type === SnapCaveatType.SnapIds && isObject(caveat.value), `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
//# sourceMappingURL=snaps.js.map
|
package/dist/esm/snaps.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/snaps.ts"],"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: ValidatedSnapId };\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 * The source code of the Snap.\n */\n sourceCode: string;\n};\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: ValidatedSnapId;\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 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 * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(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"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":"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"}
|
package/dist/esm/types.js
DELETED
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import { assertStruct, VersionStruct } from '@metamask/utils';
|
|
2
|
-
import { instance, is, object, optional, pattern, refine, size, string, type, union, assert as assertSuperstruct } from 'superstruct';
|
|
3
|
-
export var NpmSnapFileNames;
|
|
4
|
-
(function(NpmSnapFileNames) {
|
|
5
|
-
NpmSnapFileNames["PackageJson"] = 'package.json';
|
|
6
|
-
NpmSnapFileNames["Manifest"] = 'snap.manifest.json';
|
|
7
|
-
})(NpmSnapFileNames || (NpmSnapFileNames = {}));
|
|
8
|
-
export const NameStruct = size(pattern(string(), /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/u), 1, 214);
|
|
9
|
-
// Note we use `type` instead of `object` here, because the latter does not
|
|
10
|
-
// allow unknown keys.
|
|
11
|
-
export const NpmSnapPackageJsonStruct = type({
|
|
12
|
-
version: VersionStruct,
|
|
13
|
-
name: NameStruct,
|
|
14
|
-
main: optional(size(string(), 1, Infinity)),
|
|
15
|
-
repository: optional(object({
|
|
16
|
-
type: size(string(), 1, Infinity),
|
|
17
|
-
url: size(string(), 1, Infinity)
|
|
18
|
-
}))
|
|
19
|
-
});
|
|
20
|
-
/**
|
|
21
|
-
* Check if the given value is a valid {@link NpmSnapPackageJson} object.
|
|
22
|
-
*
|
|
23
|
-
* @param value - The value to check.
|
|
24
|
-
* @returns Whether the value is a valid {@link NpmSnapPackageJson} object.
|
|
25
|
-
*/ export function isNpmSnapPackageJson(value) {
|
|
26
|
-
return is(value, NpmSnapPackageJsonStruct);
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Asserts that the given value is a valid {@link NpmSnapPackageJson} object.
|
|
30
|
-
*
|
|
31
|
-
* @param value - The value to check.
|
|
32
|
-
* @throws If the value is not a valid {@link NpmSnapPackageJson} object.
|
|
33
|
-
*/ export function assertIsNpmSnapPackageJson(value) {
|
|
34
|
-
assertStruct(value, NpmSnapPackageJsonStruct, `"${NpmSnapFileNames.PackageJson}" is invalid`);
|
|
35
|
-
}
|
|
36
|
-
export var SnapIdPrefixes;
|
|
37
|
-
(function(SnapIdPrefixes) {
|
|
38
|
-
SnapIdPrefixes["npm"] = 'npm:';
|
|
39
|
-
SnapIdPrefixes["local"] = 'local:';
|
|
40
|
-
})(SnapIdPrefixes || (SnapIdPrefixes = {}));
|
|
41
|
-
export var SnapValidationFailureReason;
|
|
42
|
-
(function(SnapValidationFailureReason) {
|
|
43
|
-
SnapValidationFailureReason["NameMismatch"] = '"name" field mismatch';
|
|
44
|
-
SnapValidationFailureReason["VersionMismatch"] = '"version" field mismatch';
|
|
45
|
-
SnapValidationFailureReason["RepositoryMismatch"] = '"repository" field mismatch';
|
|
46
|
-
SnapValidationFailureReason["ShasumMismatch"] = '"shasum" field mismatch';
|
|
47
|
-
})(SnapValidationFailureReason || (SnapValidationFailureReason = {}));
|
|
48
|
-
export var SNAP_STREAM_NAMES;
|
|
49
|
-
(function(SNAP_STREAM_NAMES) {
|
|
50
|
-
SNAP_STREAM_NAMES["JSON_RPC"] = 'jsonRpc';
|
|
51
|
-
SNAP_STREAM_NAMES["COMMAND"] = 'command';
|
|
52
|
-
})(SNAP_STREAM_NAMES || (SNAP_STREAM_NAMES = {}));
|
|
53
|
-
export var HandlerType;
|
|
54
|
-
(function(HandlerType) {
|
|
55
|
-
HandlerType["OnRpcRequest"] = 'onRpcRequest';
|
|
56
|
-
HandlerType["OnTransaction"] = 'onTransaction';
|
|
57
|
-
HandlerType["OnCronjob"] = 'onCronjob';
|
|
58
|
-
})(HandlerType || (HandlerType = {}));
|
|
59
|
-
export const SNAP_EXPORT_NAMES = Object.values(HandlerType);
|
|
60
|
-
export const uri = (opts = {})=>refine(union([
|
|
61
|
-
string(),
|
|
62
|
-
instance(URL)
|
|
63
|
-
]), 'uri', (value)=>{
|
|
64
|
-
try {
|
|
65
|
-
const url = new URL(value);
|
|
66
|
-
const UrlStruct = type(opts);
|
|
67
|
-
assertSuperstruct(url, UrlStruct);
|
|
68
|
-
return true;
|
|
69
|
-
} catch {
|
|
70
|
-
return `Expected URL, got "${value.toString()}".`;
|
|
71
|
-
}
|
|
72
|
-
});
|
|
73
|
-
/**
|
|
74
|
-
* Returns whether a given value is a valid URL.
|
|
75
|
-
*
|
|
76
|
-
* @param url - The value to check.
|
|
77
|
-
* @param opts - Optional constraints for url checking.
|
|
78
|
-
* @returns Whether `url` is valid URL or not.
|
|
79
|
-
*/ export function isValidUrl(url, opts = {}) {
|
|
80
|
-
return is(url, uri(opts));
|
|
81
|
-
}
|
|
82
|
-
// redefining here to avoid circular dependency
|
|
83
|
-
export const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';
|
|
84
|
-
|
|
85
|
-
//# sourceMappingURL=types.js.map
|
package/dist/esm/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types.ts"],"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 } 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 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\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\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"],"names":["assertStruct","VersionStruct","instance","is","object","optional","pattern","refine","size","string","type","union","assert","assertSuperstruct","NpmSnapFileNames","PackageJson","Manifest","NameStruct","NpmSnapPackageJsonStruct","version","name","main","Infinity","repository","url","isNpmSnapPackageJson","value","assertIsNpmSnapPackageJson","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","SNAP_EXPORT_NAMES","Object","values","uri","opts","URL","UrlStruct","toString","isValidUrl","WALLET_SNAP_PERMISSION_KEY"],"mappings":"AAAA,SAASA,YAAY,EAAQC,aAAa,QAAQ,kBAAkB;AACpE,SAEEC,QAAQ,EACRC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,IAAI,EACJC,MAAM,EAENC,IAAI,EACJC,KAAK,EACLC,UAAUC,iBAAiB,QACtB,cAAc;WAOd;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKZ,OAAO,MAAMG,aAAaT,KACxBF,QACEG,UACA,gEAEF,GACA,KACA;AAEF,2EAA2E;AAC3E,sBAAsB;AACtB,OAAO,MAAMS,2BAA2BR,KAAK;IAC3CS,SAASlB;IACTmB,MAAMH;IACNI,MAAMhB,SAASG,KAAKC,UAAU,GAAGa;IACjCC,YAAYlB,SACVD,OAAO;QACLM,MAAMF,KAAKC,UAAU,GAAGa;QACxBE,KAAKhB,KAAKC,UAAU,GAAGa;IACzB;AAEJ,GAAG;AAKH;;;;;CAKC,GACD,OAAO,SAASG,qBACdC,KAAc;IAEd,OAAOvB,GAAGuB,OAAOR;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASS,2BACdD,KAAc;IAEd1B,aACE0B,OACAR,0BACA,CAAC,CAAC,EAAEJ,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;WA2BO;UAAKa,cAAc;IAAdA,eACVC,SAAM;IADID,eAEVE,WAAQ;GAFEF,mBAAAA;WAYL;UAAKG,2BAA2B;IAA3BA,4BACVC,kBAAe;IADLD,4BAEVE,qBAAkB;IAFRF,4BAGVG,wBAAqB;IAHXH,4BAIVI,oBAAiB;GAJPJ,gCAAAA;WAQL;UAAKK,iBAAiB;IAAjBA,kBACVC,cAAW;IADDD,kBAEVE,aAAU;GAFAF,sBAAAA;WAML;UAAKG,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;GAHFH,gBAAAA;AAMZ,OAAO,MAAMI,oBAAoBC,OAAOC,MAAM,CAACN,aAAa;AAyB5D,OAAO,MAAMO,MAAM,CAACC,OAAwB,CAAC,CAAC,GAC5CxC,OAAOI,MAAM;QAACF;QAAUP,SAAS8C;KAAK,GAAG,OAAO,CAACtB;QAC/C,IAAI;YACF,MAAMF,MAAM,IAAIwB,IAAItB;YAEpB,MAAMuB,YAAYvC,KAAKqC;YACvBlC,kBAAkBW,KAAKyB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEvB,MAAMwB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF,GAAG;AAEL;;;;;;CAMC,GACD,OAAO,SAASC,WACd3B,GAAY,EACZuB,OAAwB,CAAC,CAAC;IAE1B,OAAO5C,GAAGqB,KAAKsB,IAAIC;AACrB;AAEA,+CAA+C;AAC/C,OAAO,MAAMK,6BAA6B,cAAc"}
|
package/dist/esm/validation.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { assertIsSnapIcon } from './icon';
|
|
2
|
-
import { assertIsSnapManifest } from './manifest/validation';
|
|
3
|
-
import { validateSnapShasum } from './snaps';
|
|
4
|
-
/**
|
|
5
|
-
* Validates the files contained in a fetched snap.
|
|
6
|
-
*
|
|
7
|
-
* @param files - All potentially included files in a fetched snap.
|
|
8
|
-
* @throws If any of the files are considered invalid.
|
|
9
|
-
*/ export function validateFetchedSnap(files) {
|
|
10
|
-
assertIsSnapManifest(files.manifest.result);
|
|
11
|
-
validateSnapShasum(files);
|
|
12
|
-
if (files.svgIcon) {
|
|
13
|
-
assertIsSnapIcon(files.svgIcon);
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
//# sourceMappingURL=validation.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport { SnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["assertIsSnapIcon","assertIsSnapManifest","validateSnapShasum","validateFetchedSnap","files","manifest","result","svgIcon"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,kBAAkB,QAAQ,UAAU;AAG7C;;;;;CAKC,GACD,OAAO,SAASC,oBACdC,KAA6D;IAE7DH,qBAAqBG,MAAMC,QAAQ,CAACC,MAAM;IAC1CJ,mBAAmBE;IAEnB,IAAIA,MAAMG,OAAO,EAAE;QACjBP,iBAAiBI,MAAMG,OAAO;IAChC;AACF"}
|
package/dist/esm/versions.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/versions.ts"],"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"],"names":["VersionRangeStruct","maxSatisfying","maxSatisfyingSemver","validate","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","versions","versionRange","maxSatisfyingNonPreRelease","includePrerelease","resolveVersionRange","version","undefined"],"mappings":"AAAA,SAIEA,kBAAkB,QACb,kBAAkB;AACzB,SAASC,iBAAiBC,mBAAmB,QAAQ,SAAS;AAC9D,SAASC,QAAQ,QAAQ,cAAc;AAEvC,OAAO,MAAMC,iCAAiC,IAAmB;AAEjE;;;;;;;;;CASC,GACD,OAAO,SAASC,iBACdC,QAAyB,EACzBC,YAAyB;IAEzB,MAAMC,6BAA6BN,oBACjCI,UACAC;IAGF,4CAA4C;IAC5C,IAAIC,4BAA4B;QAC9B,OAAOA;IACT;IAEA,iFAAiF;IACjF,OAAON,oBAAoBI,UAAUC,cAAc;QACjDE,mBAAmB;IACrB;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,oBACdC,OAAc;IAEd,IAAIA,YAAYC,aAAaD,YAAY,UAAU;QACjD,OAAO;YAACC;YAAWR;SAA+B;IACpD;IACA,OAAOD,SAASQ,SAASX;AAC3B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/virtual-file/VirtualFile.ts"],"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"],"names":["assert","deepClone","VirtualFile","toString","encoding","value","undefined","decoder","TextDecoder","decode","clone","vfile","slice","result","data","path","constructor","options","Uint8Array"],"mappings":"AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;;;;;;;;;;;;;;AACtD,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,SAAS,QAAQ,gBAAgB;AA+B1C,OAAO,MAAMC;IAgCXC,SAASC,QAAiB,EAAE;QAC1B,IAAI,OAAO,IAAI,CAACC,KAAK,KAAK,UAAU;YAClCL,OAAOI,aAAaE,WAAW;YAC/B,OAAO,IAAI,CAACD,KAAK;QACnB;QACA,MAAME,UAAU,IAAIC,YAAYJ;QAChC,OAAOG,QAAQE,MAAM,CAAC,IAAI,CAACJ,KAAK;IAClC;IAEAK,QAAQ;QACN,MAAMC,QAAQ,IAAIT;QAClB,IAAI,OAAO,IAAI,CAACG,KAAK,KAAK,UAAU;YAClCM,MAAMN,KAAK,GAAG,IAAI,CAACA,KAAK;QAC1B,OAAO;YACL,mFAAmF;YACnFM,MAAMN,KAAK,GAAG,IAAI,CAACA,KAAK,CAACO,KAAK,CAAC;QACjC;QACAD,MAAME,MAAM,GAAGZ,UAAU,IAAI,CAACY,MAAM;QACpCF,MAAMG,IAAI,GAAGb,UAAU,IAAI,CAACa,IAAI;QAChCH,MAAMI,IAAI,GAAG,IAAI,CAACA,IAAI;QACtB,OAAOJ;IACT;IApDAK,YAAYX,KAA0B,CAAE;QAuBxCA,uBAAAA,SAAAA,KAAAA;QAEAQ,uBAAAA,UAAAA,KAAAA;QAEAC,uBAAAA,QAAAA,KAAAA;QAEAC,uBAAAA,QAAAA,KAAAA;QA5BE,IAAIE;QACJ,IAAI,OAAOZ,UAAU,YAAYA,iBAAiBa,YAAY;YAC5DD,UAAU;gBAAEZ;YAAM;QACpB,OAAO;YACLY,UAAUZ;QACZ;QAEA,IAAI,CAACA,KAAK,GAAGY,SAASZ,SAAS;QAC/B,wDAAwD;QACxD,gEAAgE;QAChE,4DAA4D;QAC5D,EAAE;QACF,wEAAwE;QACxE,4EAA4E;QAC5E,8EAA8E;QAC9E,EAAE;QACF,iDAAiD;QACjD,IAAI,CAACQ,MAAM,GAAGI,SAASJ,UAAWP;QAClC,IAAI,CAACQ,IAAI,GAAGG,SAASH,QAAQ,CAAC;QAC9B,IAAI,CAACC,IAAI,GAAGE,SAASF,QAAQ;IAC/B;AAgCF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/virtual-file/index.browser.ts"],"sourcesContent":["export * from './VirtualFile';\n"],"names":[],"mappings":"AAAA,cAAc,gBAAgB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/virtual-file/index.ts"],"sourcesContent":["export * from './toVirtualFile';\nexport * from './VirtualFile';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB;AAChC,cAAc,gBAAgB"}
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { promises as fsPromises } from 'fs';
|
|
2
|
-
import { VirtualFile } from './VirtualFile';
|
|
3
|
-
/**
|
|
4
|
-
* Reads a file from filesystem and creates a vfile.
|
|
5
|
-
*
|
|
6
|
-
* @param path - Filesystem path to load the contents from.
|
|
7
|
-
* @param encoding - Optional encoding to pass down to fs.readFile.
|
|
8
|
-
* @returns Promise returning VFile with loaded file contents.
|
|
9
|
-
*/ export async function readVirtualFile(path, encoding = null) {
|
|
10
|
-
return new VirtualFile({
|
|
11
|
-
path,
|
|
12
|
-
value: await fsPromises.readFile(path, {
|
|
13
|
-
encoding
|
|
14
|
-
})
|
|
15
|
-
});
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Writes vfile to filesystem.
|
|
19
|
-
*
|
|
20
|
-
* @param vfile - The vfile to write.
|
|
21
|
-
* @param options - Options to pass down to fs.writeFile.
|
|
22
|
-
*/ export async function writeVirtualFile(vfile, options) {
|
|
23
|
-
return fsPromises.writeFile(vfile.path, vfile.value, options);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
//# sourceMappingURL=toVirtualFile.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/virtual-file/toVirtualFile.ts"],"sourcesContent":["import { promises as fsPromises } from 'fs';\n\nimport { VirtualFile } from './VirtualFile';\n\n/**\n * Reads a file from filesystem and creates a vfile.\n *\n * @param path - Filesystem path to load the contents from.\n * @param encoding - Optional encoding to pass down to fs.readFile.\n * @returns Promise returning VFile with loaded file contents.\n */\nexport async function readVirtualFile(\n path: string,\n encoding: BufferEncoding | null = null,\n) {\n return new VirtualFile({\n path,\n value: await fsPromises.readFile(path, { encoding }),\n });\n}\n\ntype WriteVFileOptions = Exclude<\n Parameters<typeof fsPromises['writeFile']>[2],\n undefined\n>;\n\n/**\n * Writes vfile to filesystem.\n *\n * @param vfile - The vfile to write.\n * @param options - Options to pass down to fs.writeFile.\n */\nexport async function writeVirtualFile(\n vfile: VirtualFile,\n options?: WriteVFileOptions,\n) {\n return fsPromises.writeFile(vfile.path, vfile.value, options);\n}\n"],"names":["promises","fsPromises","VirtualFile","readVirtualFile","path","encoding","value","readFile","writeVirtualFile","vfile","options","writeFile"],"mappings":"AAAA,SAASA,YAAYC,UAAU,QAAQ,KAAK;AAE5C,SAASC,WAAW,QAAQ,gBAAgB;AAE5C;;;;;;CAMC,GACD,OAAO,eAAeC,gBACpBC,IAAY,EACZC,WAAkC,IAAI;IAEtC,OAAO,IAAIH,YAAY;QACrBE;QACAE,OAAO,MAAML,WAAWM,QAAQ,CAACH,MAAM;YAAEC;QAAS;IACpD;AACF;AAOA;;;;;CAKC,GACD,OAAO,eAAeG,iBACpBC,KAAkB,EAClBC,OAA2B;IAE3B,OAAOT,WAAWU,SAAS,CAACF,MAAML,IAAI,EAAEK,MAAMH,KAAK,EAAEI;AACvD"}
|
package/dist/types/enum.d.ts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { Struct } from 'superstruct';
|
|
2
|
-
/**
|
|
3
|
-
* Get the enum values as union type. This allows using both the enum string
|
|
4
|
-
* values and the enum itself as values.
|
|
5
|
-
*
|
|
6
|
-
* Note: This only works for string enums.
|
|
7
|
-
*
|
|
8
|
-
* @example
|
|
9
|
-
* ```typescript
|
|
10
|
-
* enum Foo {
|
|
11
|
-
* Bar = 'bar',
|
|
12
|
-
* Baz = 'baz',
|
|
13
|
-
* }
|
|
14
|
-
*
|
|
15
|
-
* type FooValue = EnumToUnion<Foo>;
|
|
16
|
-
* // FooValue is 'bar' | 'baz'
|
|
17
|
-
*
|
|
18
|
-
* const foo: FooValue = Foo.Bar; // Works
|
|
19
|
-
* const foo: FooValue = 'bar'; // Also works
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
export declare type EnumToUnion<Type extends string> = `${Type}`;
|
|
23
|
-
/**
|
|
24
|
-
* Superstruct struct for validating an enum value. This allows using both the
|
|
25
|
-
* enum string values and the enum itself as values.
|
|
26
|
-
*
|
|
27
|
-
* @param constant - The enum to validate against.
|
|
28
|
-
* @returns The superstruct struct.
|
|
29
|
-
*/
|
|
30
|
-
export declare function enumValue<Type extends string>(constant: Type): Struct<EnumToUnion<Type>, EnumToUnion<Type>>;
|
package/dist/types/icon.d.ts
DELETED
package/dist/types/json.d.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { Json } from '@metamask/utils';
|
|
2
|
-
/**
|
|
3
|
-
* Parse JSON safely.
|
|
4
|
-
*
|
|
5
|
-
* Does multiple kinds of validation and strips unwanted properties like
|
|
6
|
-
* `__proto__` and `constructor`.
|
|
7
|
-
*
|
|
8
|
-
* @param json - A JSON string to be parsed.
|
|
9
|
-
* @returns The parsed JSON object.
|
|
10
|
-
* @template Type - The type of the JSON object. The type is not actually
|
|
11
|
-
* checked, but it is used to infer the return type.
|
|
12
|
-
*/
|
|
13
|
-
export declare function parseJson<Type extends Json = Json>(json: string): Type;
|
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
import { Infer } from 'superstruct';
|
|
2
|
-
export declare const CHAIN_ID_REGEX: RegExp;
|
|
3
|
-
export declare const ACCOUNT_ID_REGEX: RegExp;
|
|
4
|
-
/**
|
|
5
|
-
* Parse a chain ID string to an object containing the namespace and reference.
|
|
6
|
-
* This validates the chain ID before parsing it.
|
|
7
|
-
*
|
|
8
|
-
* @param chainId - The chain ID to validate and parse.
|
|
9
|
-
* @returns The parsed chain ID.
|
|
10
|
-
*/
|
|
11
|
-
export declare function parseChainId(chainId: ChainId): {
|
|
12
|
-
namespace: NamespaceId;
|
|
13
|
-
reference: string;
|
|
14
|
-
};
|
|
15
|
-
/**
|
|
16
|
-
* Parse an account ID to an object containing the chain, chain ID and address.
|
|
17
|
-
* This validates the account ID before parsing it.
|
|
18
|
-
*
|
|
19
|
-
* @param accountId - The account ID to validate and parse.
|
|
20
|
-
* @returns The parsed account ID.
|
|
21
|
-
*/
|
|
22
|
-
export declare function parseAccountId(accountId: AccountId): {
|
|
23
|
-
chain: {
|
|
24
|
-
namespace: NamespaceId;
|
|
25
|
-
reference: string;
|
|
26
|
-
};
|
|
27
|
-
chainId: ChainId;
|
|
28
|
-
address: string;
|
|
29
|
-
};
|
|
30
|
-
/**
|
|
31
|
-
* A helper struct for a string with a minimum length of 1 and a maximum length
|
|
32
|
-
* of 40.
|
|
33
|
-
*/
|
|
34
|
-
export declare const LimitedString: import("superstruct").Struct<string, null>;
|
|
35
|
-
/**
|
|
36
|
-
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
37
|
-
*/
|
|
38
|
-
export declare const ChainIdStruct: import("superstruct").Struct<string, null>;
|
|
39
|
-
export declare type ChainId = `${string}:${string}`;
|
|
40
|
-
export declare const AccountIdStruct: import("superstruct").Struct<string, null>;
|
|
41
|
-
export declare type AccountId = `${ChainId}:${string}`;
|
|
42
|
-
export declare const AccountIdArrayStruct: import("superstruct").Struct<string[], import("superstruct").Struct<string, null>>;
|
|
43
|
-
/**
|
|
44
|
-
* A chain descriptor.
|
|
45
|
-
*/
|
|
46
|
-
export declare const ChainStruct: import("superstruct").Struct<{
|
|
47
|
-
name: string;
|
|
48
|
-
id: string;
|
|
49
|
-
}, {
|
|
50
|
-
id: import("superstruct").Struct<string, null>;
|
|
51
|
-
name: import("superstruct").Struct<string, null>;
|
|
52
|
-
}>;
|
|
53
|
-
export declare type Chain = Infer<typeof ChainStruct>;
|
|
54
|
-
export declare const NamespaceStruct: import("superstruct").Struct<{
|
|
55
|
-
chains: {
|
|
56
|
-
name: string;
|
|
57
|
-
id: string;
|
|
58
|
-
}[];
|
|
59
|
-
methods?: string[] | undefined;
|
|
60
|
-
events?: string[] | undefined;
|
|
61
|
-
}, {
|
|
62
|
-
/**
|
|
63
|
-
* A list of supported chains in the namespace.
|
|
64
|
-
*/
|
|
65
|
-
chains: import("superstruct").Struct<{
|
|
66
|
-
name: string;
|
|
67
|
-
id: string;
|
|
68
|
-
}[], import("superstruct").Struct<{
|
|
69
|
-
name: string;
|
|
70
|
-
id: string;
|
|
71
|
-
}, {
|
|
72
|
-
id: import("superstruct").Struct<string, null>;
|
|
73
|
-
name: import("superstruct").Struct<string, null>;
|
|
74
|
-
}>>;
|
|
75
|
-
/**
|
|
76
|
-
* A list of supported RPC methods on the namespace, that a DApp can call.
|
|
77
|
-
*/
|
|
78
|
-
methods: import("superstruct").Struct<string[] | undefined, import("superstruct").Struct<string, null>>;
|
|
79
|
-
/**
|
|
80
|
-
* A list of supported RPC events on the namespace, that a DApp can listen to.
|
|
81
|
-
*/
|
|
82
|
-
events: import("superstruct").Struct<string[] | undefined, import("superstruct").Struct<string, null>>;
|
|
83
|
-
}>;
|
|
84
|
-
export declare type Namespace = Infer<typeof NamespaceStruct>;
|
|
85
|
-
/**
|
|
86
|
-
* A CAIP-2 namespace, i.e., the first part of a chain ID.
|
|
87
|
-
*/
|
|
88
|
-
export declare const NamespaceIdStruct: import("superstruct").Struct<string, null>;
|
|
89
|
-
export declare type NamespaceId = Infer<typeof NamespaceIdStruct>;
|
|
90
|
-
/**
|
|
91
|
-
* Check if the given value is a CAIP-2 namespace ID.
|
|
92
|
-
*
|
|
93
|
-
* @param value - The value to check.
|
|
94
|
-
* @returns Whether the value is a CAIP-2 namespace ID.
|
|
95
|
-
*/
|
|
96
|
-
export declare function isNamespaceId(value: unknown): value is NamespaceId;
|
|
97
|
-
/**
|
|
98
|
-
* Check if the given value is a CAIP-2 chain ID.
|
|
99
|
-
*
|
|
100
|
-
* @param value - The value to check.
|
|
101
|
-
* @returns Whether the value is a CAIP-2 chain ID.
|
|
102
|
-
*/
|
|
103
|
-
export declare function isChainId(value: unknown): value is ChainId;
|
|
104
|
-
/**
|
|
105
|
-
* Check if the given value is a CAIP-10 account ID.
|
|
106
|
-
*
|
|
107
|
-
* @param value - The value to check.
|
|
108
|
-
* @returns Whether the value is a CAIP-10 account ID.
|
|
109
|
-
*/
|
|
110
|
-
export declare function isAccountId(value: unknown): value is AccountId;
|
|
111
|
-
/**
|
|
112
|
-
* Check if the given value is an array of CAIP-10 account IDs.
|
|
113
|
-
*
|
|
114
|
-
* @param value - The value to check.
|
|
115
|
-
* @returns Whether the value is an array of CAIP-10 account IDs.
|
|
116
|
-
*/
|
|
117
|
-
export declare function isAccountIdArray(value: unknown): value is AccountId[];
|
|
118
|
-
/**
|
|
119
|
-
* Check if a value is a {@link Namespace}.
|
|
120
|
-
*
|
|
121
|
-
* @param value - The value to validate.
|
|
122
|
-
* @returns True if the value is a valid {@link Namespace}.
|
|
123
|
-
*/
|
|
124
|
-
export declare function isNamespace(value: unknown): value is Namespace;
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { SnapFiles } from './types';
|
|
2
|
-
/**
|
|
3
|
-
* Validates the files contained in a fetched snap.
|
|
4
|
-
*
|
|
5
|
-
* @param files - All potentially included files in a fetched snap.
|
|
6
|
-
* @throws If any of the files are considered invalid.
|
|
7
|
-
*/
|
|
8
|
-
export declare function validateFetchedSnap(files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>): void;
|
|
File without changes
|