@metamask/utils 3.1.0 → 3.3.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 ADDED
@@ -0,0 +1,102 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [3.3.0]
10
+ ### Added
11
+ - Add more assertion utils ([#49](https://github.com/MetaMask/utils/pull/49))
12
+ - Add JSON-RPC error validation functions ([#46](https://github.com/MetaMask/utils/pull/46))
13
+ - Add convenience function for creating a `DataView` ([#45](https://github.com/MetaMask/utils/pull/45))
14
+
15
+ ### Fixed
16
+ - Update JSON validation logic ([#47](https://github.com/MetaMask/utils/pull/47))
17
+ - Validation would previously allow for `undefined` values, which is not a standard JSON type
18
+
19
+ ## [3.2.0]
20
+ ### Added
21
+ - Add `PendingJsonRpcResponse` type ([#43](https://github.com/MetaMask/utils/pull/43))
22
+ - Add utils for converting between numbers and hex ([#41](https://github.com/MetaMask/utils/pull/41))
23
+ - Add coercion utils ([#38](https://github.com/MetaMask/utils/pull/38))
24
+
25
+ ## [3.1.0]
26
+ ### Added
27
+ - Add assertion utils ([#33](https://github.com/MetaMask/utils/pull/33))
28
+ - Add util functions for encoding and decoding bytes ([#34](https://github.com/MetaMask/utils/pull/34))
29
+
30
+ ### Fixed
31
+ - Make JSON-RPC error `data` property optional ([#31](https://github.com/MetaMask/utils/pull/31))
32
+ - Don't include test files in dist folder ([#35](https://github.com/MetaMask/utils/pull/35))
33
+ - Fix typo in README ([#28](https://github.com/MetaMask/utils/pull/28))
34
+
35
+ ## [3.0.3]
36
+ ### Fixed
37
+ - Allow omitting JSON-RPC params when params can be undefined ([#29](https://github.com/MetaMask/utils/pull/29))
38
+
39
+ ## [3.0.2]
40
+ ### Fixed
41
+ - Bump `superstruct` to ^0.16.5 ([#26](https://github.com/MetaMask/utils/pull/26))
42
+ - `superstruct`s 0.16.1 through 0.16.4 were not compatible with Node 14; this restores that compatibility.
43
+
44
+ ## [3.0.1]
45
+ ### Fixed
46
+ - Promote `@types/debug` from development dependencies to production dependencies ([#23](https://github.com/MetaMask/utils/pull/23))
47
+
48
+ ## [3.0.0]
49
+ ### Added
50
+ - Add logging functions ([#20](https://github.com/MetaMask/utils/pull/20))
51
+ - Add frozen collections (implemented in [#5](https://github.com/MetaMask/utils/pull/5) but exported in [#19](https://github.com/MetaMask/utils/pull/19))
52
+
53
+ ### Changed
54
+ - **BREAKING:** Improve types and type validation ([#19](https://github.com/MetaMask/utils/pull/19))
55
+ - Various type changes have been made that might be breaking:
56
+ - The `JsonRpcRequest` and `JsonRpcNotification` types now include a generic constraint requiring that the `Params` type extends the `JsonRpcParams` type.
57
+ - The `JsonRpcSuccess` and `JsonRpcResponse` types now include a generic contraint for the `Result` type, requiring that it extends the `Json` type.
58
+ - Various validation functions now accept `unknown` parameters rather than specific types. This should not be breaking except that it may affect type inference for the parameters passed in.
59
+ - New JSON-related functions have been added:
60
+ - `assertIsJsonRpcResponse`
61
+ - `isJsonRpcResponse`
62
+ - `InferWithParams`
63
+ - `JsonRpcParams`
64
+ - New JSON Struct types have been added:
65
+ - `JsonRpcErrorStruct`
66
+ - `JsonRpcFailureStruct`
67
+ - `JsonRpcIdStruct`
68
+ - `JsonRpcParamsStruct`
69
+ - `JsonRpcRequestStruct`
70
+ - `JsonRpcResponseStruct`
71
+ - `JsonRpcSuccessStruct`
72
+ - `JsonRpcVersionStruct`
73
+ - `JsonStruct`
74
+
75
+ ## [2.1.0]
76
+ ### Added
77
+ - Add JSON storage validation and limit utilities ([#14](https://github.com/MetaMask/utils/pull/14))
78
+ - Adds a new function `validateJsonAndGetSize`.
79
+
80
+ ## [2.0.0]
81
+ ### Added
82
+ - Add more JSON utils ([#8](https://github.com/MetaMask/utils/pull/8))
83
+
84
+ ### Changed
85
+ - **BREAKING:** Refactor and expand time utils ([#9](https://github.com/MetaMask/utils/pull/9))
86
+ - Adds a new function, `inMilliseconds`, and moves the time constants into a TypeScript `enum`.
87
+
88
+ ## [1.0.0]
89
+ ### Added
90
+ - Initial release
91
+
92
+ [Unreleased]: https://github.com/MetaMask/utils/compare/v3.3.0...HEAD
93
+ [3.3.0]: https://github.com/MetaMask/utils/compare/v3.2.0...v3.3.0
94
+ [3.2.0]: https://github.com/MetaMask/utils/compare/v3.1.0...v3.2.0
95
+ [3.1.0]: https://github.com/MetaMask/utils/compare/v3.0.3...v3.1.0
96
+ [3.0.3]: https://github.com/MetaMask/utils/compare/v3.0.2...v3.0.3
97
+ [3.0.2]: https://github.com/MetaMask/utils/compare/v3.0.1...v3.0.2
98
+ [3.0.1]: https://github.com/MetaMask/utils/compare/v3.0.0...v3.0.1
99
+ [3.0.0]: https://github.com/MetaMask/utils/compare/v2.1.0...v3.0.0
100
+ [2.1.0]: https://github.com/MetaMask/utils/compare/v2.0.0...v2.1.0
101
+ [2.0.0]: https://github.com/MetaMask/utils/compare/v1.0.0...v2.0.0
102
+ [1.0.0]: https://github.com/MetaMask/utils/releases/tag/v1.0.0
package/dist/assert.d.ts CHANGED
@@ -1,3 +1,12 @@
1
+ import { Struct } from 'superstruct';
2
+ export declare type AssertionErrorConstructor = (new (args: {
3
+ message: string;
4
+ }) => Error) | ((args: {
5
+ message: string;
6
+ }) => Error);
7
+ /**
8
+ * The default error class that is thrown if an assertion fails.
9
+ */
1
10
  export declare class AssertionError extends Error {
2
11
  readonly code = "ERR_ASSERTION";
3
12
  constructor(options: {
@@ -8,12 +17,27 @@ export declare class AssertionError extends Error {
8
17
  * Same as Node.js assert.
9
18
  * If the value is falsy, throws an error, does nothing otherwise.
10
19
  *
11
- * @throws {@link AssertionError}. If value is falsy.
20
+ * @throws {@link AssertionError} If value is falsy.
12
21
  * @param value - The test that should be truthy to pass.
13
22
  * @param message - Message to be passed to {@link AssertionError} or an
14
23
  * {@link Error} instance to throw.
24
+ * @param ErrorWrapper - The error class to throw if the assertion fails.
25
+ * Defaults to {@link AssertionError}. If a custom error class is provided for
26
+ * the `message` argument, this argument is ignored.
27
+ */
28
+ export declare function assert(value: any, message?: string | Error, ErrorWrapper?: AssertionErrorConstructor): asserts value;
29
+ /**
30
+ * Assert a value against a Superstruct struct.
31
+ *
32
+ * @param value - The value to validate.
33
+ * @param struct - The struct to validate against.
34
+ * @param errorPrefix - A prefix to add to the error message. Defaults to
35
+ * "Assertion failed".
36
+ * @param ErrorWrapper - The error class to throw if the assertion fails.
37
+ * Defaults to {@link AssertionError}.
38
+ * @throws If the value is not valid.
15
39
  */
16
- export declare function assert(value: any, message?: string | Error): asserts value;
40
+ export declare function assertStruct<T, S>(value: unknown, struct: Struct<T, S>, errorPrefix?: string, ErrorWrapper?: AssertionErrorConstructor): asserts value is T;
17
41
  /**
18
42
  * Use in the default case of a switch that you want to be fully exhaustive.
19
43
  * Using this function forces the compiler to enforce exhaustivity during
package/dist/assert.js CHANGED
@@ -1,6 +1,65 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assertExhaustive = exports.assert = exports.AssertionError = void 0;
3
+ exports.assertExhaustive = exports.assertStruct = exports.assert = exports.AssertionError = void 0;
4
+ const superstruct_1 = require("superstruct");
5
+ /**
6
+ * Type guard for determining whether the given value is an error object with a
7
+ * `message` property, such as an instance of Error.
8
+ *
9
+ * @param error - The object to check.
10
+ * @returns True or false, depending on the result.
11
+ */
12
+ function isErrorWithMessage(error) {
13
+ return typeof error === 'object' && error !== null && 'message' in error;
14
+ }
15
+ /**
16
+ * Check if a value is a constructor, i.e., a function that can be called with
17
+ * the `new` keyword.
18
+ *
19
+ * @param fn - The value to check.
20
+ * @returns `true` if the value is a constructor, or `false` otherwise.
21
+ */
22
+ function isConstructable(fn) {
23
+ var _a, _b;
24
+ /* istanbul ignore next */
25
+ return Boolean(typeof ((_b = (_a = fn === null || fn === void 0 ? void 0 : fn.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) === 'string');
26
+ }
27
+ /**
28
+ * Get the error message from an unknown error object. If the error object has
29
+ * a `message` property, that property is returned. Otherwise, the stringified
30
+ * error object is returned.
31
+ *
32
+ * @param error - The error object to get the message from.
33
+ * @returns The error message.
34
+ */
35
+ function getErrorMessage(error) {
36
+ const message = isErrorWithMessage(error) ? error.message : String(error);
37
+ // If the error ends with a period, remove it, as we'll add our own period.
38
+ if (message.endsWith('.')) {
39
+ return message.slice(0, -1);
40
+ }
41
+ return message;
42
+ }
43
+ /**
44
+ * Initialise an {@link AssertionErrorConstructor} error.
45
+ *
46
+ * @param ErrorWrapper - The error class to use.
47
+ * @param message - The error message.
48
+ * @returns The error object.
49
+ */
50
+ function getError(ErrorWrapper, message) {
51
+ if (isConstructable(ErrorWrapper)) {
52
+ return new ErrorWrapper({
53
+ message,
54
+ });
55
+ }
56
+ return ErrorWrapper({
57
+ message,
58
+ });
59
+ }
60
+ /**
61
+ * The default error class that is thrown if an assertion fails.
62
+ */
4
63
  class AssertionError extends Error {
5
64
  constructor(options) {
6
65
  super(options.message);
@@ -12,20 +71,43 @@ exports.AssertionError = AssertionError;
12
71
  * Same as Node.js assert.
13
72
  * If the value is falsy, throws an error, does nothing otherwise.
14
73
  *
15
- * @throws {@link AssertionError}. If value is falsy.
74
+ * @throws {@link AssertionError} If value is falsy.
16
75
  * @param value - The test that should be truthy to pass.
17
76
  * @param message - Message to be passed to {@link AssertionError} or an
18
77
  * {@link Error} instance to throw.
78
+ * @param ErrorWrapper - The error class to throw if the assertion fails.
79
+ * Defaults to {@link AssertionError}. If a custom error class is provided for
80
+ * the `message` argument, this argument is ignored.
19
81
  */
20
- function assert(value, message) {
82
+ function assert(value, message = 'Assertion failed.', ErrorWrapper = AssertionError) {
21
83
  if (!value) {
22
84
  if (message instanceof Error) {
23
85
  throw message;
24
86
  }
25
- throw new AssertionError({ message: message !== null && message !== void 0 ? message : 'Assertion failed.' });
87
+ throw getError(ErrorWrapper, message);
26
88
  }
27
89
  }
28
90
  exports.assert = assert;
91
+ /**
92
+ * Assert a value against a Superstruct struct.
93
+ *
94
+ * @param value - The value to validate.
95
+ * @param struct - The struct to validate against.
96
+ * @param errorPrefix - A prefix to add to the error message. Defaults to
97
+ * "Assertion failed".
98
+ * @param ErrorWrapper - The error class to throw if the assertion fails.
99
+ * Defaults to {@link AssertionError}.
100
+ * @throws If the value is not valid.
101
+ */
102
+ function assertStruct(value, struct, errorPrefix = 'Assertion failed', ErrorWrapper = AssertionError) {
103
+ try {
104
+ (0, superstruct_1.assert)(value, struct);
105
+ }
106
+ catch (error) {
107
+ throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);
108
+ }
109
+ }
110
+ exports.assertStruct = assertStruct;
29
111
  /**
30
112
  * Use in the default case of a switch that you want to be fully exhaustive.
31
113
  * Using this function forces the compiler to enforce exhaustivity during
@@ -1 +1 @@
1
- {"version":3,"file":"assert.js","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":";;;AAAA,MAAa,cAAe,SAAQ,KAAK;IAGvC,YAAY,OAA4B;QACtC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAHhB,SAAI,GAAG,eAAe,CAAC;IAIhC,CAAC;CACF;AAND,wCAMC;AAED;;;;;;;;GAQG;AACH,SAAgB,MAAM,CAAC,KAAU,EAAE,OAAwB;IACzD,IAAI,CAAC,KAAK,EAAE;QACV,IAAI,OAAO,YAAY,KAAK,EAAE;YAC5B,MAAM,OAAO,CAAC;SACf;QACD,MAAM,IAAI,cAAc,CAAC,EAAE,OAAO,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,mBAAmB,EAAE,CAAC,CAAC;KACvE;AACH,CAAC;AAPD,wBAOC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,gBAAgB,CAAC,OAAc;IAC7C,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;AACJ,CAAC;AAJD,4CAIC","sourcesContent":["export class AssertionError extends Error {\n readonly code = 'ERR_ASSERTION';\n\n constructor(options: { message: string }) {\n super(options.message);\n }\n}\n\n/**\n * Same as Node.js assert.\n * If the value is falsy, throws an error, does nothing otherwise.\n *\n * @throws {@link AssertionError}. If value is falsy.\n * @param value - The test that should be truthy to pass.\n * @param message - Message to be passed to {@link AssertionError} or an\n * {@link Error} instance to throw.\n */\nexport function assert(value: any, message?: string | Error): asserts value {\n if (!value) {\n if (message instanceof Error) {\n throw message;\n }\n throw new AssertionError({ message: message ?? 'Assertion failed.' });\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n"]}
1
+ {"version":3,"file":"assert.js","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":";;;AAAA,6CAAkE;AAMlE;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,SAAS,IAAI,KAAK,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,SAAS,eAAe,CACtB,EAA6B;;IAE7B,0BAA0B;IAC1B,OAAO,OAAO,CAAC,OAAO,CAAA,MAAA,MAAA,EAAE,aAAF,EAAE,uBAAF,EAAE,CAAE,SAAS,0CAAE,WAAW,0CAAE,IAAI,CAAA,KAAK,QAAQ,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,eAAe,CAAC,KAAc;IACrC,MAAM,OAAO,GAAG,kBAAkB,CAAC,K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AAK,CAAC,GAAG,CAAC,CAAC;KAC5E;AACH,CAAC;AAXD,oCAWC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,gBAAgB,CAAC,OAAc;IAC7C,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;AACJ,CAAC;AAJD,4CAIC","sourcesContent":["import { assert as assertSuperstruct, Struct } from 'superstruct';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `message` property, such as an instance of Error.\n *\n * @param error - The object to check.\n * @returns True or false, depending on the result.\n */\nfunction isErrorWithMessage(error: unknown): error is { message: string } {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n\n/**\n * Check if a value is a constructor, i.e., a function that can be called with\n * the `new` keyword.\n *\n * @param fn - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nfunction isConstructable(\n fn: AssertionErrorConstructor,\n): fn is new (args: { message: string }) => Error {\n /* istanbul ignore next */\n return Boolean(typeof fn?.prototype?.constructor?.name === 'string');\n}\n\n/**\n * Get the error message from an unknown error object. If the error object has\n * a `message` property, that property is returned. Otherwise, the stringified\n * error object is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The error message.\n */\nfunction getErrorMessage(error: unknown): string {\n const message = isErrorWithMessage(error) ? error.message : String(error);\n\n // If the error ends with a period, remove it, as we'll add our own period.\n if (message.endsWith('.')) {\n return message.slice(0, -1);\n }\n\n return message;\n}\n\n/**\n * Initialise an {@link AssertionErrorConstructor} error.\n *\n * @param ErrorWrapper - The error class to use.\n * @param message - The error message.\n * @returns The error object.\n */\nfunction getError(ErrorWrapper: AssertionErrorConstructor, message: string) {\n if (isConstructable(ErrorWrapper)) {\n return new ErrorWrapper({\n message,\n });\n }\n return ErrorWrapper({\n message,\n });\n}\n\n/**\n * The default error class that is thrown if an assertion fails.\n */\nexport class AssertionError extends Error {\n readonly code = 'ERR_ASSERTION';\n\n constructor(options: { message: string }) {\n super(options.message);\n }\n}\n\n/**\n * Same as Node.js assert.\n * If the value is falsy, throws an error, does nothing otherwise.\n *\n * @throws {@link AssertionError} If value is falsy.\n * @param value - The test that should be truthy to pass.\n * @param message - Message to be passed to {@link AssertionError} or an\n * {@link Error} instance to throw.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}. If a custom error class is provided for\n * the `message` argument, this argument is ignored.\n */\nexport function assert(\n value: any,\n message: string | Error = 'Assertion failed.',\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value {\n if (!value) {\n if (message instanceof Error) {\n throw message;\n }\n\n throw getError(ErrorWrapper, message);\n }\n}\n\n/**\n * Assert a value against a Superstruct struct.\n *\n * @param value - The value to validate.\n * @param struct - The struct to validate against.\n * @param errorPrefix - A prefix to add to the error message. Defaults to\n * \"Assertion failed\".\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the value is not valid.\n */\nexport function assertStruct<T, S>(\n value: unknown,\n struct: Struct<T, S>,\n errorPrefix = 'Assertion failed',\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is T {\n try {\n assertSuperstruct(value, struct);\n } catch (error) {\n throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n"]}
package/dist/bytes.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Hex } from './hex';
1
2
  export declare type Bytes = bigint | number | string | Uint8Array;
2
3
  /**
3
4
  * Check if a value is a `Uint8Array`.
@@ -19,7 +20,7 @@ export declare function assertIsBytes(value: unknown): asserts value is Uint8Arr
19
20
  * @param bytes - The bytes to convert to a hexadecimal string.
20
21
  * @returns The hexadecimal string.
21
22
  */
22
- export declare function bytesToHex(bytes: Uint8Array): string;
23
+ export declare function bytesToHex(bytes: Uint8Array): Hex;
23
24
  /**
24
25
  * Convert a `Uint8Array` to a `bigint`.
25
26
  *
@@ -64,6 +65,8 @@ export declare function bytesToString(bytes: Uint8Array): string;
64
65
  * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be
65
66
  * prefixed with `0x`. It accepts even and odd length strings.
66
67
  *
68
+ * If the value is "0x", an empty `Uint8Array` is returned.
69
+ *
67
70
  * @param value - The hexadecimal string to convert to bytes.
68
71
  * @returns The bytes as `Uint8Array`.
69
72
  */
@@ -112,6 +115,10 @@ export declare function stringToBytes(value: string): Uint8Array;
112
115
  * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,
113
116
  * a `bigint`, a `number`, or a `string`.
114
117
  *
118
+ * This will attempt to guess the type of the value based on its type and
119
+ * contents. For more control over the conversion, use the more specific
120
+ * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.
121
+ *
115
122
  * If the value is a `string`, and it is prefixed with `0x`, it will be
116
123
  * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a
117
124
  * UTF-8 string. To convert a hexadecimal string to bytes without interpreting
@@ -136,3 +143,26 @@ export declare function valueToBytes(value: Bytes): Uint8Array;
136
143
  * @returns The concatenated bytes as `Uint8Array`.
137
144
  */
138
145
  export declare function concatBytes(values: Bytes[]): Uint8Array;
146
+ /**
147
+ * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience
148
+ * function that avoids having to create a {@link DataView} manually, which
149
+ * requires passing the `byteOffset` and `byteLength` parameters every time.
150
+ *
151
+ * Not passing the `byteOffset` and `byteLength` parameters can result in
152
+ * unexpected behavior when the {@link Uint8Array} is a view of a larger
153
+ * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.
154
+ *
155
+ * This function also supports Node.js {@link Buffer}s.
156
+ *
157
+ * @example
158
+ * ```typescript
159
+ * const bytes = new Uint8Array([1, 2, 3]);
160
+ *
161
+ * // This is equivalent to:
162
+ * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
163
+ * const dataView = createDataView(bytes);
164
+ * ```
165
+ * @param bytes - The bytes to create the {@link DataView} from.
166
+ * @returns The {@link DataView}.
167
+ */
168
+ export declare function createDataView(bytes: Uint8Array): DataView;
package/dist/bytes.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.concatBytes = exports.valueToBytes = exports.stringToBytes = exports.numberToBytes = exports.signedBigIntToBytes = exports.bigIntToBytes = exports.hexToBytes = exports.bytesToString = exports.bytesToNumber = exports.bytesToSignedBigInt = exports.bytesToBigInt = exports.bytesToHex = exports.assertIsBytes = exports.isBytes = void 0;
3
+ exports.createDataView = exports.concatBytes = exports.valueToBytes = exports.stringToBytes = exports.numberToBytes = exports.signedBigIntToBytes = exports.bigIntToBytes = exports.hexToBytes = exports.bytesToString = exports.bytesToNumber = exports.bytesToSignedBigInt = exports.bytesToBigInt = exports.bytesToHex = exports.assertIsBytes = exports.isBytes = void 0;
4
4
  const assert_1 = require("./assert");
5
5
  const hex_1 = require("./hex");
6
6
  // '0'.charCodeAt(0) === 48
@@ -70,6 +70,9 @@ exports.assertIsBytes = assertIsBytes;
70
70
  */
71
71
  function bytesToHex(bytes) {
72
72
  assertIsBytes(bytes);
73
+ if (bytes.length === 0) {
74
+ return '0x';
75
+ }
73
76
  const lookupTable = getPrecomputedHexValues();
74
77
  const hex = new Array(bytes.length);
75
78
  for (let i = 0; i < bytes.length; i++) {
@@ -140,17 +143,24 @@ exports.bytesToNumber = bytesToNumber;
140
143
  */
141
144
  function bytesToString(bytes) {
142
145
  assertIsBytes(bytes);
143
- return new TextDecoder(undefined).decode(bytes);
146
+ return new TextDecoder().decode(bytes);
144
147
  }
145
148
  exports.bytesToString = bytesToString;
146
149
  /**
147
150
  * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be
148
151
  * prefixed with `0x`. It accepts even and odd length strings.
149
152
  *
153
+ * If the value is "0x", an empty `Uint8Array` is returned.
154
+ *
150
155
  * @param value - The hexadecimal string to convert to bytes.
151
156
  * @returns The bytes as `Uint8Array`.
152
157
  */
153
158
  function hexToBytes(value) {
159
+ var _a;
160
+ // "0x" is often used as empty byte array.
161
+ if (((_a = value === null || value === void 0 ? void 0 : value.toLowerCase) === null || _a === void 0 ? void 0 : _a.call(value)) === '0x') {
162
+ return new Uint8Array();
163
+ }
154
164
  (0, hex_1.assertIsHexString)(value);
155
165
  // Remove the `0x` prefix if it exists, and pad the string to have an even
156
166
  // number of characters.
@@ -267,6 +277,10 @@ exports.stringToBytes = stringToBytes;
267
277
  * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,
268
278
  * a `bigint`, a `number`, or a `string`.
269
279
  *
280
+ * This will attempt to guess the type of the value based on its type and
281
+ * contents. For more control over the conversion, use the more specific
282
+ * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.
283
+ *
270
284
  * If the value is a `string`, and it is prefixed with `0x`, it will be
271
285
  * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a
272
286
  * UTF-8 string. To convert a hexadecimal string to bytes without interpreting
@@ -327,4 +341,34 @@ function concatBytes(values) {
327
341
  return bytes;
328
342
  }
329
343
  exports.concatBytes = concatBytes;
344
+ /**
345
+ * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience
346
+ * function that avoids having to create a {@link DataView} manually, which
347
+ * requires passing the `byteOffset` and `byteLength` parameters every time.
348
+ *
349
+ * Not passing the `byteOffset` and `byteLength` parameters can result in
350
+ * unexpected behavior when the {@link Uint8Array} is a view of a larger
351
+ * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.
352
+ *
353
+ * This function also supports Node.js {@link Buffer}s.
354
+ *
355
+ * @example
356
+ * ```typescript
357
+ * const bytes = new Uint8Array([1, 2, 3]);
358
+ *
359
+ * // This is equivalent to:
360
+ * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
361
+ * const dataView = createDataView(bytes);
362
+ * ```
363
+ * @param bytes - The bytes to create the {@link DataView} from.
364
+ * @returns The {@link DataView}.
365
+ */
366
+ function createDataView(bytes) {
367
+ if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {
368
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
369
+ return new DataView(buffer);
370
+ }
371
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
372
+ }
373
+ exports.createDataView = createDataView;
330
374
  //# sourceMappingURL=bytes.js.map
package/dist/bytes.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bytes.js","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":";;;AAAA,qCAAkC;AAClC,+BAA2D;AAE3D,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;YAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;gBAC5B,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;aACnD;SACF;QAED,OAAO,WA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AAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,oEAAoE;QACpE,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC,CAAC;QAEvC,gBAAgB,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;QAC5B,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC;KAC5B;IAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;IACzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC5D,gEAAgE;QAChE,uEAAuE;QACvE,KAAK,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACvC,MAAM,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;KACtC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AArBD,kCAqBC","sourcesContent":["import { assert } from './assert';\nimport { add0x, assertIsHexString, remove0x } from './hex';\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 * 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): string {\n assertIsBytes(bytes);\n\n const lookupTable = getPrecomputedHexValues();\n const hex = 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 hex[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hex.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 hex = bytesToHex(bytes);\n return BigInt(hex);\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(undefined).decode(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 * @param value - The hexadecimal string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function hexToBytes(value: string): Uint8Array {\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 {\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 hex = value.toString(16);\n return hexToBytes(hex);\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 {\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 {\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 hex = value.toString(16);\n return hexToBytes(hex);\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 {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return new TextEncoder().encode(value);\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 * 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 {\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 (isBytes(value)) {\n return 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 {\n const normalizedValues = new Array(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 for (let i = 0, offset = 0; i < normalizedValues.length; i++) {\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(normalizedValues[i], offset);\n offset += normalizedValues[i].length;\n }\n\n return bytes;\n}\n"]}
1
+ {"version":3,"file":"bytes.js","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":";;;AAAA,qCAAkC;AAClC,+BAAgE;AAEhE,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;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9C,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,KAAK,YAAY,MAAM,EAAE;QAC5D,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAC/B,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CACpC,CAAC;QAEF,OAAO,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC;KAC7B;IAED,OAAO,IAAI,QAAQ,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;AACxE,CAAC;AAXD,wCAWC","sourcesContent":["import { assert } from './assert';\nimport { add0x, assertIsHexString, Hex, remove0x } from './hex';\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 * 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 hex = 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 hex[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hex.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 hex = bytesToHex(bytes);\n return BigInt(hex);\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 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 {\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 {\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 hex = value.toString(16);\n return hexToBytes(hex);\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 {\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 {\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 hex = value.toString(16);\n return hexToBytes(hex);\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 {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return new TextEncoder().encode(value);\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 {\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 (isBytes(value)) {\n return 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 {\n const normalizedValues = new Array(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 for (let i = 0, offset = 0; i < normalizedValues.length; i++) {\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(normalizedValues[i], offset);\n offset += normalizedValues[i].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(bytes: Uint8Array): DataView {\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(buffer);\n }\n\n return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\n"]}
@@ -0,0 +1,96 @@
1
+ import { Infer } from 'superstruct';
2
+ import { Hex } from './hex';
3
+ declare const NumberLikeStruct: import("superstruct").Struct<string | number | bigint, null>;
4
+ declare const BytesLikeStruct: import("superstruct").Struct<Uint8Array | `0x${string}`, null>;
5
+ export declare type NumberLike = Infer<typeof NumberLikeStruct>;
6
+ export declare type BytesLike = Infer<typeof BytesLikeStruct>;
7
+ /**
8
+ * Create a number from a number-like value.
9
+ *
10
+ * - If the value is a number, it is returned as-is.
11
+ * - If the value is a `bigint`, it is converted to a number.
12
+ * - If the value is a string, it is interpreted as a decimal number.
13
+ * - If the value is a hex string (i.e., it starts with "0x"), it is
14
+ * interpreted as a hexadecimal number.
15
+ *
16
+ * This validates that the value is a number-like value, and that the resulting
17
+ * number is not `NaN` or `Infinity`.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const value = createNumber('0x010203');
22
+ * console.log(value); // 66051
23
+ *
24
+ * const otherValue = createNumber(123n);
25
+ * console.log(otherValue); // 123
26
+ * ```
27
+ * @param value - The value to create the number from.
28
+ * @returns The created number.
29
+ * @throws If the value is not a number-like value, or if the resulting number
30
+ * is `NaN` or `Infinity`.
31
+ */
32
+ export declare function createNumber(value: NumberLike): number;
33
+ /**
34
+ * Create a `bigint` from a number-like value.
35
+ *
36
+ * - If the value is a number, it is converted to a `bigint`.
37
+ * - If the value is a `bigint`, it is returned as-is.
38
+ * - If the value is a string, it is interpreted as a decimal number and
39
+ * converted to a `bigint`.
40
+ * - If the value is a hex string (i.e., it starts with "0x"), it is
41
+ * interpreted as a hexadecimal number and converted to a `bigint`.
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const value = createBigInt('0x010203');
46
+ * console.log(value); // 16909060n
47
+ *
48
+ * const otherValue = createBigInt(123);
49
+ * console.log(otherValue); // 123n
50
+ * ```
51
+ * @param value - The value to create the bigint from.
52
+ * @returns The created bigint.
53
+ * @throws If the value is not a number-like value.
54
+ */
55
+ export declare function createBigInt(value: NumberLike): bigint;
56
+ /**
57
+ * Create a byte array from a bytes-like value.
58
+ *
59
+ * - If the value is a byte array, it is returned as-is.
60
+ * - If the value is a hex string (i.e., it starts with "0x"), it is interpreted
61
+ * as a hexadecimal number and converted to a byte array.
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * const value = createBytes('0x010203');
66
+ * console.log(value); // Uint8Array [ 1, 2, 3 ]
67
+ *
68
+ * const otherValue = createBytes('0x010203');
69
+ * console.log(otherValue); // Uint8Array [ 1, 2, 3 ]
70
+ * ```
71
+ * @param value - The value to create the byte array from.
72
+ * @returns The created byte array.
73
+ * @throws If the value is not a bytes-like value.
74
+ */
75
+ export declare function createBytes(value: BytesLike): Uint8Array;
76
+ /**
77
+ * Create a hexadecimal string from a bytes-like value.
78
+ *
79
+ * - If the value is a hex string (i.e., it starts with "0x"), it is returned
80
+ * as-is.
81
+ * - If the value is a `Uint8Array`, it is converted to a hex string.
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * const value = createHex(new Uint8Array([1, 2, 3]));
86
+ * console.log(value); // '0x010203'
87
+ *
88
+ * const otherValue = createHex('0x010203');
89
+ * console.log(otherValue); // '0x010203'
90
+ * ```
91
+ * @param value - The value to create the hex string from.
92
+ * @returns The created hex string.
93
+ * @throws If the value is not a bytes-like value.
94
+ */
95
+ export declare function createHex(value: BytesLike): Hex;
96
+ export {};