@aztec/foundation 0.0.1-commit.179ed20 → 0.0.1-commit.189eedb3

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 (307) hide show
  1. package/dest/array/sorted_array.d.ts +6 -1
  2. package/dest/array/sorted_array.d.ts.map +1 -1
  3. package/dest/array/sorted_array.js +18 -15
  4. package/dest/bigint-buffer/index.d.ts +1 -1
  5. package/dest/bigint-buffer/index.d.ts.map +1 -1
  6. package/dest/bigint-buffer/index.js +6 -1
  7. package/dest/branded-types/block_number.d.ts +3 -3
  8. package/dest/branded-types/block_number.d.ts.map +1 -1
  9. package/dest/branded-types/block_number.js +15 -4
  10. package/dest/branded-types/buffer32_hash.d.ts +27 -0
  11. package/dest/branded-types/buffer32_hash.d.ts.map +1 -0
  12. package/dest/branded-types/buffer32_hash.js +12 -0
  13. package/dest/branded-types/checkpoint_number.d.ts +9 -3
  14. package/dest/branded-types/checkpoint_number.d.ts.map +1 -1
  15. package/dest/branded-types/checkpoint_number.js +11 -0
  16. package/dest/branded-types/epoch.d.ts +2 -2
  17. package/dest/branded-types/epoch.d.ts.map +1 -1
  18. package/dest/branded-types/index.d.ts +2 -1
  19. package/dest/branded-types/index.d.ts.map +1 -1
  20. package/dest/branded-types/index.js +1 -0
  21. package/dest/branded-types/index_within_checkpoint.d.ts +2 -2
  22. package/dest/branded-types/index_within_checkpoint.d.ts.map +1 -1
  23. package/dest/branded-types/slot.d.ts +5 -2
  24. package/dest/branded-types/slot.d.ts.map +1 -1
  25. package/dest/branded-types/slot.js +3 -0
  26. package/dest/buffer/buffer16.d.ts +3 -1
  27. package/dest/buffer/buffer16.d.ts.map +1 -1
  28. package/dest/buffer/buffer32.d.ts +28 -61
  29. package/dest/buffer/buffer32.d.ts.map +1 -1
  30. package/dest/buffer/buffer32.js +29 -63
  31. package/dest/buffer/index.d.ts +2 -1
  32. package/dest/buffer/index.d.ts.map +1 -1
  33. package/dest/buffer/index.js +1 -0
  34. package/dest/buffer/utils.d.ts +3 -0
  35. package/dest/buffer/utils.d.ts.map +1 -0
  36. package/dest/buffer/utils.js +7 -0
  37. package/dest/collection/array.d.ts +11 -1
  38. package/dest/collection/array.d.ts.map +1 -1
  39. package/dest/collection/array.js +33 -0
  40. package/dest/collection/index.d.ts +3 -1
  41. package/dest/collection/index.d.ts.map +1 -1
  42. package/dest/collection/index.js +2 -0
  43. package/dest/collection/lru_map.d.ts +41 -0
  44. package/dest/collection/lru_map.d.ts.map +1 -0
  45. package/dest/collection/lru_map.js +119 -0
  46. package/dest/collection/lru_set.d.ts +35 -0
  47. package/dest/collection/lru_set.d.ts.map +1 -0
  48. package/dest/collection/lru_set.js +95 -0
  49. package/dest/committable/committable.js +1 -1
  50. package/dest/config/env_var.d.ts +2 -2
  51. package/dest/config/env_var.d.ts.map +1 -1
  52. package/dest/config/index.d.ts +47 -30
  53. package/dest/config/index.d.ts.map +1 -1
  54. package/dest/config/index.js +44 -44
  55. package/dest/config/network_config.d.ts +15 -41
  56. package/dest/config/network_config.d.ts.map +1 -1
  57. package/dest/config/network_config.js +4 -1
  58. package/dest/config/network_name.d.ts +2 -2
  59. package/dest/config/network_name.d.ts.map +1 -1
  60. package/dest/config/network_name.js +3 -3
  61. package/dest/config/secret_value.d.ts +2 -2
  62. package/dest/config/secret_value.d.ts.map +1 -1
  63. package/dest/crypto/aes128/index.d.ts +2 -1
  64. package/dest/crypto/aes128/index.d.ts.map +1 -1
  65. package/dest/crypto/aes128/index.js +11 -2
  66. package/dest/crypto/bls/bn254_keystore.d.ts +9 -176
  67. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  68. package/dest/crypto/bls/bn254_keystore.js +0 -17
  69. package/dest/crypto/poseidon/index.d.ts +1 -1
  70. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  71. package/dest/crypto/poseidon/index.js +40 -33
  72. package/dest/crypto/schnorr/index.d.ts +8 -7
  73. package/dest/crypto/schnorr/index.d.ts.map +1 -1
  74. package/dest/crypto/schnorr/index.js +6 -6
  75. package/dest/crypto/schnorr/signature.d.ts +9 -29
  76. package/dest/crypto/schnorr/signature.d.ts.map +1 -1
  77. package/dest/crypto/schnorr/signature.js +20 -36
  78. package/dest/crypto/secp256k1-signer/utils.d.ts +12 -1
  79. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -1
  80. package/dest/crypto/secp256k1-signer/utils.js +26 -0
  81. package/dest/curves/bls12/field.d.ts +3 -3
  82. package/dest/curves/bls12/field.d.ts.map +1 -1
  83. package/dest/curves/bls12/field.js +0 -5
  84. package/dest/curves/bls12/point.d.ts +2 -2
  85. package/dest/curves/bls12/point.d.ts.map +1 -1
  86. package/dest/curves/bn254/field.d.ts +24 -19
  87. package/dest/curves/bn254/field.d.ts.map +1 -1
  88. package/dest/curves/bn254/field.js +28 -19
  89. package/dest/curves/grumpkin/point.d.ts +14 -28
  90. package/dest/curves/grumpkin/point.d.ts.map +1 -1
  91. package/dest/curves/grumpkin/point.js +29 -43
  92. package/dest/eth-address/index.d.ts +2 -2
  93. package/dest/eth-address/index.d.ts.map +1 -1
  94. package/dest/eth-address/index.js +0 -3
  95. package/dest/eth-signature/eth_signature.d.ts +3 -2
  96. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  97. package/dest/eth-signature/eth_signature.js +7 -2
  98. package/dest/fifo/fifo_frame_reader.d.ts +41 -0
  99. package/dest/fifo/fifo_frame_reader.d.ts.map +1 -0
  100. package/dest/fifo/fifo_frame_reader.js +91 -0
  101. package/dest/fifo/index.d.ts +2 -0
  102. package/dest/fifo/index.d.ts.map +1 -0
  103. package/dest/fifo/index.js +1 -0
  104. package/dest/fifo_set/fifo_set.d.ts +15 -0
  105. package/dest/fifo_set/fifo_set.d.ts.map +1 -0
  106. package/dest/fifo_set/fifo_set.js +39 -0
  107. package/dest/fifo_set/index.d.ts +2 -0
  108. package/dest/fifo_set/index.d.ts.map +1 -0
  109. package/dest/fifo_set/index.js +1 -0
  110. package/dest/jest/setup.js +24 -0
  111. package/dest/json-rpc/client/fetch.d.ts +1 -1
  112. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  113. package/dest/json-rpc/client/fetch.js +4 -3
  114. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +2 -1
  115. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  116. package/dest/json-rpc/client/safe_json_rpc_client.js +3 -3
  117. package/dest/json-rpc/client/undici.d.ts +1 -1
  118. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  119. package/dest/json-rpc/client/undici.js +5 -3
  120. package/dest/json-rpc/fixtures/test_state.d.ts +4 -8
  121. package/dest/json-rpc/fixtures/test_state.d.ts.map +1 -1
  122. package/dest/json-rpc/fixtures/test_state.js +57 -17
  123. package/dest/json-rpc/server/api_key_auth.d.ts +19 -0
  124. package/dest/json-rpc/server/api_key_auth.d.ts.map +1 -0
  125. package/dest/json-rpc/server/api_key_auth.js +57 -0
  126. package/dest/json-rpc/server/index.d.ts +2 -1
  127. package/dest/json-rpc/server/index.d.ts.map +1 -1
  128. package/dest/json-rpc/server/index.js +1 -0
  129. package/dest/json-rpc/server/safe_json_rpc_server.d.ts +8 -3
  130. package/dest/json-rpc/server/safe_json_rpc_server.d.ts.map +1 -1
  131. package/dest/json-rpc/server/safe_json_rpc_server.js +27 -13
  132. package/dest/log/bigint-utils.d.ts +5 -0
  133. package/dest/log/bigint-utils.d.ts.map +1 -0
  134. package/dest/log/bigint-utils.js +21 -0
  135. package/dest/log/gcloud-logger-config.d.ts +1 -1
  136. package/dest/log/gcloud-logger-config.d.ts.map +1 -1
  137. package/dest/log/gcloud-logger-config.js +3 -0
  138. package/dest/log/log-filters.d.ts +17 -4
  139. package/dest/log/log-filters.d.ts.map +1 -1
  140. package/dest/log/log-filters.js +26 -12
  141. package/dest/log/pino-logger.d.ts +1 -1
  142. package/dest/log/pino-logger.d.ts.map +1 -1
  143. package/dest/log/pino-logger.js +23 -4
  144. package/dest/noir/noir_package_config.d.ts +19 -104
  145. package/dest/noir/noir_package_config.d.ts.map +1 -1
  146. package/dest/noir/noir_package_config.js +1 -1
  147. package/dest/queue/base_memory_queue.d.ts +2 -2
  148. package/dest/queue/base_memory_queue.d.ts.map +1 -1
  149. package/dest/queue/batch_queue.d.ts +1 -1
  150. package/dest/queue/batch_queue.d.ts.map +1 -1
  151. package/dest/queue/batch_queue.js +1 -0
  152. package/dest/retry/index.d.ts +12 -1
  153. package/dest/retry/index.d.ts.map +1 -1
  154. package/dest/retry/index.js +21 -0
  155. package/dest/schemas/api.d.ts +12 -10
  156. package/dest/schemas/api.d.ts.map +1 -1
  157. package/dest/schemas/api.js +7 -1
  158. package/dest/schemas/parse.d.ts +4 -4
  159. package/dest/schemas/parse.d.ts.map +1 -1
  160. package/dest/schemas/parse.js +6 -5
  161. package/dest/schemas/schemas.d.ts +15 -15
  162. package/dest/schemas/types.d.ts +3 -3
  163. package/dest/schemas/types.d.ts.map +1 -1
  164. package/dest/schemas/utils.d.ts +7 -11
  165. package/dest/schemas/utils.d.ts.map +1 -1
  166. package/dest/schemas/utils.js +2 -18
  167. package/dest/serialize/buffer_reader.d.ts +8 -1
  168. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  169. package/dest/serialize/buffer_reader.js +13 -0
  170. package/dest/serialize/buffer_sink.d.ts +134 -0
  171. package/dest/serialize/buffer_sink.d.ts.map +1 -0
  172. package/dest/serialize/buffer_sink.js +297 -0
  173. package/dest/serialize/index.d.ts +2 -1
  174. package/dest/serialize/index.d.ts.map +1 -1
  175. package/dest/serialize/index.js +1 -0
  176. package/dest/serialize/serialize.d.ts +19 -1
  177. package/dest/serialize/serialize.d.ts.map +1 -1
  178. package/dest/serialize/serialize.js +31 -0
  179. package/dest/sleep/index.d.ts +2 -1
  180. package/dest/sleep/index.d.ts.map +1 -1
  181. package/dest/sleep/index.js +10 -1
  182. package/dest/string/index.js +1 -1
  183. package/dest/timer/date.d.ts +25 -1
  184. package/dest/timer/date.d.ts.map +1 -1
  185. package/dest/timer/date.js +33 -0
  186. package/dest/timer/index.d.ts +2 -2
  187. package/dest/timer/index.d.ts.map +1 -1
  188. package/dest/timer/index.js +1 -1
  189. package/dest/timer/timeout.d.ts +3 -1
  190. package/dest/timer/timeout.d.ts.map +1 -1
  191. package/dest/timer/timeout.js +26 -0
  192. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  193. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  194. package/dest/transport/index.d.ts +1 -2
  195. package/dest/transport/index.d.ts.map +1 -1
  196. package/dest/transport/index.js +0 -1
  197. package/dest/transport/transport_client.js +2 -2
  198. package/dest/trees/balanced_merkle_tree_root.d.ts +2 -3
  199. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -1
  200. package/dest/trees/balanced_merkle_tree_root.js +2 -3
  201. package/dest/trees/hasher.d.ts +3 -2
  202. package/dest/trees/hasher.d.ts.map +1 -1
  203. package/dest/trees/hasher.js +5 -5
  204. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  205. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  206. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  207. package/dest/trees/membership_witness.d.ts +2 -2
  208. package/dest/trees/membership_witness.d.ts.map +1 -1
  209. package/dest/trees/merkle_tree_calculator.d.ts +4 -2
  210. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  211. package/dest/trees/merkle_tree_calculator.js +1 -5
  212. package/dest/trees/sibling_path.d.ts +5 -4
  213. package/dest/trees/sibling_path.d.ts.map +1 -1
  214. package/dest/trees/sibling_path.js +10 -8
  215. package/dest/trees/unbalanced_merkle_tree_root.d.ts +2 -3
  216. package/dest/trees/unbalanced_merkle_tree_root.d.ts.map +1 -1
  217. package/dest/trees/unbalanced_merkle_tree_root.js +2 -3
  218. package/dest/types/index.d.ts +23 -1
  219. package/dest/types/index.d.ts.map +1 -1
  220. package/dest/types/index.js +15 -0
  221. package/package.json +26 -4
  222. package/src/array/sorted_array.ts +22 -17
  223. package/src/bigint-buffer/index.ts +6 -1
  224. package/src/branded-types/block_number.ts +20 -2
  225. package/src/branded-types/buffer32_hash.ts +38 -0
  226. package/src/branded-types/checkpoint_number.ts +16 -1
  227. package/src/branded-types/epoch.ts +1 -1
  228. package/src/branded-types/index.ts +1 -0
  229. package/src/branded-types/index_within_checkpoint.ts +1 -1
  230. package/src/branded-types/slot.ts +6 -1
  231. package/src/buffer/buffer16.ts +3 -0
  232. package/src/buffer/buffer32.ts +39 -68
  233. package/src/buffer/index.ts +1 -0
  234. package/src/buffer/utils.ts +8 -0
  235. package/src/collection/array.ts +34 -0
  236. package/src/collection/index.ts +2 -0
  237. package/src/collection/lru_map.ts +143 -0
  238. package/src/collection/lru_set.ts +115 -0
  239. package/src/committable/committable.ts +1 -1
  240. package/src/config/env_var.ts +69 -22
  241. package/src/config/index.ts +116 -96
  242. package/src/config/network_config.ts +3 -0
  243. package/src/config/network_name.ts +6 -6
  244. package/src/config/secret_value.ts +1 -1
  245. package/src/crypto/aes128/index.ts +11 -2
  246. package/src/crypto/bls/bn254_keystore.ts +0 -23
  247. package/src/crypto/poseidon/index.ts +42 -34
  248. package/src/crypto/schnorr/index.ts +9 -8
  249. package/src/crypto/schnorr/signature.ts +17 -46
  250. package/src/crypto/secp256k1-signer/utils.ts +32 -0
  251. package/src/curves/bls12/field.ts +0 -7
  252. package/src/curves/bn254/field.ts +41 -36
  253. package/src/curves/grumpkin/point.ts +23 -40
  254. package/src/eth-address/index.ts +0 -4
  255. package/src/eth-signature/eth_signature.ts +7 -1
  256. package/src/fifo/fifo_frame_reader.ts +113 -0
  257. package/src/fifo/index.ts +1 -0
  258. package/src/fifo_set/fifo_set.ts +52 -0
  259. package/src/fifo_set/index.ts +1 -0
  260. package/src/jest/setup.mjs +27 -0
  261. package/src/json-rpc/client/fetch.ts +4 -3
  262. package/src/json-rpc/client/safe_json_rpc_client.ts +4 -2
  263. package/src/json-rpc/client/undici.ts +5 -3
  264. package/src/json-rpc/fixtures/test_state.ts +10 -10
  265. package/src/json-rpc/server/api_key_auth.ts +63 -0
  266. package/src/json-rpc/server/index.ts +1 -0
  267. package/src/json-rpc/server/safe_json_rpc_server.ts +31 -13
  268. package/src/log/bigint-utils.ts +25 -0
  269. package/src/log/gcloud-logger-config.ts +5 -0
  270. package/src/log/log-filters.ts +29 -11
  271. package/src/log/pino-logger.ts +25 -4
  272. package/src/noir/noir_package_config.ts +32 -20
  273. package/src/queue/base_memory_queue.ts +1 -1
  274. package/src/queue/batch_queue.ts +1 -0
  275. package/src/retry/index.ts +30 -0
  276. package/src/schemas/api.ts +25 -25
  277. package/src/schemas/parse.ts +9 -6
  278. package/src/schemas/schemas.ts +4 -4
  279. package/src/schemas/types.ts +2 -2
  280. package/src/schemas/utils.ts +4 -38
  281. package/src/serialize/buffer_reader.ts +15 -0
  282. package/src/serialize/buffer_sink.ts +350 -0
  283. package/src/serialize/index.ts +1 -0
  284. package/src/serialize/serialize.ts +32 -0
  285. package/src/sleep/index.ts +10 -1
  286. package/src/string/index.ts +1 -1
  287. package/src/timer/date.ts +48 -0
  288. package/src/timer/index.ts +1 -1
  289. package/src/timer/timeout.ts +31 -0
  290. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  291. package/src/transport/index.ts +0 -1
  292. package/src/transport/transport_client.ts +2 -2
  293. package/src/trees/balanced_merkle_tree_root.ts +2 -5
  294. package/src/trees/hasher.ts +6 -3
  295. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
  296. package/src/trees/merkle_tree_calculator.ts +4 -10
  297. package/src/trees/sibling_path.ts +11 -6
  298. package/src/trees/unbalanced_merkle_tree_root.ts +2 -5
  299. package/src/types/index.ts +47 -0
  300. package/dest/crypto/serialize.d.ts +0 -51
  301. package/dest/crypto/serialize.d.ts.map +0 -1
  302. package/dest/crypto/serialize.js +0 -68
  303. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  304. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  305. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  306. package/src/crypto/serialize.ts +0 -85
  307. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -10,3 +10,30 @@ import pretty from 'pino-pretty';
