@metamask/utils 8.1.0 → 8.2.1

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.
Files changed (272) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/assert.js +16 -0
  3. package/dist/assert.js.map +1 -0
  4. package/dist/assert.mjs +16 -0
  5. package/dist/assert.mjs.map +1 -0
  6. package/dist/base64.js +11 -0
  7. package/dist/base64.js.map +1 -0
  8. package/dist/base64.mjs +11 -0
  9. package/dist/base64.mjs.map +1 -0
  10. package/dist/bytes.js +43 -0
  11. package/dist/bytes.js.map +1 -0
  12. package/dist/bytes.mjs +43 -0
  13. package/dist/bytes.mjs.map +1 -0
  14. package/dist/caip-types.js +40 -0
  15. package/dist/caip-types.js.map +1 -0
  16. package/dist/caip-types.mjs +40 -0
  17. package/dist/caip-types.mjs.map +1 -0
  18. package/dist/checksum.js +12 -0
  19. package/dist/checksum.js.map +1 -0
  20. package/dist/checksum.mjs +12 -0
  21. package/dist/checksum.mjs.map +1 -0
  22. package/dist/chunk-2LBGT4GH.js +15 -0
  23. package/dist/chunk-2LBGT4GH.js.map +1 -0
  24. package/dist/chunk-2TBCL6EF.js +1 -0
  25. package/dist/chunk-2TBCL6EF.js.map +1 -0
  26. package/dist/chunk-3W5G4CYI.js +25 -0
  27. package/dist/chunk-3W5G4CYI.js.map +1 -0
  28. package/dist/chunk-4D6XQBHA.js +69 -0
  29. package/dist/chunk-4D6XQBHA.js.map +1 -0
  30. package/dist/chunk-4RMX5YWE.js +34 -0
  31. package/dist/chunk-4RMX5YWE.js.map +1 -0
  32. package/dist/chunk-52OU772R.mjs +122 -0
  33. package/dist/chunk-52OU772R.mjs.map +1 -0
  34. package/dist/chunk-6C35XQOF.mjs +257 -0
  35. package/dist/chunk-6C35XQOF.mjs.map +1 -0
  36. package/dist/chunk-6NZW4WK4.js +35 -0
  37. package/dist/chunk-6NZW4WK4.js.map +1 -0
  38. package/dist/chunk-6ZDHSOUV.js +59 -0
  39. package/dist/chunk-6ZDHSOUV.js.map +1 -0
  40. package/dist/chunk-74DGVJVE.mjs +59 -0
  41. package/dist/chunk-74DGVJVE.mjs.map +1 -0
  42. package/dist/chunk-AY6FDCBT.mjs +1 -0
  43. package/dist/chunk-AY6FDCBT.mjs.map +1 -0
  44. package/dist/chunk-BFQDMI3M.js +122 -0
  45. package/dist/chunk-BFQDMI3M.js.map +1 -0
  46. package/dist/chunk-DHVKFDHQ.js +95 -0
  47. package/dist/chunk-DHVKFDHQ.js.map +1 -0
  48. package/dist/chunk-DYMCEQIV.mjs +1 -0
  49. package/dist/chunk-DYMCEQIV.mjs.map +1 -0
  50. package/dist/chunk-E4C7EW4R.js +16 -0
  51. package/dist/chunk-E4C7EW4R.js.map +1 -0
  52. package/dist/chunk-EQMZL4XU.js +1 -0
  53. package/dist/chunk-EQMZL4XU.js.map +1 -0
  54. package/dist/chunk-GZS3IQBZ.mjs +16 -0
  55. package/dist/chunk-GZS3IQBZ.mjs.map +1 -0
  56. package/dist/chunk-H4YFDLB7.mjs +70 -0
  57. package/dist/chunk-H4YFDLB7.mjs.map +1 -0
  58. package/dist/chunk-I575FZFH.mjs +1 -0
  59. package/dist/chunk-I575FZFH.mjs.map +1 -0
  60. package/dist/chunk-IZC266HS.js +55 -0
  61. package/dist/chunk-IZC266HS.js.map +1 -0
  62. package/dist/chunk-JPAL7Q5S.mjs +90 -0
  63. package/dist/chunk-JPAL7Q5S.mjs.map +1 -0
  64. package/dist/chunk-LC2CRSWD.js +1 -0
  65. package/dist/chunk-LC2CRSWD.js.map +1 -0
  66. package/dist/chunk-NQMRFZHB.mjs +35 -0
  67. package/dist/chunk-NQMRFZHB.mjs.map +1 -0
  68. package/dist/chunk-O3EIM33O.mjs +95 -0
  69. package/dist/chunk-O3EIM33O.mjs.map +1 -0
  70. package/dist/chunk-OLLG4H35.js +257 -0
  71. package/dist/chunk-OLLG4H35.js.map +1 -0
  72. package/dist/chunk-QEPVHEP7.js +273 -0
  73. package/dist/chunk-QEPVHEP7.js.map +1 -0
  74. package/dist/chunk-QVEKZRZ2.js +70 -0
  75. package/dist/chunk-QVEKZRZ2.js.map +1 -0
  76. package/dist/chunk-RIRDOQPX.mjs +15 -0
  77. package/dist/chunk-RIRDOQPX.mjs.map +1 -0
  78. package/dist/chunk-RKRGAFXY.js +1 -0
  79. package/dist/chunk-RKRGAFXY.js.map +1 -0
  80. package/dist/chunk-ROQSKDP5.mjs +69 -0
  81. package/dist/chunk-ROQSKDP5.mjs.map +1 -0
  82. package/dist/chunk-RRYOWRCV.mjs +1 -0
  83. package/dist/chunk-RRYOWRCV.mjs.map +1 -0
  84. package/dist/chunk-S3UHBN2Z.mjs +44 -0
  85. package/dist/chunk-S3UHBN2Z.mjs.map +1 -0
  86. package/dist/chunk-TGOMTREC.mjs +75 -0
  87. package/dist/chunk-TGOMTREC.mjs.map +1 -0
  88. package/dist/chunk-THNLGEXV.mjs +34 -0
  89. package/dist/chunk-THNLGEXV.mjs.map +1 -0
  90. package/dist/chunk-U7ZUGCE7.js +75 -0
  91. package/dist/chunk-U7ZUGCE7.js.map +1 -0
  92. package/dist/chunk-UOTVU7OQ.js +1 -0
  93. package/dist/chunk-UOTVU7OQ.js.map +1 -0
  94. package/dist/chunk-VA2DRBDE.mjs +273 -0
  95. package/dist/chunk-VA2DRBDE.mjs.map +1 -0
  96. package/dist/chunk-VFXTVNXN.js +44 -0
  97. package/dist/chunk-VFXTVNXN.js.map +1 -0
  98. package/dist/chunk-WA4DHIND.mjs +1 -0
  99. package/dist/chunk-WA4DHIND.mjs.map +1 -0
  100. package/dist/chunk-X66SUIEF.mjs +25 -0
  101. package/dist/chunk-X66SUIEF.mjs.map +1 -0
  102. package/dist/chunk-XYGUOY6N.mjs +55 -0
  103. package/dist/chunk-XYGUOY6N.mjs.map +1 -0
  104. package/dist/chunk-Z2RGWDD7.js +90 -0
  105. package/dist/chunk-Z2RGWDD7.js.map +1 -0
  106. package/dist/coercers.js +18 -0
  107. package/dist/coercers.js.map +1 -0
  108. package/dist/coercers.mjs +18 -0
  109. package/dist/coercers.mjs.map +1 -0
  110. package/dist/collections.js +10 -0
  111. package/dist/collections.js.map +1 -0
  112. package/dist/collections.mjs +10 -0
  113. package/dist/collections.mjs.map +1 -0
  114. package/dist/encryption-types.js +2 -0
  115. package/dist/encryption-types.js.map +1 -0
  116. package/dist/encryption-types.mjs +2 -0
  117. package/dist/encryption-types.mjs.map +1 -0
  118. package/dist/errors.js +17 -0
  119. package/dist/errors.js.map +1 -0
  120. package/dist/errors.mjs +17 -0
  121. package/dist/errors.mjs.map +1 -0
  122. package/dist/fs.js +26 -0
  123. package/dist/fs.js.map +1 -0
  124. package/dist/fs.mjs +26 -0
  125. package/dist/fs.mjs.map +1 -0
  126. package/dist/hex.js +35 -0
  127. package/dist/hex.js.map +1 -0
  128. package/dist/hex.mjs +35 -0
  129. package/dist/hex.mjs.map +1 -0
  130. package/dist/index.js +289 -0
  131. package/dist/index.js.map +1 -0
  132. package/dist/index.mjs +289 -0
  133. package/dist/index.mjs.map +1 -0
  134. package/dist/json.js +75 -0
  135. package/dist/json.js.map +1 -0
  136. package/dist/json.mjs +75 -0
  137. package/dist/json.mjs.map +1 -0
  138. package/dist/keyring.js +2 -0
  139. package/dist/keyring.js.map +1 -0
  140. package/dist/keyring.mjs +2 -0
  141. package/dist/keyring.mjs.map +1 -0
  142. package/dist/logging.js +10 -0
  143. package/dist/logging.js.map +1 -0
  144. package/dist/logging.mjs +10 -0
  145. package/dist/logging.mjs.map +1 -0
  146. package/dist/misc.js +28 -0
  147. package/dist/misc.js.map +1 -0
  148. package/dist/misc.mjs +28 -0
  149. package/dist/misc.mjs.map +1 -0
  150. package/dist/node.js +309 -0
  151. package/dist/node.js.map +1 -0
  152. package/dist/node.mjs +309 -0
  153. package/dist/node.mjs.map +1 -0
  154. package/dist/number.js +18 -0
  155. package/dist/number.js.map +1 -0
  156. package/dist/number.mjs +18 -0
  157. package/dist/number.mjs.map +1 -0
  158. package/dist/opaque.js +2 -0
  159. package/dist/opaque.js.map +1 -0
  160. package/dist/opaque.mjs +2 -0
  161. package/dist/opaque.mjs.map +1 -0
  162. package/dist/time.js +12 -0
  163. package/dist/time.js.map +1 -0
  164. package/dist/time.mjs +12 -0
  165. package/dist/time.mjs.map +1 -0
  166. package/dist/transaction-types.js +2 -0
  167. package/dist/transaction-types.js.map +1 -0
  168. package/dist/transaction-types.mjs +2 -0
  169. package/dist/transaction-types.mjs.map +1 -0
  170. package/dist/types/assert.d.ts.map +1 -1
  171. package/dist/types/bytes.d.ts +14 -0
  172. package/dist/types/bytes.d.ts.map +1 -1
  173. package/dist/types/errors.d.ts +58 -0
  174. package/dist/types/errors.d.ts.map +1 -0
  175. package/dist/types/fs.d.ts +133 -0
  176. package/dist/types/fs.d.ts.map +1 -0
  177. package/dist/types/index.d.ts +1 -0
  178. package/dist/types/index.d.ts.map +1 -1
  179. package/dist/types/json.d.ts +83 -44
  180. package/dist/types/json.d.ts.map +1 -1
  181. package/dist/types/node.d.ts +3 -0
  182. package/dist/types/node.d.ts.map +1 -0
  183. package/dist/versions.js +27 -0
  184. package/dist/versions.js.map +1 -0
  185. package/dist/versions.mjs +27 -0
  186. package/dist/versions.mjs.map +1 -0
  187. package/package.json +22 -21
  188. package/dist/cjs/assert.js +0 -116
  189. package/dist/cjs/assert.js.map +0 -1
  190. package/dist/cjs/base64.js +0 -32
  191. package/dist/cjs/base64.js.map +0 -1
  192. package/dist/cjs/bytes.js +0 -255
  193. package/dist/cjs/bytes.js.map +0 -1
  194. package/dist/cjs/caip-types.js +0 -115
  195. package/dist/cjs/caip-types.js.map +0 -1
  196. package/dist/cjs/checksum.js +0 -17
  197. package/dist/cjs/checksum.js.map +0 -1
  198. package/dist/cjs/coercers.js +0 -96
  199. package/dist/cjs/coercers.js.map +0 -1
  200. package/dist/cjs/collections.js +0 -157
  201. package/dist/cjs/collections.js.map +0 -1
  202. package/dist/cjs/encryption-types.js +0 -6
  203. package/dist/cjs/encryption-types.js.map +0 -1
  204. package/dist/cjs/hex.js +0 -107
  205. package/dist/cjs/hex.js.map +0 -1
  206. package/dist/cjs/index.js +0 -37
  207. package/dist/cjs/index.js.map +0 -1
  208. package/dist/cjs/json.js +0 -265
  209. package/dist/cjs/json.js.map +0 -1
  210. package/dist/cjs/keyring.js +0 -6
  211. package/dist/cjs/keyring.js.map +0 -1
  212. package/dist/cjs/logging.js +0 -33
  213. package/dist/cjs/logging.js.map +0 -1
  214. package/dist/cjs/misc.js +0 -111
  215. package/dist/cjs/misc.js.map +0 -1
  216. package/dist/cjs/number.js +0 -52
  217. package/dist/cjs/number.js.map +0 -1
  218. package/dist/cjs/opaque.js +0 -8
  219. package/dist/cjs/opaque.js.map +0 -1
  220. package/dist/cjs/time.js +0 -63
  221. package/dist/cjs/time.js.map +0 -1
  222. package/dist/cjs/transaction-types.js +0 -6
  223. package/dist/cjs/transaction-types.js.map +0 -1
  224. package/dist/cjs/versions.js +0 -79
  225. package/dist/cjs/versions.js.map +0 -1
  226. package/dist/esm/assert.js +0 -133
  227. package/dist/esm/assert.js.map +0 -1
  228. package/dist/esm/base64.js +0 -28
  229. package/dist/esm/base64.js.map +0 -1
  230. package/dist/esm/bytes.js +0 -334
  231. package/dist/esm/bytes.js.map +0 -1
  232. package/dist/esm/caip-types.js +0 -99
  233. package/dist/esm/caip-types.js.map +0 -1
  234. package/dist/esm/checksum.js +0 -7
  235. package/dist/esm/checksum.js.map +0 -1
  236. package/dist/esm/coercers.js +0 -153
  237. package/dist/esm/coercers.js.map +0 -1
  238. package/dist/esm/collections.js +0 -140
  239. package/dist/esm/collections.js.map +0 -1
  240. package/dist/esm/encryption-types.js +0 -3
  241. package/dist/esm/encryption-types.js.map +0 -1
  242. package/dist/esm/hex.js +0 -108
  243. package/dist/esm/hex.js.map +0 -1
  244. package/dist/esm/index.js +0 -20
  245. package/dist/esm/index.js.map +0 -1
  246. package/dist/esm/json.js +0 -303
  247. package/dist/esm/json.js.map +0 -1
  248. package/dist/esm/keyring.js +0 -3
  249. package/dist/esm/keyring.js.map +0 -1
  250. package/dist/esm/logging.js +0 -34
  251. package/dist/esm/logging.js.map +0 -1
  252. package/dist/esm/misc.js +0 -129
  253. package/dist/esm/misc.js.map +0 -1
  254. package/dist/esm/number.js +0 -92
  255. package/dist/esm/number.js.map +0 -1
  256. package/dist/esm/opaque.js +0 -5
  257. package/dist/esm/opaque.js.map +0 -1
  258. package/dist/esm/package.json +0 -1
  259. package/dist/esm/time.js +0 -53
  260. package/dist/esm/time.js.map +0 -1
  261. package/dist/esm/transaction-types.js +0 -3
  262. package/dist/esm/transaction-types.js.map +0 -1
  263. package/dist/esm/versions.js +0 -78
  264. package/dist/esm/versions.js.map +0 -1
  265. package/dist/types/caip-types.test-d.d.ts +0 -2
  266. package/dist/types/caip-types.test-d.d.ts.map +0 -1
  267. package/dist/types/hex.test-d.d.ts +0 -2
  268. package/dist/types/hex.test-d.d.ts.map +0 -1
  269. package/dist/types/json.test-d.d.ts +0 -2
  270. package/dist/types/json.test-d.d.ts.map +0 -1
  271. package/dist/types/misc.test-d.d.ts +0 -2
  272. package/dist/types/misc.test-d.d.ts.map +0 -1
