@metamask/utils 8.4.0 → 8.5.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.
Files changed (346) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/dist/assert.cjs +127 -0
  3. package/dist/assert.cjs.map +1 -0
  4. package/dist/{types/assert.d.ts → assert.d.cts} +3 -3
  5. package/dist/assert.d.cts.map +1 -0
  6. package/dist/assert.d.mts +61 -0
  7. package/dist/assert.d.mts.map +1 -0
  8. package/dist/assert.mjs +119 -15
  9. package/dist/assert.mjs.map +1 -1
  10. package/dist/base64.cjs +34 -0
  11. package/dist/base64.cjs.map +1 -0
  12. package/dist/{types/base64.d.ts → base64.d.cts} +3 -3
  13. package/dist/base64.d.cts.map +1 -0
  14. package/dist/base64.d.mts +25 -0
  15. package/dist/base64.d.mts.map +1 -0
  16. package/dist/base64.mjs +28 -9
  17. package/dist/base64.mjs.map +1 -1
  18. package/dist/bytes.cjs +400 -0
  19. package/dist/{chunk-QEPVHEP7.js.map → bytes.cjs.map} +1 -1
  20. package/dist/{types/bytes.d.ts → bytes.d.cts} +3 -3
  21. package/dist/bytes.d.cts.map +1 -0
  22. package/dist/bytes.d.mts +183 -0
  23. package/dist/bytes.d.mts.map +1 -0
  24. package/dist/bytes.mjs +379 -42
  25. package/dist/bytes.mjs.map +1 -1
  26. package/dist/caip-types.cjs +151 -0
  27. package/dist/caip-types.cjs.map +1 -0
  28. package/dist/{types/caip-types.d.ts → caip-types.d.cts} +12 -12
  29. package/dist/caip-types.d.cts.map +1 -0
  30. package/dist/caip-types.d.mts +114 -0
  31. package/dist/caip-types.d.mts.map +1 -0
  32. package/dist/caip-types.mjs +139 -43
  33. package/dist/caip-types.mjs.map +1 -1
  34. package/dist/checksum.cjs +7 -0
  35. package/dist/checksum.cjs.map +1 -0
  36. package/dist/checksum.d.cts +2 -0
  37. package/dist/checksum.d.cts.map +1 -0
  38. package/dist/checksum.d.mts +2 -0
  39. package/dist/checksum.d.mts.map +1 -0
  40. package/dist/checksum.mjs +3 -11
  41. package/dist/checksum.mjs.map +1 -1
  42. package/dist/coercers.cjs +162 -0
  43. package/dist/coercers.cjs.map +1 -0
  44. package/dist/{types/coercers.d.ts → coercers.d.cts} +7 -7
  45. package/dist/coercers.d.cts.map +1 -0
  46. package/dist/coercers.d.mts +97 -0
  47. package/dist/coercers.d.mts.map +1 -0
  48. package/dist/coercers.mjs +154 -17
  49. package/dist/coercers.mjs.map +1 -1
  50. package/dist/collections.cjs +109 -0
  51. package/dist/collections.cjs.map +1 -0
  52. package/dist/{types/collections.d.ts → collections.d.cts} +1 -1
  53. package/dist/collections.d.cts.map +1 -0
  54. package/dist/collections.d.mts +39 -0
  55. package/dist/collections.d.mts.map +1 -0
  56. package/dist/collections.mjs +103 -8
  57. package/dist/collections.mjs.map +1 -1
  58. package/dist/encryption-types.cjs +3 -0
  59. package/dist/encryption-types.cjs.map +1 -0
  60. package/dist/{types/encryption-types.d.ts → encryption-types.d.cts} +2 -2
  61. package/dist/encryption-types.d.cts.map +1 -0
  62. package/dist/encryption-types.d.mts +7 -0
  63. package/dist/encryption-types.d.mts.map +1 -0
  64. package/dist/encryption-types.mjs +1 -1
  65. package/dist/encryption-types.mjs.map +1 -1
  66. package/dist/errors.cjs +111 -0
  67. package/dist/errors.cjs.map +1 -0
  68. package/dist/{types/errors.d.ts → errors.d.cts} +1 -1
  69. package/dist/errors.d.cts.map +1 -0
  70. package/dist/errors.d.mts +58 -0
  71. package/dist/errors.d.mts.map +1 -0
  72. package/dist/errors.mjs +102 -16
  73. package/dist/errors.mjs.map +1 -1
  74. package/dist/fs.cjs +248 -0
  75. package/dist/fs.cjs.map +1 -0
  76. package/dist/{types/fs.d.ts → fs.d.cts} +3 -3
  77. package/dist/fs.d.cts.map +1 -0
  78. package/dist/fs.d.mts +133 -0
  79. package/dist/fs.d.mts.map +1 -0
  80. package/dist/fs.mjs +209 -25
  81. package/dist/fs.mjs.map +1 -1
  82. package/dist/hex.cjs +134 -0
  83. package/dist/hex.cjs.map +1 -0
  84. package/dist/{types/hex.d.ts → hex.d.cts} +3 -3
  85. package/dist/hex.d.cts.map +1 -0
  86. package/dist/hex.d.mts +77 -0
  87. package/dist/hex.d.mts.map +1 -0
  88. package/dist/hex.mjs +121 -34
  89. package/dist/hex.mjs.map +1 -1
  90. package/dist/index.cjs +37 -0
  91. package/dist/index.cjs.map +1 -0
  92. package/dist/index.d.cts +21 -0
  93. package/dist/index.d.cts.map +1 -0
  94. package/dist/index.d.mts +21 -0
  95. package/dist/index.d.mts.map +1 -0
  96. package/dist/index.mjs +20 -296
  97. package/dist/index.mjs.map +1 -1
  98. package/dist/json.cjs +413 -0
  99. package/dist/json.cjs.map +1 -0
  100. package/dist/{types/json.d.ts → json.d.cts} +21 -22
  101. package/dist/json.d.cts.map +1 -0
  102. package/dist/json.d.mts +383 -0
  103. package/dist/json.d.mts.map +1 -0
  104. package/dist/json.mjs +389 -74
  105. package/dist/json.mjs.map +1 -1
  106. package/dist/keyring.cjs +3 -0
  107. package/dist/keyring.cjs.map +1 -0
  108. package/dist/{types/keyring.d.ts → keyring.d.cts} +7 -7
  109. package/dist/keyring.d.cts.map +1 -0
  110. package/dist/keyring.d.mts +224 -0
  111. package/dist/keyring.d.mts.map +1 -0
  112. package/dist/keyring.mjs +1 -1
  113. package/dist/keyring.mjs.map +1 -1
  114. package/dist/logging.cjs +43 -0
  115. package/dist/logging.cjs.map +1 -0
  116. package/dist/{types/logging.d.ts → logging.d.cts} +2 -2
  117. package/dist/logging.d.cts.map +1 -0
  118. package/dist/logging.d.mts +30 -0
  119. package/dist/logging.d.mts.map +1 -0
  120. package/dist/logging.mjs +34 -9
  121. package/dist/logging.mjs.map +1 -1
  122. package/dist/misc.cjs +149 -0
  123. package/dist/misc.cjs.map +1 -0
  124. package/dist/{types/misc.d.ts → misc.d.cts} +6 -6
  125. package/dist/misc.d.cts.map +1 -0
  126. package/dist/misc.d.mts +119 -0
  127. package/dist/misc.d.mts.map +1 -0
  128. package/dist/misc.mjs +136 -27
  129. package/dist/misc.mjs.map +1 -1
  130. package/dist/node.cjs +19 -0
  131. package/dist/node.cjs.map +1 -0
  132. package/dist/node.d.cts +3 -0
  133. package/dist/node.d.cts.map +1 -0
  134. package/dist/node.d.mts +3 -0
  135. package/dist/node.d.mts.map +1 -0
  136. package/dist/node.mjs +2 -316
  137. package/dist/node.mjs.map +1 -1
  138. package/dist/number.cjs +102 -0
  139. package/dist/number.cjs.map +1 -0
  140. package/dist/{types/number.d.ts → number.d.cts} +1 -1
  141. package/dist/number.d.cts.map +1 -0
  142. package/dist/number.d.mts +73 -0
  143. package/dist/number.d.mts.map +1 -0
  144. package/dist/number.mjs +93 -16
  145. package/dist/number.mjs.map +1 -1
  146. package/dist/opaque.cjs +3 -0
  147. package/dist/opaque.cjs.map +1 -0
  148. package/dist/opaque.d.cts +6 -0
  149. package/dist/opaque.d.cts.map +1 -0
  150. package/dist/opaque.d.mts +6 -0
  151. package/dist/opaque.d.mts.map +1 -0
  152. package/dist/opaque.mjs +1 -1
  153. package/dist/opaque.mjs.map +1 -1
  154. package/dist/promise.cjs +40 -0
  155. package/dist/promise.cjs.map +1 -0
  156. package/dist/{types/promise.d.ts → promise.d.cts} +2 -2
  157. package/dist/promise.d.cts.map +1 -0
  158. package/dist/promise.d.mts +45 -0
  159. package/dist/promise.d.mts.map +1 -0
  160. package/dist/promise.mjs +35 -7
  161. package/dist/promise.mjs.map +1 -1
  162. package/dist/time.cjs +67 -0
  163. package/dist/time.cjs.map +1 -0
  164. package/dist/{types/time.d.ts → time.d.cts} +1 -1
  165. package/dist/time.d.cts.map +1 -0
  166. package/dist/time.d.mts +49 -0
  167. package/dist/time.d.mts.map +1 -0
  168. package/dist/time.mjs +60 -10
  169. package/dist/time.mjs.map +1 -1
  170. package/dist/transaction-types.cjs +3 -0
  171. package/dist/transaction-types.cjs.map +1 -0
  172. package/dist/{types/transaction-types.d.ts → transaction-types.d.cts} +11 -11
  173. package/dist/transaction-types.d.cts.map +1 -0
  174. package/dist/transaction-types.d.mts +117 -0
  175. package/dist/transaction-types.d.mts.map +1 -0
  176. package/dist/transaction-types.mjs +1 -1
  177. package/dist/transaction-types.mjs.map +1 -1
  178. package/dist/versions.cjs +95 -0
  179. package/dist/versions.cjs.map +1 -0
  180. package/dist/{types/versions.d.ts → versions.d.cts} +5 -5
  181. package/dist/versions.d.cts.map +1 -0
  182. package/dist/versions.d.mts +101 -0
  183. package/dist/versions.d.mts.map +1 -0
  184. package/dist/versions.mjs +85 -26
  185. package/dist/versions.mjs.map +1 -1
  186. package/package.json +26 -17
  187. package/dist/assert.js +0 -16
  188. package/dist/assert.js.map +0 -1
  189. package/dist/base64.js +0 -11
  190. package/dist/base64.js.map +0 -1
  191. package/dist/bytes.js +0 -43
  192. package/dist/bytes.js.map +0 -1
  193. package/dist/caip-types.js +0 -44
  194. package/dist/caip-types.js.map +0 -1
  195. package/dist/checksum.js +0 -12
  196. package/dist/checksum.js.map +0 -1
  197. package/dist/chunk-2LBGT4GH.js +0 -15
  198. package/dist/chunk-2LBGT4GH.js.map +0 -1
  199. package/dist/chunk-3W5G4CYI.js +0 -25
  200. package/dist/chunk-3W5G4CYI.js.map +0 -1
  201. package/dist/chunk-4D6XQBHA.js +0 -69
  202. package/dist/chunk-4D6XQBHA.js.map +0 -1
  203. package/dist/chunk-4RMX5YWE.js +0 -34
  204. package/dist/chunk-4RMX5YWE.js.map +0 -1
  205. package/dist/chunk-5AVWINSB.js +0 -1
  206. package/dist/chunk-5AVWINSB.js.map +0 -1
  207. package/dist/chunk-622IOGVI.mjs +0 -1
  208. package/dist/chunk-622IOGVI.mjs.map +0 -1
  209. package/dist/chunk-6C35XQOF.mjs +0 -257
  210. package/dist/chunk-6C35XQOF.mjs.map +0 -1
  211. package/dist/chunk-6NZW4WK4.js +0 -35
  212. package/dist/chunk-6NZW4WK4.js.map +0 -1
  213. package/dist/chunk-6ZDHSOUV.js +0 -59
  214. package/dist/chunk-6ZDHSOUV.js.map +0 -1
  215. package/dist/chunk-74DGVJVE.mjs +0 -59
  216. package/dist/chunk-74DGVJVE.mjs.map +0 -1
  217. package/dist/chunk-AY6FDCBT.mjs +0 -1
  218. package/dist/chunk-AY6FDCBT.mjs.map +0 -1
  219. package/dist/chunk-C6HGFEYL.js +0 -23
  220. package/dist/chunk-C6HGFEYL.js.map +0 -1
  221. package/dist/chunk-DHVKFDHQ.js +0 -95
  222. package/dist/chunk-DHVKFDHQ.js.map +0 -1
  223. package/dist/chunk-DYRKZQMK.mjs +0 -122
  224. package/dist/chunk-DYRKZQMK.mjs.map +0 -1
  225. package/dist/chunk-E4C7EW4R.js +0 -16
  226. package/dist/chunk-E4C7EW4R.js.map +0 -1
  227. package/dist/chunk-EQMZL4XU.js +0 -1
  228. package/dist/chunk-EQMZL4XU.js.map +0 -1
  229. package/dist/chunk-GZS3IQBZ.mjs +0 -16
  230. package/dist/chunk-GZS3IQBZ.mjs.map +0 -1
  231. package/dist/chunk-H4YFDLB7.mjs +0 -70
  232. package/dist/chunk-H4YFDLB7.mjs.map +0 -1
  233. package/dist/chunk-I575FZFH.mjs +0 -1
  234. package/dist/chunk-I575FZFH.mjs.map +0 -1
  235. package/dist/chunk-IZC266HS.js +0 -55
  236. package/dist/chunk-IZC266HS.js.map +0 -1
  237. package/dist/chunk-JPAL7Q5S.mjs +0 -90
  238. package/dist/chunk-JPAL7Q5S.mjs.map +0 -1
  239. package/dist/chunk-LC2CRSWD.js +0 -1
  240. package/dist/chunk-LC2CRSWD.js.map +0 -1
  241. package/dist/chunk-NQMRFZHB.mjs +0 -35
  242. package/dist/chunk-NQMRFZHB.mjs.map +0 -1
  243. package/dist/chunk-O3EIM33O.mjs +0 -95
  244. package/dist/chunk-O3EIM33O.mjs.map +0 -1
  245. package/dist/chunk-OLLG4H35.js +0 -257
  246. package/dist/chunk-OLLG4H35.js.map +0 -1
  247. package/dist/chunk-OUZ3LSLX.mjs +0 -94
  248. package/dist/chunk-OUZ3LSLX.mjs.map +0 -1
  249. package/dist/chunk-QEPVHEP7.js +0 -273
  250. package/dist/chunk-QVEKZRZ2.js +0 -70
  251. package/dist/chunk-QVEKZRZ2.js.map +0 -1
  252. package/dist/chunk-RIRDOQPX.mjs +0 -15
  253. package/dist/chunk-RIRDOQPX.mjs.map +0 -1
  254. package/dist/chunk-RKRGAFXY.js +0 -1
  255. package/dist/chunk-RKRGAFXY.js.map +0 -1
  256. package/dist/chunk-RNEXSCNP.js +0 -122
  257. package/dist/chunk-RNEXSCNP.js.map +0 -1
  258. package/dist/chunk-ROQSKDP5.mjs +0 -69
  259. package/dist/chunk-ROQSKDP5.mjs.map +0 -1
  260. package/dist/chunk-RRYOWRCV.mjs +0 -1
  261. package/dist/chunk-RRYOWRCV.mjs.map +0 -1
  262. package/dist/chunk-S3UHBN2Z.mjs +0 -44
  263. package/dist/chunk-S3UHBN2Z.mjs.map +0 -1
  264. package/dist/chunk-THNLGEXV.mjs +0 -34
  265. package/dist/chunk-THNLGEXV.mjs.map +0 -1
  266. package/dist/chunk-UOTVU7OQ.js +0 -1
  267. package/dist/chunk-UOTVU7OQ.js.map +0 -1
  268. package/dist/chunk-VA2DRBDE.mjs +0 -273
  269. package/dist/chunk-VA2DRBDE.mjs.map +0 -1
  270. package/dist/chunk-VFXTVNXN.js +0 -44
  271. package/dist/chunk-VFXTVNXN.js.map +0 -1
  272. package/dist/chunk-W5XI7ERF.mjs +0 -23
  273. package/dist/chunk-W5XI7ERF.mjs.map +0 -1
  274. package/dist/chunk-WA4DHIND.mjs +0 -1
  275. package/dist/chunk-WA4DHIND.mjs.map +0 -1
  276. package/dist/chunk-X66SUIEF.mjs +0 -25
  277. package/dist/chunk-X66SUIEF.mjs.map +0 -1
  278. package/dist/chunk-XYGUOY6N.mjs +0 -55
  279. package/dist/chunk-XYGUOY6N.mjs.map +0 -1
  280. package/dist/chunk-YWAID473.js +0 -94
  281. package/dist/chunk-YWAID473.js.map +0 -1
  282. package/dist/chunk-Z2RGWDD7.js +0 -90
  283. package/dist/chunk-Z2RGWDD7.js.map +0 -1
  284. package/dist/coercers.js +0 -18
  285. package/dist/coercers.js.map +0 -1
  286. package/dist/collections.js +0 -10
  287. package/dist/collections.js.map +0 -1
  288. package/dist/encryption-types.js +0 -2
  289. package/dist/encryption-types.js.map +0 -1
  290. package/dist/errors.js +0 -17
  291. package/dist/errors.js.map +0 -1
  292. package/dist/fs.js +0 -26
  293. package/dist/fs.js.map +0 -1
  294. package/dist/hex.js +0 -35
  295. package/dist/hex.js.map +0 -1
  296. package/dist/index.js +0 -297
  297. package/dist/index.js.map +0 -1
  298. package/dist/json.js +0 -75
  299. package/dist/json.js.map +0 -1
  300. package/dist/keyring.js +0 -2
  301. package/dist/keyring.js.map +0 -1
  302. package/dist/logging.js +0 -10
  303. package/dist/logging.js.map +0 -1
  304. package/dist/misc.js +0 -28
  305. package/dist/misc.js.map +0 -1
  306. package/dist/node.js +0 -317
  307. package/dist/node.js.map +0 -1
  308. package/dist/number.js +0 -18
  309. package/dist/number.js.map +0 -1
  310. package/dist/opaque.js +0 -2
  311. package/dist/opaque.js.map +0 -1
  312. package/dist/promise.js +0 -8
  313. package/dist/promise.js.map +0 -1
  314. package/dist/time.js +0 -12
  315. package/dist/time.js.map +0 -1
  316. package/dist/transaction-types.js +0 -2
  317. package/dist/transaction-types.js.map +0 -1
  318. package/dist/types/assert.d.ts.map +0 -1
  319. package/dist/types/base64.d.ts.map +0 -1
  320. package/dist/types/bytes.d.ts.map +0 -1
  321. package/dist/types/caip-types.d.ts.map +0 -1
  322. package/dist/types/checksum.d.ts +0 -2
  323. package/dist/types/checksum.d.ts.map +0 -1
  324. package/dist/types/coercers.d.ts.map +0 -1
  325. package/dist/types/collections.d.ts.map +0 -1
  326. package/dist/types/encryption-types.d.ts.map +0 -1
  327. package/dist/types/errors.d.ts.map +0 -1
  328. package/dist/types/fs.d.ts.map +0 -1
  329. package/dist/types/hex.d.ts.map +0 -1
  330. package/dist/types/index.d.ts +0 -21
  331. package/dist/types/index.d.ts.map +0 -1
  332. package/dist/types/json.d.ts.map +0 -1
  333. package/dist/types/keyring.d.ts.map +0 -1
  334. package/dist/types/logging.d.ts.map +0 -1
  335. package/dist/types/misc.d.ts.map +0 -1
  336. package/dist/types/node.d.ts +0 -3
  337. package/dist/types/node.d.ts.map +0 -1
  338. package/dist/types/number.d.ts.map +0 -1
  339. package/dist/types/opaque.d.ts +0 -6
  340. package/dist/types/opaque.d.ts.map +0 -1
  341. package/dist/types/promise.d.ts.map +0 -1
  342. package/dist/types/time.d.ts.map +0 -1
  343. package/dist/types/transaction-types.d.ts.map +0 -1
  344. package/dist/types/versions.d.ts.map +0 -1
  345. package/dist/versions.js +0 -27
  346. package/dist/versions.js.map +0 -1