10
10
  if (!parseBooleanEnv(process.env.LOG_JSON)) {
11
11
  overwriteLoggingStream(pretty(pinoPrettyOpts));
12
12
  }
13
+
14
+ // Prevent timers from keeping the process alive after tests complete.
15
+ // Libraries like viem create internal polling loops (via setTimeout) that
16
+ // reschedule themselves indefinitely. In test environments we never want a
17
+ // timer to be the reason the process can't exit. We also unref stdout/stderr
18
+ // which, when they are pipes (as in Jest workers), remain ref'd by default.
19
+ {
20
+ const origSetTimeout = globalThis.setTimeout;
21
+ const origSetInterval = globalThis.setInterval;
22
+ globalThis.setTimeout = function unrefSetTimeout(...args) {
23
+ const id = origSetTimeout.apply(this, args);
24
+ id?.unref?.();
25
+ return id;
26
+ };
27
+ // Preserve .unref, .__promisify__ etc. that may exist on the original
28
+ Object.setPrototypeOf(globalThis.setTimeout, origSetTimeout);
29
+
30
+ globalThis.setInterval = function unrefSetInterval(...args) {
31
+ const id = origSetInterval.apply(this, args);
32
+ id?.unref?.();
33
+ return id;
34
+ };
35
+ Object.setPrototypeOf(globalThis.setInterval, origSetInterval);
36
+
37
+ if (process.stdout?._handle?.unref) process.stdout._handle.unref();
38
+ if (process.stderr?._handle?.unref) process.stderr._handle.unref();
39
+ }
@@ -43,17 +43,18 @@ export async function defaultFetch(
43
43
  }