@@ -0,0 +1,257 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunk6ZDHSOUVjs = require('./chunk-6ZDHSOUV.js');
4
+
5
+
6
+ var _chunkQVEKZRZ2js = require('./chunk-QVEKZRZ2.js');
7
+
8
+ // src/json.ts
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+ var _superstruct = require('superstruct');
30
+ var object = (schema) => (
31
+ // The type is slightly different from a regular object struct, because we
32
+ // want to make properties with `undefined` in their type optional, but not
33
+ // `undefined` itself. This means that we need a type cast.
34
+ _superstruct.object.call(void 0, schema)
35
+ );
36
+ function hasOptional({ path, branch }) {
37
+ const field = path[path.length - 1];
38
+ return _chunkQVEKZRZ2js.hasProperty.call(void 0, branch[branch.length - 2], field);
39
+ }
40
+ function exactOptional(struct) {
41
+ return new (0, _superstruct.Struct)({
42
+ ...struct,
43
+ type: `optional ${struct.type}`,
44
+ validator: (value, context) => !hasOptional(context) || struct.validator(value, context),
45
+ refiner: (value, context) => !hasOptional(context) || struct.refiner(value, context)
46
+ });
47
+ }
48
+ var finiteNumber = () => _superstruct.define.call(void 0, "finite number", (value) => {
49
+ return _superstruct.is.call(void 0, value, _superstruct.number.call(void 0, )) && Number.isFinite(value);
50
+ });
51
+ var UnsafeJsonStruct = _superstruct.union.call(void 0, [
52
+ _superstruct.literal.call(void 0, null),
53
+ _superstruct.boolean.call(void 0, ),
54
+ finiteNumber(),
55
+ _superstruct.string.call(void 0, ),
56
+ _superstruct.array.call(void 0, _superstruct.lazy.call(void 0, () => UnsafeJsonStruct)),
57
+ _superstruct.record.call(void 0,
58
+ _superstruct.string.call(void 0, ),
59
+ _superstruct.lazy.call(void 0, () => UnsafeJsonStruct)
60
+ )
61
+ ]);
62
+ var JsonStruct = _superstruct.coerce.call(void 0, UnsafeJsonStruct, _superstruct.any.call(void 0, ), (value) => {
63
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0, value, UnsafeJsonStruct);
64
+ return JSON.parse(
65
+ JSON.stringify(value, (propKey, propValue) => {
66
+ if (propKey === "__proto__" || propKey === "constructor") {
67
+ return void 0;
68
+ }
69
+ return propValue;
70
+ })
71
+ );
72
+ });
73
+ function isValidJson(value) {
74
+ try {
75
+ getSafeJson(value);
76
+ return true;
77
+ } catch (e) {
78
+ return false;
79
+ }
80
+ }
81
+ function getSafeJson(value) {
82
+ return _superstruct.create.call(void 0, value, JsonStruct);
83
+ }
84
+ function getJsonSize(value) {
85
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0, value, JsonStruct, "Invalid JSON value");
86
+ const json = JSON.stringify(value);
87
+ return new TextEncoder().encode(json).byteLength;
88
+ }
89
+ var jsonrpc2 = "2.0";
90
+ var JsonRpcVersionStruct = _superstruct.literal.call(void 0, jsonrpc2);
91
+ var JsonRpcIdStruct = _superstruct.nullable.call(void 0, _superstruct.union.call(void 0, [_superstruct.number.call(void 0, ), _superstruct.string.call(void 0, )]));
92
+ var JsonRpcErrorStruct = object({
93
+ code: _superstruct.integer.call(void 0, ),
94
+ message: _superstruct.string.call(void 0, ),
95
+ data: exactOptional(JsonStruct),
96
+ stack: exactOptional(_superstruct.string.call(void 0, ))
97
+ });
98
+ var JsonRpcParamsStruct = _superstruct.union.call(void 0, [_superstruct.record.call(void 0, _superstruct.string.call(void 0, ), JsonStruct), _superstruct.array.call(void 0, JsonStruct)]);
99
+ var JsonRpcRequestStruct = object({
100
+ id: JsonRpcIdStruct,
101
+ jsonrpc: JsonRpcVersionStruct,
102
+ method: _superstruct.string.call(void 0, ),
103
+ params: exactOptional(JsonRpcParamsStruct)
104
+ });
105
+ var JsonRpcNotificationStruct = object({
106
+ jsonrpc: JsonRpcVersionStruct,
107
+ method: _superstruct.string.call(void 0, ),
108
+ params: exactOptional(JsonRpcParamsStruct)
109
+ });
110
+ function isJsonRpcNotification(value) {
111
+ return _superstruct.is.call(void 0, value, JsonRpcNotificationStruct);
112
+ }
113
+ function assertIsJsonRpcNotification(value, ErrorWrapper) {
114
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0,
115
+ value,
116
+ JsonRpcNotificationStruct,
117
+ "Invalid JSON-RPC notification",
118
+ ErrorWrapper
119
+ );
120
+ }
121
+ function isJsonRpcRequest(value) {
122
+ return _superstruct.is.call(void 0, value, JsonRpcRequestStruct);
123
+ }
124
+ function assertIsJsonRpcRequest(value, ErrorWrapper) {
125
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0,
126
+ value,
127
+ JsonRpcRequestStruct,
128
+ "Invalid JSON-RPC request",
129
+ ErrorWrapper
130
+ );
131
+ }
132
+ var PendingJsonRpcResponseStruct = _superstruct.object.call(void 0, {
133
+ id: JsonRpcIdStruct,
134
+ jsonrpc: JsonRpcVersionStruct,
135
+ result: _superstruct.optional.call(void 0, _superstruct.unknown.call(void 0, )),
136
+ error: _superstruct.optional.call(void 0, JsonRpcErrorStruct)
137
+ });
138
+ var JsonRpcSuccessStruct = object({
139
+ id: JsonRpcIdStruct,
140
+ jsonrpc: JsonRpcVersionStruct,
141
+ result: JsonStruct
142
+ });
143
+ var JsonRpcFailureStruct = object({
144
+ id: JsonRpcIdStruct,
145
+ jsonrpc: JsonRpcVersionStruct,
146
+ error: JsonRpcErrorStruct
147
+ });
148
+ var JsonRpcResponseStruct = _superstruct.union.call(void 0, [
149
+ JsonRpcSuccessStruct,
150
+ JsonRpcFailureStruct
151
+ ]);
152
+ function isPendingJsonRpcResponse(response) {
153
+ return _superstruct.is.call(void 0, response, PendingJsonRpcResponseStruct);
154
+ }
155
+ function assertIsPendingJsonRpcResponse(response, ErrorWrapper) {
156
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0,
157
+ response,
158
+ PendingJsonRpcResponseStruct,
159
+ "Invalid pending JSON-RPC response",
160
+ ErrorWrapper
161
+ );
162
+ }
163
+ function isJsonRpcResponse(response) {
164
+ return _superstruct.is.call(void 0, response, JsonRpcResponseStruct);
165
+ }
166
+ function assertIsJsonRpcResponse(value, ErrorWrapper) {
167
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0,
168
+ value,
169
+ JsonRpcResponseStruct,
170
+ "Invalid JSON-RPC response",
171
+ ErrorWrapper
172
+ );
173
+ }
174
+ function isJsonRpcSuccess(value) {
175
+ return _superstruct.is.call(void 0, value, JsonRpcSuccessStruct);
176
+ }
177
+ function assertIsJsonRpcSuccess(value, ErrorWrapper) {
178
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0,
179
+ value,
180
+ JsonRpcSuccessStruct,
181
+ "Invalid JSON-RPC success response",
182
+ ErrorWrapper
183
+ );
184
+ }
185
+ function isJsonRpcFailure(value) {
186
+ return _superstruct.is.call(void 0, value, JsonRpcFailureStruct);
187
+ }
188
+ function assertIsJsonRpcFailure(value, ErrorWrapper) {
189
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0,
190
+ value,
191
+ JsonRpcFailureStruct,
192
+ "Invalid JSON-RPC failure response",
193
+ ErrorWrapper
194
+ );
195
+ }
196
+ function isJsonRpcError(value) {
197
+ return _superstruct.is.call(void 0, value, JsonRpcErrorStruct);
198
+ }
199
+ function assertIsJsonRpcError(value, ErrorWrapper) {
200
+ _chunk6ZDHSOUVjs.assertStruct.call(void 0,
201
+ value,
202
+ JsonRpcErrorStruct,
203
+ "Invalid JSON-RPC error",
204
+ ErrorWrapper
205
+ );
206
+ }
207
+ function getJsonRpcIdValidator(options) {
208
+ const { permitEmptyString, permitFractions, permitNull } = {
209
+ permitEmptyString: true,
210
+ permitFractions: false,
211
+ permitNull: true,
212
+ ...options
213
+ };
214
+ const isValidJsonRpcId = (id) => {
215
+ return Boolean(
216
+ typeof id === "number" && (permitFractions || Number.isInteger(id)) || typeof id === "string" && (permitEmptyString || id.length > 0) || permitNull && id === null
217
+ );
218
+ };
219
+ return isValidJsonRpcId;
220
+ }
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+
255
+
256
+ exports.object = object; exports.exactOptional = exactOptional; exports.UnsafeJsonStruct = UnsafeJsonStruct; exports.JsonStruct = JsonStruct; exports.isValidJson = isValidJson; exports.getSafeJson = getSafeJson; exports.getJsonSize = getJsonSize; exports.jsonrpc2 = jsonrpc2; exports.JsonRpcVersionStruct = JsonRpcVersionStruct; exports.JsonRpcIdStruct = JsonRpcIdStruct; exports.JsonRpcErrorStruct = JsonRpcErrorStruct; exports.JsonRpcParamsStruct = JsonRpcParamsStruct; exports.JsonRpcRequestStruct = JsonRpcRequestStruct; exports.JsonRpcNotificationStruct = JsonRpcNotificationStruct; exports.isJsonRpcNotification = isJsonRpcNotification; exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification; exports.isJsonRpcRequest = isJsonRpcRequest; exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest; exports.PendingJsonRpcResponseStruct = PendingJsonRpcResponseStruct; exports.JsonRpcSuccessStruct = JsonRpcSuccessStruct; exports.JsonRpcFailureStruct = JsonRpcFailureStruct; exports.JsonRpcResponseStruct = JsonRpcResponseStruct; exports.isPendingJsonRpcResponse = isPendingJsonRpcResponse; exports.assertIsPendingJsonRpcResponse = assertIsPendingJsonRpcResponse; exports.isJsonRpcResponse = isJsonRpcResponse; exports.assertIsJsonRpcResponse = assertIsJsonRpcResponse; exports.isJsonRpcSuccess = isJsonRpcSuccess; exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess; exports.isJsonRpcFailure = isJsonRpcFailure; exports.assertIsJsonRpcFailure = assertIsJsonRpcFailure; exports.isJsonRpcError = isJsonRpcError; exports.assertIsJsonRpcError = assertIsJsonRpcError; exports.getJsonRpcIdValidator = getJsonRpcIdValidator;
257
+ //# sourceMappingURL=chunk-OLLG4H35.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/json.ts"],"names":[],"mappings":";;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgEA,IAAM,SAAS,CACpB;AAAA;AAAA;AAAA;AAAA,EAKA,kBAAkB,MAAM;AAAA;AAe1B,SAAS,YAAY,EAAE,MAAM,OAAO,GAAqB;AACvD,QAAM,QAAQ,KAAK,KAAK,SAAS,CAAC;AAClC,SAAO,YAAY,OAAO,OAAO,SAAS,CAAC,GAAG,KAAK;AACrD;AA8BO,SAAS,cACd,QAC2C;AAC3C,SAAO,IAAI,OAA0C;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Content":["import type { Context, Infer } from 'superstruct';\nimport {\n any,\n array,\n boolean,\n coerce,\n create,\n define,\n integer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n} from 'superstruct';\nimport type {\n ObjectSchema,\n Optionalize,\n Simplify,\n} from 'superstruct/dist/utils';\n\nimport type { AssertionErrorConstructor } from './assert';\nimport { assertStruct } from './assert';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & infer Original\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value as Type, context),\n });\n}\n\n/**\n * A struct to check if the given value is finite number. Superstruct's\n * `number()` struct does not check if the value is finite.\n *\n * @returns A struct to check if the given value is finite number.\n */\nconst finiteNumber = () =>\n define<number>('finite number', (value) => {\n return is(value, number()) && Number.isFinite(value);\n });\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\n// We cannot infer the type of the struct, because it is recursive.\nexport const UnsafeJsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n finiteNumber(),\n string(),\n array(lazy(() => UnsafeJsonStruct)),\n record(\n string(),\n lazy(() => UnsafeJsonStruct),\n ),\n]);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {\n assertStruct(value, UnsafeJsonStruct);\n return JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n );\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: exactOptional(JsonStruct),\n stack: exactOptional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\n params?: Params;\n};\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = superstructObject({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"]}
@@ -0,0 +1,273 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunk6ZDHSOUVjs = require('./chunk-6ZDHSOUV.js');
4
+
5
+ // src/hex.ts
6
+ var _sha3 = require('@noble/hashes/sha3');
7
+ var _superstruct = require('superstruct');
8
+
9
+ // src/bytes.ts
10
+ var _base = require('@scure/base');
11
+ var HEX_MINIMUM_NUMBER_CHARACTER = 48;
12
+ var HEX_MAXIMUM_NUMBER_CHARACTER = 58;
13
+ var HEX_CHARACTER_OFFSET = 87;
14
+ function getPrecomputedHexValuesBuilder() {
15
+ const lookupTable = [];
16
+ return () => {
17
+ if (lookupTable.length === 0) {
18
+ for (let i = 0; i < 256; i++) {
19
+ lookupTable.push(i.toString(16).padStart(2, "0"));
20
+ }
21
+ }
22
+ return lookupTable;
23
+ };
24
+ }
25
+ var getPrecomputedHexValues = getPrecomputedHexValuesBuilder();
26
+ function isBytes(value) {
27
+ return value instanceof Uint8Array;
28
+ }
29
+ function assertIsBytes(value) {
30
+ _chunk6ZDHSOUVjs.assert.call(void 0, isBytes(value), "Value must be a Uint8Array.");
31
+ }
32
+ function bytesToHex(bytes) {
33
+ assertIsBytes(bytes);
34
+ if (bytes.length === 0) {
35
+ return "0x";
36
+ }
37
+ const lookupTable = getPrecomputedHexValues();
38
+ const hexadecimal = new Array(bytes.length);
39
+ for (let i = 0; i < bytes.length; i++) {
40
+ hexadecimal[i] = lookupTable[bytes[i]];
41
+ }
42
+ return add0x(hexadecimal.join(""));
43
+ }
44
+ function bytesToBigInt(bytes) {
45
+ assertIsBytes(bytes);
46
+ const hexadecimal = bytesToHex(bytes);
47
+ return BigInt(hexadecimal);
48
+ }
49
+ function bytesToSignedBigInt(bytes) {
50
+ assertIsBytes(bytes);
51
+ let value = BigInt(0);
52
+ for (const byte of bytes) {
53
+ value = (value << BigInt(8)) + BigInt(byte);
54
+ }
55
+ return BigInt.asIntN(bytes.length * 8, value);
56
+ }
57
+ function bytesToNumber(bytes) {
58
+ assertIsBytes(bytes);
59
+ const bigint = bytesToBigInt(bytes);
60
+ _chunk6ZDHSOUVjs.assert.call(void 0,
61
+ bigint <= BigInt(Number.MAX_SAFE_INTEGER),
62
+ "Number is not a safe integer. Use `bytesToBigInt` instead."
63
+ );
64
+ return Number(bigint);
65
+ }
66
+ function bytesToString(bytes) {
67
+ assertIsBytes(bytes);
68
+ return new TextDecoder().decode(bytes);
69
+ }
70
+ function bytesToBase64(bytes) {
71
+ assertIsBytes(bytes);
72
+ return _base.base64.encode(bytes);
73
+ }
74
+ function hexToBytes(value) {
75
+ if (_optionalChain([value, 'optionalAccess', _ => _.toLowerCase, 'optionalCall', _2 => _2()]) === "0x") {
76
+ return new Uint8Array();
77
+ }
78
+ assertIsHexString(value);
79
+ const strippedValue = remove0x(value).toLowerCase();
80
+ const normalizedValue = strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;
81
+ const bytes = new Uint8Array(normalizedValue.length / 2);
82
+ for (let i = 0; i < bytes.length; i++) {
83
+ const c1 = normalizedValue.charCodeAt(i * 2);
84
+ const c2 = normalizedValue.charCodeAt(i * 2 + 1);
85
+ const n1 = c1 - (c1 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET);
86
+ const n2 = c2 - (c2 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET);
87
+ bytes[i] = n1 * 16 + n2;
88
+ }
89
+ return bytes;
90
+ }
91
+ function bigIntToBytes(value) {
92
+ _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint.");
93
+ _chunk6ZDHSOUVjs.assert.call(void 0, value >= BigInt(0), "Value must be a non-negative bigint.");
94
+ const hexadecimal = value.toString(16);
95
+ return hexToBytes(hexadecimal);
96
+ }
97
+ function bigIntFits(value, bytes) {
98
+ _chunk6ZDHSOUVjs.assert.call(void 0, bytes > 0);
99
+ const mask = value >> BigInt(31);
100
+ return !((~value & mask) + (value & ~mask) >> BigInt(bytes * 8 + ~0));
101
+ }
102
+ function signedBigIntToBytes(value, byteLength) {
103
+ _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint.");
104
+ _chunk6ZDHSOUVjs.assert.call(void 0, typeof byteLength === "number", "Byte length must be a number.");
105
+ _chunk6ZDHSOUVjs.assert.call(void 0, byteLength > 0, "Byte length must be greater than 0.");
106
+ _chunk6ZDHSOUVjs.assert.call(void 0,
107
+ bigIntFits(value, byteLength),
108
+ "Byte length is too small to represent the given value."
109
+ );
110
+ let numberValue = value;
111
+ const bytes = new Uint8Array(byteLength);
112
+ for (let i = 0; i < bytes.length; i++) {
113
+ bytes[i] = Number(BigInt.asUintN(8, numberValue));
114
+ numberValue >>= BigInt(8);
115
+ }
116
+ return bytes.reverse();
117
+ }
118
+ function numberToBytes(value) {
119
+ _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "number", "Value must be a number.");
120
+ _chunk6ZDHSOUVjs.assert.call(void 0, value >= 0, "Value must be a non-negative number.");
121
+ _chunk6ZDHSOUVjs.assert.call(void 0,
122
+ Number.isSafeInteger(value),
123
+ "Value is not a safe integer. Use `bigIntToBytes` instead."
124
+ );
125
+ const hexadecimal = value.toString(16);
126
+ return hexToBytes(hexadecimal);
127
+ }
128
+ function stringToBytes(value) {
129
+ _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "string", "Value must be a string.");
130
+ return new TextEncoder().encode(value);
131
+ }
132
+ function base64ToBytes(value) {
133
+ _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "string", "Value must be a string.");
134
+ return _base.base64.decode(value);
135
+ }
136
+ function valueToBytes(value) {
137
+ if (typeof value === "bigint") {
138
+ return bigIntToBytes(value);
139
+ }
140
+ if (typeof value === "number") {
141
+ return numberToBytes(value);
142
+ }
143
+ if (typeof value === "string") {
144
+ if (value.startsWith("0x")) {
145
+ return hexToBytes(value);
146
+ }
147
+ return stringToBytes(value);
148
+ }
149
+ if (isBytes(value)) {
150
+ return value;
151
+ }
152
+ throw new TypeError(`Unsupported value type: "${typeof value}".`);
153
+ }
154
+ function concatBytes(values) {
155
+ const normalizedValues = new Array(values.length);
156
+ let byteLength = 0;
157
+ for (let i = 0; i < values.length; i++) {
158
+ const value = valueToBytes(values[i]);
159
+ normalizedValues[i] = value;
160
+ byteLength += value.length;
161
+ }
162
+ const bytes = new Uint8Array(byteLength);
163
+ for (let i = 0, offset = 0; i < normalizedValues.length; i++) {
164
+ bytes.set(normalizedValues[i], offset);
165
+ offset += normalizedValues[i].length;
166
+ }
167
+ return bytes;
168
+ }
169
+ function createDataView(bytes) {
170
+ if (typeof Buffer !== "undefined" && bytes instanceof Buffer) {
171
+ const buffer = bytes.buffer.slice(
172
+ bytes.byteOffset,
173
+ bytes.byteOffset + bytes.byteLength
174
+ );
175
+ return new DataView(buffer);
176
+ }
177
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
178
+ }
179
+
180
+ // src/hex.ts
181
+ var HexStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^(?:0x)?[0-9a-f]+$/iu);
182
+ var StrictHexStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^0x[0-9a-f]+$/iu);
183
+ var HexAddressStruct = _superstruct.pattern.call(void 0,
184
+ _superstruct.string.call(void 0, ),
185
+ /^0x[0-9a-f]{40}$/u
186
+ );
187
+ var HexChecksumAddressStruct = _superstruct.pattern.call(void 0,
188
+ _superstruct.string.call(void 0, ),
189
+ /^0x[0-9a-fA-F]{40}$/u
190
+ );
191
+ function isHexString(value) {
192
+ return _superstruct.is.call(void 0, value, HexStruct);
193
+ }
194
+ function isStrictHexString(value) {
195
+ return _superstruct.is.call(void 0, value, StrictHexStruct);
196
+ }
197
+ function assertIsHexString(value) {
198
+ _chunk6ZDHSOUVjs.assert.call(void 0, isHexString(value), "Value must be a hexadecimal string.");
199
+ }
200
+ function assertIsStrictHexString(value) {
201
+ _chunk6ZDHSOUVjs.assert.call(void 0,
202
+ isStrictHexString(value),
203
+ 'Value must be a hexadecimal string, starting with "0x".'
204
+ );
205
+ }
206
+ function isValidHexAddress(possibleAddress) {
207
+ return _superstruct.is.call(void 0, possibleAddress, HexAddressStruct) || isValidChecksumAddress(possibleAddress);
208
+ }
209
+ function getChecksumAddress(address) {
210
+ _chunk6ZDHSOUVjs.assert.call(void 0, _superstruct.is.call(void 0, address, HexChecksumAddressStruct), "Invalid hex address.");
211
+ const unPrefixed = remove0x(address.toLowerCase());
212
+ const unPrefixedHash = remove0x(bytesToHex(_sha3.keccak_256.call(void 0, unPrefixed)));
213
+ return `0x${unPrefixed.split("").map((character, nibbleIndex) => {
214
+ const hashCharacter = unPrefixedHash[nibbleIndex];
215
+ _chunk6ZDHSOUVjs.assert.call(void 0, _superstruct.is.call(void 0, hashCharacter, _superstruct.string.call(void 0, )), "Hash shorter than address.");
216
+ return parseInt(hashCharacter, 16) > 7 ? character.toUpperCase() : character;
217
+ }).join("")}`;
218
+ }
219
+ function isValidChecksumAddress(possibleChecksum) {
220
+ if (!_superstruct.is.call(void 0, possibleChecksum, HexChecksumAddressStruct)) {
221
+ return false;
222
+ }
223
+ return getChecksumAddress(possibleChecksum) === possibleChecksum;
224
+ }
225
+ function add0x(hexadecimal) {
226
+ if (hexadecimal.startsWith("0x")) {
227
+ return hexadecimal;
228
+ }
229
+ if (hexadecimal.startsWith("0X")) {
230
+ return `0x${hexadecimal.substring(2)}`;
231
+ }
232
+ return `0x${hexadecimal}`;
233
+ }
234
+ function remove0x(hexadecimal) {
235
+ if (hexadecimal.startsWith("0x") || hexadecimal.startsWith("0X")) {
236
+ return hexadecimal.substring(2);
237
+ }
238
+ return hexadecimal;
239
+ }
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+
255
+
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+ exports.HexStruct = HexStruct; exports.StrictHexStruct = StrictHexStruct; exports.HexAddressStruct = HexAddressStruct; exports.HexChecksumAddressStruct = HexChecksumAddressStruct; exports.isHexString = isHexString; exports.isStrictHexString = isStrictHexString; exports.assertIsHexString = assertIsHexString; exports.assertIsStrictHexString = assertIsStrictHexString; exports.isValidHexAddress = isValidHexAddress; exports.getChecksumAddress = getChecksumAddress; exports.isValidChecksumAddress = isValidChecksumAddress; exports.add0x = add0x; exports.remove0x = remove0x; exports.isBytes = isBytes; exports.assertIsBytes = assertIsBytes; exports.bytesToHex = bytesToHex; exports.bytesToBigInt = bytesToBigInt; exports.bytesToSignedBigInt = bytesToSignedBigInt; exports.bytesToNumber = bytesToNumber; exports.bytesToString = bytesToString; exports.bytesToBase64 = bytesToBase64; exports.hexToBytes = hexToBytes; exports.bigIntToBytes = bigIntToBytes; exports.signedBigIntToBytes = signedBigIntToBytes; exports.numberToBytes = numberToBytes; exports.stringToBytes = stringToBytes; exports.base64ToBytes = base64ToBytes; exports.valueToBytes = valueToBytes; exports.concatBytes = concatBytes; exports.createDataView = createDataView;
273
+ //# sourceMappingURL=chunk-QEPVHEP7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hex.ts","../src/bytes.ts"],"names":[],"mappings":";;;;;AAAA,SAAS,cAAc,iBAAiB;AAExC,SAAS,IAAI,SAAS,cAAc;;;ACFpC,SAAS,cAAc;AAOvB,IAAM,+BAA+B;AAGrC,IAAM,+BAA+B;AACrC,IAAM,uBAAuB;AAkB7B,SAAS,iCAAiD;AAKxD,QAAM,cAAwB,CAAC;AAE/B,SAAO,MAAM;AACX,QAAI,YAAY,WAAW,GAAG;AAC5B,eAAS,IAAI,GAAG,IAAI,KAAK,KAAK;AAC5B,oBAAY,KAAK,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AAAA,MAClD;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;AAMA,IAAM,0BAA0B,+BAA+B;AAQxD,SAAS,QAAQ,OAAqC;AAC3D,SAAO,iBAAiB;AAC1B;AAQO,SAAS,cAAc,OAA6C;AACzE,SAAO,QAAQ,KAAK,GAAG,6BAA6B;AACtD;AAQO,SAAS,WAAW,OAAwB;AACjD,gBAAc,KAAK;AAEnB,MAAI,MAAM,WAAW,GAAG;AACtB,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,wBAAwB;AAC5C,QAAM,cAAc,IAAI,MAAM,MAAM,MAAM;AAE1C,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AAErC,gBAAY,CAAC,IAAI,YAAY,MAAM,CAAC,CAAE;AAAA,EACxC;AAEA,SAAO,MAAM,YAAY,KAAK,EAAE,CAAC;AACnC;AAYO,SAAS,cAAc,OAA2B;AACvD,gBAAc,KAAK;AAEnB,QAAM,cAAc,W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;AASO,SAAS,SAAS,aAA6B;AACpD,MAAI,YAAY,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,GAAG;AAChE,WAAO,YAAY,UAAU,CAAC;AAAA,EAChC;AAEA,SAAO;AACT","sourcesContent":["import { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport type { Struct } from 'superstruct';\nimport { is, pattern, string } from 'superstruct';\n\nimport { assert } from './assert';\nimport { bytesToHex } from './bytes';\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>;\nexport const HexAddressStruct = pattern(\n string(),\n /^0x[0-9a-f]{40}$/u,\n) as Struct<Hex, null>;\nexport const HexChecksumAddressStruct = pattern(\n string(),\n /^0x[0-9a-fA-F]{40}$/u,\n) as Struct<Hex, null>;\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 * Validate that the passed prefixed hex string is an all-lowercase\n * hex address, or a valid mixed-case checksum address.\n *\n * @param possibleAddress - Input parameter to check against.\n * @returns Whether or not the input is a valid hex address.\n */\nexport function isValidHexAddress(possibleAddress: Hex) {\n return (\n is(possibleAddress, HexAddressStruct) ||\n isValidChecksumAddress(possibleAddress)\n );\n}\n\n/**\n * Encode a passed hex string as an ERC-55 mixed-case checksum address.\n *\n * @param address - The hex address to encode.\n * @returns The address encoded according to ERC-55.\n * @see https://eips.ethereum.org/EIPS/eip-55\n */\nexport function getChecksumAddress(address: Hex) {\n assert(is(address, HexChecksumAddressStruct), 'Invalid hex address.');\n const unPrefixed = remove0x(address.toLowerCase());\n const unPrefixedHash = remove0x(bytesToHex(keccak256(unPrefixed)));\n return `0x${unPrefixed\n .split('')\n .map((character, nibbleIndex) => {\n const hashCharacter = unPrefixedHash[nibbleIndex];\n assert(is(hashCharacter, string()), 'Hash shorter than address.');\n return parseInt(hashCharacter, 16) > 7\n ? character.toUpperCase()\n : character;\n })\n .join('')}`;\n}\n\n/**\n * Validate that the passed hex string is a valid ERC-55 mixed-case\n * checksum address.\n *\n * @param possibleChecksum - The hex address to check.\n * @returns True if the address is a checksum address.\n */\nexport function isValidChecksumAddress(possibleChecksum: Hex) {\n if (!is(possibleChecksum, HexChecksumAddressStruct)) {\n return false;\n }\n\n return getChecksumAddress(possibleChecksum) === possibleChecksum;\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","import { base64 } from '@scure/base';\n\nimport { assert } from './assert';\nimport type { Hex } from './hex';\nimport { add0x, assertIsHexString, remove0x } from './hex';\n\n// '0'.charCodeAt(0) === 48\nconst HEX_MINIMUM_NUMBER_CHARACTER = 48;\n\n// '9'.charCodeAt(0) === 57\nconst HEX_MAXIMUM_NUMBER_CHARACTER = 58;\nconst HEX_CHARACTER_OFFSET = 87;\n\nexport type Bytes = bigint | number | string | Uint8Array;\n\n/**\n * Memoized function that returns an array to be used as a lookup table for\n * converting bytes to hexadecimal values.\n *\n * The array is created lazily and then cached for future use. The benefit of\n * this approach is that the performance of converting bytes to hex is much\n * better than if we were to call `toString(16)` on each byte.\n *\n * The downside is that the array is created once and then never garbage\n * collected. This is not a problem in practice because the array is only 256\n * elements long.\n *\n * @returns A function that returns the lookup table.\n */\nfunction getPrecomputedHexValuesBuilder(): () => string[] {\n // To avoid issues with tree shaking, we need to use a function to return the\n // array. This is because the array is only used in the `bytesToHex` function\n // and if we were to use a global variable, the array might be removed by the\n // tree shaker.\n const lookupTable: string[] = [];\n\n return () => {\n if (lookupTable.length === 0) {\n for (let i = 0; i < 256; i++) {\n lookupTable.push(i.toString(16).padStart(2, '0'));\n }\n }\n\n return lookupTable;\n };\n}\n\n/**\n * Function implementation of the {@link getPrecomputedHexValuesBuilder}\n * function.\n */\nconst getPrecomputedHexValues = getPrecomputedHexValuesBuilder();\n\n/**\n * Check if a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @returns Whether the value is a `Uint8Array`.\n */\nexport function isBytes(value: unknown): value is Uint8Array {\n return value instanceof Uint8Array;\n}\n\n/**\n * Assert that a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @throws If the value is not a `Uint8Array`.\n */\nexport function assertIsBytes(value: unknown): asserts value is Uint8Array {\n assert(isBytes(value), 'Value must be a Uint8Array.');\n}\n\n/**\n * Convert a `Uint8Array` to a hexadecimal string.\n *\n * @param bytes - The bytes to convert to a hexadecimal string.\n * @returns The hexadecimal string.\n */\nexport function bytesToHex(bytes: Uint8Array): Hex {\n assertIsBytes(bytes);\n\n if (bytes.length === 0) {\n return '0x';\n }\n\n const lookupTable = getPrecomputedHexValues();\n const hexadecimal = new Array(bytes.length);\n\n for (let i = 0; i < bytes.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n hexadecimal[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hexadecimal.join(''));\n}\n\n/**\n * Convert a `Uint8Array` to a `bigint`.\n *\n * To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}.\n * To convert a two's complement encoded `Uint8Array` to a `bigint`, use\n * {@link bytesToSignedBigInt}.\n *\n * @param bytes - The bytes to convert to a `bigint`.\n * @returns The `bigint`.\n */\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n const hexadecimal = bytesToHex(bytes);\n return BigInt(hexadecimal);\n}\n\n/**\n * Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are\n * encoded in two's complement.\n *\n * To convert a `Uint8Array` to an unsigned `bigint` instead, use\n * {@link bytesToBigInt}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param bytes - The bytes to convert to a signed `bigint`.\n * @returns The signed `bigint`.\n */\nexport function bytesToSignedBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n let value = BigInt(0);\n for (const byte of bytes) {\n // eslint-disable-next-line no-bitwise\n value = (value << BigInt(8)) + BigInt(byte);\n }\n\n return BigInt.asIntN(bytes.length * 8, value);\n}\n\n/**\n * Convert a `Uint8Array` to a `number`.\n *\n * To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}.\n *\n * @param bytes - The bytes to convert to a number.\n * @returns The number.\n * @throws If the resulting number is not a safe integer.\n */\nexport function bytesToNumber(bytes: Uint8Array): number {\n assertIsBytes(bytes);\n\n const bigint = bytesToBigInt(bytes);\n\n assert(\n bigint <= BigInt(Number.MAX_SAFE_INTEGER),\n 'Number is not a safe integer. Use `bytesToBigInt` instead.',\n );\n\n return Number(bigint);\n}\n\n/**\n * Convert a UTF-8 encoded `Uint8Array` to a `string`.\n *\n * @param bytes - The bytes to convert to a string.\n * @returns The string.\n */\nexport function bytesToString(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert a `Uint8Array` to a base64 encoded string.\n *\n * @param bytes - The bytes to convert to a base64 encoded string.\n * @returns The base64 encoded string.\n */\nexport function bytesToBase64(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return base64.encode(bytes);\n}\n\n/**\n * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be\n * prefixed with `0x`. It accepts even and odd length strings.\n *\n * If the value is \"0x\", an empty `Uint8Array` is returned.\n *\n * @param value - The hexadecimal string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function hexToBytes(value: string): Uint8Array {\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 base64 encoded string to a `Uint8Array`.\n *\n * @param value - The base64 encoded string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function base64ToBytes(value: string): Uint8Array {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return base64.decode(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"]}