@@ -1,257 +0,0 @@
1
- import {
2
- assertStruct
3
- } from "./chunk-74DGVJVE.mjs";
4
- import {
5
- hasProperty
6
- } from "./chunk-H4YFDLB7.mjs";
7
-
8
- // src/json.ts
9
- import {
10
- any,
11
- array,
12
- boolean,
13
- coerce,
14
- create,
15
- define,
16
- integer,
17
- is,
18
- lazy,
19
- literal,
20
- nullable,
21
- number,
22
- object as superstructObject,
23
- optional,
24
- record,
25
- string,
26
- union,
27
- unknown,
28
- Struct
29
- } from "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
- superstructObject(schema)
35
- );
36
- function hasOptional({ path, branch }) {
37
- const field = path[path.length - 1];
38
- return hasProperty(branch[branch.length - 2], field);
39
- }
40
- function exactOptional(struct) {
41
- return new 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 = () => define("finite number", (value) => {
49
- return is(value, number()) && Number.isFinite(value);
50
- });
51
- var UnsafeJsonStruct = union([
52
- literal(null),
53
- boolean(),
54
- finiteNumber(),
55
- string(),
56
- array(lazy(() => UnsafeJsonStruct)),
57
- record(
58
- string(),
59
- lazy(() => UnsafeJsonStruct)
60
- )
61
- ]);
62
- var JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {
63
- assertStruct(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 {
78
- return false;
79
- }
80
- }
81
- function getSafeJson(value) {
82
- return create(value, JsonStruct);
83
- }
84
- function getJsonSize(value) {
85
- assertStruct(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 = literal(jsonrpc2);
91
- var JsonRpcIdStruct = nullable(union([number(), string()]));
92
- var JsonRpcErrorStruct = object({
93
- code: integer(),
94
- message: string(),
95
- data: exactOptional(JsonStruct),
96
- stack: exactOptional(string())
97
- });
98
- var JsonRpcParamsStruct = union([record(string(), JsonStruct), array(JsonStruct)]);
99
- var JsonRpcRequestStruct = object({
100
- id: JsonRpcIdStruct,
101
- jsonrpc: JsonRpcVersionStruct,
102
- method: string(),
103
- params: exactOptional(JsonRpcParamsStruct)
104
- });
105
- var JsonRpcNotificationStruct = object({
106
- jsonrpc: JsonRpcVersionStruct,
107
- method: string(),
108
- params: exactOptional(JsonRpcParamsStruct)
109
- });
110
- function isJsonRpcNotification(value) {
111
- return is(value, JsonRpcNotificationStruct);
112
- }
113
- function assertIsJsonRpcNotification(value, ErrorWrapper) {
114
- assertStruct(
115
- value,
116
- JsonRpcNotificationStruct,
117
- "Invalid JSON-RPC notification",
118
- ErrorWrapper
119
- );
120
- }
121
- function isJsonRpcRequest(value) {
122
- return is(value, JsonRpcRequestStruct);
123
- }
124
- function assertIsJsonRpcRequest(value, ErrorWrapper) {
125
- assertStruct(
126
- value,
127
- JsonRpcRequestStruct,
128
- "Invalid JSON-RPC request",
129
- ErrorWrapper
130
- );
131
- }
132
- var PendingJsonRpcResponseStruct = superstructObject({
133
- id: JsonRpcIdStruct,
134
- jsonrpc: JsonRpcVersionStruct,
135
- result: optional(unknown()),
136
- error: optional(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 = union([
149
- JsonRpcSuccessStruct,
150
- JsonRpcFailureStruct
151
- ]);
152
- function isPendingJsonRpcResponse(response) {
153
- return is(response, PendingJsonRpcResponseStruct);
154
- }
155
- function assertIsPendingJsonRpcResponse(response, ErrorWrapper) {
156
- assertStruct(
157
- response,
158
- PendingJsonRpcResponseStruct,
159
- "Invalid pending JSON-RPC response",
160
- ErrorWrapper
161
- );
162
- }
163
- function isJsonRpcResponse(response) {
164
- return is(response, JsonRpcResponseStruct);
165
- }
166
- function assertIsJsonRpcResponse(value, ErrorWrapper) {
167
- assertStruct(
168
- value,
169
- JsonRpcResponseStruct,
170
- "Invalid JSON-RPC response",
171
- ErrorWrapper
172
- );
173
- }
174
- function isJsonRpcSuccess(value) {
175
- return is(value, JsonRpcSuccessStruct);
176
- }
177
- function assertIsJsonRpcSuccess(value, ErrorWrapper) {
178
- assertStruct(
179
- value,
180
- JsonRpcSuccessStruct,
181
- "Invalid JSON-RPC success response",
182
- ErrorWrapper
183
- );
184
- }
185
- function isJsonRpcFailure(value) {
186
- return is(value, JsonRpcFailureStruct);
187
- }
188
- function assertIsJsonRpcFailure(value, ErrorWrapper) {
189
- assertStruct(
190
- value,
191
- JsonRpcFailureStruct,
192
- "Invalid JSON-RPC failure response",
193
- ErrorWrapper
194
- );
195
- }
196
- function isJsonRpcError(value) {
197
- return is(value, JsonRpcErrorStruct);
198
- }
199
- function assertIsJsonRpcError(value, ErrorWrapper) {
200
- assertStruct(
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
- export {
223
- object,
224
- exactOptional,
225
- UnsafeJsonStruct,
226
- JsonStruct,
227
- isValidJson,
228
- getSafeJson,
229
- getJsonSize,
230
- jsonrpc2,
231
- JsonRpcVersionStruct,
232
- JsonRpcIdStruct,
233
- JsonRpcErrorStruct,
234
- JsonRpcParamsStruct,
235
- JsonRpcRequestStruct,
236
- JsonRpcNotificationStruct,
237
- isJsonRpcNotification,
238
- assertIsJsonRpcNotification,
239
- isJsonRpcRequest,
240
- assertIsJsonRpcRequest,
241
- PendingJsonRpcResponseStruct,
242
- JsonRpcSuccessStruct,
243
- JsonRpcFailureStruct,
244
- JsonRpcResponseStruct,
245
- isPendingJsonRpcResponse,
246
- assertIsPendingJsonRpcResponse,
247
- isJsonRpcResponse,
248
- assertIsJsonRpcResponse,
249
- isJsonRpcSuccess,
250
- assertIsJsonRpcSuccess,
251
- isJsonRpcFailure,
252
- assertIsJsonRpcFailure,
253
- isJsonRpcError,
254
- assertIsJsonRpcError,
255
- getJsonRpcIdValidator
256
- };
257
- //# sourceMappingURL=chunk-6C35XQOF.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/json.ts"],"sourcesContent":["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"],"mappings":"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","names":[]}
@@ -1,35 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
-
3
- var _chunk6ZDHSOUVjs = require('./chunk-6ZDHSOUV.js');
4
-
5
- // src/base64.ts
6
- var _superstruct = require('superstruct');
7
- var base64 = (struct, options = {}) => {
8
- const paddingRequired = _nullishCoalesce(options.paddingRequired, () => ( false));
9
- const characterSet = _nullishCoalesce(options.characterSet, () => ( "base64"));
10
- let letters;
11
- if (characterSet === "base64") {
12
- letters = String.raw`[A-Za-z0-9+\/]`;
13
- } else {
14
- _chunk6ZDHSOUVjs.assert.call(void 0, characterSet === "base64url");
15
- letters = String.raw`[-_A-Za-z0-9]`;
16
- }
17
- let re;
18
- if (paddingRequired) {
19
- re = new RegExp(
20
- `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,
21
- "u"
22
- );
23
- } else {
24
- re = new RegExp(
25
- `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,
26
- "u"
27
- );
28
- }
29
- return _superstruct.pattern.call(void 0, struct, re);
30
- };
31
-
32
-
33
-
34
- exports.base64 = base64;
35
- //# sourceMappingURL=chunk-6NZW4WK4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/base64.ts"],"names":[],"mappings":";;;;;AACA,SAAS,eAAe;AA4BjB,IAAM,SAAS,CACpB,QACA,UAAyB,CAAC,MACvB;AACH,QAAM,kBAAkB,QAAQ,mBAAmB;AACnD,QAAM,eAAe,QAAQ,gBAAgB;AAE7C,MAAI;AACJ,MAAI,iBAAiB,UAAU;AAC7B,cAAU,OAAO;AAAA,EACnB,OAAO;AACL,WAAO,iBAAiB,WAAW;AACnC,cAAU,OAAO;AAAA,EACnB;AAEA,MAAI;AACJ,MAAI,iBAAiB;AACnB,SAAK,IAAI;AAAA,MACP,OAAO,OAAO,WAAW,OAAO,QAAQ,OAAO;AAAA,MAC/C;AAAA,IACF;AAAA,EACF,OAAO;AACL,SAAK,IAAI;AAAA,MACP,OAAO,OAAO,WAAW,OAAO,SAAS,OAAO,QAAQ,OAAO;AAAA,MAC/D;AAAA,IACF;AAAA,EACF;AAEA,SAAO,QAAQ,QAAQ,EAAE;AAC3B","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"]}
@@ -1,59 +0,0 @@
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 _chunkIZC266HSjs = require('./chunk-IZC266HS.js');
4
-
5
- // src/assert.ts
6
- var _superstruct = require('superstruct');
7
- function isConstructable(fn) {
8
- return Boolean(typeof _optionalChain([fn, 'optionalAccess', _ => _.prototype, 'optionalAccess', _2 => _2.constructor, 'optionalAccess', _3 => _3.name]) === "string");
9
- }
10
- function getErrorMessageWithoutTrailingPeriod(error) {
11
- return _chunkIZC266HSjs.getErrorMessage.call(void 0, error).replace(/\.$/u, "");
12
- }
13
- function getError(ErrorWrapper, message) {
14
- if (isConstructable(ErrorWrapper)) {
15
- return new ErrorWrapper({
16
- message
17
- });
18
- }
19
- return ErrorWrapper({
20
- message
21
- });
22
- }
23
- var AssertionError = class extends Error {
24
- constructor(options) {
25
- super(options.message);
26
- this.code = "ERR_ASSERTION";
27
- }
28
- };
29
- function assert(value, message = "Assertion failed.", ErrorWrapper = AssertionError) {
30
- if (!value) {
31
- if (message instanceof Error) {
32
- throw message;
33
- }
34
- throw getError(ErrorWrapper, message);
35
- }
36
- }
37
- function assertStruct(value, struct, errorPrefix = "Assertion failed", ErrorWrapper = AssertionError) {
38
- try {
39
- _superstruct.assert.call(void 0, value, struct);
40
- } catch (error) {
41
- throw getError(
42
- ErrorWrapper,
43
- `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`
44
- );
45
- }
46
- }
47
- function assertExhaustive(_object) {
48
- throw new Error(
49
- "Invalid branch reached. Should be detected during compilation."
50
- );
51
- }
52
-
53
-
54
-
55
-
56
-
57
-
58
- exports.AssertionError = AssertionError; exports.assert = assert; exports.assertStruct = assertStruct; exports.assertExhaustive = assertExhaustive;
59
- //# sourceMappingURL=chunk-6ZDHSOUV.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/assert.ts"],"names":[],"mappings":";;;;;AACA,SAAS,UAAU,yBAAyB;AAe5C,SAAS,gBACP,IACgD;AAEhD,SAAO,QAAQ,OAAO,IAAI,WAAW,aAAa,SAAS,QAAQ;AACrE;AAYA,SAAS,qCAAqC,OAAwB;AAEpE,SAAO,gBAAgB,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAClD;AAUA,SAAS,SAAS,cAAyC,SAAiB;AAC1E,MAAI,gBAAgB,YAAY,GAAG;AACjC,WAAO,IAAI,aAAa;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,aAAa;AAAA,IAClB;AAAA,EACF,CAAC;AACH;AAKO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAGxC,YAAY,SAA8B;AACxC,UAAM,QAAQ,OAAO;AAHvB,SAAS,OAAO;AAAA,EAIhB;AACF;AAcO,SAAS,OACd,OACA,UAA0B,qBAE1B,eAA0C,gBAC3B;AACf,MAAI,CAAC,OAAO;AACV,QAAI,mBAAmB,OAAO;AAC5B,YAAM;AAAA,IACR;AAEA,UAAM,SAAS,cAAc,OAAO;AAAA,EACtC;AACF;AAaO,SAAS,aACd,OACA,QACA,cAAc,oBAEd,eAA0C,gBACnB;AACvB,MAAI;AACF,sBAAkB,OAAO,MAAM;AAAA,EACjC,SAAS,OAAO;AACd,UAAM;AAAA,MACJ;AAAA,MACA,GAAG,WAAW,KAAK,qCAAqC,KAAK,CAAC;AAAA,IAChE;AAAA,EACF;AACF;AAqBO,SAAS,iBAAiB,SAAuB;AACtD,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF","sourcesContent":["import type { Struct } from 'superstruct';\nimport { assert as assertSuperstruct } from 'superstruct';\n\nimport { getErrorMessage } from './errors';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\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 * Attempts to obtain the message from a possible error object. If it is\n * possible to do so, any trailing period will be removed from the message;\n * otherwise an empty string is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The message without any trailing period if `error` is an object\n * with a `message` property; the string version of `error` without any trailing\n * period if it is not `undefined` or `null`; otherwise an empty string.\n */\nfunction getErrorMessageWithoutTrailingPeriod(error: unknown): string {\n // We'll add our own period.\n return getErrorMessage(error).replace(/\\.$/u, '');\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(\n ErrorWrapper,\n `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`,\n );\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n"]}
@@ -1,59 +0,0 @@
1
- import {
2
- getErrorMessage
3
- } from "./chunk-XYGUOY6N.mjs";
4
-
5
- // src/assert.ts
6
- import { assert as assertSuperstruct } from "superstruct";
7
- function isConstructable(fn) {
8
- return Boolean(typeof fn?.prototype?.constructor?.name === "string");
9
- }
10
- function getErrorMessageWithoutTrailingPeriod(error) {
11
- return getErrorMessage(error).replace(/\.$/u, "");
12
- }
13
- function getError(ErrorWrapper, message) {
14
- if (isConstructable(ErrorWrapper)) {
15
- return new ErrorWrapper({
16
- message
17
- });
18
- }
19
- return ErrorWrapper({
20
- message
21
- });
22
- }
23
- var AssertionError = class extends Error {
24
- constructor(options) {
25
- super(options.message);
26
- this.code = "ERR_ASSERTION";
27
- }
28
- };
29
- function assert(value, message = "Assertion failed.", ErrorWrapper = AssertionError) {
30
- if (!value) {
31
- if (message instanceof Error) {
32
- throw message;
33
- }
34
- throw getError(ErrorWrapper, message);
35
- }
36
- }
37
- function assertStruct(value, struct, errorPrefix = "Assertion failed", ErrorWrapper = AssertionError) {
38
- try {
39
- assertSuperstruct(value, struct);
40
- } catch (error) {
41
- throw getError(
42
- ErrorWrapper,
43
- `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`
44
- );
45
- }
46
- }
47
- function assertExhaustive(_object) {
48
- throw new Error(
49
- "Invalid branch reached. Should be detected during compilation."
50
- );
51
- }
52
-
53
- export {
54
- AssertionError,
55
- assert,
56
- assertStruct,
57
- assertExhaustive
58
- };
59
- //# sourceMappingURL=chunk-74DGVJVE.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/assert.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { assert as assertSuperstruct } from 'superstruct';\n\nimport { getErrorMessage } from './errors';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\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 * Attempts to obtain the message from a possible error object. If it is\n * possible to do so, any trailing period will be removed from the message;\n * otherwise an empty string is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The message without any trailing period if `error` is an object\n * with a `message` property; the string version of `error` without any trailing\n * period if it is not `undefined` or `null`; otherwise an empty string.\n */\nfunction getErrorMessageWithoutTrailingPeriod(error: unknown): string {\n // We'll add our own period.\n return getErrorMessage(error).replace(/\\.$/u, '');\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(\n ErrorWrapper,\n `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`,\n );\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"],"mappings":";;;;;AACA,SAAS,UAAU,yBAAyB;AAe5C,SAAS,gBACP,IACgD;AAEhD,SAAO,QAAQ,OAAO,IAAI,WAAW,aAAa,SAAS,QAAQ;AACrE;AAYA,SAAS,qCAAqC,OAAwB;AAEpE,SAAO,gBAAgB,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAClD;AAUA,SAAS,SAAS,cAAyC,SAAiB;AAC1E,MAAI,gBAAgB,YAAY,GAAG;AACjC,WAAO,IAAI,aAAa;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,aAAa;AAAA,IAClB;AAAA,EACF,CAAC;AACH;AAKO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAGxC,YAAY,SAA8B;AACxC,UAAM,QAAQ,OAAO;AAHvB,SAAS,OAAO;AAAA,EAIhB;AACF;AAcO,SAAS,OACd,OACA,UAA0B,qBAE1B,eAA0C,gBAC3B;AACf,MAAI,CAAC,OAAO;AACV,QAAI,mBAAmB,OAAO;AAC5B,YAAM;AAAA,IACR;AAEA,UAAM,SAAS,cAAc,OAAO;AAAA,EACtC;AACF;AAaO,SAAS,aACd,OACA,QACA,cAAc,oBAEd,eAA0C,gBACnB;AACvB,MAAI;AACF,sBAAkB,OAAO,MAAM;AAAA,EACjC,SAAS,OAAO;AACd,UAAM;AAAA,MACJ;AAAA,MACA,GAAG,WAAW,KAAK,qCAAqC,KAAK,CAAC;AAAA,IAChE;AAAA,EACF;AACF;AAqBO,SAAS,iBAAiB,SAAuB;AACtD,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- //# sourceMappingURL=chunk-AY6FDCBT.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,23 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/promise.ts
2
- function createDeferredPromise({
3
- suppressUnhandledRejection = false
4
- } = {}) {
5
- let resolve;
6
- let reject;
7
- const promise = new Promise(
8
- (innerResolve, innerReject) => {
9
- resolve = innerResolve;
10
- reject = innerReject;
11
- }
12
- );
13
- if (suppressUnhandledRejection) {
14
- promise.catch((_error) => {
15
- });
16
- }
17
- return { promise, resolve, reject };
18
- }
19
-
20
-
21
-
22
- exports.createDeferredPromise = createDeferredPromise;
23
- //# sourceMappingURL=chunk-C6HGFEYL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/promise.ts"],"names":[],"mappings":";AA0CO,SAAS,sBAAqC;AAAA,EACnD,6BAA6B;AAC/B,IAEI,CAAC,GAA4B;AAC/B,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,IAAI;AAAA,IAClB,CACE,cACA,gBACG;AACH,gBAAU;AACV,eAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI,4BAA4B;AAC9B,YAAQ,MAAM,CAAC,WAAW;AAAA,IAE1B,CAAC;AAAA,EACH;AAGA,SAAO,EAAE,SAAS,SAAS,OAAO;AACpC","sourcesContent":["/**\n * A deferred Promise.\n *\n * A deferred Promise is one that can be resolved or rejected independently of\n * the Promise construction.\n * @template Result - The result type of the Promise.\n */\nexport type DeferredPromise<Result = void> = {\n /**\n * The Promise that has been deferred.\n */\n promise: Promise<Result>;\n /**\n * A function that resolves the Promise.\n */\n resolve: (result: Result) => void;\n /**\n * A function that rejects the Promise.\n */\n reject: (error: unknown) => void;\n};\n\n/**\n * Create a defered Promise.\n *\n * If the Promise is rejected prior to a handler being added, this can result in an\n * `UnhandledPromiseRejection` error. Optionally this can be suppressed with the\n * `suppressUnhandledRejection` flag, as it's common to belatedly handle deferred Promises, or to\n * ignore them if they're no longer relevant (e.g. related to a cancelled request).\n *\n * However, be very careful that you have handled the Promise if you do this. Suppressing these\n * errors is dangerous, they exist for good reason. An unhandled rejection can hide errors, making\n * debugging extremely difficult. They should only be suppressed if you're confident that the\n * Promise is always handled correctly, in both the success and failure cases.\n *\n * @param args - The arguments.\n * @param args.suppressUnhandledRejection - This option adds an empty error handler\n * to the Promise to suppress the UnhandledPromiseRejection error. This can be\n * useful if the deferred Promise is sometimes intentionally not used.\n * @returns A deferred Promise.\n * @template Result - The result type of the Promise.\n */\nexport function createDeferredPromise<Result = void>({\n suppressUnhandledRejection = false,\n}: {\n suppressUnhandledRejection?: boolean;\n} = {}): DeferredPromise<Result> {\n let resolve: DeferredPromise<Result>['resolve'];\n let reject: DeferredPromise<Result>['reject'];\n const promise = new Promise<Result>(\n (\n innerResolve: DeferredPromise<Result>['resolve'],\n innerReject: DeferredPromise<Result>['reject'],\n ) => {\n resolve = innerResolve;\n reject = innerReject;\n },\n );\n\n if (suppressUnhandledRejection) {\n promise.catch((_error) => {\n // This handler is used to suppress the UnhandledPromiseRejection error\n });\n }\n\n // @ts-expect-error We know that these are assigned, but TypeScript doesn't\n return { promise, resolve, reject };\n}\n"]}
@@ -1,95 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
-
4
-
5
- var _chunkQEPVHEP7js = require('./chunk-QEPVHEP7.js');
6
-
7
-
8
- var _chunk6ZDHSOUVjs = require('./chunk-6ZDHSOUV.js');
9
-
10
- // src/coercers.ts
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
- var _superstruct = require('superstruct');
21
- var NumberLikeStruct = _superstruct.union.call(void 0, [_superstruct.number.call(void 0, ), _superstruct.bigint.call(void 0, ), _superstruct.string.call(void 0, ), _chunkQEPVHEP7js.StrictHexStruct]);
22
- var NumberCoercer = _superstruct.coerce.call(void 0, _superstruct.number.call(void 0, ), NumberLikeStruct, Number);
23
- var BigIntCoercer = _superstruct.coerce.call(void 0, _superstruct.bigint.call(void 0, ), NumberLikeStruct, BigInt);
24
- var BytesLikeStruct = _superstruct.union.call(void 0, [_chunkQEPVHEP7js.StrictHexStruct, _superstruct.instance.call(void 0, Uint8Array)]);
25
- var BytesCoercer = _superstruct.coerce.call(void 0,
26
- _superstruct.instance.call(void 0, Uint8Array),
27
- _superstruct.union.call(void 0, [_chunkQEPVHEP7js.StrictHexStruct]),
28
- _chunkQEPVHEP7js.hexToBytes
29
- );
30
- var HexCoercer = _superstruct.coerce.call(void 0, _chunkQEPVHEP7js.StrictHexStruct, _superstruct.instance.call(void 0, Uint8Array), _chunkQEPVHEP7js.bytesToHex);
31
- function createNumber(value) {
32
- try {
33
- const result = _superstruct.create.call(void 0, value, NumberCoercer);
34
- _chunk6ZDHSOUVjs.assert.call(void 0,
35
- Number.isFinite(result),
36
- `Expected a number-like value, got "${value}".`
37
- );
38
- return result;
39
- } catch (error) {
40
- if (error instanceof _superstruct.StructError) {
41
- throw new Error(`Expected a number-like value, got "${value}".`);
42
- }
43
- throw error;
44
- }
45
- }
46
- function createBigInt(value) {
47
- try {
48
- return _superstruct.create.call(void 0, value, BigIntCoercer);
49
- } catch (error) {
50
- if (error instanceof _superstruct.StructError) {
51
- throw new Error(
52
- `Expected a number-like value, got "${String(error.value)}".`
53
- );
54
- }
55
- throw error;
56
- }
57
- }
58
- function createBytes(value) {
59
- if (typeof value === "string" && value.toLowerCase() === "0x") {
60
- return new Uint8Array();
61
- }
62
- try {
63
- return _superstruct.create.call(void 0, value, BytesCoercer);
64
- } catch (error) {
65
- if (error instanceof _superstruct.StructError) {
66
- throw new Error(
67
- `Expected a bytes-like value, got "${String(error.value)}".`
68
- );
69
- }
70
- throw error;
71
- }
72
- }
73
- function createHex(value) {
74
- if (value instanceof Uint8Array && value.length === 0 || typeof value === "string" && value.toLowerCase() === "0x") {
75
- return "0x";
76
- }
77
- try {
78
- return _superstruct.create.call(void 0, value, HexCoercer);
79
- } catch (error) {
80
- if (error instanceof _superstruct.StructError) {
81
- throw new Error(
82
- `Expected a bytes-like value, got "${String(error.value)}".`
83
- );
84
- }
85
- throw error;
86
- }
87
- }
88
-
89
-
90
-
91
-
92
-
93
-
94
- exports.createNumber = createNumber; exports.createBigInt = createBigInt; exports.createBytes = createBytes; exports.createHex = createHex;
95
- //# sourceMappingURL=chunk-DHVKFDHQ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/coercers.ts"],"names":[],"mappings":";;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,IAAM,mBAAmB,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,eAAe,CAAC;AAC9E,IAAM,gBAAgB,OAAO,OAAO,GAAG,kBAAkB,MAAM;AAC/D,IAAM,gBAAgB,OAAO,OAAO,GAAG,kBAAkB,MAAM;AAE/D,IAAM,kBAAkB,MAAM,CAAC,iBAAiB,SAAS,UAAU,CAAC,CAAC;AACrE,IAAM,eAAe;AAAA,EACnB,SAAS,UAAU;AAAA,EACnB,MAAM,CAAC,eAAe,CAAC;AAAA,EACvB;AACF;AAEA,IAAM,aAAa,OAAO,iBAAiB,SAAS,UAAU,GAAG,UAAU;AA8BpE,SAAS,aAAa,OAA2B;AACtD,MAAI;AACF,UAAM,SAAS,OAAO,OAAO,aAAa;AAE1C;AAAA,MACE,OAAO,SAAS,MAAM;AAAA,MACtB,sCAAsC,KAAK;AAAA,IAC7C;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,IAAI,MAAM,sCAAsC,KAAK,IAAI;AAAA,IACjE;AAGA,UAAM;AAAA,EACR;AACF;AAwBO,SAAS,aAAa,OAA2B;AACtD,MAAI;AAGF,WAAO,OAAO,OAAO,aAAa;AAAA,EACpC,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,IAAI;AAAA,QACR,sCAAsC,OAAO,MAAM,KAAK,CAAC;AAAA,MAC3D;AAAA,IACF;AAGA,UAAM;AAAA,EACR;AACF;AAqBO,SAAS,YAAY,OAA8B;AACxD,MAAI,OAAO,UAAU,YAAY,MAAM,YAAY,MAAM,MAAM;AAC7D,WAAO,IAAI,WAAW;AAAA,EACxB;AAEA,MAAI;AACF,WAAO,OAAO,OAAO,YAAY;AAAA,EACnC,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,IAAI;AAAA,QACR,qCAAqC,OAAO,MAAM,KAAK,CAAC;AAAA,MAC1D;AAAA,IACF;AAGA,UAAM;AAAA,EACR;AACF;AAqBO,SAAS,UAAU,OAAuB;AAC/C,MACG,iBAAiB,cAAc,MAAM,WAAW,KAChD,OAAO,UAAU,YAAY,MAAM,YAAY,MAAM,MACtD;AACA,WAAO;AAAA,EACT;AAEA,MAAI;AACF,WAAO,OAAO,OAAO,UAAU;AAAA,EACjC,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,IAAI;AAAA,QACR,qCAAqC,OAAO,MAAM,KAAK,CAAC;AAAA,MAC1D;AAAA,IACF;AAGA,UAAM;AAAA,EACR;AACF","sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n bigint,\n coerce,\n create,\n instance,\n number,\n string,\n StructError,\n union,\n} from 'superstruct';\n\nimport { assert } from './assert';\nimport { bytesToHex, hexToBytes } from './bytes';\nimport type { Hex } from './hex';\nimport { StrictHexStruct } from './hex';\n\nconst NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);\nconst NumberCoercer = coerce(number(), NumberLikeStruct, Number);\nconst BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);\n\nconst BytesLikeStruct = union([StrictHexStruct, instance(Uint8Array)]);\nconst BytesCoercer = coerce(\n instance(Uint8Array),\n union([StrictHexStruct]),\n hexToBytes,\n);\n\nconst HexCoercer = coerce(StrictHexStruct, instance(Uint8Array), bytesToHex);\n\nexport type NumberLike = Infer<typeof NumberLikeStruct>;\nexport type BytesLike = Infer<typeof BytesLikeStruct>;\n\n/**\n * Create a number from a number-like value.\n *\n * - If the value is a number, it is returned as-is.\n * - If the value is a `bigint`, it is converted to a number.\n * - If the value is a string, it is interpreted as a decimal number.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number.\n *\n * This validates that the value is a number-like value, and that the resulting\n * number is not `NaN` or `Infinity`.\n *\n * @example\n * ```typescript\n * const value = createNumber('0x010203');\n * console.log(value); // 66051\n *\n * const otherValue = createNumber(123n);\n * console.log(otherValue); // 123\n * ```\n * @param value - The value to create the number from.\n * @returns The created number.\n * @throws If the value is not a number-like value, or if the resulting number\n * is `NaN` or `Infinity`.\n */\nexport function createNumber(value: NumberLike): number {\n try {\n const result = create(value, NumberCoercer);\n\n assert(\n Number.isFinite(result),\n `Expected a number-like value, got \"${value}\".`,\n );\n\n return result;\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(`Expected a number-like value, got \"${value}\".`);\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a `bigint` from a number-like value.\n *\n * - If the value is a number, it is converted to a `bigint`.\n * - If the value is a `bigint`, it is returned as-is.\n * - If the value is a string, it is interpreted as a decimal number and\n * converted to a `bigint`.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number and converted to a `bigint`.\n *\n * @example\n * ```typescript\n * const value = createBigInt('0x010203');\n * console.log(value); // 16909060n\n *\n * const otherValue = createBigInt(123);\n * console.log(otherValue); // 123n\n * ```\n * @param value - The value to create the bigint from.\n * @returns The created bigint.\n * @throws If the value is not a number-like value.\n */\nexport function createBigInt(value: NumberLike): bigint {\n try {\n // The `BigInt` constructor throws if the value is not a number-like value.\n // There is no need to validate the value manually.\n return create(value, BigIntCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a number-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a byte array from a bytes-like value.\n *\n * - If the value is a byte array, it is returned as-is.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is interpreted\n * as a hexadecimal number and converted to a byte array.\n *\n * @example\n * ```typescript\n * const value = createBytes('0x010203');\n * console.log(value); // Uint8Array [ 1, 2, 3 ]\n *\n * const otherValue = createBytes('0x010203');\n * console.log(otherValue); // Uint8Array [ 1, 2, 3 ]\n * ```\n * @param value - The value to create the byte array from.\n * @returns The created byte array.\n * @throws If the value is not a bytes-like value.\n */\nexport function createBytes(value: BytesLike): Uint8Array {\n if (typeof value === 'string' && value.toLowerCase() === '0x') {\n return new Uint8Array();\n }\n\n try {\n return create(value, BytesCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a hexadecimal string from a bytes-like value.\n *\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is returned\n * as-is.\n * - If the value is a `Uint8Array`, it is converted to a hex string.\n *\n * @example\n * ```typescript\n * const value = createHex(new Uint8Array([1, 2, 3]));\n * console.log(value); // '0x010203'\n *\n * const otherValue = createHex('0x010203');\n * console.log(otherValue); // '0x010203'\n * ```\n * @param value - The value to create the hex string from.\n * @returns The created hex string.\n * @throws If the value is not a bytes-like value.\n */\nexport function createHex(value: BytesLike): Hex {\n if (\n (value instanceof Uint8Array && value.length === 0) ||\n (typeof value === 'string' && value.toLowerCase() === '0x')\n ) {\n return '0x';\n }\n\n try {\n return create(value, HexCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n"]}