44
44
 
45
45
  let responseJson;
46
+ const responseText = await resp.text();
46
47
  try {
47
- responseJson = await resp.json();
48
+ responseJson = JSON.parse(responseText);
48
49
  } catch {
49
50
  if (!resp.ok) {
50
51
  throw new Error(resp.statusText);
51
52
  }
52
- throw new Error(`Failed to parse body as JSON: ${await resp.text()}`);
53
+ throw new Error(`Failed to parse body as JSON: ${responseText}`);
53
54
  }
54
55
 
55
56
  if (!resp.ok) {
56
- const errorMessage = `Error ${resp.status} from server ${host}: ${responseJson.error.message}`;
57
+ const errorMessage = `Error ${resp.status} from server ${host}: ${responseJson?.error?.message ?? JSON.stringify(responseJson)}`;
57
58
  if (noRetry || (resp.status >= 400 && resp.status < 500)) {
58
59
  throw new NoRetryError(errorMessage);
59
60
  } else {
@@ -2,7 +2,7 @@ import { format } from 'util';
2
2
 
3
3
  import { type Logger, createLogger } from '../../log/pino-logger.js';
4
4
  import { type PromiseWithResolvers, promiseWithResolvers } from '../../promise/utils.js';
5
- import { type ApiSchema, type ApiSchemaFor, schemaHasMethod } from '../../schemas/api.js';
5
+ import { type ApiSchema, type ApiSchemaFor, getSchemaReturnType, schemaHasMethod } from '../../schemas/api.js';
6
6
  import { jsonStringify } from '../convert.js';
7
7
  import { type JsonRpcFetch, defaultFetch } from './fetch.js';
8
8
 
@@ -24,6 +24,7 @@ export type SafeJsonRpcClientOptions = {
24
24
  batchWindowMS?: number;
25
25
  maxBatchSize?: number;
26
26
  maxRequestBodySize?: number;
27
+ extraHeaders?: Record<string, string>;
27
28
  onResponse?: (res: {
28
29
  response: any;
29
30
  headers: { get: (header: string) => string | null | undefined };
@@ -129,6 +130,7 @@ export function createSafeJsonRpcClient<T extends object>(
129
130
  const { response, headers } = await fetch(
130
131
  host,
131
132
  rpcCalls.map(({ request }) => request),
133
+ config.extraHeaders,
132
134
  );
133
135
 
134
136
  if (config.onResponse) {
@@ -234,7 +236,7 @@ export function createSafeJsonRpcClient<T extends object>(
234
236
  if ([null, undefined, 'null', 'undefined'].includes(response.result)) {
235
237
  return;
236
238
  }
237
- return (schema as ApiSchema)[methodName].returnType().parseAsync(response.result);
239
+ return getSchemaReturnType((schema as ApiSchema)[methodName]).parseAsync(response.result);
238
240
  };
239
241
 
240
242
  const clientId = nextClientId++;
@@ -44,18 +44,20 @@ export function makeUndiciFetch(client = new Agent()): JsonRpcFetch {
44
44
  let responseJson: any;
45
45
  const responseOk = resp.statusCode >= 200 && resp.statusCode <= 299;
46
46
  const contentEncoding = resp.headers['content-encoding'];
47
+ let responseText: string;
47
48
  try {
48
49
  if (contentEncoding === 'gzip') {
49
50
  const jsonBuffer = await gunzip(await resp.body.arrayBuffer());
50
- responseJson = JSON.parse(jsonBuffer.toString('utf-8'));
51
+ responseText = jsonBuffer.toString('utf-8');
51
52
  } else {
52
- responseJson = await resp.body.json();
53
+ responseText = await resp.body.text();
53
54
  }
55
+ responseJson = JSON.parse(responseText);
54
56
  } catch {
55
57
  if (!responseOk) {
56
58
  throw new Error('HTTP ' + resp.statusCode);
57
59
  }
58
- throw new Error(`Failed to parse body as JSON. encoding: ${contentEncoding}, body: ${await resp.body.text()}`);
60
+ throw new Error(`Failed to parse body as JSON. encoding: ${contentEncoding}, body: ${responseText!}`);
59
61
  }
60
62
 
61
63
  if (!responseOk) {
@@ -130,14 +130,14 @@ export class TestState implements TestStateApi {
130
130
  }
131
131
 
132
132
  export const TestStateSchema: ApiSchemaFor<TestStateApi> = {
133
- getNote: z.function().args(z.number()).returns(TestNote.schema.optional()),
134
- getNotes: z.function().args(optional(schemas.Integer)).returns(z.array(TestNote.schema)),
135
- getNotes2: z.function().args(optional(schemas.BigInt)).returns(z.array(TestNote.schema)),
136
- getNotes3: z.function().args(optional(schemas.Integer)).returns(z.array(TestNote.schema)),
137
- clear: z.function().returns(z.void()),
138
- addNotes: z.function().args(z.array(TestNote.schema)).returns(z.array(TestNote.schema)),
139
- fail: z.function().returns(z.void()),
140
- count: z.function().returns(z.number()),
141
- getStatus: z.function().returns(z.object({ status: z.string(), count: schemas.BigInt })),
142
- getTuple: z.function().returns(z.tuple([z.string(), optional(z.string()), z.number()])),
133
+ getNote: z.function({ input: z.tuple([z.number()]), output: TestNote.schema.optional() }),
134
+ getNotes: z.function({ input: z.tuple([optional(schemas.Integer)]), output: z.array(TestNote.schema) }),
135
+ getNotes2: z.function({ input: z.tuple([optional(schemas.BigInt)]), output: z.array(TestNote.schema) }),
136
+ getNotes3: z.function({ input: z.tuple([optional(schemas.Integer)]), output: z.array(TestNote.schema) }),
137
+ clear: z.function({ input: z.tuple([]), output: z.void() }),
138
+ addNotes: z.function({ input: z.tuple([z.array(TestNote.schema)]), output: z.array(TestNote.schema) }),
139
+ fail: z.function({ input: z.tuple([]), output: z.void() }),
140
+ count: z.function({ input: z.tuple([]), output: z.number() }),
141
+ getStatus: z.function({ input: z.tuple([]), output: z.object({ status: z.string(), count: schemas.BigInt }) }),
142
+ getTuple: z.function({ input: z.tuple([]), output: z.tuple([z.string(), optional(z.string()), z.number()]) }),
143
143
  };
@@ -0,0 +1,63 @@
1
+ import { timingSafeEqual } from 'crypto';
2
+ import type Koa from 'koa';
3
+
4
+ import { sha256 } from '../../crypto/sha256/index.js';
5
+ import { createLogger } from '../../log/index.js';
6
+
7
+ const log = createLogger('json-rpc:api-key-auth');
8
+
9
+ /**
10
+ * Computes the SHA-256 hash of a string and returns it as a Buffer.
11
+ * @param input - The input string to hash.
12
+ * @returns The SHA-256 hash as a Buffer.
13
+ */
14
+ export function sha256Hash(input: string): Buffer {
15
+ return sha256(Buffer.from(input));
16
+ }
17
+
18
+ /**
19
+ * Creates a Koa middleware that enforces API key authentication on all requests
20
+ * except the health check endpoint (GET /status).
21
+ *
22
+ * The API key can be provided via the `x-api-key` header or the `Authorization: Bearer <key>` header.
23
+ * Comparison is done by hashing the provided key with SHA-256 and comparing against the stored hash.
24
+ *
25
+ * @param apiKeyHash - The SHA-256 hash of the expected API key as a Buffer.
26
+ * @returns A Koa middleware that rejects requests without a valid API key.
27
+ */
28
+ export function getApiKeyAuthMiddleware(
29
+ apiKeyHash: Buffer,
30
+ ): (ctx: Koa.Context, next: () => Promise<void>) => Promise<void> {
31
+ return async (ctx: Koa.Context, next: () => Promise<void>) => {
32
+ // Allow health check through without auth
33
+ if (ctx.path === '/status' && ctx.method === 'GET') {
34
+ return next();
35
+ }
36
+
37
+ const providedKey = ctx.get('x-api-key') || ctx.get('authorization')?.replace(/^Bearer\s+/i, '');
38
+ if (!providedKey) {
39
+ log.warn(`Rejected admin RPC request from ${ctx.ip}: missing API key`);
40
+ ctx.status = 401;
41
+ ctx.body = {
42
+ jsonrpc: '2.0',
43
+ id: null,
44
+ error: { code: -32000, message: 'Unauthorized: invalid or missing API key' },
45
+ };
46
+ return;
47
+ }
48
+
49
+ const providedHashBuf = sha256Hash(providedKey);
50
+ if (!timingSafeEqual(apiKeyHash, providedHashBuf)) {
51
+ log.warn(`Rejected admin RPC request from ${ctx.ip}: invalid API key`);
52
+ ctx.status = 401;
53
+ ctx.body = {
54
+ jsonrpc: '2.0',
55
+ id: null,
56
+ error: { code: -32000, message: 'Unauthorized: invalid or missing API key' },
57
+ };
58
+ return;
59
+ }
60
+
61
+ await next();
62
+ };
63
+ }
@@ -1 +1,2 @@
1
+ export * from './api_key_auth.js';
1
2
  export * from './safe_json_rpc_server.js';
@@ -10,7 +10,13 @@ import { ZodError } from 'zod';
10
10
 
11
11
  import { type Logger, createLogger } from '../../log/index.js';
12
12
  import { promiseWithResolvers } from '../../promise/utils.js';
13
- import { type ApiSchema, type ApiSchemaFor, parseWithOptionals, schemaHasMethod } from '../../schemas/index.js';
13
+ import {
14
+ type ApiSchema,
15
+ type ApiSchemaFor,
16
+ getSchemaParameters,
17
+ parseWithOptionals,
18
+ schemaHasMethod,
19
+ } from '../../schemas/index.js';
14
20
  import { jsonStringify } from '../convert.js';
15
21
  import { assert } from '../js_utils.js';
16
22
 
@@ -53,8 +59,10 @@ export class SafeJsonRpcServer {
53
59
  config: Partial<SafeJsonRpcServerConfig> = {},
54
60
  /** Health check function */
55
61
  private readonly healthCheck: StatusCheckFn = () => true,
56
- /** Additional middlewares */
62
+ /** Additional Koa middlewares */
57
63
  private extraMiddlewares: Application.Middleware[] = [],
64
+ /** Additional per-request diagnostics middlewares */
65
+ private diagnosticsMiddleware?: DiagnosticsMiddleware,
58
66
  /** Logger */
59
67
  private log = createLogger('json-rpc:server'),
60
68
  ) {
@@ -155,7 +163,7 @@ export class SafeJsonRpcServer {
155
163
  };
156
164
  return;
157
165
  }
158
- const resp = await this.processBatch(ctx.request.body);
166
+ const resp = await this.processBatch(ctx.request.body, ctx.request.headers);
159
167
  if (Array.isArray(resp)) {
160
168
  ctx.status = 200;
161
169
  ctx.body = resp;
@@ -164,7 +172,7 @@ export class SafeJsonRpcServer {
164
172
  ctx.body = resp;
165
173
  }
166
174
  } else {
167
- const resp = await this.processRequest(ctx.request.body);
175
+ const resp = await this.processRequest(ctx.request.body, ctx.request.headers);
168
176
  if ('error' in resp) {
169
177
  ctx.status = this.config.http200OnError ? 200 : 400;
170
178
  }
@@ -176,11 +184,11 @@ export class SafeJsonRpcServer {
176
184
  return router;
177
185
  }
178
186
 
179
- private async processBatch(requests: any[]) {
187
+ private async processBatch(requests: any[], headers: http.IncomingHttpHeaders = {}) {
180
188
  if (requests.length === 0) {
181
189
  return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null };
182
190
  }
183
- const results = await Promise.allSettled(requests.map(req => this.processRequest(req)));
191
+ const results = await Promise.allSettled(requests.map(req => this.processRequest(req, headers)));
184
192
  return results.map(res => {
185
193
  if (res.status === 'fulfilled') {
186
194
  return res.value;
@@ -191,7 +199,7 @@ export class SafeJsonRpcServer {
191
199
  });
192
200
  }
193
201
 
194
- private async processRequest(request: any) {
202
+ private async processRequest(request: any, headers: http.IncomingHttpHeaders = {}) {
195
203
  if (!request || typeof request !== 'object') {
196
204
  return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null };
197
205
  }
@@ -206,7 +214,16 @@ export class SafeJsonRpcServer {
206
214
  return { jsonrpc, id, error: { code: -32601, message: `Method not found: ${method}` } };
207
215
  } else {
208
216
  try {
209
- const result = await this.proxy.call(method, params);
217
+ let result: any;
218
+
219
+ if (this.diagnosticsMiddleware) {
220
+ await this.diagnosticsMiddleware({ id: id ?? null, method, params, headers }, async () => {
221
+ result = await this.proxy.call(method, params);
222
+ });
223
+ } else {
224
+ result = await this.proxy.call(method, params);
225
+ }
226
+
210
227
  return { jsonrpc, id, result };
211
228
  } catch (err: any) {
212
229
  if (err && err instanceof ZodError) {
@@ -309,7 +326,7 @@ export class SafeJsonProxy<T extends object = any> implements Proxy {
309
326
  assert(schemaHasMethod(this.schema, methodName), `Method ${methodName} not found in schema`);
310
327
  const method = this.handler[methodName as keyof T];
311
328
  assert(typeof method === 'function', `Method ${methodName} is not a function`);
312
- const args = await parseWithOptionals(jsonParams, this.schema[methodName].parameters());
329
+ const args = await parseWithOptionals(jsonParams, getSchemaParameters(this.schema[methodName]));
313
330
  const ret = await method.apply(this.handler, args);
314
331
  this.log.debug(format('response', methodName, ret));
315
332
  return ret;
@@ -377,6 +394,7 @@ function makeAggregateHealthcheck(namedHandlers: NamespacedApiHandlers, log?: Lo
377
394
  export type SafeJsonRpcServerOptions = Partial<
378
395
  SafeJsonRpcServerConfig & {
379
396
  healthCheck: StatusCheckFn;
397
+ diagnostic: DiagnosticsMiddleware;
380
398
  log: Logger;
381
399
  middlewares: Application.Middleware[];
382
400
  }
@@ -391,10 +409,10 @@ export function createNamespacedSafeJsonRpcServer(
391
409
  handlers: NamespacedApiHandlers,
392
410
  options: Omit<SafeJsonRpcServerOptions, 'healthcheck'> = {},
393
411
  ): SafeJsonRpcServer {
394
- const { middlewares, log } = options;
412
+ const { diagnostic, middlewares, log } = options;
395
413
  const proxy = new NamespacedSafeJsonProxy(handlers);
396
414
  const healthCheck = makeAggregateHealthcheck(handlers, log);
397
- return new SafeJsonRpcServer(proxy, options, healthCheck, middlewares, log);
415
+ return new SafeJsonRpcServer(proxy, options, healthCheck, middlewares, diagnostic, log);
398
416
  }
399
417
 
400
418
  export function createSafeJsonRpcServer<T extends object = any>(
@@ -402,9 +420,9 @@ export function createSafeJsonRpcServer<T extends object = any>(
402
420
  schema: ApiSchemaFor<T>,
403
421
  options: SafeJsonRpcServerOptions = {},
404
422
  ) {
405
- const { log, healthCheck, middlewares: extraMiddlewares } = options;
423
+ const { diagnostic, log, healthCheck, middlewares: extraMiddlewares } = options;
406
424
  const proxy = new SafeJsonProxy(handler, schema);
407
- return new SafeJsonRpcServer(proxy, options, healthCheck, extraMiddlewares, log);
425
+ return new SafeJsonRpcServer(proxy, options, healthCheck, extraMiddlewares, diagnostic, log);
408
426
  }
409
427
 
410
428
  /**
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Converts bigint values to strings recursively in a log object to avoid serialization issues.
3
+ */
4
+ export function convertBigintsToStrings(obj: unknown): unknown {
5
+ if (typeof obj === 'bigint') {
6
+ return String(obj);
7
+ }
8
+
9
+ if (Array.isArray(obj)) {
10
+ return obj.map(item => convertBigintsToStrings(item));
11
+ }
12
+
13
+ if (obj !== null && typeof obj === 'object') {
14
+ if (typeof (obj as any).toJSON === 'function') {
15
+ return convertBigintsToStrings((obj as any).toJSON());
16
+ }
17
+ const result: Record<string, unknown> = {};
18
+ for (const key in obj) {
19
+ result[key] = convertBigintsToStrings((obj as Record<string, unknown>)[key]);
20
+ }
21
+ return result;
22
+ }
23
+
24
+ return obj;
25
+ }
@@ -1,5 +1,7 @@
1
1
  import type { pino } from 'pino';
2
2
 
3
+ import { convertBigintsToStrings } from './bigint-utils.js';
4
+
3
5
  /* eslint-disable camelcase */
4
6
 
5
7
  const GOOGLE_CLOUD_TRACE_ID = 'logging.googleapis.com/trace';
@@ -15,6 +17,9 @@ export const GoogleCloudLoggerConfig = {
15
17
  messageKey: 'message',
16
18
  formatters: {
17
19
  log(object: Record<string, unknown>): Record<string, unknown> {
20
+ // Convert bigints to strings recursively to avoid serialization issues
21
+ object = convertBigintsToStrings(object) as Record<string, unknown>;
22
+
18
23
  // Add trace context attributes following Cloud Logging structured log format described
19
24
  // in https://cloud.google.com/logging/docs/structured-logging#special-payload-fields
20
25
  const { trace_id, span_id, trace_flags, ...rest } = object;
@@ -19,22 +19,40 @@ export function getLogLevelFromFilters(filters: LogFilters, module: string): Log
19
19
  return undefined;
20
20
  }
21
21
 
22
- export function assertLogLevel(level: string): asserts level is LogLevel {
23
- if (!LogLevels.includes(level as LogLevel)) {
24
- throw new Error(`Invalid log level: ${level}`);
22
+ /**
23
+ * Parses the LOG_LEVEL env string into a default level and per-module filter overrides.
24
+ *
25
+ * Format: `<default_level>;<level>:<module1>,<module2>;<level>:<module3>;...`
26
+ * - First segment (before the first `;`) is the default log level for all modules.
27
+ * - Remaining segments are `level:module` pairs: apply the given level to the listed modules (comma-separated).
28
+ * - Later filters override earlier ones for overlapping module matches.
29
+ * - The `aztec:` prefix is stripped from module names; spaces are trimmed.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * parseLogLevel('debug;warn:module1,module2;error:module3', 'info')
34
+ * // => ['debug', [['module3', 'error'], ['module2', 'warn'], ['module1', 'warn']]]
35
+ * ```
36
+ */
37
+ export function parseLogLevelEnvVar(
38
+ logLevelEnvVar: string | undefined,
39
+ defaultLevel: LogLevel,
40
+ ): [LogLevel, LogFilters] {
41
+ if (!logLevelEnvVar) {
42
+ return [defaultLevel, []];
25
43
  }
44
+ const [level] = logLevelEnvVar.split(';', 1);
45
+ assertValidLogLevel(level);
46
+ return [level, parseFilters(logLevelEnvVar.slice(level.length + 1))];
26
47
  }
27
48
 
28
- export function parseEnv(env: string | undefined, defaultLevel: LogLevel): [LogLevel, LogFilters] {
29
- if (!env) {
30
- return [defaultLevel, []];
49
+ function assertValidLogLevel(level: string): asserts level is LogLevel {
50
+ if (!LogLevels.includes(level as LogLevel)) {
51
+ throw new Error(`Invalid log level: ${level}`);
31
52
  }
32
- const [level] = env.split(';', 1);
33
- assertLogLevel(level);
34
- return [level, parseFilters(env.slice(level.length + 1))];
35
53
  }
36
54
 
37
- export function parseFilters(definition: string | undefined): LogFilters {
55
+ function parseFilters(definition: string | undefined): LogFilters {
38
56
  if (!definition) {
39
57
  return [];
40
58
  }
@@ -48,7 +66,7 @@ export function parseFilters(definition: string | undefined): LogFilters {
48
66
  throw new Error(`Invalid log filter statement: ${statement}`);
49
67
  }
50
68
  const sanitizedLevel = level.trim().toLowerCase();
51
- assertLogLevel(sanitizedLevel);
69
+ assertValidLogLevel(sanitizedLevel);
52
70
  for (const module of modules.split(',')) {
53
71
  filters.push([
54
72
  module
@@ -7,8 +7,9 @@ import { inspect } from 'util';
7
7
  import { compactArray } from '../collection/array.js';
8
8
  import type { EnvVar } from '../config/index.js';
9
9
  import { parseBooleanEnv } from '../config/parse-env.js';
10
+ import { convertBigintsToStrings } from './bigint-utils.js';
10
11
  import { GoogleCloudLoggerConfig } from './gcloud-logger-config.js';
11
- import { getLogLevelFromFilters, parseEnv } from './log-filters.js';
12
+ import { getLogLevelFromFilters, parseLogLevelEnvVar } from './log-filters.js';
12
13
  import type { LogLevel } from './log-levels.js';
13
14
  import type { LogData, LogFn } from './log_fn.js';
14
15
 
@@ -20,6 +21,8 @@ export type LoggerBindings = {
20
21
  instanceId?: string;
21
22
  };
22
23
 
24
+ const MAX_MODULE_NAME_LENGTH = 256;
25
+
23
26
  // Allow global hooks for providing default bindings.
24
27
  // Used by withLoggerBindings in pino-logger-server to propagate bindings via AsyncLocalStorage.
25
28
  type LogBindingsHandler = () => LoggerBindings | undefined;
@@ -47,7 +50,7 @@ function getBindingsFromHandlers(): LoggerBindings | undefined {
47
50
  }
48
51
 
49
52
  export function createLogger(module: string, bindings?: LoggerBindings): Logger {
50
- module = module.replace(/^aztec:/, '');
53
+ module = module.slice(0, MAX_MODULE_NAME_LENGTH).replace(/^aztec:/, '');
51
54
 
52
55
  const resolvedBindings = { ...getBindingsFromHandlers(), ...bindings };
53
56
  const actor = resolvedBindings?.actor;
@@ -126,7 +129,7 @@ function isLevelEnabled(logger: pino.Logger<'verbose', boolean>, level: LogLevel
126
129
 
127
130
  // Load log levels from environment variables.
128
131
  const defaultLogLevel = process.env.NODE_ENV === 'test' ? 'silent' : 'info';
129
- export const [logLevel, logFilters] = parseEnv(process.env.LOG_LEVEL, defaultLogLevel);
132
+ export const [logLevel, logFilters] = parseLogLevelEnvVar(process.env.LOG_LEVEL, defaultLogLevel);
130
133
 
131
134
  // Define custom logging levels for pino.
132
135
  const customLevels = { verbose: 25 };
@@ -165,6 +168,9 @@ const pinoOpts: pino.LoggerOptions<keyof typeof customLevels> = {
165
168
  ...redactedPaths.map(p => `opts.${p}`),
166
169
  ],
167
170
  },
171
+ formatters: {
172
+ log: obj => convertBigintsToStrings(obj) as Record<string, unknown>,
173
+ },
168
174
  ...(useGcloudLogging ? GoogleCloudLoggerConfig : {}),
169
175
  };
170
176
 
@@ -371,5 +377,20 @@ export type Logger = { [K in LogLevel]: LogFn } & { /** Error log function */ er
371
377
  * @returns A string with both the log message and the error message.
372
378
  */
373
379
  function formatErr(msg: string, err?: unknown): string {
374
- return err ? `${msg}: ${inspect(err)}` : msg;
380
+ if (!err) {
381
+ return msg;
382
+ }
383
+
384
+ try {
385
+ return `${msg}: ${inspect(err)}`;
386
+ } catch {
387
+ // inspect can crash on error objects with broken property descriptors
388
+ try {
389
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
390
+ return `${msg}: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`;
391
+ } catch {
392
+ // if even String(err) fails, return the original message with a note about the error
393
+ return `${msg}: [unserializable error]`;
394
+ }
395
+ }
375
396
  }
@@ -10,26 +10,6 @@ const noirLocalDependencySchema = z.object({
10
10
  path: z.string(),
11
11
  });
12
12
 
13
- const noirPackageConfigSchema = z.object({
14
- package: z.object({
15
- name: z.string().default(''),
16
- type: z.enum(['lib', 'contract', 'bin']).default('bin'),
17
- entry: z.string().optional(),
18
- description: z.string().optional(),
19
- authors: z.array(z.string()).optional(),
20
- // eslint-disable-next-line camelcase
21
- compiler_version: z.string().optional(),
22
- backend: z.string().optional(),
23
- license: z.string().optional(),
24
- }),
25
- dependencies: z.record(z.union([noirGitDependencySchema, noirLocalDependencySchema])).default({}),
26
- });
27
-
28
- /**
29
- * Noir package configuration.
30
- */
31
- export type NoirPackageConfig = z.infer<typeof noirPackageConfigSchema>;
32
-
33
13
  /**
34
14
  * A remote package dependency.
35
15
  */
@@ -45,6 +25,38 @@ export type NoirLocalDependencyConfig = z.infer<typeof noirLocalDependencySchema
45
25
  */
46
26
  export type NoirDependencyConfig = NoirGitDependencyConfig | NoirLocalDependencyConfig;
47
27
 
28
+ /**
29
+ * Noir package configuration.
30
+ */
31
+ export type NoirPackageConfig = {
32
+ package: {
33
+ name: string;
34
+ type: 'lib' | 'contract' | 'bin';
35
+ entry?: string | undefined;
36
+ description?: string | undefined;
37
+ authors?: string[] | undefined;
38
+ compiler_version?: string | undefined;
39
+ backend?: string | undefined;
40
+ license?: string | undefined;
41
+ };
42
+ dependencies: Record<string, NoirDependencyConfig>;
43
+ };
44
+
45
+ const noirPackageConfigSchema: z.ZodType<NoirPackageConfig> = z.object({
46
+ package: z.object({
47
+ name: z.string().default(''),
48
+ type: z.enum(['lib', 'contract', 'bin']).default('bin'),
49
+ entry: z.string().optional(),
50
+ description: z.string().optional(),
51
+ authors: z.array(z.string()).optional(),
52
+ // eslint-disable-next-line camelcase
53
+ compiler_version: z.string().optional(),
54
+ backend: z.string().optional(),
55
+ license: z.string().optional(),
56
+ }),
57
+ dependencies: z.record(z.string(), z.union([noirGitDependencySchema, noirLocalDependencySchema])).default({}),
58
+ });
59
+
48
60
  /**
49
61
  * Checks that an object is a package configuration.
50
62
  * @param config - Config to check
@@ -122,7 +122,7 @@ export abstract class BaseMemoryQueue<T> {
122
122
  * @param handler - A function that takes an item of type T and returns a Promise<void> after processing the item.
123
123
  * @returns A Promise<void> that resolves when the queue is finished processing.
124
124
  */
125
- public async process(handler: (item: T) => Promise<void>) {
125
+ public async process(handler: (item: T) => Promise<void> | void) {
126
126
  try {
127
127
  while (true) {
128
128
  const item = await this.get();
@@ -105,6 +105,7 @@ export class BatchQueue<T, K extends string | number> {
105
105
  return Promise.resolve();
106
106
  }
107
107
 
108
+ this.flushCurrentBatch();
108
109
  this.container.end();
109
110
  return runningPromise;
110
111
  }
@@ -104,6 +104,36 @@ export async function retryUntil<T>(
104
104
  }
105
105
  }
106
106
 
107
+ /**
108
+ * Retry an asynchronous function until it returns a truthy value or the maximum number of retries is exceeded.
109
+ * The function is retried periodically with a fixed interval between attempts.
110
+ *
111
+ * @param fn - The asynchronous function to be retried, which should return a truthy value upon success or undefined otherwise.
112
+ * @param name - The optional name of the operation, used for generating error messages.
113
+ * @param maxRetries - The maximum number of retry attempts before throwing an error.
114
+ * @param retryInterval - The optional interval, in seconds, between retry attempts. Defaults to 1 second.
115
+ * @returns A Promise that resolves with the successful (truthy) result of the provided function, or rejects if retries are exhausted.
116
+ */
117
+ export async function retryTimes<T>(
118
+ fn: () => (T | undefined) | Promise<T | undefined>,
119
+ name = '',
120
+ maxRetries: number,
121
+ retryInterval = 1,
122
+ ) {
123
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
124
+ const result = await fn();
125
+ if (result) {
126
+ return result;
127
+ }
128
+
129
+ if (attempt < maxRetries) {
130
+ await sleep(retryInterval * 1000);
131
+ }
132
+ }
133
+
134
+ throw new Error(name ? `Retries exhausted awaiting ${name}` : 'Retries exhausted');
135
+ }
136
+
107
137
  /**
108
138
  * Convenience wrapper around retryUntil with fast polling for tests.
109
139
  * Uses 10s timeout and 100ms polling interval by default.