@metamask/utils 6.2.0 → 7.1.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 +16 -1
- package/dist/cjs/assert.js +116 -0
- package/dist/cjs/assert.js.map +1 -0
- package/dist/cjs/base64.js +32 -0
- package/dist/cjs/base64.js.map +1 -0
- package/dist/cjs/bytes.js +255 -0
- package/dist/cjs/bytes.js.map +1 -0
- package/dist/cjs/caip-types.js +115 -0
- package/dist/cjs/caip-types.js.map +1 -0
- package/dist/cjs/checksum.js +17 -0
- package/dist/cjs/checksum.js.map +1 -0
- package/dist/cjs/coercers.js +96 -0
- package/dist/cjs/coercers.js.map +1 -0
- package/dist/cjs/collections.js +157 -0
- package/dist/cjs/collections.js.map +1 -0
- package/dist/cjs/encryption-types.js +6 -0
- package/dist/cjs/encryption-types.js.map +1 -0
- package/dist/cjs/hex.js +107 -0
- package/dist/cjs/hex.js.map +1 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/json.js +263 -0
- package/dist/cjs/json.js.map +1 -0
- package/dist/cjs/keyring.js +6 -0
- package/dist/cjs/keyring.js.map +1 -0
- package/dist/cjs/logging.js +33 -0
- package/dist/cjs/logging.js.map +1 -0
- package/dist/cjs/misc.js +111 -0
- package/dist/cjs/misc.js.map +1 -0
- package/dist/cjs/number.js +52 -0
- package/dist/cjs/number.js.map +1 -0
- package/dist/cjs/opaque.js +8 -0
- package/dist/cjs/opaque.js.map +1 -0
- package/dist/cjs/time.js +63 -0
- package/dist/cjs/time.js.map +1 -0
- package/dist/cjs/transaction-types.js +6 -0
- package/dist/cjs/transaction-types.js.map +1 -0
- package/dist/cjs/versions.js +79 -0
- package/dist/cjs/versions.js.map +1 -0
- package/dist/{assert.js → esm/assert.js} +30 -35
- package/dist/esm/assert.js.map +1 -0
- package/dist/{base64.js → esm/base64.js} +10 -16
- package/dist/esm/base64.js.map +1 -0
- package/dist/{bytes.js → esm/bytes.js} +50 -93
- package/dist/esm/bytes.js.map +1 -0
- package/dist/esm/caip-types.js +99 -0
- package/dist/esm/caip-types.js.map +1 -0
- package/dist/esm/checksum.js +7 -0
- package/dist/esm/checksum.js.map +1 -0
- package/dist/{coercers.js → esm/coercers.js} +43 -52
- package/dist/esm/coercers.js.map +1 -0
- package/dist/esm/collections.js +140 -0
- package/dist/esm/collections.js.map +1 -0
- package/dist/esm/encryption-types.js +3 -0
- package/dist/esm/encryption-types.js.map +1 -0
- package/dist/esm/hex.js +108 -0
- package/dist/esm/hex.js.map +1 -0
- package/dist/{index.d.ts → esm/index.js} +3 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/json.js +301 -0
- package/dist/esm/json.js.map +1 -0
- package/dist/esm/keyring.js +3 -0
- package/dist/esm/keyring.js.map +1 -0
- package/dist/{logging.js → esm/logging.js} +5 -14
- package/dist/esm/logging.js.map +1 -0
- package/dist/{misc.js → esm/misc.js} +37 -42
- package/dist/esm/misc.js.map +1 -0
- package/dist/{number.js → esm/number.js} +18 -28
- package/dist/esm/number.js.map +1 -0
- package/dist/esm/opaque.js +5 -0
- package/dist/esm/opaque.js.map +1 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/time.js +53 -0
- package/dist/esm/time.js.map +1 -0
- package/dist/esm/transaction-types.js +3 -0
- package/dist/esm/transaction-types.js.map +1 -0
- package/dist/esm/versions.js +78 -0
- package/dist/esm/versions.js.map +1 -0
- package/dist/{assert.d.ts → types/assert.d.ts} +3 -2
- package/dist/types/assert.d.ts.map +1 -0
- package/dist/{base64.d.ts → types/base64.d.ts} +3 -2
- package/dist/types/base64.d.ts.map +1 -0
- package/dist/{bytes.d.ts → types/bytes.d.ts} +2 -1
- package/dist/types/bytes.d.ts.map +1 -0
- package/dist/types/caip-types.d.ts +93 -0
- package/dist/types/caip-types.d.ts.map +1 -0
- package/dist/types/caip-types.test-d.d.ts +2 -0
- package/dist/types/caip-types.test-d.d.ts.map +1 -0
- package/dist/{checksum.d.ts → types/checksum.d.ts} +1 -0
- package/dist/types/checksum.d.ts.map +1 -0
- package/dist/{coercers.d.ts → types/coercers.d.ts} +3 -2
- package/dist/types/coercers.d.ts.map +1 -0
- package/dist/{collections.d.ts → types/collections.d.ts} +1 -0
- package/dist/types/collections.d.ts.map +1 -0
- package/dist/{encryption-types.d.ts → types/encryption-types.d.ts} +1 -0
- package/dist/types/encryption-types.d.ts.map +1 -0
- package/dist/{hex.d.ts → types/hex.d.ts} +2 -1
- package/dist/types/hex.d.ts.map +1 -0
- package/dist/types/hex.test-d.d.ts +2 -0
- package/dist/types/hex.test-d.d.ts.map +1 -0
- package/dist/types/index.d.ts +19 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/{json.d.ts → types/json.d.ts} +3 -2
- package/dist/types/json.d.ts.map +1 -0
- package/dist/types/json.test-d.d.ts +2 -0
- package/dist/types/json.test-d.d.ts.map +1 -0
- package/dist/{keyring.d.ts → types/keyring.d.ts} +3 -2
- package/dist/types/keyring.d.ts.map +1 -0
- package/dist/{logging.d.ts → types/logging.d.ts} +2 -1
- package/dist/types/logging.d.ts.map +1 -0
- package/dist/{misc.d.ts → types/misc.d.ts} +13 -0
- package/dist/types/misc.d.ts.map +1 -0
- package/dist/types/misc.test-d.d.ts +2 -0
- package/dist/types/misc.test-d.d.ts.map +1 -0
- package/dist/{number.d.ts → types/number.d.ts} +1 -0
- package/dist/types/number.d.ts.map +1 -0
- package/dist/{opaque.d.ts → types/opaque.d.ts} +1 -0
- package/dist/types/opaque.d.ts.map +1 -0
- package/dist/{time.d.ts → types/time.d.ts} +1 -0
- package/dist/types/time.d.ts.map +1 -0
- package/dist/{transaction-types.d.ts → types/transaction-types.d.ts} +3 -2
- package/dist/types/transaction-types.d.ts.map +1 -0
- package/dist/{versions.d.ts → types/versions.d.ts} +3 -2
- package/dist/types/versions.d.ts.map +1 -0
- package/package.json +40 -20
- package/dist/__fixtures__/bytes.d.ts +0 -25
- package/dist/__fixtures__/bytes.js +0 -234
- package/dist/__fixtures__/bytes.js.map +0 -1
- package/dist/__fixtures__/coercions.d.ts +0 -5
- package/dist/__fixtures__/coercions.js +0 -22
- package/dist/__fixtures__/coercions.js.map +0 -1
- package/dist/__fixtures__/index.d.ts +0 -4
- package/dist/__fixtures__/index.js +0 -21
- package/dist/__fixtures__/index.js.map +0 -1
- package/dist/__fixtures__/json.d.ts +0 -1226
- package/dist/__fixtures__/json.js +0 -1491
- package/dist/__fixtures__/json.js.map +0 -1
- package/dist/__fixtures__/numbers.d.ts +0 -5
- package/dist/__fixtures__/numbers.js +0 -56
- package/dist/__fixtures__/numbers.js.map +0 -1
- package/dist/assert.js.map +0 -1
- package/dist/base64.js.map +0 -1
- package/dist/bytes.js.map +0 -1
- package/dist/checksum.js +0 -7
- package/dist/checksum.js.map +0 -1
- package/dist/coercers.js.map +0 -1
- package/dist/collections.js +0 -109
- package/dist/collections.js.map +0 -1
- package/dist/encryption-types.js +0 -3
- package/dist/encryption-types.js.map +0 -1
- package/dist/hex.js +0 -134
- package/dist/hex.js.map +0 -1
- package/dist/hex.test-d.d.ts +0 -1
- package/dist/hex.test-d.js +0 -16
- package/dist/hex.test-d.js.map +0 -1
- package/dist/index.js +0 -34
- package/dist/index.js.map +0 -1
- package/dist/json.js +0 -346
- package/dist/json.js.map +0 -1
- package/dist/json.test-d.d.ts +0 -1
- package/dist/json.test-d.js +0 -62
- package/dist/json.test-d.js.map +0 -1
- package/dist/keyring.js +0 -3
- package/dist/keyring.js.map +0 -1
- package/dist/logging.js.map +0 -1
- package/dist/misc.js.map +0 -1
- package/dist/misc.test-d.d.ts +0 -1
- package/dist/misc.test-d.js +0 -97
- package/dist/misc.test-d.js.map +0 -1
- package/dist/number.js.map +0 -1
- package/dist/opaque.js +0 -3
- package/dist/opaque.js.map +0 -1
- package/dist/time.js +0 -67
- package/dist/time.js.map +0 -1
- package/dist/transaction-types.js +0 -3
- package/dist/transaction-types.js.map +0 -1
- package/dist/versions.js +0 -95
- package/dist/versions.js.map +0 -1
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
VersionStruct: function() {
|
|
13
|
+
return VersionStruct;
|
|
14
|
+
},
|
|
15
|
+
VersionRangeStruct: function() {
|
|
16
|
+
return VersionRangeStruct;
|
|
17
|
+
},
|
|
18
|
+
isValidSemVerVersion: function() {
|
|
19
|
+
return isValidSemVerVersion;
|
|
20
|
+
},
|
|
21
|
+
isValidSemVerRange: function() {
|
|
22
|
+
return isValidSemVerRange;
|
|
23
|
+
},
|
|
24
|
+
assertIsSemVerVersion: function() {
|
|
25
|
+
return assertIsSemVerVersion;
|
|
26
|
+
},
|
|
27
|
+
assertIsSemVerRange: function() {
|
|
28
|
+
return assertIsSemVerRange;
|
|
29
|
+
},
|
|
30
|
+
gtVersion: function() {
|
|
31
|
+
return gtVersion;
|
|
32
|
+
},
|
|
33
|
+
gtRange: function() {
|
|
34
|
+
return gtRange;
|
|
35
|
+
},
|
|
36
|
+
satisfiesVersionRange: function() {
|
|
37
|
+
return satisfiesVersionRange;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
const _semver = require("semver");
|
|
41
|
+
const _superstruct = require("superstruct");
|
|
42
|
+
const _assert = require("./assert");
|
|
43
|
+
const VersionStruct = (0, _superstruct.refine)((0, _superstruct.string)(), 'Version', (value)=>{
|
|
44
|
+
if ((0, _semver.valid)(value) === null) {
|
|
45
|
+
return `Expected SemVer version, got "${value}"`;
|
|
46
|
+
}
|
|
47
|
+
return true;
|
|
48
|
+
});
|
|
49
|
+
const VersionRangeStruct = (0, _superstruct.refine)((0, _superstruct.string)(), 'Version range', (value)=>{
|
|
50
|
+
if ((0, _semver.validRange)(value) === null) {
|
|
51
|
+
return `Expected SemVer range, got "${value}"`;
|
|
52
|
+
}
|
|
53
|
+
return true;
|
|
54
|
+
});
|
|
55
|
+
function isValidSemVerVersion(version) {
|
|
56
|
+
return (0, _superstruct.is)(version, VersionStruct);
|
|
57
|
+
}
|
|
58
|
+
function isValidSemVerRange(versionRange) {
|
|
59
|
+
return (0, _superstruct.is)(versionRange, VersionRangeStruct);
|
|
60
|
+
}
|
|
61
|
+
function assertIsSemVerVersion(version) {
|
|
62
|
+
(0, _assert.assertStruct)(version, VersionStruct);
|
|
63
|
+
}
|
|
64
|
+
function assertIsSemVerRange(range) {
|
|
65
|
+
(0, _assert.assertStruct)(range, VersionRangeStruct);
|
|
66
|
+
}
|
|
67
|
+
function gtVersion(version1, version2) {
|
|
68
|
+
return (0, _semver.gt)(version1, version2);
|
|
69
|
+
}
|
|
70
|
+
function gtRange(version, range) {
|
|
71
|
+
return (0, _semver.gtr)(version, range);
|
|
72
|
+
}
|
|
73
|
+
function satisfiesVersionRange(version, versionRange) {
|
|
74
|
+
return (0, _semver.satisfies)(version, versionRange, {
|
|
75
|
+
includePrerelease: true
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
//# sourceMappingURL=versions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/versions.ts"],"sourcesContent":["import {\n gt as gtSemver,\n gtr as gtrSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\nimport type { Struct } from 'superstruct';\nimport { is, refine, string } from 'superstruct';\n\nimport { assertStruct } from './assert';\nimport type { Opaque } from './opaque';\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque<string, typeof semVerRange>;\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque<string, typeof semVerVersion>;\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine<SemVerVersion, null>(\n string() as unknown as Struct<SemVerVersion, null>,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine<SemVerRange, null>(\n string() as unknown as Struct<SemVerRange, null>,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Checks whether a SemVer version is greater than all possibilities in a range.\n *\n * @param version - A SemvVer version.\n * @param range - The range to check against.\n * @returns `version > range`.\n */\nexport function gtRange(version: SemVerVersion, range: SemVerRange): boolean {\n return gtrSemver(version, range);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n"],"names":["VersionStruct","VersionRangeStruct","isValidSemVerVersion","isValidSemVerRange","assertIsSemVerVersion","assertIsSemVerRange","gtVersion","gtRange","satisfiesVersionRange","refine","string","value","validSemVerVersion","validSemVerRange","version","is","versionRange","assertStruct","range","version1","version2","gtSemver","gtrSemver","satisfiesSemver","includePrerelease"],"mappings":";;;;;;;;;;;IA4DaA,aAAa;eAAbA;;IAWAC,kBAAkB;eAAlBA;;IAiBGC,oBAAoB;eAApBA;;IAYAC,kBAAkB;eAAlBA;;IAWAC,qBAAqB;eAArBA;;IAWAC,mBAAmB;eAAnBA;;IAaAC,SAAS;eAATA;;IAcAC,OAAO;eAAPA;;IAWAC,qBAAqB;eAArBA;;;wBA1JT;6BAE4B;wBAEN;AAkDtB,MAAMR,gBAAgBS,IAAAA,mBAAM,EACjCC,IAAAA,mBAAM,KACN,WACA,CAACC;IACC,IAAIC,IAAAA,aAAkB,EAACD,WAAW,MAAM;QACtC,OAAO,CAAC,8BAA8B,EAAEA,MAAM,CAAC,CAAC;IAClD;IACA,OAAO;AACT;AAGK,MAAMV,qBAAqBQ,IAAAA,mBAAM,EACtCC,IAAAA,mBAAM,KACN,iBACA,CAACC;IACC,IAAIE,IAAAA,kBAAgB,EAACF,WAAW,MAAM;QACpC,OAAO,CAAC,4BAA4B,EAAEA,MAAM,CAAC,CAAC;IAChD;IACA,OAAO;AACT;AASK,SAAST,qBACdY,OAAgB;IAEhB,OAAOC,IAAAA,eAAE,EAACD,SAASd;AACrB;AAQO,SAASG,mBACda,YAAqB;IAErB,OAAOD,IAAAA,eAAE,EAACC,cAAcf;AAC1B;AAOO,SAASG,sBACdU,OAAgB;IAEhBG,IAAAA,oBAAY,EAACH,SAASd;AACxB;AAOO,SAASK,oBACda,KAAc;IAEdD,IAAAA,oBAAY,EAACC,OAAOjB;AACtB;AASO,SAASK,UACda,QAAuB,EACvBC,QAAuB;IAEvB,OAAOC,IAAAA,UAAQ,EAACF,UAAUC;AAC5B;AASO,SAASb,QAAQO,OAAsB,EAAEI,KAAkB;IAChE,OAAOI,IAAAA,WAAS,EAACR,SAASI;AAC5B;AASO,SAASV,sBACdM,OAAsB,EACtBE,YAAyB;IAEzB,OAAOO,IAAAA,iBAAe,EAACT,SAASE,cAAc;QAC5CQ,mBAAmB;IACrB;AACF"}
|
|
@@ -1,15 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
function _define_property(obj, key, value) {
|
|
2
|
+
if (key in obj) {
|
|
3
|
+
Object.defineProperty(obj, key, {
|
|
4
|
+
value: value,
|
|
5
|
+
enumerable: true,
|
|
6
|
+
configurable: true,
|
|
7
|
+
writable: true
|
|
8
|
+
});
|
|
9
|
+
} else {
|
|
10
|
+
obj[key] = value;
|
|
11
|
+
}
|
|
12
|
+
return obj;
|
|
13
|
+
}
|
|
14
|
+
import { assert as assertSuperstruct } from 'superstruct';
|
|
5
15
|
/**
|
|
6
16
|
* Type guard for determining whether the given value is an error object with a
|
|
7
17
|
* `message` property, such as an instance of Error.
|
|
8
18
|
*
|
|
9
19
|
* @param error - The object to check.
|
|
10
20
|
* @returns True or false, depending on the result.
|
|
11
|
-
*/
|
|
12
|
-
function isErrorWithMessage(error) {
|
|
21
|
+
*/ function isErrorWithMessage(error) {
|
|
13
22
|
return typeof error === 'object' && error !== null && 'message' in error;
|
|
14
23
|
}
|
|
15
24
|
/**
|
|
@@ -18,10 +27,8 @@ function isErrorWithMessage(error) {
|
|
|
18
27
|
*
|
|
19
28
|
* @param fn - The value to check.
|
|
20
29
|
* @returns `true` if the value is a constructor, or `false` otherwise.
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
/* istanbul ignore next */
|
|
24
|
-
return Boolean(typeof fn?.prototype?.constructor?.name === 'string');
|
|
30
|
+
*/ function isConstructable(fn) {
|
|
31
|
+
/* istanbul ignore next */ return Boolean(typeof fn?.prototype?.constructor?.name === 'string');
|
|
25
32
|
}
|
|
26
33
|
/**
|
|
27
34
|
* Get the error message from an unknown error object. If the error object has
|
|
@@ -30,8 +37,7 @@ function isConstructable(fn) {
|
|
|
30
37
|
*
|
|
31
38
|
* @param error - The error object to get the message from.
|
|
32
39
|
* @returns The error message.
|
|
33
|
-
*/
|
|
34
|
-
function getErrorMessage(error) {
|
|
40
|
+
*/ function getErrorMessage(error) {
|
|
35
41
|
const message = isErrorWithMessage(error) ? error.message : String(error);
|
|
36
42
|
// If the error ends with a period, remove it, as we'll add our own period.
|
|
37
43
|
if (message.endsWith('.')) {
|
|
@@ -45,28 +51,25 @@ function getErrorMessage(error) {
|
|
|
45
51
|
* @param ErrorWrapper - The error class to use.
|
|
46
52
|
* @param message - The error message.
|
|
47
53
|
* @returns The error object.
|
|
48
|
-
*/
|
|
49
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
54
|
+
*/ // eslint-disable-next-line @typescript-eslint/naming-convention
|
|
50
55
|
function getError(ErrorWrapper, message) {
|
|
51
56
|
if (isConstructable(ErrorWrapper)) {
|
|
52
57
|
return new ErrorWrapper({
|
|
53
|
-
message
|
|
58
|
+
message
|
|
54
59
|
});
|
|
55
60
|
}
|
|
56
61
|
return ErrorWrapper({
|
|
57
|
-
message
|
|
62
|
+
message
|
|
58
63
|
});
|
|
59
64
|
}
|
|
60
65
|
/**
|
|
61
66
|
* The default error class that is thrown if an assertion fails.
|
|
62
|
-
*/
|
|
63
|
-
|
|
64
|
-
constructor(options) {
|
|
67
|
+
*/ export class AssertionError extends Error {
|
|
68
|
+
constructor(options){
|
|
65
69
|
super(options.message);
|
|
66
|
-
this
|
|
70
|
+
_define_property(this, "code", 'ERR_ASSERTION');
|
|
67
71
|
}
|
|
68
72
|
}
|
|
69
|
-
exports.AssertionError = AssertionError;
|
|
70
73
|
/**
|
|
71
74
|
* Same as Node.js assert.
|
|
72
75
|
* If the value is falsy, throws an error, does nothing otherwise.
|
|
@@ -78,9 +81,7 @@ exports.AssertionError = AssertionError;
|
|
|
78
81
|
* @param ErrorWrapper - The error class to throw if the assertion fails.
|
|
79
82
|
* Defaults to {@link AssertionError}. If a custom error class is provided for
|
|
80
83
|
* the `message` argument, this argument is ignored.
|
|
81
|
-
*/
|
|
82
|
-
function assert(value, message = 'Assertion failed.',
|
|
83
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
84
|
+
*/ export function assert(value, message = 'Assertion failed.', // eslint-disable-next-line @typescript-eslint/naming-convention
|
|
84
85
|
ErrorWrapper = AssertionError) {
|
|
85
86
|
if (!value) {
|
|
86
87
|
if (message instanceof Error) {
|
|
@@ -89,7 +90,6 @@ ErrorWrapper = AssertionError) {
|
|
|
89
90
|
throw getError(ErrorWrapper, message);
|
|
90
91
|
}
|
|
91
92
|
}
|
|
92
|
-
exports.assert = assert;
|
|
93
93
|
/**
|
|
94
94
|
* Assert a value against a Superstruct struct.
|
|
95
95
|
*
|
|
@@ -100,18 +100,14 @@ exports.assert = assert;
|
|
|
100
100
|
* @param ErrorWrapper - The error class to throw if the assertion fails.
|
|
101
101
|
* Defaults to {@link AssertionError}.
|
|
102
102
|
* @throws If the value is not valid.
|
|
103
|
-
*/
|
|
104
|
-
function assertStruct(value, struct, errorPrefix = 'Assertion failed',
|
|
105
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
103
|
+
*/ export function assertStruct(value, struct, errorPrefix = 'Assertion failed', // eslint-disable-next-line @typescript-eslint/naming-convention
|
|
106
104
|
ErrorWrapper = AssertionError) {
|
|
107
105
|
try {
|
|
108
|
-
(
|
|
109
|
-
}
|
|
110
|
-
catch (error) {
|
|
106
|
+
assertSuperstruct(value, struct);
|
|
107
|
+
} catch (error) {
|
|
111
108
|
throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);
|
|
112
109
|
}
|
|
113
110
|
}
|
|
114
|
-
exports.assertStruct = assertStruct;
|
|
115
111
|
/**
|
|
116
112
|
* Use in the default case of a switch that you want to be fully exhaustive.
|
|
117
113
|
* Using this function forces the compiler to enforce exhaustivity during
|
|
@@ -130,9 +126,8 @@ exports.assertStruct = assertStruct;
|
|
|
130
126
|
* }
|
|
131
127
|
* ```
|
|
132
128
|
* @param _object - The object on which the switch is being operated.
|
|
133
|
-
*/
|
|
134
|
-
function assertExhaustive(_object) {
|
|
129
|
+
*/ export function assertExhaustive(_object) {
|
|
135
130
|
throw new Error('Invalid branch reached. Should be detected during compilation.');
|
|
136
131
|
}
|
|
137
|
-
|
|
132
|
+
|
|
138
133
|
//# sourceMappingURL=assert.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/assert.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { assert as assertSuperstruct } 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<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n errorPrefix = 'Assertion failed',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is Type {\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"],"names":["assert","assertSuperstruct","isErrorWithMessage","error","isConstructable","fn","Boolean","prototype","constructor","name","getErrorMessage","message","String","endsWith","slice","getError","ErrorWrapper","AssertionError","Error","options","code","value","assertStruct","struct","errorPrefix","assertExhaustive","_object"],"mappings":";;;;;;;;;;;;;AACA,SAASA,UAAUC,iBAAiB,QAAQ,cAAc;AAM1D;;;;;;CAMC,GACD,SAASC,mBAAmBC,KAAc;IACxC,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,aAAaA;AACrE;AAEA;;;;;;CAMC,GACD,SAASC,gBACPC,EAA6B;IAE7B,wBAAwB,GACxB,OAAOC,QAAQ,OAAOD,IAAIE,WAAWC,aAAaC,SAAS;AAC7D;AAEA;;;;;;;CAOC,GACD,SAASC,gBAAgBP,KAAc;IACrC,MAAMQ,UAAUT,mBAAmBC,SAASA,MAAMQ,OAAO,GAAGC,OAAOT;IAEnE,2EAA2E;IAC3E,IAAIQ,QAAQE,QAAQ,CAAC,MAAM;QACzB,OAAOF,QAAQG,KAAK,CAAC,GAAG,CAAC;IAC3B;IAEA,OAAOH;AACT;AAEA;;;;;;CAMC,GACD,gEAAgE;AAChE,SAASI,SAASC,YAAuC,EAAEL,OAAe;IACxE,IAAIP,gBAAgBY,eAAe;QACjC,OAAO,IAAIA,aAAa;YACtBL;QACF;IACF;IACA,OAAOK,aAAa;QAClBL;IACF;AACF;AAEA;;CAEC,GACD,OAAO,MAAMM,uBAAuBC;IAGlCV,YAAYW,OAA4B,CAAE;QACxC,KAAK,CAACA,QAAQR,OAAO;QAHvB,uBAASS,QAAO;IAIhB;AACF;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASpB,OACdqB,KAAU,EACVV,UAA0B,mBAAmB,EAC7C,gEAAgE;AAChEK,eAA0CC,cAAc;IAExD,IAAI,CAACI,OAAO;QACV,IAAIV,mBAAmBO,OAAO;YAC5B,MAAMP;QACR;QAEA,MAAMI,SAASC,cAAcL;IAC/B;AACF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASW,aACdD,KAAc,EACdE,MAA4B,EAC5BC,cAAc,kBAAkB,EAChC,gEAAgE;AAChER,eAA0CC,cAAc;IAExD,IAAI;QACFhB,kBAAkBoB,OAAOE;IAC3B,EAAE,OAAOpB,OAAO;QACd,MAAMY,SAASC,cAAc,CAAC,EAAEQ,YAAY,EAAE,EAAEd,gBAAgBP,OAAO,CAAC,CAAC;IAC3E;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASsB,iBAAiBC,OAAc;IAC7C,MAAM,IAAIR,MACR;AAEJ"}
|
|
@@ -1,34 +1,28 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
exports.base64 = void 0;
|
|
4
|
-
const superstruct_1 = require("superstruct");
|
|
5
|
-
const assert_1 = require("./assert");
|
|
1
|
+
import { pattern } from 'superstruct';
|
|
2
|
+
import { assert } from './assert';
|
|
6
3
|
/**
|
|
7
4
|
* Ensure that a provided string-based struct is valid base64.
|
|
8
5
|
*
|
|
9
6
|
* @param struct - The string based struct.
|
|
10
7
|
* @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.
|
|
11
8
|
* @returns A superstruct validating base64.
|
|
12
|
-
*/
|
|
13
|
-
const base64 = (struct, options = {}) => {
|
|
9
|
+
*/ export const base64 = (struct, options = {})=>{
|
|
14
10
|
const paddingRequired = options.paddingRequired ?? false;
|
|
15
11
|
const characterSet = options.characterSet ?? 'base64';
|
|
16
12
|
let letters;
|
|
17
13
|
if (characterSet === 'base64') {
|
|
18
|
-
letters = String.raw
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
letters = String.raw `[-_A-Za-z0-9]`;
|
|
14
|
+
letters = String.raw`[A-Za-z0-9+\/]`;
|
|
15
|
+
} else {
|
|
16
|
+
assert(characterSet === 'base64url');
|
|
17
|
+
letters = String.raw`[-_A-Za-z0-9]`;
|
|
23
18
|
}
|
|
24
19
|
let re;
|
|
25
20
|
if (paddingRequired) {
|
|
26
21
|
re = new RegExp(`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, 'u');
|
|
27
|
-
}
|
|
28
|
-
else {
|
|
22
|
+
} else {
|
|
29
23
|
re = new RegExp(`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, 'u');
|
|
30
24
|
}
|
|
31
|
-
return
|
|
25
|
+
return pattern(struct, re);
|
|
32
26
|
};
|
|
33
|
-
|
|
27
|
+
|
|
34
28
|
//# sourceMappingURL=base64.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/base64.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { pattern } 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 = <Type extends string, Schema>(\n struct: Struct<Type, Schema>,\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"],"names":["pattern","assert","base64","struct","options","paddingRequired","characterSet","letters","String","raw","re","RegExp"],"mappings":"AACA,SAASA,OAAO,QAAQ,cAAc;AAEtC,SAASC,MAAM,QAAQ,WAAW;AAmBlC;;;;;;CAMC,GACD,OAAO,MAAMC,SAAS,CACpBC,QACAC,UAAyB,CAAC,CAAC;IAE3B,MAAMC,kBAAkBD,QAAQC,eAAe,IAAI;IACnD,MAAMC,eAAeF,QAAQE,YAAY,IAAI;IAE7C,IAAIC;IACJ,IAAID,iBAAiB,UAAU;QAC7BC,UAAUC,OAAOC,GAAG,CAAC,cAAc,CAAC;IACtC,OAAO;QACLR,OAAOK,iBAAiB;QACxBC,UAAUC,OAAOC,GAAG,CAAC,aAAa,CAAC;IACrC;IAEA,IAAIC;IACJ,IAAIL,iBAAiB;QACnBK,KAAK,IAAIC,OACP,CAAC,IAAI,EAAEJ,QAAQ,QAAQ,EAAEA,QAAQ,KAAK,EAAEA,QAAQ,QAAQ,CAAC,EACzD;IAEJ,OAAO;QACLG,KAAK,IAAIC,OACP,CAAC,IAAI,EAAEJ,QAAQ,QAAQ,EAAEA,QAAQ,MAAM,EAAEA,QAAQ,KAAK,EAAEA,QAAQ,QAAQ,CAAC,EACzE;IAEJ;IAEA,OAAOP,QAAQG,QAAQO;AACzB,EAAE"}
|
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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
|
-
const assert_1 = require("./assert");
|
|
5
|
-
const hex_1 = require("./hex");
|
|
1
|
+
import { assert } from './assert';
|
|
2
|
+
import { add0x, assertIsHexString, remove0x } from './hex';
|
|
6
3
|
// '0'.charCodeAt(0) === 48
|
|
7
4
|
const HEX_MINIMUM_NUMBER_CHARACTER = 48;
|
|
8
5
|
// '9'.charCodeAt(0) === 57
|
|
@@ -21,16 +18,15 @@ const HEX_CHARACTER_OFFSET = 87;
|
|
|
21
18
|
* elements long.
|
|
22
19
|
*
|
|
23
20
|
* @returns A function that returns the lookup table.
|
|
24
|
-
*/
|
|
25
|
-
function getPrecomputedHexValuesBuilder() {
|
|
21
|
+
*/ function getPrecomputedHexValuesBuilder() {
|
|
26
22
|
// To avoid issues with tree shaking, we need to use a function to return the
|
|
27
23
|
// array. This is because the array is only used in the `bytesToHex` function
|
|
28
24
|
// and if we were to use a global variable, the array might be removed by the
|
|
29
25
|
// tree shaker.
|
|
30
26
|
const lookupTable = [];
|
|
31
|
-
return ()
|
|
27
|
+
return ()=>{
|
|
32
28
|
if (lookupTable.length === 0) {
|
|
33
|
-
for
|
|
29
|
+
for(let i = 0; i < 256; i++){
|
|
34
30
|
lookupTable.push(i.toString(16).padStart(2, '0'));
|
|
35
31
|
}
|
|
36
32
|
}
|
|
@@ -40,48 +36,41 @@ function getPrecomputedHexValuesBuilder() {
|
|
|
40
36
|
/**
|
|
41
37
|
* Function implementation of the {@link getPrecomputedHexValuesBuilder}
|
|
42
38
|
* function.
|
|
43
|
-
*/
|
|
44
|
-
const getPrecomputedHexValues = getPrecomputedHexValuesBuilder();
|
|
39
|
+
*/ const getPrecomputedHexValues = getPrecomputedHexValuesBuilder();
|
|
45
40
|
/**
|
|
46
41
|
* Check if a value is a `Uint8Array`.
|
|
47
42
|
*
|
|
48
43
|
* @param value - The value to check.
|
|
49
44
|
* @returns Whether the value is a `Uint8Array`.
|
|
50
|
-
*/
|
|
51
|
-
function isBytes(value) {
|
|
45
|
+
*/ export function isBytes(value) {
|
|
52
46
|
return value instanceof Uint8Array;
|
|
53
47
|
}
|
|
54
|
-
exports.isBytes = isBytes;
|
|
55
48
|
/**
|
|
56
49
|
* Assert that a value is a `Uint8Array`.
|
|
57
50
|
*
|
|
58
51
|
* @param value - The value to check.
|
|
59
52
|
* @throws If the value is not a `Uint8Array`.
|
|
60
|
-
*/
|
|
61
|
-
|
|
62
|
-
(0, assert_1.assert)(isBytes(value), 'Value must be a Uint8Array.');
|
|
53
|
+
*/ export function assertIsBytes(value) {
|
|
54
|
+
assert(isBytes(value), 'Value must be a Uint8Array.');
|
|
63
55
|
}
|
|
64
|
-
exports.assertIsBytes = assertIsBytes;
|
|
65
56
|
/**
|
|
66
57
|
* Convert a `Uint8Array` to a hexadecimal string.
|
|
67
58
|
*
|
|
68
59
|
* @param bytes - The bytes to convert to a hexadecimal string.
|
|
69
60
|
* @returns The hexadecimal string.
|
|
70
|
-
*/
|
|
71
|
-
function bytesToHex(bytes) {
|
|
61
|
+
*/ export function bytesToHex(bytes) {
|
|
72
62
|
assertIsBytes(bytes);
|
|
73
63
|
if (bytes.length === 0) {
|
|
74
64
|
return '0x';
|
|
75
65
|
}
|
|
76
66
|
const lookupTable = getPrecomputedHexValues();
|
|
77
67
|
const hexadecimal = new Array(bytes.length);
|
|
78
|
-
for
|
|
68
|
+
for(let i = 0; i < bytes.length; i++){
|
|
79
69
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
80
70
|
hexadecimal[i] = lookupTable[bytes[i]];
|
|
81
71
|
}
|
|
82
|
-
return
|
|
72
|
+
return add0x(hexadecimal.join(''));
|
|
83
73
|
}
|
|
84
|
-
exports.bytesToHex = bytesToHex;
|
|
85
74
|
/**
|
|
86
75
|
* Convert a `Uint8Array` to a `bigint`.
|
|
87
76
|
*
|
|
@@ -91,13 +80,11 @@ exports.bytesToHex = bytesToHex;
|
|
|
91
80
|
*
|
|
92
81
|
* @param bytes - The bytes to convert to a `bigint`.
|
|
93
82
|
* @returns The `bigint`.
|
|
94
|
-
*/
|
|
95
|
-
function bytesToBigInt(bytes) {
|
|
83
|
+
*/ export function bytesToBigInt(bytes) {
|
|
96
84
|
assertIsBytes(bytes);
|
|
97
85
|
const hexadecimal = bytesToHex(bytes);
|
|
98
86
|
return BigInt(hexadecimal);
|
|
99
87
|
}
|
|
100
|
-
exports.bytesToBigInt = bytesToBigInt;
|
|
101
88
|
/**
|
|
102
89
|
* Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are
|
|
103
90
|
* encoded in two's complement.
|
|
@@ -108,17 +95,15 @@ exports.bytesToBigInt = bytesToBigInt;
|
|
|
108
95
|
* @see https://en.wikipedia.org/wiki/Two%27s_complement
|
|
109
96
|
* @param bytes - The bytes to convert to a signed `bigint`.
|
|
110
97
|
* @returns The signed `bigint`.
|
|
111
|
-
*/
|
|
112
|
-
function bytesToSignedBigInt(bytes) {
|
|
98
|
+
*/ export function bytesToSignedBigInt(bytes) {
|
|
113
99
|
assertIsBytes(bytes);
|
|
114
100
|
let value = BigInt(0);
|
|
115
|
-
for (const byte of bytes)
|
|
101
|
+
for (const byte of bytes){
|
|
116
102
|
// eslint-disable-next-line no-bitwise
|
|
117
103
|
value = (value << BigInt(8)) + BigInt(byte);
|
|
118
104
|
}
|
|
119
105
|
return BigInt.asIntN(bytes.length * 8, value);
|
|
120
106
|
}
|
|
121
|
-
exports.bytesToSignedBigInt = bytesToSignedBigInt;
|
|
122
107
|
/**
|
|
123
108
|
* Convert a `Uint8Array` to a `number`.
|
|
124
109
|
*
|
|
@@ -127,25 +112,21 @@ exports.bytesToSignedBigInt = bytesToSignedBigInt;
|
|
|
127
112
|
* @param bytes - The bytes to convert to a number.
|
|
128
113
|
* @returns The number.
|
|
129
114
|
* @throws If the resulting number is not a safe integer.
|
|
130
|
-
*/
|
|
131
|
-
function bytesToNumber(bytes) {
|
|
115
|
+
*/ export function bytesToNumber(bytes) {
|
|
132
116
|
assertIsBytes(bytes);
|
|
133
117
|
const bigint = bytesToBigInt(bytes);
|
|
134
|
-
|
|
118
|
+
assert(bigint <= BigInt(Number.MAX_SAFE_INTEGER), 'Number is not a safe integer. Use `bytesToBigInt` instead.');
|
|
135
119
|
return Number(bigint);
|
|
136
120
|
}
|
|
137
|
-
exports.bytesToNumber = bytesToNumber;
|
|
138
121
|
/**
|
|
139
122
|
* Convert a UTF-8 encoded `Uint8Array` to a `string`.
|
|
140
123
|
*
|
|
141
124
|
* @param bytes - The bytes to convert to a string.
|
|
142
125
|
* @returns The string.
|
|
143
|
-
*/
|
|
144
|
-
function bytesToString(bytes) {
|
|
126
|
+
*/ export function bytesToString(bytes) {
|
|
145
127
|
assertIsBytes(bytes);
|
|
146
128
|
return new TextDecoder().decode(bytes);
|
|
147
129
|
}
|
|
148
|
-
exports.bytesToString = bytesToString;
|
|
149
130
|
/**
|
|
150
131
|
* Convert a hexadecimal string to a `Uint8Array`. The string can optionally be
|
|
151
132
|
* prefixed with `0x`. It accepts even and odd length strings.
|
|
@@ -154,37 +135,29 @@ exports.bytesToString = bytesToString;
|
|
|
154
135
|
*
|
|
155
136
|
* @param value - The hexadecimal string to convert to bytes.
|
|
156
137
|
* @returns The bytes as `Uint8Array`.
|
|
157
|
-
*/
|
|
158
|
-
function hexToBytes(value) {
|
|
138
|
+
*/ export function hexToBytes(value) {
|
|
159
139
|
// "0x" is often used as empty byte array.
|
|
160
140
|
if (value?.toLowerCase?.() === '0x') {
|
|
161
141
|
return new Uint8Array();
|
|
162
142
|
}
|
|
163
|
-
|
|
143
|
+
assertIsHexString(value);
|
|
164
144
|
// Remove the `0x` prefix if it exists, and pad the string to have an even
|
|
165
145
|
// number of characters.
|
|
166
|
-
const strippedValue =
|
|
146
|
+
const strippedValue = remove0x(value).toLowerCase();
|
|
167
147
|
const normalizedValue = strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;
|
|
168
148
|
const bytes = new Uint8Array(normalizedValue.length / 2);
|
|
169
|
-
for
|
|
149
|
+
for(let i = 0; i < bytes.length; i++){
|
|
170
150
|
// While this is not the prettiest way to convert a hexadecimal string to a
|
|
171
151
|
// `Uint8Array`, it is a lot faster than using `parseInt` to convert each
|
|
172
152
|
// character.
|
|
173
153
|
const c1 = normalizedValue.charCodeAt(i * 2);
|
|
174
154
|
const c2 = normalizedValue.charCodeAt(i * 2 + 1);
|
|
175
|
-
const n1 = c1 -
|
|
176
|
-
|
|
177
|
-
? HEX_MINIMUM_NUMBER_CHARACTER
|
|
178
|
-
: HEX_CHARACTER_OFFSET);
|
|
179
|
-
const n2 = c2 -
|
|
180
|
-
(c2 < HEX_MAXIMUM_NUMBER_CHARACTER
|
|
181
|
-
? HEX_MINIMUM_NUMBER_CHARACTER
|
|
182
|
-
: HEX_CHARACTER_OFFSET);
|
|
155
|
+
const n1 = c1 - (c1 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET);
|
|
156
|
+
const n2 = c2 - (c2 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET);
|
|
183
157
|
bytes[i] = n1 * 16 + n2;
|
|
184
158
|
}
|
|
185
159
|
return bytes;
|
|
186
160
|
}
|
|
187
|
-
exports.hexToBytes = hexToBytes;
|
|
188
161
|
/**
|
|
189
162
|
* Convert a `bigint` to a `Uint8Array`.
|
|
190
163
|
*
|
|
@@ -193,28 +166,23 @@ exports.hexToBytes = hexToBytes;
|
|
|
193
166
|
*
|
|
194
167
|
* @param value - The bigint to convert to bytes.
|
|
195
168
|
* @returns The bytes as `Uint8Array`.
|
|
196
|
-
*/
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
(0, assert_1.assert)(value >= BigInt(0), 'Value must be a non-negative bigint.');
|
|
169
|
+
*/ export function bigIntToBytes(value) {
|
|
170
|
+
assert(typeof value === 'bigint', 'Value must be a bigint.');
|
|
171
|
+
assert(value >= BigInt(0), 'Value must be a non-negative bigint.');
|
|
200
172
|
const hexadecimal = value.toString(16);
|
|
201
173
|
return hexToBytes(hexadecimal);
|
|
202
174
|
}
|
|
203
|
-
exports.bigIntToBytes = bigIntToBytes;
|
|
204
175
|
/**
|
|
205
176
|
* Check if a `bigint` fits in a certain number of bytes.
|
|
206
177
|
*
|
|
207
178
|
* @param value - The `bigint` to check.
|
|
208
179
|
* @param bytes - The number of bytes.
|
|
209
180
|
* @returns Whether the `bigint` fits in the number of bytes.
|
|
210
|
-
*/
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0));
|
|
216
|
-
/* eslint-enable no-bitwise */
|
|
217
|
-
}
|
|
181
|
+
*/ function bigIntFits(value, bytes) {
|
|
182
|
+
assert(bytes > 0);
|
|
183
|
+
/* eslint-disable no-bitwise */ const mask = value >> BigInt(31);
|
|
184
|
+
return !((~value & mask) + (value & ~mask) >> BigInt(bytes * 8 + ~0));
|
|
185
|
+
/* eslint-enable no-bitwise */ }
|
|
218
186
|
/**
|
|
219
187
|
* Convert a signed `bigint` to a `Uint8Array`. This uses two's complement
|
|
220
188
|
* encoding to represent negative numbers.
|
|
@@ -228,50 +196,44 @@ function bigIntFits(value, bytes) {
|
|
|
228
196
|
* is larger than the maximum value that can be represented by the given length,
|
|
229
197
|
* an error is thrown.
|
|
230
198
|
* @returns The bytes as `Uint8Array`.
|
|
231
|
-
*/
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
(
|
|
236
|
-
(0, assert_1.assert)(bigIntFits(value, byteLength), 'Byte length is too small to represent the given value.');
|
|
199
|
+
*/ export function signedBigIntToBytes(value, byteLength) {
|
|
200
|
+
assert(typeof value === 'bigint', 'Value must be a bigint.');
|
|
201
|
+
assert(typeof byteLength === 'number', 'Byte length must be a number.');
|
|
202
|
+
assert(byteLength > 0, 'Byte length must be greater than 0.');
|
|
203
|
+
assert(bigIntFits(value, byteLength), 'Byte length is too small to represent the given value.');
|
|
237
204
|
// ESLint doesn't like mutating function parameters, so to avoid having to
|
|
238
205
|
// disable the rule, we create a new variable.
|
|
239
206
|
let numberValue = value;
|
|
240
207
|
const bytes = new Uint8Array(byteLength);
|
|
241
|
-
for
|
|
208
|
+
for(let i = 0; i < bytes.length; i++){
|
|
242
209
|
bytes[i] = Number(BigInt.asUintN(8, numberValue));
|
|
243
210
|
// eslint-disable-next-line no-bitwise
|
|
244
211
|
numberValue >>= BigInt(8);
|
|
245
212
|
}
|
|
246
213
|
return bytes.reverse();
|
|
247
214
|
}
|
|
248
|
-
exports.signedBigIntToBytes = signedBigIntToBytes;
|
|
249
215
|
/**
|
|
250
216
|
* Convert a `number` to a `Uint8Array`.
|
|
251
217
|
*
|
|
252
218
|
* @param value - The number to convert to bytes.
|
|
253
219
|
* @returns The bytes as `Uint8Array`.
|
|
254
220
|
* @throws If the number is not a safe integer.
|
|
255
|
-
*/
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
(
|
|
259
|
-
(0, assert_1.assert)(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToBytes` instead.');
|
|
221
|
+
*/ export function numberToBytes(value) {
|
|
222
|
+
assert(typeof value === 'number', 'Value must be a number.');
|
|
223
|
+
assert(value >= 0, 'Value must be a non-negative number.');
|
|
224
|
+
assert(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToBytes` instead.');
|
|
260
225
|
const hexadecimal = value.toString(16);
|
|
261
226
|
return hexToBytes(hexadecimal);
|
|
262
227
|
}
|
|
263
|
-
exports.numberToBytes = numberToBytes;
|
|
264
228
|
/**
|
|
265
229
|
* Convert a `string` to a UTF-8 encoded `Uint8Array`.
|
|
266
230
|
*
|
|
267
231
|
* @param value - The string to convert to bytes.
|
|
268
232
|
* @returns The bytes as `Uint8Array`.
|
|
269
|
-
*/
|
|
270
|
-
|
|
271
|
-
(0, assert_1.assert)(typeof value === 'string', 'Value must be a string.');
|
|
233
|
+
*/ export function stringToBytes(value) {
|
|
234
|
+
assert(typeof value === 'string', 'Value must be a string.');
|
|
272
235
|
return new TextEncoder().encode(value);
|
|
273
236
|
}
|
|
274
|
-
exports.stringToBytes = stringToBytes;
|
|
275
237
|
/**
|
|
276
238
|
* Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,
|
|
277
239
|
* a `bigint`, a `number`, or a `string`.
|
|
@@ -292,8 +254,7 @@ exports.stringToBytes = stringToBytes;
|
|
|
292
254
|
*
|
|
293
255
|
* @param value - The value to convert to bytes.
|
|
294
256
|
* @returns The bytes as `Uint8Array`.
|
|
295
|
-
*/
|
|
296
|
-
function valueToBytes(value) {
|
|
257
|
+
*/ export function valueToBytes(value) {
|
|
297
258
|
if (typeof value === 'bigint') {
|
|
298
259
|
return bigIntToBytes(value);
|
|
299
260
|
}
|
|
@@ -311,7 +272,6 @@ function valueToBytes(value) {
|
|
|
311
272
|
}
|
|
312
273
|
throw new TypeError(`Unsupported value type: "${typeof value}".`);
|
|
313
274
|
}
|
|
314
|
-
exports.valueToBytes = valueToBytes;
|
|
315
275
|
/**
|
|
316
276
|
* Concatenate multiple byte-like values into a single `Uint8Array`. The values
|
|
317
277
|
* can be `Uint8Array`, `bigint`, `number`, or `string`. This uses
|
|
@@ -320,18 +280,17 @@ exports.valueToBytes = valueToBytes;
|
|
|
320
280
|
*
|
|
321
281
|
* @param values - The values to concatenate.
|
|
322
282
|
* @returns The concatenated bytes as `Uint8Array`.
|
|
323
|
-
*/
|
|
324
|
-
function concatBytes(values) {
|
|
283
|
+
*/ export function concatBytes(values) {
|
|
325
284
|
const normalizedValues = new Array(values.length);
|
|
326
285
|
let byteLength = 0;
|
|
327
|
-
for
|
|
286
|
+
for(let i = 0; i < values.length; i++){
|
|
328
287
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
329
288
|
const value = valueToBytes(values[i]);
|
|
330
289
|
normalizedValues[i] = value;
|
|
331
290
|
byteLength += value.length;
|
|
332
291
|
}
|
|
333
292
|
const bytes = new Uint8Array(byteLength);
|
|
334
|
-
for
|
|
293
|
+
for(let i = 0, offset = 0; i < normalizedValues.length; i++){
|
|
335
294
|
// While we could simply spread the values into an array and use
|
|
336
295
|
// `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.
|
|
337
296
|
bytes.set(normalizedValues[i], offset);
|
|
@@ -339,7 +298,6 @@ function concatBytes(values) {
|
|
|
339
298
|
}
|
|
340
299
|
return bytes;
|
|
341
300
|
}
|
|
342
|
-
exports.concatBytes = concatBytes;
|
|
343
301
|
/**
|
|
344
302
|
* Create a {@link DataView} from a {@link Uint8Array}. This is a convenience
|
|
345
303
|
* function that avoids having to create a {@link DataView} manually, which
|
|
@@ -361,8 +319,7 @@ exports.concatBytes = concatBytes;
|
|
|
361
319
|
* ```
|
|
362
320
|
* @param bytes - The bytes to create the {@link DataView} from.
|
|
363
321
|
* @returns The {@link DataView}.
|
|
364
|
-
*/
|
|
365
|
-
function createDataView(bytes) {
|
|
322
|
+
*/ export function createDataView(bytes) {
|
|
366
323
|
// To maintain compatibility with Node.js, we need to check if the bytes are
|
|
367
324
|
// a Buffer. If so, we need to slice the buffer to get the underlying
|
|
368
325
|
// ArrayBuffer.
|
|
@@ -373,5 +330,5 @@ function createDataView(bytes) {
|
|
|
373
330
|
}
|
|
374
331
|
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
375
332
|
}
|
|
376
|
-
|
|
333
|
+
|
|
377
334
|
//# sourceMappingURL=bytes.js.map
|