@metamask-previews/utils 12.0.0-preview-41650ee6d → 12.0.0-preview-7fb08ad32
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 +1 -20
- package/dist/assert.d.ts +47 -1
- package/dist/assert.d.ts.map +1 -1
- package/dist/assert.js +81 -3
- package/dist/assert.js.map +1 -1
- package/dist/base64.d.ts.map +1 -1
- package/dist/base64.js +1 -1
- package/dist/base64.js.map +1 -1
- package/dist/bytes.d.ts +198 -0
- package/dist/bytes.d.ts.map +1 -0
- package/dist/bytes.js +419 -0
- package/dist/bytes.js.map +1 -0
- package/dist/coercers.d.ts +1 -1
- package/dist/coercers.d.ts.map +1 -1
- package/dist/coercers.js +2 -2
- package/dist/coercers.js.map +1 -1
- package/dist/errors.d.ts +68 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +114 -0
- package/dist/errors.js.map +1 -0
- package/dist/fs.d.ts +133 -0
- package/dist/fs.d.ts.map +1 -0
- package/dist/fs.js +210 -0
- package/dist/fs.js.map +1 -0
- package/dist/hex.d.ts +47 -1
- package/dist/hex.d.ts.map +1 -1
- package/dist/hex.js +72 -2
- package/dist/hex.js.map +1 -1
- package/dist/index.d.ts +5 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +7 -2
- package/dist/json.d.ts.map +1 -1
- package/dist/json.js +1 -1
- package/dist/json.js.map +1 -1
- package/dist/keyring.d.ts +2 -2
- package/dist/keyring.d.ts.map +1 -1
- package/dist/keyring.js.map +1 -1
- package/dist/misc.d.ts +88 -0
- package/dist/misc.d.ts.map +1 -1
- package/dist/misc.js +83 -0
- package/dist/misc.js.map +1 -1
- package/dist/node.d.ts +1 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -1
- package/dist/node.js.map +1 -1
- package/dist/number.d.ts +74 -0
- package/dist/number.d.ts.map +1 -0
- package/dist/number.js +95 -0
- package/dist/number.js.map +1 -0
- package/dist/transaction-types.d.ts +2 -2
- package/dist/transaction-types.d.ts.map +1 -1
- package/dist/transaction-types.js.map +1 -1
- package/package.json +30 -15
package/dist/bytes.js
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { base64 } from '@scure/base';
|
|
2
|
+
import { assert } from './assert.js';
|
|
3
|
+
import { add0x, assertIsHexString, remove0x } from './hex.js';
|
|
4
|
+
// '0'.charCodeAt(0) === 48
|
|
5
|
+
const HEX_MINIMUM_NUMBER_CHARACTER = 48;
|
|
6
|
+
// '9'.charCodeAt(0) === 57
|
|
7
|
+
const HEX_MAXIMUM_NUMBER_CHARACTER = 58;
|
|
8
|
+
const HEX_CHARACTER_OFFSET = 87;
|
|
9
|
+
/**
|
|
10
|
+
* Memoized function that returns an array to be used as a lookup table for
|
|
11
|
+
* converting bytes to hexadecimal values.
|
|
12
|
+
*
|
|
13
|
+
* The array is created lazily and then cached for future use. The benefit of
|
|
14
|
+
* this approach is that the performance of converting bytes to hex is much
|
|
15
|
+
* better than if we were to call `toString(16)` on each byte.
|
|
16
|
+
*
|
|
17
|
+
* The downside is that the array is created once and then never garbage
|
|
18
|
+
* collected. This is not a problem in practice because the array is only 256
|
|
19
|
+
* elements long.
|
|
20
|
+
*
|
|
21
|
+
* @returns A function that returns the lookup table.
|
|
22
|
+
*/
|
|
23
|
+
function getPrecomputedHexValuesBuilder() {
|
|
24
|
+
// To avoid issues with tree shaking, we need to use a function to return the
|
|
25
|
+
// array. This is because the array is only used in the `bytesToHex` function
|
|
26
|
+
// and if we were to use a global variable, the array might be removed by the
|
|
27
|
+
// tree shaker.
|
|
28
|
+
const lookupTable = [];
|
|
29
|
+
return () => {
|
|
30
|
+
if (lookupTable.length === 0) {
|
|
31
|
+
for (let i = 0; i < 256; i++) {
|
|
32
|
+
lookupTable.push(i.toString(16).padStart(2, '0'));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return lookupTable;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Function implementation of the {@link getPrecomputedHexValuesBuilder}
|
|
40
|
+
* function.
|
|
41
|
+
*/
|
|
42
|
+
const getPrecomputedHexValues = getPrecomputedHexValuesBuilder();
|
|
43
|
+
/**
|
|
44
|
+
* Check if a value is a `Uint8Array`.
|
|
45
|
+
*
|
|
46
|
+
* @param value - The value to check.
|
|
47
|
+
* @returns Whether the value is a `Uint8Array`.
|
|
48
|
+
*/
|
|
49
|
+
export function isBytes(value) {
|
|
50
|
+
return value instanceof Uint8Array;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Check if a value is a `Uint8Array` backed by an `ArrayBuffer`.
|
|
54
|
+
*
|
|
55
|
+
* @param value - The value to check.
|
|
56
|
+
* @returns Whether the value is a `Uint8Array` backed by an `ArrayBuffer`.
|
|
57
|
+
*/
|
|
58
|
+
function isArrayBufferBytes(value) {
|
|
59
|
+
return isBytes(value) && value.buffer instanceof ArrayBuffer;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Assert that a value is a `Uint8Array`.
|
|
63
|
+
*
|
|
64
|
+
* @param value - The value to check.
|
|
65
|
+
* @throws If the value is not a `Uint8Array`.
|
|
66
|
+
*/
|
|
67
|
+
export function assertIsBytes(value) {
|
|
68
|
+
assert(isBytes(value), 'Value must be a Uint8Array.');
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Convert a `Uint8Array` to a hexadecimal string.
|
|
72
|
+
*
|
|
73
|
+
* @param bytes - The bytes to convert to a hexadecimal string.
|
|
74
|
+
* @returns The hexadecimal string.
|
|
75
|
+
*/
|
|
76
|
+
export function bytesToHex(bytes) {
|
|
77
|
+
assertIsBytes(bytes);
|
|
78
|
+
if (bytes.length === 0) {
|
|
79
|
+
return '0x';
|
|
80
|
+
}
|
|
81
|
+
const lookupTable = getPrecomputedHexValues();
|
|
82
|
+
const hexadecimal = new Array(bytes.length);
|
|
83
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
84
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
85
|
+
hexadecimal[i] = lookupTable[bytes[i]];
|
|
86
|
+
}
|
|
87
|
+
return add0x(hexadecimal.join(''));
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Convert a `Uint8Array` to a `bigint`.
|
|
91
|
+
*
|
|
92
|
+
* To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}.
|
|
93
|
+
* To convert a two's complement encoded `Uint8Array` to a `bigint`, use
|
|
94
|
+
* {@link bytesToSignedBigInt}.
|
|
95
|
+
*
|
|
96
|
+
* @param bytes - The bytes to convert to a `bigint`.
|
|
97
|
+
* @returns The `bigint`.
|
|
98
|
+
*/
|
|
99
|
+
export function bytesToBigInt(bytes) {
|
|
100
|
+
assertIsBytes(bytes);
|
|
101
|
+
const hexadecimal = bytesToHex(bytes);
|
|
102
|
+
return BigInt(hexadecimal);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are
|
|
106
|
+
* encoded in two's complement.
|
|
107
|
+
*
|
|
108
|
+
* To convert a `Uint8Array` to an unsigned `bigint` instead, use
|
|
109
|
+
* {@link bytesToBigInt}.
|
|
110
|
+
*
|
|
111
|
+
* @see https://en.wikipedia.org/wiki/Two%27s_complement
|
|
112
|
+
* @param bytes - The bytes to convert to a signed `bigint`.
|
|
113
|
+
* @returns The signed `bigint`.
|
|
114
|
+
*/
|
|
115
|
+
export function bytesToSignedBigInt(bytes) {
|
|
116
|
+
assertIsBytes(bytes);
|
|
117
|
+
let value = BigInt(0);
|
|
118
|
+
for (const byte of bytes) {
|
|
119
|
+
// eslint-disable-next-line no-bitwise
|
|
120
|
+
value = (value << BigInt(8)) + BigInt(byte);
|
|
121
|
+
}
|
|
122
|
+
return BigInt.asIntN(bytes.length * 8, value);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Convert a `Uint8Array` to a `number`.
|
|
126
|
+
*
|
|
127
|
+
* To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}.
|
|
128
|
+
*
|
|
129
|
+
* @param bytes - The bytes to convert to a number.
|
|
130
|
+
* @returns The number.
|
|
131
|
+
* @throws If the resulting number is not a safe integer.
|
|
132
|
+
*/
|
|
133
|
+
export function bytesToNumber(bytes) {
|
|
134
|
+
assertIsBytes(bytes);
|
|
135
|
+
const bigint = bytesToBigInt(bytes);
|
|
136
|
+
assert(bigint <= BigInt(Number.MAX_SAFE_INTEGER), 'Number is not a safe integer. Use `bytesToBigInt` instead.');
|
|
137
|
+
return Number(bigint);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Convert a UTF-8 encoded `Uint8Array` to a `string`.
|
|
141
|
+
*
|
|
142
|
+
* @param bytes - The bytes to convert to a string.
|
|
143
|
+
* @returns The string.
|
|
144
|
+
*/
|
|
145
|
+
export function bytesToString(bytes) {
|
|
146
|
+
assertIsBytes(bytes);
|
|
147
|
+
return new TextDecoder().decode(bytes);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Convert a `Uint8Array` to a base64 encoded string.
|
|
151
|
+
*
|
|
152
|
+
* @param bytes - The bytes to convert to a base64 encoded string.
|
|
153
|
+
* @returns The base64 encoded string.
|
|
154
|
+
*/
|
|
155
|
+
export function bytesToBase64(bytes) {
|
|
156
|
+
assertIsBytes(bytes);
|
|
157
|
+
return base64.encode(bytes);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Convert a hexadecimal string to a `Uint8Array`. The string can optionally be
|
|
161
|
+
* prefixed with `0x`. It accepts even and odd length strings.
|
|
162
|
+
*
|
|
163
|
+
* If the value is "0x", an empty `Uint8Array` is returned.
|
|
164
|
+
*
|
|
165
|
+
* @param value - The hexadecimal string to convert to bytes.
|
|
166
|
+
* @returns The bytes as `Uint8Array`.
|
|
167
|
+
*/
|
|
168
|
+
export function hexToBytes(value) {
|
|
169
|
+
// "0x" is often used as empty byte array.
|
|
170
|
+
if (value?.toLowerCase?.() === '0x') {
|
|
171
|
+
return new Uint8Array();
|
|
172
|
+
}
|
|
173
|
+
assertIsHexString(value);
|
|
174
|
+
// Remove the `0x` prefix if it exists, and pad the string to have an even
|
|
175
|
+
// number of characters.
|
|
176
|
+
const strippedValue = remove0x(value).toLowerCase();
|
|
177
|
+
const normalizedValue = strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;
|
|
178
|
+
const bytes = new Uint8Array(normalizedValue.length / 2);
|
|
179
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
180
|
+
// While this is not the prettiest way to convert a hexadecimal string to a
|
|
181
|
+
// `Uint8Array`, it is a lot faster than using `parseInt` to convert each
|
|
182
|
+
// character.
|
|
183
|
+
const c1 = normalizedValue.charCodeAt(i * 2);
|
|
184
|
+
const c2 = normalizedValue.charCodeAt(i * 2 + 1);
|
|
185
|
+
const n1 = c1 -
|
|
186
|
+
(c1 < HEX_MAXIMUM_NUMBER_CHARACTER
|
|
187
|
+
? HEX_MINIMUM_NUMBER_CHARACTER
|
|
188
|
+
: HEX_CHARACTER_OFFSET);
|
|
189
|
+
const n2 = c2 -
|
|
190
|
+
(c2 < HEX_MAXIMUM_NUMBER_CHARACTER
|
|
191
|
+
? HEX_MINIMUM_NUMBER_CHARACTER
|
|
192
|
+
: HEX_CHARACTER_OFFSET);
|
|
193
|
+
bytes[i] = n1 * 16 + n2;
|
|
194
|
+
}
|
|
195
|
+
return bytes;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Convert a `bigint` to a `Uint8Array`.
|
|
199
|
+
*
|
|
200
|
+
* This assumes that the `bigint` is an unsigned integer. To convert a signed
|
|
201
|
+
* `bigint` instead, use {@link signedBigIntToBytes}.
|
|
202
|
+
*
|
|
203
|
+
* @param value - The bigint to convert to bytes.
|
|
204
|
+
* @returns The bytes as `Uint8Array`.
|
|
205
|
+
*/
|
|
206
|
+
export function bigIntToBytes(value) {
|
|
207
|
+
assert(typeof value === 'bigint', 'Value must be a bigint.');
|
|
208
|
+
assert(value >= BigInt(0), 'Value must be a non-negative bigint.');
|
|
209
|
+
const hexadecimal = value.toString(16);
|
|
210
|
+
return hexToBytes(hexadecimal);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Check if a `bigint` fits in a certain number of bytes.
|
|
214
|
+
*
|
|
215
|
+
* @param value - The `bigint` to check.
|
|
216
|
+
* @param bytes - The number of bytes.
|
|
217
|
+
* @returns Whether the `bigint` fits in the number of bytes.
|
|
218
|
+
*/
|
|
219
|
+
function bigIntFits(value, bytes) {
|
|
220
|
+
assert(bytes > 0);
|
|
221
|
+
/* eslint-disable no-bitwise */
|
|
222
|
+
const mask = value >> BigInt(31);
|
|
223
|
+
return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0));
|
|
224
|
+
/* eslint-enable no-bitwise */
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Convert a signed `bigint` to a `Uint8Array`. This uses two's complement
|
|
228
|
+
* encoding to represent negative numbers.
|
|
229
|
+
*
|
|
230
|
+
* To convert an unsigned `bigint` to a `Uint8Array` instead, use
|
|
231
|
+
* {@link bigIntToBytes}.
|
|
232
|
+
*
|
|
233
|
+
* @see https://en.wikipedia.org/wiki/Two%27s_complement
|
|
234
|
+
* @param value - The number to convert to bytes.
|
|
235
|
+
* @param byteLength - The length of the resulting `Uint8Array`. If the number
|
|
236
|
+
* is larger than the maximum value that can be represented by the given length,
|
|
237
|
+
* an error is thrown.
|
|
238
|
+
* @returns The bytes as `Uint8Array`.
|
|
239
|
+
*/
|
|
240
|
+
export function signedBigIntToBytes(value, byteLength) {
|
|
241
|
+
assert(typeof value === 'bigint', 'Value must be a bigint.');
|
|
242
|
+
assert(typeof byteLength === 'number', 'Byte length must be a number.');
|
|
243
|
+
assert(byteLength > 0, 'Byte length must be greater than 0.');
|
|
244
|
+
assert(bigIntFits(value, byteLength), 'Byte length is too small to represent the given value.');
|
|
245
|
+
// ESLint doesn't like mutating function parameters, so to avoid having to
|
|
246
|
+
// disable the rule, we create a new variable.
|
|
247
|
+
let numberValue = value;
|
|
248
|
+
const bytes = new Uint8Array(byteLength);
|
|
249
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
250
|
+
bytes[i] = Number(BigInt.asUintN(8, numberValue));
|
|
251
|
+
// eslint-disable-next-line no-bitwise
|
|
252
|
+
numberValue >>= BigInt(8);
|
|
253
|
+
}
|
|
254
|
+
return bytes.reverse();
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Convert a `number` to a `Uint8Array`.
|
|
258
|
+
*
|
|
259
|
+
* @param value - The number to convert to bytes.
|
|
260
|
+
* @returns The bytes as `Uint8Array`.
|
|
261
|
+
* @throws If the number is not a safe integer.
|
|
262
|
+
*/
|
|
263
|
+
export function numberToBytes(value) {
|
|
264
|
+
assert(typeof value === 'number', 'Value must be a number.');
|
|
265
|
+
assert(value >= 0, 'Value must be a non-negative number.');
|
|
266
|
+
assert(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToBytes` instead.');
|
|
267
|
+
const hexadecimal = value.toString(16);
|
|
268
|
+
return hexToBytes(hexadecimal);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Convert a `string` to a UTF-8 encoded `Uint8Array`.
|
|
272
|
+
*
|
|
273
|
+
* @param value - The string to convert to bytes.
|
|
274
|
+
* @returns The bytes as `Uint8Array`.
|
|
275
|
+
*/
|
|
276
|
+
export function stringToBytes(value) {
|
|
277
|
+
assert(typeof value === 'string', 'Value must be a string.');
|
|
278
|
+
return new TextEncoder().encode(value);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Convert a base64 encoded string to a `Uint8Array`.
|
|
282
|
+
*
|
|
283
|
+
* @param value - The base64 encoded string to convert to bytes.
|
|
284
|
+
* @returns The bytes as `Uint8Array`.
|
|
285
|
+
*/
|
|
286
|
+
export function base64ToBytes(value) {
|
|
287
|
+
assert(typeof value === 'string', 'Value must be a string.');
|
|
288
|
+
return base64.decode(value);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,
|
|
292
|
+
* a `bigint`, a `number`, or a `string`.
|
|
293
|
+
*
|
|
294
|
+
* This will attempt to guess the type of the value based on its type and
|
|
295
|
+
* contents. For more control over the conversion, use the more specific
|
|
296
|
+
* conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.
|
|
297
|
+
*
|
|
298
|
+
* If the value is a `string`, and it is prefixed with `0x`, it will be
|
|
299
|
+
* interpreted as a hexadecimal string. Otherwise, it will be interpreted as a
|
|
300
|
+
* UTF-8 string. To convert a hexadecimal string to bytes without interpreting
|
|
301
|
+
* it as a UTF-8 string, use {@link hexToBytes} instead.
|
|
302
|
+
*
|
|
303
|
+
* If the value is a `bigint`, it is assumed to be unsigned. To convert a signed
|
|
304
|
+
* `bigint` to bytes, use {@link signedBigIntToBytes} instead.
|
|
305
|
+
*
|
|
306
|
+
* If the value is a `Uint8Array`, it will be returned as-is.
|
|
307
|
+
*
|
|
308
|
+
* @param value - The value to convert to bytes.
|
|
309
|
+
* @returns The bytes as `Uint8Array`.
|
|
310
|
+
*/
|
|
311
|
+
export function valueToBytes(value) {
|
|
312
|
+
if (typeof value === 'bigint') {
|
|
313
|
+
return bigIntToBytes(value);
|
|
314
|
+
}
|
|
315
|
+
if (typeof value === 'number') {
|
|
316
|
+
return numberToBytes(value);
|
|
317
|
+
}
|
|
318
|
+
if (typeof value === 'string') {
|
|
319
|
+
if (value.startsWith('0x')) {
|
|
320
|
+
return hexToBytes(value);
|
|
321
|
+
}
|
|
322
|
+
return stringToBytes(value);
|
|
323
|
+
}
|
|
324
|
+
if (isArrayBufferBytes(value)) {
|
|
325
|
+
return value;
|
|
326
|
+
}
|
|
327
|
+
if (isBytes(value)) {
|
|
328
|
+
return new Uint8Array(value);
|
|
329
|
+
}
|
|
330
|
+
throw new TypeError(`Unsupported value type: "${typeof value}".`);
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Concatenate multiple byte-like values into a single `Uint8Array`. The values
|
|
334
|
+
* can be `Uint8Array`, `bigint`, `number`, or `string`. This uses
|
|
335
|
+
* {@link valueToBytes} under the hood to convert each value to bytes. Refer to
|
|
336
|
+
* the documentation of that function for more information.
|
|
337
|
+
*
|
|
338
|
+
* @param values - The values to concatenate.
|
|
339
|
+
* @returns The concatenated bytes as `Uint8Array`.
|
|
340
|
+
*/
|
|
341
|
+
export function concatBytes(values) {
|
|
342
|
+
const normalizedValues = new Array(values.length);
|
|
343
|
+
let byteLength = 0;
|
|
344
|
+
for (let i = 0; i < values.length; i++) {
|
|
345
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
346
|
+
const value = valueToBytes(values[i]);
|
|
347
|
+
normalizedValues[i] = value;
|
|
348
|
+
byteLength += value.length;
|
|
349
|
+
}
|
|
350
|
+
const bytes = new Uint8Array(byteLength);
|
|
351
|
+
let offset = 0;
|
|
352
|
+
for (const normalizedValue of normalizedValues) {
|
|
353
|
+
// While we could simply spread the values into an array and use
|
|
354
|
+
// `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.
|
|
355
|
+
bytes.set(normalizedValue, offset);
|
|
356
|
+
offset += normalizedValue.length;
|
|
357
|
+
}
|
|
358
|
+
return bytes;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Create a {@link DataView} from a {@link Uint8Array}. This is a convenience
|
|
362
|
+
* function that avoids having to create a {@link DataView} manually, which
|
|
363
|
+
* requires passing the `byteOffset` and `byteLength` parameters every time.
|
|
364
|
+
*
|
|
365
|
+
* Not passing the `byteOffset` and `byteLength` parameters can result in
|
|
366
|
+
* unexpected behavior when the {@link Uint8Array} is a view of a larger
|
|
367
|
+
* {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.
|
|
368
|
+
*
|
|
369
|
+
* This function also supports Node.js {@link Buffer}s.
|
|
370
|
+
*
|
|
371
|
+
* @example
|
|
372
|
+
* ```typescript
|
|
373
|
+
* const bytes = new Uint8Array([1, 2, 3]);
|
|
374
|
+
*
|
|
375
|
+
* // This is equivalent to:
|
|
376
|
+
* // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
377
|
+
* const dataView = createDataView(bytes);
|
|
378
|
+
* ```
|
|
379
|
+
* @param bytes - The bytes to create the {@link DataView} from.
|
|
380
|
+
* @returns The {@link DataView}.
|
|
381
|
+
*/
|
|
382
|
+
export function createDataView(bytes) {
|
|
383
|
+
// To maintain compatibility with Node.js, we need to check if the bytes are
|
|
384
|
+
// a Buffer. If so, we need to slice the buffer to get the underlying
|
|
385
|
+
// ArrayBuffer.
|
|
386
|
+
// eslint-disable-next-line no-restricted-globals
|
|
387
|
+
if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {
|
|
388
|
+
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
389
|
+
return new DataView(buffer);
|
|
390
|
+
}
|
|
391
|
+
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Compare two Uint8Arrays using a constant-time style loop to reduce timing
|
|
395
|
+
* side-channels when comparing sensitive data (e.g., mnemonic bytes, keys,
|
|
396
|
+
* authentication tags). Does not early-return on the first difference:
|
|
397
|
+
* work done depends only on the input lengths, so byte content does not affect timing.
|
|
398
|
+
*
|
|
399
|
+
* When to use:
|
|
400
|
+
* - Use for secret or security-sensitive byte comparisons to avoid content-based timing leaks.
|
|
401
|
+
* - Prefer when inputs are fixed-length (or validated to equal length) at the API boundary.
|
|
402
|
+
*
|
|
403
|
+
* @param a - The first Uint8Array to compare.
|
|
404
|
+
* @param b - The second Uint8Array to compare.
|
|
405
|
+
* @returns Whether the Uint8Arrays are equal.
|
|
406
|
+
*/
|
|
407
|
+
export function areUint8ArraysEqual(a, b) {
|
|
408
|
+
// eslint-disable-next-line no-bitwise
|
|
409
|
+
let diff = a.byteLength ^ b.byteLength;
|
|
410
|
+
const len = Math.max(a.byteLength, b.byteLength);
|
|
411
|
+
for (let i = 0; i < len; i++) {
|
|
412
|
+
const aByte = a[i] ?? 0;
|
|
413
|
+
const bByte = b[i] ?? 0;
|
|
414
|
+
// eslint-disable-next-line no-bitwise
|
|
415
|
+
diff |= aByte ^ bByte;
|
|
416
|
+
}
|
|
417
|
+
return diff === 0;
|
|
418
|
+
}
|
|
419
|
+
//# sourceMappingURL=bytes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,KAAK,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAE9D,2BAA2B;AAC3B,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAExC,2BAA2B;AAC3B,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAIhC;;;;;;;;;;;;;GAaG;AACH,SAAS,8BAA8B;IACrC,6EAA6E;IAC7E,6EAA6E;IAC7E,6EAA6E;IAC7E,eAAe;IACf,MAAM,WAAW,GAAa,EAAE,CAAC;IAEjC,OAAO,GAAG,EAAE;QACV,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC7B,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,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AC","sourcesContent":["import { base64 } from '@scure/base';\n\nimport { assert } from './assert.js';\nimport type { Hex } from './hex.js';\nimport { add0x, assertIsHexString, remove0x } from './hex.js';\n\n// '0'.charCodeAt(0) === 48\nconst HEX_MINIMUM_NUMBER_CHARACTER = 48;\n\n// '9'.charCodeAt(0) === 57\nconst HEX_MAXIMUM_NUMBER_CHARACTER = 58;\nconst HEX_CHARACTER_OFFSET = 87;\n\nexport type Bytes = bigint | number | string | Uint8Array;\n\n/**\n * Memoized function that returns an array to be used as a lookup table for\n * converting bytes to hexadecimal values.\n *\n * The array is created lazily and then cached for future use. The benefit of\n * this approach is that the performance of converting bytes to hex is much\n * better than if we were to call `toString(16)` on each byte.\n *\n * The downside is that the array is created once and then never garbage\n * collected. This is not a problem in practice because the array is only 256\n * elements long.\n *\n * @returns A function that returns the lookup table.\n */\nfunction getPrecomputedHexValuesBuilder(): () => string[] {\n // To avoid issues with tree shaking, we need to use a function to return the\n // array. This is because the array is only used in the `bytesToHex` function\n // and if we were to use a global variable, the array might be removed by the\n // tree shaker.\n const lookupTable: string[] = [];\n\n return () => {\n if (lookupTable.length === 0) {\n for (let i = 0; i < 256; i++) {\n lookupTable.push(i.toString(16).padStart(2, '0'));\n }\n }\n\n return lookupTable;\n };\n}\n\n/**\n * Function implementation of the {@link getPrecomputedHexValuesBuilder}\n * function.\n */\nconst getPrecomputedHexValues = getPrecomputedHexValuesBuilder();\n\n/**\n * Check if a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @returns Whether the value is a `Uint8Array`.\n */\nexport function isBytes(value: unknown): value is Uint8Array {\n return value instanceof Uint8Array;\n}\n\n/**\n * Check if a value is a `Uint8Array` backed by an `ArrayBuffer`.\n *\n * @param value - The value to check.\n * @returns Whether the value is a `Uint8Array` backed by an `ArrayBuffer`.\n */\nfunction isArrayBufferBytes(value: unknown): value is Uint8Array<ArrayBuffer> {\n return isBytes(value) && value.buffer instanceof ArrayBuffer;\n}\n\n/**\n * Assert that a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @throws If the value is not a `Uint8Array`.\n */\nexport function assertIsBytes(value: unknown): asserts value is Uint8Array {\n assert(isBytes(value), 'Value must be a Uint8Array.');\n}\n\n/**\n * Convert a `Uint8Array` to a hexadecimal string.\n *\n * @param bytes - The bytes to convert to a hexadecimal string.\n * @returns The hexadecimal string.\n */\nexport function bytesToHex(bytes: Uint8Array): Hex {\n assertIsBytes(bytes);\n\n if (bytes.length === 0) {\n return '0x';\n }\n\n const lookupTable = getPrecomputedHexValues();\n const hexadecimal = new Array(bytes.length);\n\n for (let i = 0; i < bytes.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n hexadecimal[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hexadecimal.join(''));\n}\n\n/**\n * Convert a `Uint8Array` to a `bigint`.\n *\n * To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}.\n * To convert a two's complement encoded `Uint8Array` to a `bigint`, use\n * {@link bytesToSignedBigInt}.\n *\n * @param bytes - The bytes to convert to a `bigint`.\n * @returns The `bigint`.\n */\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n const hexadecimal = bytesToHex(bytes);\n return BigInt(hexadecimal);\n}\n\n/**\n * Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are\n * encoded in two's complement.\n *\n * To convert a `Uint8Array` to an unsigned `bigint` instead, use\n * {@link bytesToBigInt}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param bytes - The bytes to convert to a signed `bigint`.\n * @returns The signed `bigint`.\n */\nexport function bytesToSignedBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n let value = BigInt(0);\n for (const byte of bytes) {\n // eslint-disable-next-line no-bitwise\n value = (value << BigInt(8)) + BigInt(byte);\n }\n\n return BigInt.asIntN(bytes.length * 8, value);\n}\n\n/**\n * Convert a `Uint8Array` to a `number`.\n *\n * To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}.\n *\n * @param bytes - The bytes to convert to a number.\n * @returns The number.\n * @throws If the resulting number is not a safe integer.\n */\nexport function bytesToNumber(bytes: Uint8Array): number {\n assertIsBytes(bytes);\n\n const bigint = bytesToBigInt(bytes);\n\n assert(\n bigint <= BigInt(Number.MAX_SAFE_INTEGER),\n 'Number is not a safe integer. Use `bytesToBigInt` instead.',\n );\n\n return Number(bigint);\n}\n\n/**\n * Convert a UTF-8 encoded `Uint8Array` to a `string`.\n *\n * @param bytes - The bytes to convert to a string.\n * @returns The string.\n */\nexport function bytesToString(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert a `Uint8Array` to a base64 encoded string.\n *\n * @param bytes - The bytes to convert to a base64 encoded string.\n * @returns The base64 encoded string.\n */\nexport function bytesToBase64(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return base64.encode(bytes);\n}\n\n/**\n * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be\n * prefixed with `0x`. It accepts even and odd length strings.\n *\n * If the value is \"0x\", an empty `Uint8Array` is returned.\n *\n * @param value - The hexadecimal string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function hexToBytes(value: string): Uint8Array<ArrayBuffer> {\n // \"0x\" is often used as empty byte array.\n if (value?.toLowerCase?.() === '0x') {\n return new Uint8Array();\n }\n\n assertIsHexString(value);\n\n // Remove the `0x` prefix if it exists, and pad the string to have an even\n // number of characters.\n const strippedValue = remove0x(value).toLowerCase();\n const normalizedValue =\n strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;\n const bytes = new Uint8Array(normalizedValue.length / 2);\n\n for (let i = 0; i < bytes.length; i++) {\n // While this is not the prettiest way to convert a hexadecimal string to a\n // `Uint8Array`, it is a lot faster than using `parseInt` to convert each\n // character.\n const c1 = normalizedValue.charCodeAt(i * 2);\n const c2 = normalizedValue.charCodeAt(i * 2 + 1);\n const n1 =\n c1 -\n (c1 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n const n2 =\n c2 -\n (c2 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n\n bytes[i] = n1 * 16 + n2;\n }\n\n return bytes;\n}\n\n/**\n * Convert a `bigint` to a `Uint8Array`.\n *\n * This assumes that the `bigint` is an unsigned integer. To convert a signed\n * `bigint` instead, use {@link signedBigIntToBytes}.\n *\n * @param value - The bigint to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function bigIntToBytes(value: bigint): Uint8Array<ArrayBuffer> {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= BigInt(0), 'Value must be a non-negative bigint.');\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Check if a `bigint` fits in a certain number of bytes.\n *\n * @param value - The `bigint` to check.\n * @param bytes - The number of bytes.\n * @returns Whether the `bigint` fits in the number of bytes.\n */\nfunction bigIntFits(value: bigint, bytes: number): boolean {\n assert(bytes > 0);\n\n /* eslint-disable no-bitwise */\n const mask = value >> BigInt(31);\n return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0));\n /* eslint-enable no-bitwise */\n}\n\n/**\n * Convert a signed `bigint` to a `Uint8Array`. This uses two's complement\n * encoding to represent negative numbers.\n *\n * To convert an unsigned `bigint` to a `Uint8Array` instead, use\n * {@link bigIntToBytes}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param value - The number to convert to bytes.\n * @param byteLength - The length of the resulting `Uint8Array`. If the number\n * is larger than the maximum value that can be represented by the given length,\n * an error is thrown.\n * @returns The bytes as `Uint8Array`.\n */\nexport function signedBigIntToBytes(\n value: bigint,\n byteLength: number,\n): Uint8Array<ArrayBuffer> {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(typeof byteLength === 'number', 'Byte length must be a number.');\n assert(byteLength > 0, 'Byte length must be greater than 0.');\n assert(\n bigIntFits(value, byteLength),\n 'Byte length is too small to represent the given value.',\n );\n\n // ESLint doesn't like mutating function parameters, so to avoid having to\n // disable the rule, we create a new variable.\n let numberValue = value;\n const bytes = new Uint8Array(byteLength);\n\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number(BigInt.asUintN(8, numberValue));\n // eslint-disable-next-line no-bitwise\n numberValue >>= BigInt(8);\n }\n\n return bytes.reverse();\n}\n\n/**\n * Convert a `number` to a `Uint8Array`.\n *\n * @param value - The number to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n * @throws If the number is not a safe integer.\n */\nexport function numberToBytes(value: number): Uint8Array<ArrayBuffer> {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToBytes` instead.',\n );\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Convert a `string` to a UTF-8 encoded `Uint8Array`.\n *\n * @param value - The string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function stringToBytes(value: string): Uint8Array<ArrayBuffer> {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return new TextEncoder().encode(value);\n}\n\n/**\n * Convert a base64 encoded string to a `Uint8Array`.\n *\n * @param value - The base64 encoded string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function base64ToBytes(value: string): Uint8Array<ArrayBuffer> {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return base64.decode(value) as Uint8Array<ArrayBuffer>;\n}\n\n/**\n * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,\n * a `bigint`, a `number`, or a `string`.\n *\n * This will attempt to guess the type of the value based on its type and\n * contents. For more control over the conversion, use the more specific\n * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.\n *\n * If the value is a `string`, and it is prefixed with `0x`, it will be\n * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a\n * UTF-8 string. To convert a hexadecimal string to bytes without interpreting\n * it as a UTF-8 string, use {@link hexToBytes} instead.\n *\n * If the value is a `bigint`, it is assumed to be unsigned. To convert a signed\n * `bigint` to bytes, use {@link signedBigIntToBytes} instead.\n *\n * If the value is a `Uint8Array`, it will be returned as-is.\n *\n * @param value - The value to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function valueToBytes(value: Bytes): Uint8Array<ArrayBuffer> {\n if (typeof value === 'bigint') {\n return bigIntToBytes(value);\n }\n\n if (typeof value === 'number') {\n return numberToBytes(value);\n }\n\n if (typeof value === 'string') {\n if (value.startsWith('0x')) {\n return hexToBytes(value);\n }\n\n return stringToBytes(value);\n }\n\n if (isArrayBufferBytes(value)) {\n return value;\n }\n\n if (isBytes(value)) {\n return new Uint8Array(value);\n }\n\n throw new TypeError(`Unsupported value type: \"${typeof value}\".`);\n}\n\n/**\n * Concatenate multiple byte-like values into a single `Uint8Array`. The values\n * can be `Uint8Array`, `bigint`, `number`, or `string`. This uses\n * {@link valueToBytes} under the hood to convert each value to bytes. Refer to\n * the documentation of that function for more information.\n *\n * @param values - The values to concatenate.\n * @returns The concatenated bytes as `Uint8Array`.\n */\nexport function concatBytes(values: Bytes[]): Uint8Array<ArrayBuffer> {\n const normalizedValues = new Array<Uint8Array<ArrayBuffer>>(values.length);\n let byteLength = 0;\n\n for (let i = 0; i < values.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const value = valueToBytes(values[i]!);\n\n normalizedValues[i] = value;\n byteLength += value.length;\n }\n\n const bytes = new Uint8Array(byteLength);\n let offset = 0;\n for (const normalizedValue of normalizedValues) {\n // While we could simply spread the values into an array and use\n // `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.\n bytes.set(normalizedValue, offset);\n offset += normalizedValue.length;\n }\n\n return bytes;\n}\n\n/**\n * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience\n * function that avoids having to create a {@link DataView} manually, which\n * requires passing the `byteOffset` and `byteLength` parameters every time.\n *\n * Not passing the `byteOffset` and `byteLength` parameters can result in\n * unexpected behavior when the {@link Uint8Array} is a view of a larger\n * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.\n *\n * This function also supports Node.js {@link Buffer}s.\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([1, 2, 3]);\n *\n * // This is equivalent to:\n * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n * const dataView = createDataView(bytes);\n * ```\n * @param bytes - The bytes to create the {@link DataView} from.\n * @returns The {@link DataView}.\n */\nexport function createDataView<\n ArrayBufferImplementation extends ArrayBufferLike,\n>(\n bytes: Uint8Array<ArrayBufferImplementation>,\n): DataView<ArrayBufferImplementation> {\n // To maintain compatibility with Node.js, we need to check if the bytes are\n // a Buffer. If so, we need to slice the buffer to get the underlying\n // ArrayBuffer.\n // eslint-disable-next-line no-restricted-globals\n if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {\n const buffer = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n );\n\n return new DataView<ArrayBufferImplementation>(buffer);\n }\n\n return new DataView<ArrayBufferImplementation>(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n}\n\n/**\n * Compare two Uint8Arrays using a constant-time style loop to reduce timing\n * side-channels when comparing sensitive data (e.g., mnemonic bytes, keys,\n * authentication tags). Does not early-return on the first difference:\n * work done depends only on the input lengths, so byte content does not affect timing.\n *\n * When to use:\n * - Use for secret or security-sensitive byte comparisons to avoid content-based timing leaks.\n * - Prefer when inputs are fixed-length (or validated to equal length) at the API boundary.\n *\n * @param a - The first Uint8Array to compare.\n * @param b - The second Uint8Array to compare.\n * @returns Whether the Uint8Arrays are equal.\n */\nexport function areUint8ArraysEqual(a: Uint8Array, b: Uint8Array): boolean {\n // eslint-disable-next-line no-bitwise\n let diff = a.byteLength ^ b.byteLength;\n const len = Math.max(a.byteLength, b.byteLength);\n\n for (let i = 0; i < len; i++) {\n const aByte = a[i] ?? 0;\n const bByte = b[i] ?? 0;\n // eslint-disable-next-line no-bitwise\n diff |= aByte ^ bByte;\n }\n\n return diff === 0;\n}\n"]}
|
package/dist/coercers.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Hex } from '@metamask/byte-utils';
|
|
2
1
|
import type { Infer } from '@metamask/superstruct';
|
|
2
|
+
import type { Hex } from './hex.js';
|
|
3
3
|
declare const NumberLikeStruct: import("@metamask/superstruct").Struct<string | number | bigint, null>;
|
|
4
4
|
declare const BytesLikeStruct: import("@metamask/superstruct").Struct<Uint8Array<ArrayBuffer> | `0x${string}`, null>;
|
|
5
5
|
export type NumberLike = Infer<typeof NumberLikeStruct>;
|
package/dist/coercers.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coercers.d.ts","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"coercers.d.ts","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAcnD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAGpC,QAAA,MAAM,gBAAgB,wEAAyD,CAAC;AAKhF,QAAA,MAAM,eAAe,uFAAiD,CAAC;AASvE,MAAM,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AACxD,MAAM,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAkBtD;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAgBtD;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,SAAS,GAAG,UAAU,CAkBxD;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,GAAG,CAqB/C"}
|
package/dist/coercers.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { bytesToHex, hexToBytes } from '@metamask/byte-utils';
|
|
2
1
|
import { bigint, coerce, create, instance, number, string, StructError, union, } from '@metamask/superstruct';
|
|
3
|
-
import { assert } from '
|
|
2
|
+
import { assert } from './assert.js';
|
|
3
|
+
import { bytesToHex, hexToBytes } from './bytes.js';
|
|
4
4
|
import { StrictHexStruct } from './hex.js';
|
|
5
5
|
const NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);
|
|
6
6
|
const NumberCoercer = coerce(number(), NumberLikeStruct, Number);
|
package/dist/coercers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coercers.js","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"coercers.js","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":"AACA,OAAO,EACL,MAAM,EACN,MAAM,EACN,MAAM,EACN,QAAQ,EACR,MAAM,EACN,MAAM,EACN,WAAW,EACX,KAAK,GACN,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAEpD,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAE3C,MAAM,gBAAgB,GAAG,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,EAAE,eAAe,CAAC,CAAC,CAAC;AAChF,MAAM,aAAa,GAAG,MAAM,CAAC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KAAK,CAAC,IAAI,CAC7D,CAAC;QACJ,CAAC;QAED,0BAA0B;QAC1B,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { Infer } from '@metamask/superstruct';\nimport {\n bigint,\n coerce,\n create,\n instance,\n number,\n string,\n StructError,\n union,\n} from '@metamask/superstruct';\n\nimport { assert } from './assert.js';\nimport { bytesToHex, hexToBytes } from './bytes.js';\nimport type { Hex } from './hex.js';\nimport { StrictHexStruct } from './hex.js';\n\nconst NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);\nconst NumberCoercer = coerce(number(), NumberLikeStruct, Number);\nconst BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Only referenced via `Infer<typeof ...>` below, but the value is required for that.\nconst BytesLikeStruct = union([StrictHexStruct, instance(Uint8Array)]);\nconst BytesCoercer = coerce(\n instance(Uint8Array),\n union([StrictHexStruct]),\n hexToBytes,\n);\n\nconst HexCoercer = coerce(StrictHexStruct, instance(Uint8Array), bytesToHex);\n\nexport type NumberLike = Infer<typeof NumberLikeStruct>;\nexport type BytesLike = Infer<typeof BytesLikeStruct>;\n\n/**\n * Create a number from a number-like value.\n *\n * - If the value is a number, it is returned as-is.\n * - If the value is a `bigint`, it is converted to a number.\n * - If the value is a string, it is interpreted as a decimal number.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number.\n *\n * This validates that the value is a number-like value, and that the resulting\n * number is not `NaN` or `Infinity`.\n *\n * @example\n * ```typescript\n * const value = createNumber('0x010203');\n * console.log(value); // 66051\n *\n * const otherValue = createNumber(123n);\n * console.log(otherValue); // 123\n * ```\n * @param value - The value to create the number from.\n * @returns The created number.\n * @throws If the value is not a number-like value, or if the resulting number\n * is `NaN` or `Infinity`.\n */\nexport function createNumber(value: NumberLike): number {\n try {\n const result = create(value, NumberCoercer);\n\n assert(\n Number.isFinite(result),\n `Expected a number-like value, got \"${value}\".`,\n );\n\n return result;\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(`Expected a number-like value, got \"${value}\".`);\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a `bigint` from a number-like value.\n *\n * - If the value is a number, it is converted to a `bigint`.\n * - If the value is a `bigint`, it is returned as-is.\n * - If the value is a string, it is interpreted as a decimal number and\n * converted to a `bigint`.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number and converted to a `bigint`.\n *\n * @example\n * ```typescript\n * const value = createBigInt('0x010203');\n * console.log(value); // 16909060n\n *\n * const otherValue = createBigInt(123);\n * console.log(otherValue); // 123n\n * ```\n * @param value - The value to create the bigint from.\n * @returns The created bigint.\n * @throws If the value is not a number-like value.\n */\nexport function createBigInt(value: NumberLike): bigint {\n try {\n // The `BigInt` constructor throws if the value is not a number-like value.\n // There is no need to validate the value manually.\n return create(value, BigIntCoercer);\n } catch (error) {\n /* istanbul ignore else -- Coercion failures always surface as StructError; the rethrow below is a safety net. */\n if (error instanceof StructError) {\n throw new Error(\n `Expected a number-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a byte array from a bytes-like value.\n *\n * - If the value is a byte array, it is returned as-is.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is interpreted\n * as a hexadecimal number and converted to a byte array.\n *\n * @example\n * ```typescript\n * const value = createBytes('0x010203');\n * console.log(value); // Uint8Array [ 1, 2, 3 ]\n *\n * const otherValue = createBytes('0x010203');\n * console.log(otherValue); // Uint8Array [ 1, 2, 3 ]\n * ```\n * @param value - The value to create the byte array from.\n * @returns The created byte array.\n * @throws If the value is not a bytes-like value.\n */\nexport function createBytes(value: BytesLike): Uint8Array {\n if (typeof value === 'string' && value.toLowerCase() === '0x') {\n return new Uint8Array();\n }\n\n try {\n return create(value, BytesCoercer);\n } catch (error) {\n /* istanbul ignore else -- Coercion failures always surface as StructError; the rethrow below is a safety net. */\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a hexadecimal string from a bytes-like value.\n *\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is returned\n * as-is.\n * - If the value is a `Uint8Array`, it is converted to a hex string.\n *\n * @example\n * ```typescript\n * const value = createHex(new Uint8Array([1, 2, 3]));\n * console.log(value); // '0x010203'\n *\n * const otherValue = createHex('0x010203');\n * console.log(otherValue); // '0x010203'\n * ```\n * @param value - The value to create the hex string from.\n * @returns The created hex string.\n * @throws If the value is not a bytes-like value.\n */\nexport function createHex(value: BytesLike): Hex {\n if (\n (value instanceof Uint8Array && value.length === 0) ||\n (typeof value === 'string' && value.toLowerCase() === '0x')\n ) {\n return '0x';\n }\n\n try {\n return create(value, HexCoercer);\n } catch (error) {\n /* istanbul ignore else -- Coercion failures always surface as StructError; the rethrow below is a safety net. */\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n"]}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type guard for determining whether the given value is an error object with a
|
|
3
|
+
* `code` property such as the type of error that Node throws for filesystem
|
|
4
|
+
* operations, etc.
|
|
5
|
+
*
|
|
6
|
+
* @param error - The object to check.
|
|
7
|
+
* @returns A boolean.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isErrorWithCode(error: unknown): error is {
|
|
10
|
+
code: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Type guard for determining whether the given value is an error object with a
|
|
14
|
+
* `message` property, such as an instance of Error.
|
|
15
|
+
*
|
|
16
|
+
* @param error - The object to check.
|
|
17
|
+
* @returns A boolean.
|
|
18
|
+
*/
|
|
19
|
+
export declare function isErrorWithMessage(error: unknown): error is {
|
|
20
|
+
message: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Type guard for determining whether the given value is an error object with a
|
|
24
|
+
* `stack` property, such as an instance of Error.
|
|
25
|
+
*
|
|
26
|
+
* @param error - The object to check.
|
|
27
|
+
* @returns A boolean.
|
|
28
|
+
*/
|
|
29
|
+
export declare function isErrorWithStack(error: unknown): error is {
|
|
30
|
+
stack: string;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Attempts to obtain the message from a possible error object, defaulting to an
|
|
34
|
+
* empty string if it is impossible to do so.
|
|
35
|
+
*
|
|
36
|
+
* @param error - The possible error to get the message from.
|
|
37
|
+
* @returns The message if `error` is an object with a `message` property;
|
|
38
|
+
* the string version of `error` if it is not `undefined` or `null`; otherwise
|
|
39
|
+
* an empty string.
|
|
40
|
+
*/
|
|
41
|
+
export declare function getErrorMessage(error: unknown): string;
|
|
42
|
+
/**
|
|
43
|
+
* Builds a new error object, linking it to the original error via the `cause`
|
|
44
|
+
* property if it is an Error.
|
|
45
|
+
*
|
|
46
|
+
* This function is useful to reframe error messages in general, but is
|
|
47
|
+
* _critical_ when interacting with any of Node's filesystem functions as
|
|
48
|
+
* provided via `fs.promises`, because these do not produce stack traces in the
|
|
49
|
+
* case of an I/O error (see <https://github.com/nodejs/node/issues/30944>).
|
|
50
|
+
*
|
|
51
|
+
* @param originalError - The error to be wrapped (something throwable).
|
|
52
|
+
* @param message - The desired message of the new error.
|
|
53
|
+
* @returns A new error object.
|
|
54
|
+
*/
|
|
55
|
+
export declare function wrapError<Throwable>(originalError: Throwable, message: string): Error & {
|
|
56
|
+
code?: string;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Ensures we have a proper Error object.
|
|
60
|
+
* If the input is already an Error, returns it unchanged.
|
|
61
|
+
* Otherwise, converts to an Error with an appropriate message and preserves
|
|
62
|
+
* the original value as the cause.
|
|
63
|
+
*
|
|
64
|
+
* @param error - The caught error (could be Error, string, or unknown).
|
|
65
|
+
* @returns A proper Error instance.
|
|
66
|
+
*/
|
|
67
|
+
export declare function ensureError(error: unknown): Error;
|
|
68
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAmBA;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAEzE;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,OAAO,GACb,KAAK,IAAI;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAE9B;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAE3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAWtD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,SAAS,CAAC,SAAS,EACjC,aAAa,EAAE,SAAS,EACxB,OAAO,EAAE,MAAM,GACd,KAAK,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAqB3B;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAQjD"}
|