@metamask/utils 3.3.0 → 3.4.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/dist/assert.js CHANGED
@@ -47,6 +47,7 @@ function getErrorMessage(error) {
47
47
  * @param message - The error message.
48
48
  * @returns The error object.
49
49
  */
50
+ // eslint-disable-next-line @typescript-eslint/naming-convention
50
51
  function getError(ErrorWrapper, message) {
51
52
  if (isConstructable(ErrorWrapper)) {
52
53
  return new ErrorWrapper({
@@ -79,7 +80,9 @@ exports.AssertionError = AssertionError;
79
80
  * Defaults to {@link AssertionError}. If a custom error class is provided for
80
81
  * the `message` argument, this argument is ignored.
81
82
  */
82
- function assert(value, message = 'Assertion failed.', ErrorWrapper = AssertionError) {
83
+ function assert(value, message = 'Assertion failed.',
84
+ // eslint-disable-next-line @typescript-eslint/naming-convention
85
+ ErrorWrapper = AssertionError) {
83
86
  if (!value) {
84
87
  if (message instanceof Error) {
85
88
  throw message;
@@ -99,7 +102,9 @@ exports.assert = assert;
99
102
  * Defaults to {@link AssertionError}.
100
103
  * @throws If the value is not valid.
101
104
  */
102
- function assertStruct(value, struct, errorPrefix = 'Assertion failed', ErrorWrapper = AssertionError) {
105
+ function assertStruct(value, struct, errorPrefix = 'Assertion failed',
106
+ // eslint-disable-next-line @typescript-eslint/naming-convention
107
+ ErrorWrapper = AssertionError) {
103
108
  try {
104
109
  (0, superstruct_1.assert)(value, struct);
105
110
  }
@@ -1 +1 @@
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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,CAC1B,KAAc,EACd,MAAoB,EACpB,WAAW,GAAG,kBAAkB,EAChC,eAA0C,cAAc;IAExD,IAAI;QACF,IAAA,oBAAiB,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;KAClC;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,QAAQ,CAAC,YAAY,EAAE,GAAG,WAAW,KAAK,eAAe,CAAC,KAAK,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"]}
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,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAE1E,2EAA2E;IAC3E,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QACzB,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;KAC7B;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;GAMG;AACH,gEAAgE;AAChE,SAAS,QAAQ,CAAC,YAAuC,EAAE,OAAe;IACxE,IAAI,eAAe,CAAC,YAAY,CAAC,EAAE;QACjC,OAAO,IAAI,YAAY,CAAC;YACtB,OAAO;SACR,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC;QAClB,OAAO;KACR,CAAC,CAAC;AACL,CAAC;AAED;;GAEG;AACH,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;;;;;;;;;;;GAWG;AACH,SAAgB,MAAM,CACpB,KAAU,EACV,UAA0B,mBAAmB;AAC7C,gEAAgE;AAChE,eAA0C,cAAc;IAExD,IAAI,CAAC,KAAK,EAAE;QACV,IAAI,OAAO,YAAY,KAAK,EAAE;YAC5B,MAAM,OAAO,CAAC;SACf;QAED,MAAM,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;KACvC;AACH,CAAC;AAbD,wBAaC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,YAAY,CAC1B,KAAc,EACd,MAAoB,EACpB,WAAW,GAAG,kBAAkB;AAChC,gEAAgE;AAChE,eAA0C,cAAc;IAExD,IAAI;QACF,IAAA,oBAAiB,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;KAClC;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,QAAQ,CAAC,YAAY,EAAE,GAAG,WAAW,KAAK,eAAe,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;KAC5E;AACH,CAAC;AAZD,oCAYC;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 */\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 // eslint-disable-next-line @typescript-eslint/naming-convention\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 // eslint-disable-next-line @typescript-eslint/naming-convention\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"]}
@@ -0,0 +1,24 @@
1
+ import { Struct } from 'superstruct';
2
+ export declare type Base64Options = {
3
+ /**
4
+ * Is the `=` padding at the end required or not.
5
+ *
6
+ * @default false
7
+ */
8
+ paddingRequired?: boolean;
9
+ /**
10
+ * Which character set should be used.
11
+ * The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.
12
+ *
13
+ * @default 'base64'
14
+ */
15
+ characterSet?: 'base64' | 'base64url';
16
+ };
17
+ /**
18
+ * Ensure that a provided string-based struct is valid base64.
19
+ *
20
+ * @param struct - The string based struct.
21
+ * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.
22
+ * @returns A superstruct validating base64.
23
+ */
24
+ export declare const base64: <T extends string, S>(struct: Struct<T, S>, options?: Base64Options) => Struct<T, S>;
package/dist/base64.js ADDED
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.base64 = void 0;
4
+ const superstruct_1 = require("superstruct");
5
+ const assert_1 = require("./assert");
6
+ /**
7
+ * Ensure that a provided string-based struct is valid base64.
8
+ *
9
+ * @param struct - The string based struct.
10
+ * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.
11
+ * @returns A superstruct validating base64.
12
+ */
13
+ const base64 = (struct, options = {}) => {
14
+ var _a, _b;
15
+ const paddingRequired = (_a = options.paddingRequired) !== null && _a !== void 0 ? _a : false;
16
+ const characterSet = (_b = options.characterSet) !== null && _b !== void 0 ? _b : 'base64';
17
+ let letters;
18
+ if (characterSet === 'base64') {
19
+ letters = String.raw `[A-Za-z0-9+\/]`;
20
+ }
21
+ else {
22
+ (0, assert_1.assert)(characterSet === 'base64url');
23
+ letters = String.raw `[-_A-Za-z0-9]`;
24
+ }
25
+ let re;
26
+ if (paddingRequired) {
27
+ re = new RegExp(`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, 'u');
28
+ }
29
+ else {
30
+ re = new RegExp(`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, 'u');
31
+ }
32
+ return (0, superstruct_1.pattern)(struct, re);
33
+ };
34
+ exports.base64 = base64;
35
+ //# sourceMappingURL=base64.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64.js","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAE9C,qCAAkC;AAmBlC;;;;;;GAMG;AACI,MAAM,MAAM,GAAG,CACpB,MAAoB,EACpB,UAAyB,EAAE,EAC3B,EAAE;;IACF,MAAM,eAAe,GAAG,MAAA,OAAO,CAAC,eAAe,mCAAI,KAAK,CAAC;IACzD,MAAM,YAAY,GAAG,MAAA,OAAO,CAAC,YAAY,mCAAI,QAAQ,CAAC;IAEtD,IAAI,OAAe,CAAC;IACpB,IAAI,YAAY,KAAK,QAAQ,EAAE;QAC7B,OAAO,GAAG,MAAM,CAAC,GAAG,CAAA,gBAAgB,CAAC;KACtC;SAAM;QACL,IAAA,eAAM,EAAC,YAAY,KAAK,WAAW,CAAC,CAAC;QACrC,OAAO,GAAG,MAAM,CAAC,GAAG,CAAA,eAAe,CAAC;KACrC;IAED,IAAI,EAAU,CAAC;IACf,IAAI,eAAe,EAAE;QACnB,EAAE,GAAG,IAAI,MAAM,CACb,OAAO,OAAO,WAAW,OAAO,QAAQ,OAAO,UAAU,EACzD,GAAG,CACJ,CAAC;KACH;SAAM;QACL,EAAE,GAAG,IAAI,MAAM,CACb,OAAO,OAAO,WAAW,OAAO,SAAS,OAAO,QAAQ,OAAO,UAAU,EACzE,GAAG,CACJ,CAAC;KACH;IAED,OAAO,IAAA,qBAAO,EAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC,CAAC;AA7BW,QAAA,MAAM,UA6BjB","sourcesContent":["import { pattern, Struct } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Base64Options = {\n /**\n * Is the `=` padding at the end required or not.\n *\n * @default false\n */\n // Padding is optional in RFC 4648, that's why the default value is false\n paddingRequired?: boolean;\n /**\n * Which character set should be used.\n * The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.\n *\n * @default 'base64'\n */\n characterSet?: 'base64' | 'base64url';\n};\n\n/**\n * Ensure that a provided string-based struct is valid base64.\n *\n * @param struct - The string based struct.\n * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.\n * @returns A superstruct validating base64.\n */\nexport const base64 = <T extends string, S>(\n struct: Struct<T, S>,\n options: Base64Options = {},\n) => {\n const paddingRequired = options.paddingRequired ?? false;\n const characterSet = options.characterSet ?? 'base64';\n\n let letters: string;\n if (characterSet === 'base64') {\n letters = String.raw`[A-Za-z0-9+\\/]`;\n } else {\n assert(characterSet === 'base64url');\n letters = String.raw`[-_A-Za-z0-9]`;\n }\n\n let re: RegExp;\n if (paddingRequired) {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n } else {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n }\n\n return pattern(struct, re);\n};\n"]}
package/dist/bytes.js CHANGED
@@ -74,12 +74,12 @@ function bytesToHex(bytes) {
74
74
  return '0x';
75
75
  }
76
76
  const lookupTable = getPrecomputedHexValues();
77
- const hex = new Array(bytes.length);
77
+ const hexadecimal = new Array(bytes.length);
78
78
  for (let i = 0; i < bytes.length; i++) {
79
79
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
80
- hex[i] = lookupTable[bytes[i]];
80
+ hexadecimal[i] = lookupTable[bytes[i]];
81
81
  }
82
- return (0, hex_1.add0x)(hex.join(''));
82
+ return (0, hex_1.add0x)(hexadecimal.join(''));
83
83
  }
84
84
  exports.bytesToHex = bytesToHex;
85
85
  /**
@@ -94,8 +94,8 @@ exports.bytesToHex = bytesToHex;
94
94
  */
95
95
  function bytesToBigInt(bytes) {
96
96
  assertIsBytes(bytes);
97
- const hex = bytesToHex(bytes);
98
- return BigInt(hex);
97
+ const hexadecimal = bytesToHex(bytes);
98
+ return BigInt(hexadecimal);
99
99
  }
100
100
  exports.bytesToBigInt = bytesToBigInt;
101
101
  /**
@@ -198,8 +198,8 @@ exports.hexToBytes = hexToBytes;
198
198
  function bigIntToBytes(value) {
199
199
  (0, assert_1.assert)(typeof value === 'bigint', 'Value must be a bigint.');
200
200
  (0, assert_1.assert)(value >= BigInt(0), 'Value must be a non-negative bigint.');
201
- const hex = value.toString(16);
202
- return hexToBytes(hex);
201
+ const hexadecimal = value.toString(16);
202
+ return hexToBytes(hexadecimal);
203
203
  }
204
204
  exports.bigIntToBytes = bigIntToBytes;
205
205
  /**
@@ -258,8 +258,8 @@ function numberToBytes(value) {
258
258
  (0, assert_1.assert)(typeof value === 'number', 'Value must be a number.');
259
259
  (0, assert_1.assert)(value >= 0, 'Value must be a non-negative number.');
260
260
  (0, assert_1.assert)(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToBytes` instead.');
261
- const hex = value.toString(16);
262
- return hexToBytes(hex);
261
+ const hexadecimal = value.toString(16);
262
+ return hexToBytes(hexadecimal);
263
263
  }
264
264
  exports.numberToBytes = numberToBytes;
265
265
  /**
@@ -364,6 +364,10 @@ exports.concatBytes = concatBytes;
364
364
  * @returns The {@link DataView}.
365
365
  */
366
366
  function createDataView(bytes) {
367
+ // To maintain compatibility with Node.js, we need to check if the bytes are
368
+ // a Buffer. If so, we need to slice the buffer to get the underlying
369
+ // ArrayBuffer.
370
+ // eslint-disable-next-line no-restricted-globals
367
371
  if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {
368
372
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
369
373
  return new DataView(buffer);
package/dist/bytes.js.map CHANGED
@@ -1 +1 @@
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;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,CA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AAQ,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"]}
1
+ {"version":3,"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AG,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;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,SAAgB,cAAc,CAAC,KAAiB;IAC9C,4EAA4E;IAC5E,qEAAqE;IACrE,eAAe;IACf,iDAAiD;IACjD,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;AAfD,wCAeC","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 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 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 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 {\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 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 {\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 // 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(buffer);\n }\n\n return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\n"]}
@@ -0,0 +1 @@
1
+ export declare const ChecksumStruct: import("superstruct").Struct<string, null>;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChecksumStruct = void 0;
4
+ const superstruct_1 = require("superstruct");
5
+ const base64_1 = require("./base64");
6
+ exports.ChecksumStruct = (0, superstruct_1.size)((0, base64_1.base64)((0, superstruct_1.string)(), { paddingRequired: true }), 44, 44);
7
+ //# sourceMappingURL=checksum.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checksum.js","sourceRoot":"","sources":["../src/checksum.ts"],"names":[],"mappings":";;;AAAA,6CAA2C;AAE3C,qCAAkC;AAErB,QAAA,cAAc,GAAG,IAAA,kBAAI,EAChC,IAAA,eAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,EAC3C,EAAE,EACF,EAAE,CACH,CAAC","sourcesContent":["import { size, string } from 'superstruct';\n\nimport { base64 } from './base64';\n\nexport const ChecksumStruct = size(\n base64(string(), { paddingRequired: true }),\n 44,\n 44,\n);\n"]}
package/dist/coercers.js CHANGED
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createHex = exports.createBytes = exports.createBigInt = exports.createNumber = void 0;
4
4
  const superstruct_1 = require("superstruct");
5
- const hex_1 = require("./hex");
6
5
  const assert_1 = require("./assert");
7
6
  const bytes_1 = require("./bytes");
7
+ const hex_1 = require("./hex");
8
8
  const NumberLikeStruct = (0, superstruct_1.union)([(0, superstruct_1.number)(), (0, superstruct_1.bigint)(), (0, superstruct_1.string)(), hex_1.StrictHexStruct]);
9
9
  const NumberCoercer = (0, superstruct_1.coerce)((0, superstruct_1.number)(), NumberLikeStruct, Number);
10
10
  const BigIntCoercer = (0, superstruct_1.coerce)((0, superstruct_1.bigint)(), NumberLikeStruct, BigInt);
@@ -81,7 +81,7 @@ function createBigInt(value) {
81
81
  }
82
82
  catch (error) {
83
83
  if (error instanceof superstruct_1.StructError) {
84
- throw new Error(`Expected a number-like value, got "${error.value}".`);
84
+ throw new Error(`Expected a number-like value, got "${String(error.value)}".`);
85
85
  }
86
86
  /* istanbul ignore next */
87
87
  throw error;
@@ -116,7 +116,7 @@ function createBytes(value) {
116
116
  }
117
117
  catch (error) {
118
118
  if (error instanceof superstruct_1.StructError) {
119
- throw new Error(`Expected a bytes-like value, got "${error.value}".`);
119
+ throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`);
120
120
  }
121
121
  /* istanbul ignore next */
122
122
  throw error;
@@ -152,7 +152,7 @@ function createHex(value) {
152
152
  }
153
153
  catch (error) {
154
154
  if (error instanceof superstruct_1.StructError) {
155
- throw new Error(`Expected a bytes-like value, got "${error.value}".`);
155
+ throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`);
156
156
  }
157
157
  /* istanbul ignore next */
158
158
  throw error;
@@ -1 +1 @@
1
- {"version":3,"file":"coercers.js","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":";;;AAAA,6CAUqB;AACrB,+BAA6C;AAC7C,qCAAkC;AAClC,mCAAiD;AAEjD,MAAM,gBAAgB,GAAG,IAAA,mBAAK,EAAC,CAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,EAAE,qBAAe,CAAC,CAAC,CAAC;AAChF,MAAM,aAAa,GAAG,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;AACjE,MAAM,aAAa,GAAG,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;AAEjE,MAAM,eAAe,GAAG,IAAA,mBAAK,EAAC,CAAC,qBAAe,EAAE,IAAA,sBAAQ,EAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACvE,MAAM,YAAY,GAAG,IAAA,oBAAM,EACzB,IAAA,sBAAQ,EAAC,UAAU,CAAC,EACpB,IAAA,mBAAK,EAAC,CAAC,qBAAe,CAAC,CAAC,EACxB,kBAAU,CACX,CAAC;AAEF,MAAM,UAAU,GAAG,IAAA,oBAAM,EAAC,qBAAe,EAAE,IAAA,sBAAQ,EAAC,UAAU,CAAC,EAAE,kBAAU,CAAC,CAAC;AAK7E;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,SAAgB,YAAY,CAAC,KAAiB;IAC5C,IAAI;QACF,MAAM,MAAM,GAAG,IAAA,oBAAM,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QAE5C,IAAA,eAAM,EACJ,MAAM,CAAC,QAAQ,CAAC,MAA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AAU,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC;QACnD,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,EAC3D;QACA,OAAO,IAAI,CAAC;KACb;IAED,IAAI;QACF,OAAO,IAAA,oBAAM,EAAC,KAAK,EAAE,UAAU,CAAC,CAAC;KAClC;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,YAAY,yBAAW,EAAE;YAChC,MAAM,IAAI,KAAK,CAAC,qCAAqC,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC;SACvE;QAED,0BAA0B;QAC1B,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAlBD,8BAkBC","sourcesContent":["import {\n bigint,\n coerce,\n create,\n Infer,\n instance,\n number,\n string,\n StructError,\n union,\n} from 'superstruct';\nimport { Hex, StrictHexStruct } from './hex';\nimport { assert } from './assert';\nimport { bytesToHex, hexToBytes } from './bytes';\n\nconst NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);\nconst NumberCoercer = coerce(number(), NumberLikeStruct, Number);\nconst BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);\n\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 if (error instanceof StructError) {\n throw new Error(`Expected a number-like value, got \"${error.value}\".`);\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 if (error instanceof StructError) {\n throw new Error(`Expected a bytes-like value, got \"${error.value}\".`);\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 if (error instanceof StructError) {\n throw new Error(`Expected a bytes-like value, got \"${error.value}\".`);\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"coercers.js","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":";;;AAAA,6CAUqB;AAErB,qCAAkC;AAClC,mCAAiD;AACjD,+BAA6C;AAE7C,MAAM,gBAAgB,GAAG,IAAA,mBAAK,EAAC,CAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,EAAE,qBAAe,CAAC,CAAC,CAAC;AAChF,MAAM,aAAa,GAAG,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;AACjE,MAAM,aAAa,GAAG,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,gBAAgB,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AA0B;QAC1B,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAfD,oCAeC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,WAAW,CAAC,KAAgB;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;QAC7D,OAAO,IAAI,UAAU,EAAE,CAAC;KACzB;IAED,IAAI;QACF,OAAO,IAAA,oBAAM,EAAC,KAAK,EAAE,YAAY,CAAC,CAAC;KACpC;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,YAAY,yBAAW,EAAE;YAChC,MAAM,IAAI,KAAK,CACb,qCAAqC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAC7D,CAAC;SACH;QAED,0BAA0B;QAC1B,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAjBD,kCAiBC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,SAAS,CAAC,KAAgB;IACxC,IACE,CAAC,KAAK,YAAY,UAAU,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC;QACnD,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,EAC3D;QACA,OAAO,IAAI,CAAC;KACb;IAED,IAAI;QACF,OAAO,IAAA,oBAAM,EAAC,KAAK,EAAE,UAAU,CAAC,CAAC;KAClC;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,YAAY,yBAAW,EAAE;YAChC,MAAM,IAAI,KAAK,CACb,qCAAqC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAC7D,CAAC;SACH;QAED,0BAA0B;QAC1B,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AApBD,8BAoBC","sourcesContent":["import {\n bigint,\n coerce,\n create,\n Infer,\n instance,\n number,\n string,\n StructError,\n union,\n} from 'superstruct';\n\nimport { assert } from './assert';\nimport { bytesToHex, hexToBytes } from './bytes';\nimport { Hex, StrictHexStruct } from './hex';\n\nconst NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);\nconst NumberCoercer = coerce(number(), NumberLikeStruct, Number);\nconst BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);\n\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 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 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 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/hex.d.ts CHANGED
@@ -36,15 +36,15 @@ export declare function assertIsStrictHexString(value: unknown): asserts value i
36
36
  * Add the `0x`-prefix to a hexadecimal string. If the string already has the
37
37
  * prefix, it is returned as-is.
38
38
  *
39
- * @param hex - The hexadecimal string to add the prefix to.
39
+ * @param hexadecimal - The hexadecimal string to add the prefix to.
40
40
  * @returns The prefixed hexadecimal string.
41
41
  */
42
- export declare function add0x(hex: string): Hex;
42
+ export declare function add0x(hexadecimal: string): Hex;
43
43
  /**
44
44
  * Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have
45
45
  * the prefix, it is returned as-is.
46
46
  *
47
- * @param hex - The hexadecimal string to remove the prefix from.
47
+ * @param hexadecimal - The hexadecimal string to remove the prefix from.
48
48
  * @returns The un-prefixed hexadecimal string.
49
49
  */
50
- export declare function remove0x(hex: string): string;
50
+ export declare function remove0x(hexadecimal: string): string;
package/dist/hex.js CHANGED
@@ -51,31 +51,31 @@ exports.assertIsStrictHexString = assertIsStrictHexString;
51
51
  * Add the `0x`-prefix to a hexadecimal string. If the string already has the
52
52
  * prefix, it is returned as-is.
53
53
  *
54
- * @param hex - The hexadecimal string to add the prefix to.
54
+ * @param hexadecimal - The hexadecimal string to add the prefix to.
55
55
  * @returns The prefixed hexadecimal string.
56
56
  */
57
- function add0x(hex) {
58
- if (hex.startsWith('0x')) {
59
- return hex;
57
+ function add0x(hexadecimal) {
58
+ if (hexadecimal.startsWith('0x')) {
59
+ return hexadecimal;
60
60
  }
61
- if (hex.startsWith('0X')) {
62
- return `0x${hex.substring(2)}`;
61
+ if (hexadecimal.startsWith('0X')) {
62
+ return `0x${hexadecimal.substring(2)}`;
63
63
  }
64
- return `0x${hex}`;
64
+ return `0x${hexadecimal}`;
65
65
  }
66
66
  exports.add0x = add0x;
67
67
  /**
68
68
  * Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have
69
69
  * the prefix, it is returned as-is.
70
70
  *
71
- * @param hex - The hexadecimal string to remove the prefix from.
71
+ * @param hexadecimal - The hexadecimal string to remove the prefix from.
72
72
  * @returns The un-prefixed hexadecimal string.
73
73
  */
74
- function remove0x(hex) {
75
- if (hex.startsWith('0x') || hex.startsWith('0X')) {
76
- return hex.substring(2);
74
+ function remove0x(hexadecimal) {
75
+ if (hexadecimal.startsWith('0x') || hexadecimal.startsWith('0X')) {
76
+ return hexadecimal.substring(2);
77
77
  }
78
- return hex;
78
+ return hexadecimal;
79
79
  }
80
80
  exports.remove0x = remove0x;
81
81
  //# sourceMappingURL=hex.js.map
package/dist/hex.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hex.js","sourceRoot":"","sources":["../src/hex.ts"],"names":[],"mappings":";;;AAAA,6CAA0D;AAC1D,qCAAkC;AAIrB,QAAA,SAAS,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,sBAAsB,CAAC,CAAC;AACtD,QAAA,eAAe,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,iBAAiB,CAGjE,CAAC;AAEF;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,iBAAS,CAAC,CAAC;AAC9B,CAAC;AAFD,kCAEC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,uBAAe,CAAC,CAAC;AACpC,CAAC;AAFD,8CAEC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,IAAA,eAAM,EAAC,WAAW,CAAC,KAAK,CAAC,EAAE,qCAAqC,CAAC,CAAC;AACpE,CAAC;AAFD,8CAEC;AAED;;;;;;GAMG;AACH,SAAgB,uBAAuB,CAAC,KAAc;IACpD,IAAA,eAAM,EACJ,iBAAiB,CAAC,KAAK,CAAC,EACxB,yDAAyD,CAC1D,CAAC;AACJ,CAAC;AALD,0DAKC;AAED;;;;;;GAMG;AACH,SAAgB,KAAK,CAAC,GAAW;IAC/B,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QACxB,OAAO,GAAU,CAAC;KACnB;IAED,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QACxB,OAAO,KAAK,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;KAChC;IAED,OAAO,KAAK,GAAG,EAAE,CAAC;AACpB,CAAC;AAVD,sBAUC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,GAAW;IAClC,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAChD,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;KACzB;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAND,4BAMC","sourcesContent":["import { is, pattern, string, Struct } from 'superstruct';\nimport { assert } from './assert';\n\nexport type Hex = `0x${string}`;\n\nexport const HexStruct = pattern(string(), /^(?:0x)?[0-9a-f]+$/iu);\nexport const StrictHexStruct = pattern(string(), /^0x[0-9a-f]+$/iu) as Struct<\n Hex,\n null\n>;\n\n/**\n * Check if a string is a valid hex string.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isHexString(value: unknown): value is string {\n return is(value, HexStruct);\n}\n\n/**\n * Strictly check if a string is a valid hex string. A valid hex string must\n * start with the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isStrictHexString(value: unknown): value is Hex {\n return is(value, StrictHexStruct);\n}\n\n/**\n * Assert that a value is a valid hex string.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsHexString(value: unknown): asserts value is string {\n assert(isHexString(value), 'Value must be a hexadecimal string.');\n}\n\n/**\n * Assert that a value is a valid hex string. A valid hex string must start with\n * the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsStrictHexString(value: unknown): asserts value is Hex {\n assert(\n isStrictHexString(value),\n 'Value must be a hexadecimal string, starting with \"0x\".',\n );\n}\n\n/**\n * Add the `0x`-prefix to a hexadecimal string. If the string already has the\n * prefix, it is returned as-is.\n *\n * @param hex - The hexadecimal string to add the prefix to.\n * @returns The prefixed hexadecimal string.\n */\nexport function add0x(hex: string): Hex {\n if (hex.startsWith('0x')) {\n return hex as Hex;\n }\n\n if (hex.startsWith('0X')) {\n return `0x${hex.substring(2)}`;\n }\n\n return `0x${hex}`;\n}\n\n/**\n * Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have\n * the prefix, it is returned as-is.\n *\n * @param hex - The hexadecimal string to remove the prefix from.\n * @returns The un-prefixed hexadecimal string.\n */\nexport function remove0x(hex: string): string {\n if (hex.startsWith('0x') || hex.startsWith('0X')) {\n return hex.substring(2);\n }\n\n return hex;\n}\n"]}
1
+ {"version":3,"file":"hex.js","sourceRoot":"","sources":["../src/hex.ts"],"names":[],"mappings":";;;AAAA,6CAA0D;AAE1D,qCAAkC;AAIrB,QAAA,SAAS,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,sBAAsB,CAAC,CAAC;AACtD,QAAA,eAAe,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,iBAAiB,CAGjE,CAAC;AAEF;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,iBAAS,CAAC,CAAC;AAC9B,CAAC;AAFD,kCAEC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,uBAAe,CAAC,CAAC;AACpC,CAAC;AAFD,8CAEC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,IAAA,eAAM,EAAC,WAAW,CAAC,KAAK,CAAC,EAAE,qCAAqC,CAAC,CAAC;AACpE,CAAC;AAFD,8CAEC;AAED;;;;;;GAMG;AACH,SAAgB,uBAAuB,CAAC,KAAc;IACpD,IAAA,eAAM,EACJ,iBAAiB,CAAC,KAAK,CAAC,EACxB,yDAAyD,CAC1D,CAAC;AACJ,CAAC;AALD,0DAKC;AAED;;;;;;GAMG;AACH,SAAgB,KAAK,CAAC,WAAmB;IACvC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAChC,OAAO,WAAkB,CAAC;KAC3B;IAED,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAChC,OAAO,KAAK,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;KACxC;IAED,OAAO,KAAK,WAAW,EAAE,CAAC;AAC5B,CAAC;AAVD,sBAUC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,WAAmB;IAC1C,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAChE,OAAO,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;KACjC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAND,4BAMC","sourcesContent":["import { is, pattern, string, Struct } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Hex = `0x${string}`;\n\nexport const HexStruct = pattern(string(), /^(?:0x)?[0-9a-f]+$/iu);\nexport const StrictHexStruct = pattern(string(), /^0x[0-9a-f]+$/iu) as Struct<\n Hex,\n null\n>;\n\n/**\n * Check if a string is a valid hex string.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isHexString(value: unknown): value is string {\n return is(value, HexStruct);\n}\n\n/**\n * Strictly check if a string is a valid hex string. A valid hex string must\n * start with the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isStrictHexString(value: unknown): value is Hex {\n return is(value, StrictHexStruct);\n}\n\n/**\n * Assert that a value is a valid hex string.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsHexString(value: unknown): asserts value is string {\n assert(isHexString(value), 'Value must be a hexadecimal string.');\n}\n\n/**\n * Assert that a value is a valid hex string. A valid hex string must start with\n * the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsStrictHexString(value: unknown): asserts value is Hex {\n assert(\n isStrictHexString(value),\n 'Value must be a hexadecimal string, starting with \"0x\".',\n );\n}\n\n/**\n * Add the `0x`-prefix to a hexadecimal string. If the string already has the\n * prefix, it is returned as-is.\n *\n * @param hexadecimal - The hexadecimal string to add the prefix to.\n * @returns The prefixed hexadecimal string.\n */\nexport function add0x(hexadecimal: string): Hex {\n if (hexadecimal.startsWith('0x')) {\n return hexadecimal as Hex;\n }\n\n if (hexadecimal.startsWith('0X')) {\n return `0x${hexadecimal.substring(2)}`;\n }\n\n return `0x${hexadecimal}`;\n}\n\n/**\n * Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have\n * the prefix, it is returned as-is.\n *\n * @param hexadecimal - The hexadecimal string to remove the prefix from.\n * @returns The un-prefixed hexadecimal string.\n */\nexport function remove0x(hexadecimal: string): string {\n if (hexadecimal.startsWith('0x') || hexadecimal.startsWith('0X')) {\n return hexadecimal.substring(2);\n }\n\n return hexadecimal;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export * from './assert';
2
+ export * from './base64';
2
3
  export * from './bytes';
4
+ export * from './checksum';
3
5
  export * from './coercers';
4
6
  export * from './collections';
5
7
  export * from './hex';
@@ -7,4 +9,6 @@ export * from './json';
7
9
  export * from './logging';
8
10
  export * from './misc';
9
11
  export * from './number';
12
+ export * from './opaque';
10
13
  export * from './time';
14
+ export * from './versions';
package/dist/index.js CHANGED
@@ -15,7 +15,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./assert"), exports);
18
+ __exportStar(require("./base64"), exports);
18
19
  __exportStar(require("./bytes"), exports);
20
+ __exportStar(require("./checksum"), exports);
19
21
  __exportStar(require("./coercers"), exports);
20
22
  __exportStar(require("./collections"), exports);
21
23
  __exportStar(require("./hex"), exports);
@@ -23,5 +25,7 @@ __exportStar(require("./json"), exports);
23
25
  __exportStar(require("./logging"), exports);
24
26
  __exportStar(require("./misc"), exports);
25
27
  __exportStar(require("./number"), exports);
28
+ __exportStar(require("./opaque"), exports);
26
29
  __exportStar(require("./time"), exports);
30
+ __exportStar(require("./versions"), exports);
27
31
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,0CAAwB;AACxB,6CAA2B;AAC3B,gDAA8B;AAC9B,wCAAsB;AACtB,yCAAuB;AACvB,4CAA0B;AAC1B,yCAAuB;AACvB,2CAAyB;AACzB,yCAAuB","sourcesContent":["export * from './assert';\nexport * from './bytes';\nexport * from './coercers';\nexport * from './collections';\nexport * from './hex';\nexport * from './json';\nexport * from './logging';\nexport * from './misc';\nexport * from './number';\nexport * from './time';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB;AACzB,0CAAwB;AACxB,6CAA2B;AAC3B,6CAA2B;AAC3B,gDAA8B;AAC9B,wCAAsB;AACtB,yCAAuB;AACvB,4CAA0B;AAC1B,yCAAuB;AACvB,2CAAyB;AACzB,2CAAyB;AACzB,yCAAuB;AACvB,6CAA2B","sourcesContent":["export * from './assert';\nexport * from './base64';\nexport * from './bytes';\nexport * from './checksum';\nexport * from './coercers';\nexport * from './collections';\nexport * from './hex';\nexport * from './json';\nexport * from './logging';\nexport * from './misc';\nexport * from './number';\nexport * from './opaque';\nexport * from './time';\nexport * from './versions';\n"]}
package/dist/json.d.ts CHANGED
@@ -56,20 +56,20 @@ export declare type OptionalField<Type extends Record<string, unknown>, Key exte
56
56
  * `OptionalField` helper, to explicitly make it optional.
57
57
  */
58
58
  export declare type JsonRpcError = OptionalField<Infer<typeof JsonRpcErrorStruct>, 'data'>;
59
- export declare const JsonRpcParamsStruct: Struct<unknown[] | Record<string, unknown> | undefined, null>;
59
+ export declare const JsonRpcParamsStruct: Struct<Record<string, Json> | Json[] | undefined, null>;
60
60
  export declare type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;
61
61
  export declare const JsonRpcRequestStruct: Struct<{
62
62
  id: string | number | null;
63
63
  method: string;
64
64
  jsonrpc: "2.0";
65
- params?: unknown[] | Record<string, unknown> | undefined;
65
+ params?: Record<string, Json> | Json[] | undefined;
66
66
  }, {
67
67
  id: Struct<string | number | null, null>;
68
68
  jsonrpc: Struct<"2.0", "2.0">;
69
69
  method: Struct<string, null>;
70
- params: Struct<unknown[] | Record<string, unknown> | undefined, null>;
70
+ params: Struct<Record<string, Json> | Json[] | undefined, null>;
71
71
  }>;
72
- export declare type InferWithParams<Type extends Struct<any, unknown>, Params extends JsonRpcParams> = Omit<Infer<Type>, 'params'> & (keyof Params extends undefined ? {
72
+ export declare type InferWithParams<Type extends Struct<any>, Params extends JsonRpcParams> = Omit<Infer<Type>, 'params'> & (keyof Params extends undefined ? {
73
73
  params?: Params;
74
74
  } : {
75
75
  params: Params;
@@ -77,21 +77,21 @@ export declare type InferWithParams<Type extends Struct<any, unknown>, Params ex
77
77
  /**
78
78
  * A JSON-RPC request object.
79
79
  */
80
- export declare type JsonRpcRequest<Params extends JsonRpcParams> = InferWithParams<typeof JsonRpcRequestStruct, Params>;
80
+ export declare type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> = InferWithParams<typeof JsonRpcRequestStruct, Params>;
81
81
  export declare const JsonRpcNotificationStruct: Struct<{
82
82
  method: string;
83
83
  jsonrpc: "2.0";
84
- params?: unknown[] | Record<string, unknown> | undefined;
84
+ params?: Record<string, Json> | Json[] | undefined;
85
85
  }, Omit<{
86
86
  id: Struct<string | number | null, null>;
87
87
  jsonrpc: Struct<"2.0", "2.0">;
88
88
  method: Struct<string, null>;
89
- params: Struct<unknown[] | Record<string, unknown> | undefined, null>;
89
+ params: Struct<Record<string, Json> | Json[] | undefined, null>;
90
90
  }, "id">>;
91
91
  /**
92
92
  * A JSON-RPC notification object.
93
93
  */
94
- export declare type JsonRpcNotification<Params extends JsonRpcParams> = InferWithParams<typeof JsonRpcNotificationStruct, Params>;
94
+ export declare type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> = InferWithParams<typeof JsonRpcNotificationStruct, Params>;
95
95
  /**
96
96
  * Check if the given value is a valid {@link JsonRpcNotification} object.
97
97
  *
@@ -99,7 +99,7 @@ export declare type JsonRpcNotification<Params extends JsonRpcParams> = InferWit
99
99
  * @returns Whether the given value is a valid {@link JsonRpcNotification}
100
100
  * object.
101
101
  */
102
- export declare function isJsonRpcNotification(value: unknown): value is JsonRpcNotification<JsonRpcParams>;
102
+ export declare function isJsonRpcNotification(value: unknown): value is JsonRpcNotification;
103
103
  /**
104
104
  * Assert that the given value is a valid {@link JsonRpcNotification} object.
105
105
  *
@@ -108,14 +108,14 @@ export declare function isJsonRpcNotification(value: unknown): value is JsonRpcN
108
108
  * Defaults to {@link AssertionError}.
109
109
  * @throws If the given value is not a valid {@link JsonRpcNotification} object.
110
110
  */
111
- export declare function assertIsJsonRpcNotification(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcNotification<JsonRpcParams>;
111
+ export declare function assertIsJsonRpcNotification(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcNotification;
112
112
  /**
113
113
  * Check if the given value is a valid {@link JsonRpcRequest} object.
114
114
  *
115
115
  * @param value - The value to check.
116
116
  * @returns Whether the given value is a valid {@link JsonRpcRequest} object.
117
117
  */
118
- export declare function isJsonRpcRequest(value: unknown): value is JsonRpcRequest<JsonRpcParams>;
118
+ export declare function isJsonRpcRequest(value: unknown): value is JsonRpcRequest;
119
119
  /**
120
120
  * Assert that the given value is a valid {@link JsonRpcRequest} object.
121
121
  *
@@ -124,7 +124,7 @@ export declare function isJsonRpcRequest(value: unknown): value is JsonRpcReques
124
124
  * Defaults to {@link AssertionError}.
125
125
  * @throws If the given value is not a valid {@link JsonRpcRequest} object.
126
126
  */
127
- export declare function assertIsJsonRpcRequest(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcRequest<JsonRpcParams>;
127
+ export declare function assertIsJsonRpcRequest(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcRequest;
128
128
  export declare const PendingJsonRpcResponseStruct: Struct<{
129
129
  id: string | number | null;
130
130
  jsonrpc: "2.0";