@metamask/snaps-utils 5.2.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -3
- package/dist/cjs/caveats.js +6 -0
- package/dist/cjs/caveats.js.map +1 -1
- package/dist/cjs/eval-worker.js +3 -1
- package/dist/cjs/eval-worker.js.map +1 -1
- package/dist/cjs/handler-types.js +1 -0
- package/dist/cjs/handler-types.js.map +1 -1
- package/dist/cjs/handlers.js +74 -3
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/manifest/validation.js +50 -14
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/structs.js +86 -17
- package/dist/cjs/structs.js.map +1 -1
- package/dist/esm/caveats.js +6 -0
- package/dist/esm/caveats.js.map +1 -1
- package/dist/esm/eval-worker.js +3 -1
- package/dist/esm/eval-worker.js.map +1 -1
- package/dist/esm/handler-types.js +1 -0
- package/dist/esm/handler-types.js.map +1 -1
- package/dist/esm/handlers.js +45 -4
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/manifest/validation.js +38 -16
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/structs.js +133 -21
- package/dist/esm/structs.js.map +1 -1
- package/dist/types/caveats.d.ts +9 -1
- package/dist/types/handler-types.d.ts +2 -1
- package/dist/types/handlers.d.ts +349 -10
- package/dist/types/localization.d.ts +33 -13
- package/dist/types/manifest/validation.d.ts +230 -75
- package/dist/types/structs.d.ts +61 -7
- package/package.json +4 -4
package/dist/esm/structs.js
CHANGED
|
@@ -1,8 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { union } from '@metamask/snaps-sdk';
|
|
2
|
+
import { assert, isObject } from '@metamask/utils';
|
|
2
3
|
import { bold, green, red } from 'chalk';
|
|
3
4
|
import { resolve } from 'path';
|
|
4
|
-
import { Struct, StructError, create, string, coerce } from 'superstruct';
|
|
5
|
+
import { is, validate, type as superstructType, Struct, StructError, create, string, coerce as superstructCoerce } from 'superstruct';
|
|
5
6
|
import { indent } from './strings';
|
|
7
|
+
/**
|
|
8
|
+
* Colorize a value with a color function. This is useful for colorizing values
|
|
9
|
+
* in error messages. If colorization is disabled, the original value is
|
|
10
|
+
* returned.
|
|
11
|
+
*
|
|
12
|
+
* @param value - The value to colorize.
|
|
13
|
+
* @param colorFunction - The color function to use.
|
|
14
|
+
* @param enabled - Whether to colorize the value.
|
|
15
|
+
* @returns The colorized value, or the original value if colorization is
|
|
16
|
+
* disabled.
|
|
17
|
+
*/ function color(value, colorFunction, enabled) {
|
|
18
|
+
if (enabled) {
|
|
19
|
+
return colorFunction(value);
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
6
23
|
/**
|
|
7
24
|
* A wrapper of `superstruct`'s `string` struct that coerces a value to a string
|
|
8
25
|
* and resolves it relative to the current working directory. This is useful
|
|
@@ -22,7 +39,7 @@ import { indent } from './strings';
|
|
|
22
39
|
* console.log(value.file); // /process/cwd/path/to/file
|
|
23
40
|
* ```
|
|
24
41
|
*/ export function file() {
|
|
25
|
-
return
|
|
42
|
+
return superstructCoerce(string(), string(), (value)=>{
|
|
26
43
|
return resolve(process.cwd(), value);
|
|
27
44
|
});
|
|
28
45
|
}
|
|
@@ -41,12 +58,12 @@ import { indent } from './strings';
|
|
|
41
58
|
});
|
|
42
59
|
}
|
|
43
60
|
export class SnapsStructError extends StructError {
|
|
44
|
-
constructor(struct, prefix, suffix, failure, failures){
|
|
61
|
+
constructor(struct, prefix, suffix, failure, failures, colorize = true){
|
|
45
62
|
super(failure, failures);
|
|
46
63
|
this.name = 'SnapsStructError';
|
|
47
64
|
this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
|
|
48
65
|
...failures()
|
|
49
|
-
])}${suffix ? `\n\n${suffix}` : ''}`;
|
|
66
|
+
], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
|
|
50
67
|
}
|
|
51
68
|
}
|
|
52
69
|
/**
|
|
@@ -70,9 +87,10 @@ export class SnapsStructError extends StructError {
|
|
|
70
87
|
* @param options.suffix - The suffix to add to the error message. Defaults to
|
|
71
88
|
* an empty string.
|
|
72
89
|
* @param options.error - The `superstruct` error to wrap.
|
|
90
|
+
* @param options.colorize - Whether to colorize the value. Defaults to `true`.
|
|
73
91
|
* @returns The `SnapsStructError`.
|
|
74
|
-
*/ export function getError({ struct, prefix, suffix = '', error }) {
|
|
75
|
-
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
|
|
92
|
+
*/ export function getError({ struct, prefix, suffix = '', error, colorize }) {
|
|
93
|
+
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
|
|
76
94
|
}
|
|
77
95
|
/**
|
|
78
96
|
* A wrapper of `superstruct`'s `create` function that throws a
|
|
@@ -118,25 +136,27 @@ export class SnapsStructError extends StructError {
|
|
|
118
136
|
* Get the union struct names from a struct.
|
|
119
137
|
*
|
|
120
138
|
* @param struct - The struct.
|
|
139
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
121
140
|
* @returns The union struct names, or `null` if the struct is not a union
|
|
122
141
|
* struct.
|
|
123
|
-
*/ export function getUnionStructNames(struct) {
|
|
142
|
+
*/ export function getUnionStructNames(struct, colorize = true) {
|
|
124
143
|
if (Array.isArray(struct.schema)) {
|
|
125
|
-
return struct.schema.map(({ type })=>
|
|
144
|
+
return struct.schema.map(({ type })=>color(type, green, colorize));
|
|
126
145
|
}
|
|
127
146
|
return null;
|
|
128
147
|
}
|
|
129
148
|
/**
|
|
130
|
-
* Get
|
|
149
|
+
* Get an error prefix from a `superstruct` failure. This is useful for
|
|
131
150
|
* formatting the error message returned by `superstruct`.
|
|
132
151
|
*
|
|
133
152
|
* @param failure - The `superstruct` failure.
|
|
153
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
134
154
|
* @returns The error prefix.
|
|
135
|
-
*/ export function getStructErrorPrefix(failure) {
|
|
155
|
+
*/ export function getStructErrorPrefix(failure, colorize = true) {
|
|
136
156
|
if (failure.type === 'never' || failure.path.length === 0) {
|
|
137
157
|
return '';
|
|
138
158
|
}
|
|
139
|
-
return `At path: ${
|
|
159
|
+
return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;
|
|
140
160
|
}
|
|
141
161
|
/**
|
|
142
162
|
* Get a string describing the failure. This is similar to the `message`
|
|
@@ -145,13 +165,14 @@ export class SnapsStructError extends StructError {
|
|
|
145
165
|
*
|
|
146
166
|
* @param struct - The struct that caused the failure.
|
|
147
167
|
* @param failure - The `superstruct` failure.
|
|
168
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
148
169
|
* @returns A string describing the failure.
|
|
149
|
-
*/ export function getStructFailureMessage(struct, failure) {
|
|
150
|
-
const received =
|
|
151
|
-
const prefix = getStructErrorPrefix(failure);
|
|
170
|
+
*/ export function getStructFailureMessage(struct, failure, colorize = true) {
|
|
171
|
+
const received = color(JSON.stringify(failure.value), red, colorize);
|
|
172
|
+
const prefix = getStructErrorPrefix(failure, colorize);
|
|
152
173
|
if (failure.type === 'union') {
|
|
153
174
|
const childStruct = getStructFromPath(struct, failure.path);
|
|
154
|
-
const unionNames = getUnionStructNames(childStruct);
|
|
175
|
+
const unionNames = getUnionStructNames(childStruct, colorize);
|
|
155
176
|
if (unionNames) {
|
|
156
177
|
return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
|
|
157
178
|
}
|
|
@@ -160,13 +181,17 @@ export class SnapsStructError extends StructError {
|
|
|
160
181
|
if (failure.type === 'literal') {
|
|
161
182
|
// Superstruct's failure does not provide information about which literal
|
|
162
183
|
// value was expected, so we need to parse the message to get the literal.
|
|
163
|
-
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${
|
|
184
|
+
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', red, colorize)}`);
|
|
164
185
|
return `${prefix}${message}.`;
|
|
165
186
|
}
|
|
166
187
|
if (failure.type === 'never') {
|
|
167
|
-
return `Unknown key: ${
|
|
188
|
+
return `Unknown key: ${color(failure.path.join('.'), bold, colorize)}, received: ${received}.`;
|
|
168
189
|
}
|
|
169
|
-
|
|
190
|
+
if (failure.refinement === 'size') {
|
|
191
|
+
const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', green, colorize)} and ${color('$2', green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', red, colorize)}`).replace(/a array/u, 'an array');
|
|
192
|
+
return `${prefix}${message}.`;
|
|
193
|
+
}
|
|
194
|
+
return `${prefix}Expected a value of type ${color(failure.type, green, colorize)}, but received: ${received}.`;
|
|
170
195
|
}
|
|
171
196
|
/**
|
|
172
197
|
* Get a string describing the errors. This formats all the errors in a
|
|
@@ -174,10 +199,97 @@ export class SnapsStructError extends StructError {
|
|
|
174
199
|
*
|
|
175
200
|
* @param struct - The struct that caused the failures.
|
|
176
201
|
* @param failures - The `superstruct` failures.
|
|
202
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
177
203
|
* @returns A string describing the errors.
|
|
178
|
-
*/ export function getStructErrorMessage(struct, failures) {
|
|
179
|
-
const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure)}`));
|
|
204
|
+
*/ export function getStructErrorMessage(struct, failures, colorize = true) {
|
|
205
|
+
const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure, colorize)}`));
|
|
180
206
|
return formattedFailures.join('\n');
|
|
181
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* Validate a union struct, and throw readable errors if the value does not
|
|
210
|
+
* satisfy the struct. This is useful for improving the error messages returned
|
|
211
|
+
* by `superstruct`.
|
|
212
|
+
*
|
|
213
|
+
* @param value - The value to validate.
|
|
214
|
+
* @param struct - The `superstruct` union struct to validate the value against.
|
|
215
|
+
* This struct must be a union of object structs, and must have at least one
|
|
216
|
+
* shared key to validate against.
|
|
217
|
+
* @param structKey - The key to validate against. This key must be present in
|
|
218
|
+
* all the object structs in the union struct, and is expected to be a literal
|
|
219
|
+
* value.
|
|
220
|
+
* @param coerce - Whether to coerce the value to satisfy the struct. Defaults
|
|
221
|
+
* to `false`.
|
|
222
|
+
* @returns The validated value.
|
|
223
|
+
* @throws If the value does not satisfy the struct.
|
|
224
|
+
* @example
|
|
225
|
+
* const struct = union([
|
|
226
|
+
* object({ type: literal('a'), value: string() }),
|
|
227
|
+
* object({ type: literal('b'), value: number() }),
|
|
228
|
+
* object({ type: literal('c'), value: boolean() }),
|
|
229
|
+
* // ...
|
|
230
|
+
* ]);
|
|
231
|
+
*
|
|
232
|
+
* // At path: type — Expected the value to be one of: "a", "b", "c", but received: "d".
|
|
233
|
+
* validateUnion({ type: 'd', value: 'foo' }, struct, 'type');
|
|
234
|
+
*
|
|
235
|
+
* // At path: value — Expected a value of type string, but received: 42.
|
|
236
|
+
* validateUnion({ type: 'a', value: 42 }, struct, 'value');
|
|
237
|
+
*/ export function validateUnion(value, struct, structKey, coerce = false) {
|
|
238
|
+
assert(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
|
|
239
|
+
assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');
|
|
240
|
+
const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
|
|
241
|
+
const key = superstructType({
|
|
242
|
+
[structKey]: union(keyUnion)
|
|
243
|
+
});
|
|
244
|
+
const [keyError] = validate(value, key, {
|
|
245
|
+
coerce
|
|
246
|
+
});
|
|
247
|
+
if (keyError) {
|
|
248
|
+
throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
|
|
249
|
+
}
|
|
250
|
+
// At this point it's guaranteed that the value is an object, so we can safely
|
|
251
|
+
// cast it to a Record.
|
|
252
|
+
const objectValue = value;
|
|
253
|
+
const objectStructs = struct.schema.filter((innerStruct)=>is(objectValue[structKey], innerStruct.schema[structKey]));
|
|
254
|
+
assert(objectStructs.length > 0, 'Expected a struct to match the value.');
|
|
255
|
+
// We need to validate the value against all the object structs that match the
|
|
256
|
+
// struct key, and return the first validated value.
|
|
257
|
+
const validationResults = objectStructs.map((objectStruct)=>validate(objectValue, objectStruct, {
|
|
258
|
+
coerce
|
|
259
|
+
}));
|
|
260
|
+
const validatedValue = validationResults.find(([error])=>!error);
|
|
261
|
+
if (validatedValue) {
|
|
262
|
+
return validatedValue[1];
|
|
263
|
+
}
|
|
264
|
+
assert(validationResults[0][0], 'Expected at least one error.');
|
|
265
|
+
// If there is no validated value, we need to find the error with the least
|
|
266
|
+
// number of failures (with the assumption that it's the most specific error).
|
|
267
|
+
const validationError = validationResults.reduce((error, [innerError])=>{
|
|
268
|
+
assert(innerError, 'Expected an error.');
|
|
269
|
+
if (innerError.failures().length < error.failures().length) {
|
|
270
|
+
return innerError;
|
|
271
|
+
}
|
|
272
|
+
return error;
|
|
273
|
+
}, validationResults[0][0]);
|
|
274
|
+
throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Create a value with the coercion logic of a union struct, and throw readable
|
|
278
|
+
* errors if the value does not satisfy the struct. This is useful for improving
|
|
279
|
+
* the error messages returned by `superstruct`.
|
|
280
|
+
*
|
|
281
|
+
* @param value - The value to validate.
|
|
282
|
+
* @param struct - The `superstruct` union struct to validate the value against.
|
|
283
|
+
* This struct must be a union of object structs, and must have at least one
|
|
284
|
+
* shared key to validate against.
|
|
285
|
+
* @param structKey - The key to validate against. This key must be present in
|
|
286
|
+
* all the object structs in the union struct, and is expected to be a literal
|
|
287
|
+
* value.
|
|
288
|
+
* @returns The validated value.
|
|
289
|
+
* @throws If the value does not satisfy the struct.
|
|
290
|
+
* @see validateUnion
|
|
291
|
+
*/ export function createUnion(value, struct, structKey) {
|
|
292
|
+
return validateUnion(value, struct, structKey, true);
|
|
293
|
+
}
|
|
182
294
|
|
|
183
295
|
//# sourceMappingURL=structs.js.map
|
package/dist/esm/structs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport { Struct, StructError, create, string, coerce } from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["isObject","bold","green","red","resolve","Struct","StructError","create","string","coerce","indent","file","value","process","cwd","named","name","struct","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","schema","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","JSON","stringify","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SAASC,MAAM,EAAEC,WAAW,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,cAAc;AAG1E,SAASC,MAAM,QAAQ,YAAY;AA6BnC;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC;IACd,OAAOF,OAAOD,UAAUA,UAAU,CAACI;QACjC,OAAOR,QAAQS,QAAQC,GAAG,IAAIF;IAChC;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASG,MACdC,IAAY,EACZC,MAA4B;IAE5B,OAAO,IAAIZ,OAAO;QAChB,GAAGY,MAAM;QACTC,MAAMF;IACR;AACF;AAEA,OAAO,MAAMG,yBAAuCb;IACl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F,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAEjB,KACrBsB,QAAQW,IAAI,CAACW,IAAI,CAAC,MAClB,YAAY,EAAEE,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAE1B,OAAO,yBAAyB,EAAEnB,MAC1CqB,QAAQL,IAAI,EACZ,gBAAgB,EAAE6B,SAAS,CAAC,CAAC;AACjC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASrB,sBACdT,MAA4B,EAC5BO,QAAmB;IAEnB,MAAM6B,oBAAoB7B,SAASkB,GAAG,CAAC,CAACnB,UACtCb,OAAO,CAAC,EAAE,EAAEoC,wBAAwB7B,QAAQM,SAAS,CAAC;IAGxD,OAAO8B,kBAAkBR,IAAI,CAAC;AAChC"}
|
|
1
|
+
{"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { union } from '@metamask/snaps-sdk';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport {\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n string,\n coerce as superstructCoerce,\n} from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * Colorize a value with a color function. This is useful for colorizing values\n * in error messages. If colorization is disabled, the original value is\n * returned.\n *\n * @param value - The value to colorize.\n * @param colorFunction - The color function to use.\n * @param enabled - Whether to colorize the value.\n * @returns The colorized value, or the original value if colorization is\n * disabled.\n */\nfunction color(\n value: string,\n colorFunction: (value: string) => string,\n enabled: boolean,\n) {\n if (enabled) {\n return colorFunction(value);\n }\n\n return value;\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return superstructCoerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n colorize = true,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(\n struct,\n [...failures()],\n colorize,\n )}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n colorize?: boolean;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @param options.colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n colorize,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(\n struct,\n prefix,\n suffix,\n error,\n () => arrayToGenerator(error.failures()),\n colorize,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n colorize = true,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => color(type, green, colorize));\n }\n\n return null;\n}\n\n/**\n * Get an error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure, colorize = true) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n colorize = true,\n) {\n const received = color(JSON.stringify(failure.value), red, colorize);\n const prefix = getStructErrorPrefix(failure, colorize);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct, colorize);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(\n /the literal `(.+)`,/u,\n `the value to be \\`${color('$1', green, colorize)}\\`,`,\n )\n .replace(\n /, but received: (.+)/u,\n `, but received: ${color('$1', red, colorize)}`,\n );\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${color(\n failure.path.join('.'),\n bold,\n colorize,\n )}, received: ${received}.`;\n }\n\n if (failure.refinement === 'size') {\n const message = failure.message\n .replace(\n /length between `(\\d+)` and `(\\d+)`/u,\n `length between ${color('$1', green, colorize)} and ${color(\n '$2',\n green,\n colorize,\n )},`,\n )\n .replace(/length of `(\\d+)`/u, `length of ${color('$1', red, colorize)}`)\n .replace(/a array/u, 'an array');\n\n return `${prefix}${message}.`;\n }\n\n return `${prefix}Expected a value of type ${color(\n failure.type,\n green,\n colorize,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n colorize = true,\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure, colorize)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n\n/**\n * Validate a union struct, and throw readable errors if the value does not\n * satisfy the struct. This is useful for improving the error messages returned\n * by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @param coerce - Whether to coerce the value to satisfy the struct. Defaults\n * to `false`.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @example\n * const struct = union([\n * object({ type: literal('a'), value: string() }),\n * object({ type: literal('b'), value: number() }),\n * object({ type: literal('c'), value: boolean() }),\n * // ...\n * ]);\n *\n * // At path: type — Expected the value to be one of: \"a\", \"b\", \"c\", but received: \"d\".\n * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');\n *\n * // At path: value — Expected a value of type string, but received: 42.\n * validateUnion({ type: 'a', value: 42 }, struct, 'value');\n */\nexport function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n coerce = false,\n) {\n assert(\n struct.schema,\n 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.',\n );\n assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');\n\n const keyUnion = struct.schema.map(\n (innerStruct) => innerStruct.schema[structKey],\n // This is guaranteed to be a non-empty array by the assertion above. We\n // need to cast it since `superstruct` requires a non-empty array of structs\n // for the `union` struct.\n ) as NonEmptyArray<Struct>;\n\n const key = superstructType({\n [structKey]: union(keyUnion),\n });\n\n const [keyError] = validate(value, key, { coerce });\n if (keyError) {\n throw new Error(\n getStructFailureMessage(key, keyError.failures()[0], false),\n );\n }\n\n // At this point it's guaranteed that the value is an object, so we can safely\n // cast it to a Record.\n const objectValue = value as Record<PropertyKey, unknown>;\n const objectStructs = struct.schema.filter((innerStruct) =>\n is(objectValue[structKey], innerStruct.schema[structKey]),\n );\n\n assert(objectStructs.length > 0, 'Expected a struct to match the value.');\n\n // We need to validate the value against all the object structs that match the\n // struct key, and return the first validated value.\n const validationResults = objectStructs.map((objectStruct) =>\n validate(objectValue, objectStruct, { coerce }),\n );\n\n const validatedValue = validationResults.find(([error]) => !error);\n if (validatedValue) {\n return validatedValue[1];\n }\n\n assert(validationResults[0][0], 'Expected at least one error.');\n\n // If there is no validated value, we need to find the error with the least\n // number of failures (with the assumption that it's the most specific error).\n const validationError = validationResults.reduce((error, [innerError]) => {\n assert(innerError, 'Expected an error.');\n if (innerError.failures().length < error.failures().length) {\n return innerError;\n }\n\n return error;\n }, validationResults[0][0]);\n\n throw new Error(\n getStructFailureMessage(struct, validationError.failures()[0], false),\n );\n}\n\n/**\n * Create a value with the coercion logic of a union struct, and throw readable\n * errors if the value does not satisfy the struct. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @see validateUnion\n */\nexport function createUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n) {\n return validateUnion(value, struct, structKey, true);\n}\n"],"names":["union","assert","isObject","bold","green","red","resolve","is","validate","type","superstructType","Struct","StructError","create","string","coerce","superstructCoerce","indent","color","value","colorFunction","enabled","file","process","cwd","named","name","struct","SnapsStructError","constructor","prefix","suffix","failure","failures","colorize","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","schema","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","JSON","stringify","childStruct","unionNames","replace","refinement","formattedFailures","validateUnion","structKey","keyUnion","innerStruct","keyError","Error","objectValue","objectStructs","filter","validationResults","objectStruct","validatedValue","find","validationError","innerError","createUnion"],"mappings":"AAAA,SAASA,KAAK,QAAQ,sBAAsB;AAE5C,SAASC,MAAM,EAAEC,QAAQ,QAAQ,kBAAkB;AACnD,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SACEC,EAAE,EACFC,QAAQ,EACRC,QAAQC,eAAJ,EACJC,MAAM,EACNC,WAAW,EACXC,MAAM,EACNC,MAAM,EACNC,UAAUC,iBAAiB,QACtB,cAAc;AAGrB,SAASC,MAAM,QAAQ,YAAY;AA6BnC;;;;;;;;;;CAUC,GACD,SAASC,MACPC,KAAa,EACbC,aAAwC,EACxCC,OAAgB;IAEhB,IAAIA,SAAS;QACX,OAAOD,cAAcD;IACvB;IAEA,OAAOA;AACT;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASG;IACd,OAAON,kBAAkBF,UAAUA,UAAU,CAACK;QAC5C,OAAOb,QAAQiB,QAAQC,GAAG,IAAIL;IAChC;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASM,MACdC,IAAY,EACZC,MAA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OAAO8E,YAAY;QACnB,IAAIA,WAAW9C,QAAQ,GAAGqB,MAAM,GAAGb,MAAMR,QAAQ,GAAGqB,MAAM,EAAE;YAC1D,OAAOyB;QACT;QAEA,OAAOtC;IACT,GAAGiC,iBAAiB,CAAC,EAAE,CAAC,EAAE;IAE1B,MAAM,IAAIJ,MACRd,wBAAwB7B,QAAQmD,gBAAgB7C,QAAQ,EAAE,CAAC,EAAE,EAAE;AAEnE;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAAS+C,YACd7D,KAAc,EACdQ,MAA4B,EAC5BuC,SAAqB;IAErB,OAAOD,cAAc9C,OAAOQ,QAAQuC,WAAW;AACjD"}
|
package/dist/types/caveats.d.ts
CHANGED
|
@@ -34,5 +34,13 @@ export declare enum SnapCaveatType {
|
|
|
34
34
|
/**
|
|
35
35
|
* Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.
|
|
36
36
|
*/
|
|
37
|
-
ChainIds = "chainIds"
|
|
37
|
+
ChainIds = "chainIds",
|
|
38
|
+
/**
|
|
39
|
+
* Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
|
|
40
|
+
*/
|
|
41
|
+
LookupMatchers = "lookupMatchers",
|
|
42
|
+
/**
|
|
43
|
+
* Caveat specifying the max request time for a handler endowment.
|
|
44
|
+
*/
|
|
45
|
+
MaxRequestTime = "maxRequestTime"
|
|
38
46
|
}
|
|
@@ -7,7 +7,8 @@ export declare enum HandlerType {
|
|
|
7
7
|
OnUpdate = "onUpdate",
|
|
8
8
|
OnNameLookup = "onNameLookup",
|
|
9
9
|
OnKeyringRequest = "onKeyringRequest",
|
|
10
|
-
OnHomePage = "onHomePage"
|
|
10
|
+
OnHomePage = "onHomePage",
|
|
11
|
+
OnUserInput = "onUserInput"
|
|
11
12
|
}
|
|
12
13
|
export declare type SnapHandler = {
|
|
13
14
|
/**
|