modern-treasury 2.6.0 → 2.7.2

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 (474) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +8 -4
  3. package/_shims/MultipartBody.d.ts +9 -0
  4. package/_shims/MultipartBody.d.ts.map +1 -0
  5. package/_shims/MultipartBody.js +16 -0
  6. package/_shims/MultipartBody.js.map +1 -0
  7. package/_shims/MultipartBody.mjs +12 -0
  8. package/_shims/MultipartBody.mjs.map +1 -0
  9. package/_shims/README.md +46 -0
  10. package/{src/_shims/ReadableStream-node.ts → _shims/auto/runtime-bun.d.ts} +2 -3
  11. package/_shims/auto/runtime-bun.d.ts.map +1 -0
  12. package/_shims/auto/runtime-bun.js +21 -0
  13. package/_shims/auto/runtime-bun.js.map +1 -0
  14. package/_shims/auto/runtime-bun.mjs +2 -0
  15. package/_shims/auto/runtime-bun.mjs.map +1 -0
  16. package/_shims/auto/runtime-node.d.ts +5 -0
  17. package/_shims/auto/runtime-node.d.ts.map +1 -0
  18. package/_shims/auto/runtime-node.js +21 -0
  19. package/_shims/auto/runtime-node.js.map +1 -0
  20. package/_shims/auto/runtime-node.mjs +2 -0
  21. package/_shims/auto/runtime-node.mjs.map +1 -0
  22. package/_shims/auto/runtime.d.ts +5 -0
  23. package/_shims/auto/runtime.d.ts.map +1 -0
  24. package/_shims/auto/runtime.js +21 -0
  25. package/_shims/auto/runtime.js.map +1 -0
  26. package/_shims/auto/runtime.mjs +2 -0
  27. package/_shims/auto/runtime.mjs.map +1 -0
  28. package/_shims/auto/types-node.d.ts +5 -0
  29. package/_shims/auto/types-node.d.ts.map +1 -0
  30. package/_shims/auto/types-node.js +21 -0
  31. package/_shims/auto/types-node.js.map +1 -0
  32. package/_shims/auto/types-node.mjs +2 -0
  33. package/_shims/auto/types-node.mjs.map +1 -0
  34. package/_shims/auto/types.d.ts +99 -0
  35. package/_shims/{ReadableStream.js → auto/types.js} +0 -2
  36. package/{src/_shims/ReadableStream.js → _shims/auto/types.mjs} +0 -2
  37. package/_shims/bun-runtime.d.ts +6 -0
  38. package/_shims/bun-runtime.d.ts.map +1 -0
  39. package/_shims/bun-runtime.js +14 -0
  40. package/_shims/bun-runtime.js.map +1 -0
  41. package/_shims/bun-runtime.mjs +10 -0
  42. package/_shims/bun-runtime.mjs.map +1 -0
  43. package/_shims/index.d.ts +79 -0
  44. package/_shims/index.js +13 -0
  45. package/_shims/index.mjs +7 -0
  46. package/_shims/manual-types.d.ts +12 -0
  47. package/_shims/manual-types.js +3 -0
  48. package/_shims/manual-types.mjs +3 -0
  49. package/_shims/node-runtime.d.ts +3 -0
  50. package/_shims/node-runtime.d.ts.map +1 -0
  51. package/_shims/node-runtime.js +87 -0
  52. package/_shims/node-runtime.js.map +1 -0
  53. package/_shims/node-runtime.mjs +54 -0
  54. package/_shims/node-runtime.mjs.map +1 -0
  55. package/_shims/node-types.d.ts +42 -0
  56. package/_shims/node-types.js +3 -0
  57. package/_shims/node-types.mjs +3 -0
  58. package/_shims/registry.d.ts +35 -0
  59. package/_shims/registry.d.ts.map +1 -0
  60. package/_shims/registry.js +39 -0
  61. package/_shims/registry.js.map +1 -0
  62. package/_shims/registry.mjs +35 -0
  63. package/_shims/registry.mjs.map +1 -0
  64. package/_shims/web-runtime.d.ts +5 -0
  65. package/_shims/web-runtime.d.ts.map +1 -0
  66. package/_shims/web-runtime.js +70 -0
  67. package/_shims/web-runtime.js.map +1 -0
  68. package/_shims/web-runtime.mjs +63 -0
  69. package/_shims/web-runtime.mjs.map +1 -0
  70. package/_shims/web-types.d.ts +82 -0
  71. package/_shims/web-types.js +3 -0
  72. package/_shims/web-types.mjs +3 -0
  73. package/core.d.ts +170 -223
  74. package/core.d.ts.map +1 -1
  75. package/core.js +678 -731
  76. package/core.js.map +1 -1
  77. package/core.mjs +672 -682
  78. package/core.mjs.map +1 -1
  79. package/error.d.ts +32 -32
  80. package/error.d.ts.map +1 -1
  81. package/error.js +95 -106
  82. package/error.js.map +1 -1
  83. package/error.mjs +91 -91
  84. package/error.mjs.map +1 -1
  85. package/index.d.mts +323 -333
  86. package/index.d.ts +323 -333
  87. package/index.d.ts.map +1 -1
  88. package/index.js +190 -243
  89. package/index.js.map +1 -1
  90. package/index.mjs +167 -190
  91. package/index.mjs.map +1 -1
  92. package/package.json +32 -58
  93. package/pagination.d.ts +11 -11
  94. package/pagination.js +30 -26
  95. package/pagination.mjs +28 -24
  96. package/resource.d.ts +10 -10
  97. package/resource.js +12 -12
  98. package/resource.mjs +10 -10
  99. package/resources/account-collection-flows.d.ts +71 -116
  100. package/resources/account-collection-flows.js +52 -62
  101. package/resources/account-collection-flows.js.map +1 -1
  102. package/resources/account-collection-flows.mjs +47 -55
  103. package/resources/account-collection-flows.mjs.map +1 -1
  104. package/resources/account-details.d.ts +59 -81
  105. package/resources/account-details.js +47 -50
  106. package/resources/account-details.js.map +1 -1
  107. package/resources/account-details.mjs +42 -45
  108. package/resources/account-details.mjs.map +1 -1
  109. package/resources/connections.d.ts +42 -44
  110. package/resources/connections.js +15 -13
  111. package/resources/connections.mjs +10 -8
  112. package/resources/counterparties.d.ts +400 -466
  113. package/resources/counterparties.js +63 -71
  114. package/resources/counterparties.js.map +1 -1
  115. package/resources/counterparties.mjs +58 -66
  116. package/resources/counterparties.mjs.map +1 -1
  117. package/resources/documents.d.ts +88 -120
  118. package/resources/documents.js +36 -42
  119. package/resources/documents.js.map +1 -1
  120. package/resources/documents.mjs +30 -36
  121. package/resources/documents.mjs.map +1 -1
  122. package/resources/events.d.ts +56 -55
  123. package/resources/events.js +21 -19
  124. package/resources/events.mjs +16 -14
  125. package/resources/expected-payments.d.ts +321 -373
  126. package/resources/expected-payments.js +46 -51
  127. package/resources/expected-payments.js.map +1 -1
  128. package/resources/expected-payments.mjs +41 -44
  129. package/resources/expected-payments.mjs.map +1 -1
  130. package/resources/external-accounts.d.ts +295 -373
  131. package/resources/external-accounts.js +76 -91
  132. package/resources/external-accounts.js.map +1 -1
  133. package/resources/external-accounts.mjs +71 -84
  134. package/resources/external-accounts.mjs.map +1 -1
  135. package/resources/incoming-payment-details.d.ts +200 -222
  136. package/resources/incoming-payment-details.js +42 -47
  137. package/resources/incoming-payment-details.js.map +1 -1
  138. package/resources/incoming-payment-details.mjs +37 -40
  139. package/resources/incoming-payment-details.mjs.map +1 -1
  140. package/resources/index.d.ts +35 -212
  141. package/resources/index.js +111 -484
  142. package/resources/index.mjs +34 -37
  143. package/resources/internal-accounts/balance-reports.d.ts +74 -113
  144. package/resources/internal-accounts/balance-reports.js +21 -23
  145. package/resources/internal-accounts/balance-reports.mjs +16 -18
  146. package/resources/internal-accounts/index.d.ts +3 -15
  147. package/resources/internal-accounts/index.js +10 -34
  148. package/resources/internal-accounts/index.mjs +3 -3
  149. package/resources/internal-accounts/internal-accounts.d.ts +203 -233
  150. package/resources/internal-accounts/internal-accounts.js +65 -86
  151. package/resources/internal-accounts/internal-accounts.js.map +1 -1
  152. package/resources/internal-accounts/internal-accounts.mjs +41 -45
  153. package/resources/internal-accounts/internal-accounts.mjs.map +1 -1
  154. package/resources/invoices/index.d.ts +3 -17
  155. package/resources/invoices/index.js +9 -29
  156. package/resources/invoices/index.mjs +3 -3
  157. package/resources/invoices/invoices.d.ts +509 -549
  158. package/resources/invoices/invoices.js +74 -95
  159. package/resources/invoices/invoices.js.map +1 -1
  160. package/resources/invoices/invoices.mjs +50 -54
  161. package/resources/invoices/invoices.mjs.map +1 -1
  162. package/resources/invoices/line-items.d.ts +119 -133
  163. package/resources/invoices/line-items.js +49 -52
  164. package/resources/invoices/line-items.js.map +1 -1
  165. package/resources/invoices/line-items.mjs +44 -47
  166. package/resources/invoices/line-items.mjs.map +1 -1
  167. package/resources/ledger-account-balance-monitors.d.ts +213 -224
  168. package/resources/ledger-account-balance-monitors.js +49 -55
  169. package/resources/ledger-account-balance-monitors.js.map +1 -1
  170. package/resources/ledger-account-balance-monitors.mjs +44 -49
  171. package/resources/ledger-account-balance-monitors.mjs.map +1 -1
  172. package/resources/ledger-account-categories.d.ts +255 -276
  173. package/resources/ledger-account-categories.js +84 -89
  174. package/resources/ledger-account-categories.js.map +1 -1
  175. package/resources/ledger-account-categories.mjs +79 -82
  176. package/resources/ledger-account-categories.mjs.map +1 -1
  177. package/resources/ledger-account-payouts.d.ts +151 -160
  178. package/resources/ledger-account-payouts.js +45 -50
  179. package/resources/ledger-account-payouts.js.map +1 -1
  180. package/resources/ledger-account-payouts.mjs +40 -43
  181. package/resources/ledger-account-payouts.mjs.map +1 -1
  182. package/resources/ledger-account-statements.d.ts +455 -461
  183. package/resources/ledger-account-statements.js +26 -32
  184. package/resources/ledger-account-statements.js.map +1 -1
  185. package/resources/ledger-account-statements.mjs +23 -27
  186. package/resources/ledger-account-statements.mjs.map +1 -1
  187. package/resources/ledger-accounts.d.ts +347 -357
  188. package/resources/ledger-accounts.js +45 -48
  189. package/resources/ledger-accounts.js.map +1 -1
  190. package/resources/ledger-accounts.mjs +40 -43
  191. package/resources/ledger-accounts.mjs.map +1 -1
  192. package/resources/ledger-entries.d.ts +244 -250
  193. package/resources/ledger-entries.js +20 -18
  194. package/resources/ledger-entries.mjs +15 -13
  195. package/resources/ledger-event-handlers.d.ts +369 -376
  196. package/resources/ledger-event-handlers.js +44 -49
  197. package/resources/ledger-event-handlers.js.map +1 -1
  198. package/resources/ledger-event-handlers.mjs +39 -42
  199. package/resources/ledger-event-handlers.mjs.map +1 -1
  200. package/resources/ledger-transactions/index.d.ts +3 -16
  201. package/resources/ledger-transactions/index.js +10 -34
  202. package/resources/ledger-transactions/index.mjs +3 -3
  203. package/resources/ledger-transactions/ledger-transactions.d.ts +335 -389
  204. package/resources/ledger-transactions/ledger-transactions.js +70 -91
  205. package/resources/ledger-transactions/ledger-transactions.js.map +1 -1
  206. package/resources/ledger-transactions/ledger-transactions.mjs +46 -50
  207. package/resources/ledger-transactions/ledger-transactions.mjs.map +1 -1
  208. package/resources/ledger-transactions/versions.d.ts +199 -214
  209. package/resources/ledger-transactions/versions.js +18 -16
  210. package/resources/ledger-transactions/versions.mjs +13 -11
  211. package/resources/ledgerable-events.d.ts +96 -99
  212. package/resources/ledgerable-events.js +27 -33
  213. package/resources/ledgerable-events.js.map +1 -1
  214. package/resources/ledgerable-events.mjs +24 -28
  215. package/resources/ledgerable-events.mjs.map +1 -1
  216. package/resources/ledgers.d.ts +98 -97
  217. package/resources/ledgers.js +46 -49
  218. package/resources/ledgers.js.map +1 -1
  219. package/resources/ledgers.mjs +41 -44
  220. package/resources/ledgers.mjs.map +1 -1
  221. package/resources/line-items.d.ts +78 -101
  222. package/resources/line-items.js +29 -27
  223. package/resources/line-items.mjs +24 -22
  224. package/resources/paper-items.d.ts +91 -93
  225. package/resources/paper-items.js +21 -19
  226. package/resources/paper-items.mjs +16 -14
  227. package/resources/payment-flows.d.ts +132 -138
  228. package/resources/payment-flows.js +49 -57
  229. package/resources/payment-flows.js.map +1 -1
  230. package/resources/payment-flows.mjs +44 -52
  231. package/resources/payment-flows.mjs.map +1 -1
  232. package/resources/payment-orders/index.d.ts +3 -13
  233. package/resources/payment-orders/index.js +9 -29
  234. package/resources/payment-orders/index.mjs +3 -3
  235. package/resources/payment-orders/payment-orders.d.ts +1416 -1696
  236. package/resources/payment-orders/payment-orders.js +80 -109
  237. package/resources/payment-orders/payment-orders.js.map +1 -1
  238. package/resources/payment-orders/payment-orders.mjs +55 -67
  239. package/resources/payment-orders/payment-orders.mjs.map +1 -1
  240. package/resources/payment-orders/reversals.d.ts +153 -183
  241. package/resources/payment-orders/reversals.js +38 -41
  242. package/resources/payment-orders/reversals.js.map +1 -1
  243. package/resources/payment-orders/reversals.mjs +33 -36
  244. package/resources/payment-orders/reversals.mjs.map +1 -1
  245. package/resources/payment-references.d.ts +61 -118
  246. package/resources/payment-references.js +26 -26
  247. package/resources/payment-references.mjs +21 -19
  248. package/resources/returns.d.ts +167 -324
  249. package/resources/returns.js +35 -38
  250. package/resources/returns.js.map +1 -1
  251. package/resources/returns.mjs +30 -33
  252. package/resources/returns.mjs.map +1 -1
  253. package/resources/routing-details.d.ts +83 -173
  254. package/resources/routing-details.js +47 -50
  255. package/resources/routing-details.js.map +1 -1
  256. package/resources/routing-details.mjs +42 -45
  257. package/resources/routing-details.mjs.map +1 -1
  258. package/resources/shared.d.ts +4 -194
  259. package/resources/shared.js +3 -3
  260. package/resources/shared.mjs +1 -1
  261. package/resources/top-level.d.ts +4 -4
  262. package/resources/top-level.js +5 -4
  263. package/resources/top-level.mjs +3 -2
  264. package/resources/transactions/index.d.ts +3 -14
  265. package/resources/transactions/index.js +10 -34
  266. package/resources/transactions/index.mjs +3 -3
  267. package/resources/transactions/line-items.d.ts +69 -78
  268. package/resources/transactions/line-items.js +21 -19
  269. package/resources/transactions/line-items.mjs +16 -14
  270. package/resources/transactions/transactions.d.ts +163 -211
  271. package/resources/transactions/transactions.js +51 -67
  272. package/resources/transactions/transactions.mjs +27 -26
  273. package/resources/validations.d.ts +67 -111
  274. package/resources/validations.js +13 -12
  275. package/resources/validations.mjs +10 -9
  276. package/resources/virtual-accounts.d.ts +161 -201
  277. package/resources/virtual-accounts.js +46 -51
  278. package/resources/virtual-accounts.js.map +1 -1
  279. package/resources/virtual-accounts.mjs +41 -44
  280. package/resources/virtual-accounts.mjs.map +1 -1
  281. package/resources/webhooks.d.ts +21 -28
  282. package/resources/webhooks.js +35 -37
  283. package/resources/webhooks.js.map +1 -1
  284. package/resources/webhooks.mjs +30 -31
  285. package/resources/webhooks.mjs.map +1 -1
  286. package/shims/node.d.ts +29 -0
  287. package/shims/node.d.ts.map +1 -0
  288. package/shims/node.js +31 -0
  289. package/shims/node.js.map +1 -0
  290. package/shims/node.mjs +5 -0
  291. package/shims/node.mjs.map +1 -0
  292. package/shims/web.d.ts +26 -0
  293. package/shims/web.d.ts.map +1 -0
  294. package/shims/web.js +31 -0
  295. package/shims/web.js.map +1 -0
  296. package/shims/web.mjs +5 -0
  297. package/shims/web.mjs.map +1 -0
  298. package/src/_shims/MultipartBody.ts +9 -0
  299. package/src/_shims/README.md +46 -0
  300. package/src/_shims/auto/runtime-bun.ts +4 -0
  301. package/src/_shims/auto/runtime-node.ts +4 -0
  302. package/src/_shims/auto/runtime.ts +4 -0
  303. package/src/_shims/auto/types-node.ts +4 -0
  304. package/src/_shims/auto/types.d.ts +99 -0
  305. package/src/_shims/auto/types.js +3 -0
  306. package/src/_shims/auto/types.mjs +3 -0
  307. package/src/_shims/bun-runtime.ts +14 -0
  308. package/src/_shims/index.d.ts +79 -0
  309. package/src/_shims/index.js +13 -0
  310. package/src/_shims/index.mjs +7 -0
  311. package/src/_shims/manual-types.d.ts +12 -0
  312. package/src/_shims/manual-types.js +3 -0
  313. package/src/_shims/manual-types.mjs +3 -0
  314. package/src/_shims/node-runtime.ts +79 -0
  315. package/src/_shims/node-types.d.ts +42 -0
  316. package/src/_shims/node-types.js +3 -0
  317. package/src/_shims/node-types.mjs +3 -0
  318. package/src/_shims/registry.ts +64 -0
  319. package/src/_shims/web-runtime.ts +91 -0
  320. package/src/_shims/web-types.d.ts +82 -0
  321. package/src/_shims/web-types.js +3 -0
  322. package/src/_shims/web-types.mjs +3 -0
  323. package/src/core.ts +72 -43
  324. package/src/error.ts +4 -2
  325. package/src/index.ts +10 -8
  326. package/src/pagination.ts +1 -1
  327. package/src/resource.ts +1 -1
  328. package/src/resources/account-collection-flows.ts +5 -5
  329. package/src/resources/account-details.ts +6 -6
  330. package/src/resources/connections.ts +5 -5
  331. package/src/resources/counterparties.ts +8 -8
  332. package/src/resources/documents.ts +6 -6
  333. package/src/resources/events.ts +5 -5
  334. package/src/resources/expected-payments.ts +6 -6
  335. package/src/resources/external-accounts.ts +8 -8
  336. package/src/resources/incoming-payment-details.ts +7 -7
  337. package/src/resources/index.ts +34 -40
  338. package/src/resources/internal-accounts/balance-reports.ts +6 -6
  339. package/src/resources/internal-accounts/index.ts +2 -2
  340. package/src/resources/internal-accounts/internal-accounts.ts +10 -10
  341. package/src/resources/invoices/index.ts +2 -2
  342. package/src/resources/invoices/invoices.ts +8 -8
  343. package/src/resources/invoices/line-items.ts +5 -5
  344. package/src/resources/ledger-account-balance-monitors.ts +5 -5
  345. package/src/resources/ledger-account-categories.ts +5 -5
  346. package/src/resources/ledger-account-payouts.ts +5 -5
  347. package/src/resources/ledger-account-statements.ts +3 -3
  348. package/src/resources/ledger-accounts.ts +5 -5
  349. package/src/resources/ledger-entries.ts +5 -5
  350. package/src/resources/ledger-event-handlers.ts +5 -5
  351. package/src/resources/ledger-transactions/index.ts +2 -2
  352. package/src/resources/ledger-transactions/ledger-transactions.ts +7 -7
  353. package/src/resources/ledger-transactions/versions.ts +5 -5
  354. package/src/resources/ledgerable-events.ts +3 -3
  355. package/src/resources/ledgers.ts +5 -5
  356. package/src/resources/line-items.ts +5 -5
  357. package/src/resources/paper-items.ts +6 -6
  358. package/src/resources/payment-flows.ts +5 -5
  359. package/src/resources/payment-orders/index.ts +2 -2
  360. package/src/resources/payment-orders/payment-orders.ts +10 -10
  361. package/src/resources/payment-orders/reversals.ts +5 -5
  362. package/src/resources/payment-references.ts +5 -5
  363. package/src/resources/returns.ts +6 -6
  364. package/src/resources/routing-details.ts +6 -6
  365. package/src/resources/top-level.ts +1 -1
  366. package/src/resources/transactions/index.ts +2 -7
  367. package/src/resources/transactions/line-items.ts +5 -5
  368. package/src/resources/transactions/transactions.ts +7 -7
  369. package/src/resources/validations.ts +3 -3
  370. package/src/resources/virtual-accounts.ts +7 -7
  371. package/src/resources/webhooks.ts +3 -3
  372. package/src/shims/node.ts +50 -0
  373. package/src/shims/web.ts +50 -0
  374. package/src/uploads.ts +12 -16
  375. package/src/version.ts +1 -1
  376. package/uploads.d.ts +23 -39
  377. package/uploads.d.ts.map +1 -1
  378. package/uploads.js +111 -157
  379. package/uploads.js.map +1 -1
  380. package/uploads.mjs +107 -133
  381. package/uploads.mjs.map +1 -1
  382. package/version.d.ts +2 -2
  383. package/version.js +4 -4
  384. package/version.mjs +2 -2
  385. package/_shims/ReadableStream-node.d.ts +0 -6
  386. package/_shims/ReadableStream-node.d.ts.map +0 -1
  387. package/_shims/ReadableStream-node.js +0 -14
  388. package/_shims/ReadableStream-node.js.map +0 -1
  389. package/_shims/ReadableStream-node.mjs +0 -3
  390. package/_shims/ReadableStream-node.mjs.map +0 -1
  391. package/_shims/ReadableStream.d.ts +0 -38
  392. package/_shims/ReadableStream.mjs +0 -7
  393. package/_shims/agent-node.d.ts +0 -7
  394. package/_shims/agent-node.d.ts.map +0 -1
  395. package/_shims/agent-node.js +0 -28
  396. package/_shims/agent-node.js.map +0 -1
  397. package/_shims/agent-node.mjs +0 -16
  398. package/_shims/agent-node.mjs.map +0 -1
  399. package/_shims/agent.d.ts +0 -9
  400. package/_shims/agent.d.ts.map +0 -1
  401. package/_shims/agent.js +0 -14
  402. package/_shims/agent.js.map +0 -1
  403. package/_shims/agent.mjs +0 -10
  404. package/_shims/agent.mjs.map +0 -1
  405. package/_shims/fetch-node.d.ts +0 -64
  406. package/_shims/fetch-node.js +0 -12
  407. package/_shims/fetch-node.mjs +0 -14
  408. package/_shims/fetch.d.ts +0 -60
  409. package/_shims/fetch.js +0 -13
  410. package/_shims/fetch.mjs +0 -15
  411. package/_shims/fileFromPath-node.d.ts +0 -17
  412. package/_shims/fileFromPath-node.d.ts.map +0 -1
  413. package/_shims/fileFromPath-node.js +0 -17
  414. package/_shims/fileFromPath-node.js.map +0 -1
  415. package/_shims/fileFromPath-node.mjs +0 -13
  416. package/_shims/fileFromPath-node.mjs.map +0 -1
  417. package/_shims/fileFromPath.d.ts +0 -22
  418. package/_shims/fileFromPath.d.ts.map +0 -1
  419. package/_shims/fileFromPath.js +0 -16
  420. package/_shims/fileFromPath.js.map +0 -1
  421. package/_shims/fileFromPath.mjs +0 -12
  422. package/_shims/fileFromPath.mjs.map +0 -1
  423. package/_shims/form-data-node.d.ts +0 -45
  424. package/_shims/form-data-node.js +0 -11
  425. package/_shims/form-data-node.mjs +0 -9
  426. package/_shims/form-data.d.ts +0 -43
  427. package/_shims/form-data.js +0 -17
  428. package/_shims/form-data.mjs +0 -20
  429. package/_shims/getMultipartRequestOptions-node.d.ts +0 -10
  430. package/_shims/getMultipartRequestOptions-node.d.ts.map +0 -1
  431. package/_shims/getMultipartRequestOptions-node.js +0 -22
  432. package/_shims/getMultipartRequestOptions-node.js.map +0 -1
  433. package/_shims/getMultipartRequestOptions-node.mjs +0 -18
  434. package/_shims/getMultipartRequestOptions-node.mjs.map +0 -1
  435. package/_shims/getMultipartRequestOptions.d.ts +0 -10
  436. package/_shims/getMultipartRequestOptions.d.ts.map +0 -1
  437. package/_shims/getMultipartRequestOptions.js +0 -12
  438. package/_shims/getMultipartRequestOptions.js.map +0 -1
  439. package/_shims/getMultipartRequestOptions.mjs +0 -8
  440. package/_shims/getMultipartRequestOptions.mjs.map +0 -1
  441. package/_shims/node-readable-node.d.ts +0 -8
  442. package/_shims/node-readable-node.d.ts.map +0 -1
  443. package/_shims/node-readable-node.js +0 -9
  444. package/_shims/node-readable-node.js.map +0 -1
  445. package/_shims/node-readable-node.mjs +0 -5
  446. package/_shims/node-readable-node.mjs.map +0 -1
  447. package/_shims/node-readable.d.ts +0 -23
  448. package/_shims/node-readable.d.ts.map +0 -1
  449. package/_shims/node-readable.js +0 -11
  450. package/_shims/node-readable.js.map +0 -1
  451. package/_shims/node-readable.mjs +0 -7
  452. package/_shims/node-readable.mjs.map +0 -1
  453. package/src/_shims/ReadableStream.d.ts +0 -38
  454. package/src/_shims/ReadableStream.mjs +0 -7
  455. package/src/_shims/agent-node.ts +0 -22
  456. package/src/_shims/agent.ts +0 -12
  457. package/src/_shims/fetch-node.d.ts +0 -64
  458. package/src/_shims/fetch-node.js +0 -12
  459. package/src/_shims/fetch-node.mjs +0 -14
  460. package/src/_shims/fetch.d.ts +0 -60
  461. package/src/_shims/fetch.js +0 -13
  462. package/src/_shims/fetch.mjs +0 -15
  463. package/src/_shims/fileFromPath-node.ts +0 -29
  464. package/src/_shims/fileFromPath.ts +0 -29
  465. package/src/_shims/form-data-node.d.ts +0 -45
  466. package/src/_shims/form-data-node.js +0 -11
  467. package/src/_shims/form-data-node.mjs +0 -9
  468. package/src/_shims/form-data.d.ts +0 -43
  469. package/src/_shims/form-data.js +0 -17
  470. package/src/_shims/form-data.mjs +0 -20
  471. package/src/_shims/getMultipartRequestOptions-node.ts +0 -25
  472. package/src/_shims/getMultipartRequestOptions.ts +0 -14
  473. package/src/_shims/node-readable-node.ts +0 -10
  474. package/src/_shims/node-readable.ts +0 -30
package/core.mjs CHANGED
@@ -1,465 +1,445 @@
1
- var __classPrivateFieldSet =
2
- (this && this.__classPrivateFieldSet) ||
3
- function (receiver, state, value, kind, f) {
4
- if (kind === 'm') throw new TypeError('Private method is not writable');
5
- if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a setter');
6
- if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
7
- throw new TypeError('Cannot write private member to an object whose class did not declare it');
8
- return (
9
- kind === 'a' ? f.call(receiver, value)
10
- : f ? (f.value = value)
11
- : state.set(receiver, value),
12
- value
13
- );
14
- };
15
- var __classPrivateFieldGet =
16
- (this && this.__classPrivateFieldGet) ||
17
- function (receiver, state, kind, f) {
18
- if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter');
19
- if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
20
- throw new TypeError('Cannot read private member from an object whose class did not declare it');
21
- return (
22
- kind === 'm' ? f
23
- : kind === 'a' ? f.call(receiver)
24
- : f ? f.value
25
- : state.get(receiver)
26
- );
27
- };
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
28
12
  var _AbstractPage_client;
29
- import { VERSION } from './version.mjs';
30
- import { APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError } from './error.mjs';
31
- import { getDefaultAgent } from 'modern-treasury/_shims/agent';
32
- import { fetch, isPolyfilled as fetchIsPolyfilled } from 'modern-treasury/_shims/fetch';
33
- import { isMultipartBody } from './uploads.mjs';
34
- export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm } from './uploads.mjs';
13
+ import { VERSION } from "./version.mjs";
14
+ import { ModernTreasuryError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from "./error.mjs";
15
+ import { kind as shimsKind, getDefaultAgent, fetch, } from "./_shims/index.mjs";
16
+ import { isMultipartBody } from "./uploads.mjs";
17
+ export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from "./uploads.mjs";
35
18
  const MAX_RETRIES = 2;
36
19
  async function defaultParseResponse(props) {
37
- const { response } = props;
38
- const contentType = response.headers.get('content-type');
39
- if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
40
- const json = await response.json();
41
- debug('response', response.status, response.url, response.headers, json);
42
- return json;
43
- }
44
- // TODO handle blob, arraybuffer, other content types, etc.
45
- const text = await response.text();
46
- debug('response', response.status, response.url, response.headers, text);
47
- return text;
20
+ const { response } = props;
21
+ const contentType = response.headers.get('content-type');
22
+ if (contentType?.includes('application/json')) {
23
+ const json = await response.json();
24
+ debug('response', response.status, response.url, response.headers, json);
25
+ return json;
26
+ }
27
+ // TODO handle blob, arraybuffer, other content types, etc.
28
+ const text = await response.text();
29
+ debug('response', response.status, response.url, response.headers, text);
30
+ return text;
48
31
  }
49
32
  /**
50
33
  * A subclass of `Promise` providing additional helper methods
51
34
  * for interacting with the SDK.
52
35
  */
53
36
  export class APIPromise extends Promise {
54
- constructor(responsePromise, parseResponse = defaultParseResponse) {
55
- super((resolve) => {
56
- // this is maybe a bit weird but this has to be a no-op to not implicitly
57
- // parse the response body; instead .then, .catch, .finally are overridden
58
- // to parse the response
59
- resolve(null);
60
- });
61
- this.responsePromise = responsePromise;
62
- this.parseResponse = parseResponse;
63
- }
64
- _thenUnwrap(transform) {
65
- return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
66
- }
67
- /**
68
- * Gets the raw `Response` instance instead of parsing the response
69
- * data.
70
- *
71
- * If you want to parse the response body but still get the `Response`
72
- * instance, you can use {@link withResponse()}.
73
- */
74
- asResponse() {
75
- return this.responsePromise.then((p) => p.response);
76
- }
77
- /**
78
- * Gets the parsed response data and the raw `Response` instance.
79
- *
80
- * If you just want to get the raw `Response` instance without parsing it,
81
- * you can use {@link asResponse()}.
82
- */
83
- async withResponse() {
84
- const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
85
- return { data, response };
86
- }
87
- parse() {
88
- if (!this.parsedPromise) {
89
- this.parsedPromise = this.responsePromise.then(this.parseResponse);
90
- }
91
- return this.parsedPromise;
92
- }
93
- then(onfulfilled, onrejected) {
94
- return this.parse().then(onfulfilled, onrejected);
95
- }
96
- catch(onrejected) {
97
- return this.parse().catch(onrejected);
98
- }
99
- finally(onfinally) {
100
- return this.parse().finally(onfinally);
101
- }
37
+ constructor(responsePromise, parseResponse = defaultParseResponse) {
38
+ super((resolve) => {
39
+ // this is maybe a bit weird but this has to be a no-op to not implicitly
40
+ // parse the response body; instead .then, .catch, .finally are overridden
41
+ // to parse the response
42
+ resolve(null);
43
+ });
44
+ this.responsePromise = responsePromise;
45
+ this.parseResponse = parseResponse;
46
+ }
47
+ _thenUnwrap(transform) {
48
+ return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
49
+ }
50
+ /**
51
+ * Gets the raw `Response` instance instead of parsing the response
52
+ * data.
53
+ *
54
+ * If you want to parse the response body but still get the `Response`
55
+ * instance, you can use {@link withResponse()}.
56
+ *
57
+ * 👋 Getting the wrong TypeScript type for `Response`?
58
+ * Try setting `"moduleResolution": "NodeNext"` if you can,
59
+ * or add one of these imports before your first `import … from 'modern-treasury'`:
60
+ * - `import 'modern-treasury/shims/node'` (if you're running on Node)
61
+ * - `import 'modern-treasury/shims/web'` (otherwise)
62
+ */
63
+ asResponse() {
64
+ return this.responsePromise.then((p) => p.response);
65
+ }
66
+ /**
67
+ * Gets the parsed response data and the raw `Response` instance.
68
+ *
69
+ * If you just want to get the raw `Response` instance without parsing it,
70
+ * you can use {@link asResponse()}.
71
+ *
72
+ *
73
+ * 👋 Getting the wrong TypeScript type for `Response`?
74
+ * Try setting `"moduleResolution": "NodeNext"` if you can,
75
+ * or add one of these imports before your first `import … from 'modern-treasury'`:
76
+ * - `import 'modern-treasury/shims/node'` (if you're running on Node)
77
+ * - `import 'modern-treasury/shims/web'` (otherwise)
78
+ */
79
+ async withResponse() {
80
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
81
+ return { data, response };
82
+ }
83
+ parse() {
84
+ if (!this.parsedPromise) {
85
+ this.parsedPromise = this.responsePromise.then(this.parseResponse);
86
+ }
87
+ return this.parsedPromise;
88
+ }
89
+ then(onfulfilled, onrejected) {
90
+ return this.parse().then(onfulfilled, onrejected);
91
+ }
92
+ catch(onrejected) {
93
+ return this.parse().catch(onrejected);
94
+ }
95
+ finally(onfinally) {
96
+ return this.parse().finally(onfinally);
97
+ }
102
98
  }
103
99
  export class APIClient {
104
- constructor({
105
- baseURL,
106
- maxRetries,
107
- timeout = 60000, // 1 minute
108
- httpAgent,
109
- fetch: overridenFetch,
110
- }) {
111
- this.baseURL = baseURL;
112
- this.maxRetries = validatePositiveInteger(
113
- 'maxRetries',
114
- maxRetries !== null && maxRetries !== void 0 ? maxRetries : MAX_RETRIES,
115
- );
116
- this.timeout = validatePositiveInteger('timeout', timeout);
117
- this.httpAgent = httpAgent;
118
- this.fetch = overridenFetch !== null && overridenFetch !== void 0 ? overridenFetch : fetch;
119
- }
120
- authHeaders(opts) {
121
- return {};
122
- }
123
- /**
124
- * Override this to add your own default headers, for example:
125
- *
126
- * {
127
- * ...super.defaultHeaders(),
128
- * Authorization: 'Bearer 123',
129
- * }
130
- */
131
- defaultHeaders(opts) {
132
- return {
133
- Accept: 'application/json',
134
- 'Content-Type': 'application/json',
135
- 'User-Agent': this.getUserAgent(),
136
- ...getPlatformHeaders(),
137
- ...this.authHeaders(opts),
138
- };
139
- }
140
- /**
141
- * Override this to add your own headers validation:
142
- */
143
- validateHeaders(headers, customHeaders) {}
144
- defaultIdempotencyKey() {
145
- return `stainless-node-retry-${uuid4()}`;
146
- }
147
- get(path, opts) {
148
- return this.methodRequest('get', path, opts);
149
- }
150
- post(path, opts) {
151
- return this.methodRequest('post', path, opts);
152
- }
153
- patch(path, opts) {
154
- return this.methodRequest('patch', path, opts);
155
- }
156
- put(path, opts) {
157
- return this.methodRequest('put', path, opts);
158
- }
159
- delete(path, opts) {
160
- return this.methodRequest('delete', path, opts);
161
- }
162
- methodRequest(method, path, opts) {
163
- return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
164
- }
165
- getAPIList(path, Page, opts) {
166
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
167
- }
168
- calculateContentLength(body) {
169
- if (typeof body === 'string') {
170
- if (typeof Buffer !== 'undefined') {
171
- return Buffer.byteLength(body, 'utf8').toString();
172
- }
173
- if (typeof TextEncoder !== 'undefined') {
174
- const encoder = new TextEncoder();
175
- const encoded = encoder.encode(body);
176
- return encoded.length.toString();
177
- }
100
+ constructor({ baseURL, maxRetries, timeout = 60000, // 1 minute
101
+ httpAgent, fetch: overridenFetch, }) {
102
+ this.baseURL = baseURL;
103
+ this.maxRetries = validatePositiveInteger('maxRetries', maxRetries ?? MAX_RETRIES);
104
+ this.timeout = validatePositiveInteger('timeout', timeout);
105
+ this.httpAgent = httpAgent;
106
+ this.fetch = overridenFetch ?? fetch;
178
107
  }
179
- return null;
180
- }
181
- buildRequest(options) {
182
- var _a, _b, _c, _d, _e, _f;
183
- const { method, path, query, headers: headers = {} } = options;
184
- const body =
185
- isMultipartBody(options.body) ? options.body.body
186
- : options.body ? JSON.stringify(options.body, null, 2)
187
- : null;
188
- const contentLength = this.calculateContentLength(body);
189
- const url = this.buildURL(path, query);
190
- if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
191
- const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.timeout;
192
- const httpAgent =
193
- (
194
- (_c = (_b = options.httpAgent) !== null && _b !== void 0 ? _b : this.httpAgent) !== null &&
195
- _c !== void 0
196
- ) ?
197
- _c
198
- : getDefaultAgent(url);
199
- const minAgentTimeout = timeout + 1000;
200
- if (
201
- typeof ((
202
- (_d = httpAgent === null || httpAgent === void 0 ? void 0 : httpAgent.options) === null ||
203
- _d === void 0
204
- ) ?
205
- void 0
206
- : _d.timeout) === 'number' &&
207
- minAgentTimeout > ((_e = httpAgent.options.timeout) !== null && _e !== void 0 ? _e : 0)
208
- ) {
209
- // Allow any given request to bump our agent active socket timeout.
210
- // This may seem strange, but leaking active sockets should be rare and not particularly problematic,
211
- // and without mutating agent we would need to create more of them.
212
- // This tradeoff optimizes for performance.
213
- httpAgent.options.timeout = minAgentTimeout;
214
- }
215
- if (this.idempotencyHeader && method !== 'get') {
216
- if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
217
- headers[this.idempotencyHeader] = options.idempotencyKey;
218
- }
219
- const reqHeaders = {
220
- ...(contentLength && { 'Content-Length': contentLength }),
221
- ...this.defaultHeaders(options),
222
- ...headers,
223
- };
224
- // let builtin fetch set the Content-Type for multipart bodies
225
- if (isMultipartBody(options.body) && !fetchIsPolyfilled) {
226
- delete reqHeaders['Content-Type'];
227
- }
228
- // Strip any headers being explicitly omitted with null
229
- Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]);
230
- const req = {
231
- method,
232
- ...(body && { body: body }),
233
- headers: reqHeaders,
234
- ...(httpAgent && { agent: httpAgent }),
235
- // @ts-ignore node-fetch uses a custom AbortSignal type that is
236
- // not compatible with standard web types
237
- signal: (_f = options.signal) !== null && _f !== void 0 ? _f : null,
238
- };
239
- this.validateHeaders(reqHeaders, headers);
240
- return { req, url, timeout };
241
- }
242
- /**
243
- * Used as a callback for mutating the given `RequestInit` object.
244
- *
245
- * This is useful for cases where you want to add certain headers based off of
246
- * the request properties, e.g. `method` or `url`.
247
- */
248
- async prepareRequest(request, { url, options }) {}
249
- parseHeaders(headers) {
250
- return (
251
- !headers ? {}
252
- : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header]))
253
- : { ...headers }
254
- );
255
- }
256
- makeStatusError(status, error, message, headers) {
257
- return APIError.generate(status, error, message, headers);
258
- }
259
- request(options, remainingRetries = null) {
260
- return new APIPromise(this.makeRequest(options, remainingRetries));
261
- }
262
- async makeRequest(optionsInput, retriesRemaining) {
263
- var _a, _b, _c;
264
- const options = await optionsInput;
265
- if (retriesRemaining == null) {
266
- retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
267
- }
268
- const { req, url, timeout } = this.buildRequest(options);
269
- await this.prepareRequest(req, { url, options });
270
- debug('request', url, options, req.headers);
271
- if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) {
272
- throw new APIUserAbortError();
273
- }
274
- const controller = new AbortController();
275
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
276
- if (response instanceof Error) {
277
- if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
278
- throw new APIUserAbortError();
279
- }
280
- if (retriesRemaining) {
281
- return this.retryRequest(options, retriesRemaining);
282
- }
283
- if (response.name === 'AbortError') {
284
- throw new APIConnectionTimeoutError();
285
- }
286
- throw new APIConnectionError({ cause: response });
287
- }
288
- const responseHeaders = createResponseHeaders(response.headers);
289
- if (!response.ok) {
290
- if (retriesRemaining && this.shouldRetry(response)) {
291
- return this.retryRequest(options, retriesRemaining, responseHeaders);
292
- }
293
- const errText = await response.text().catch((e) => castToError(e).message);
294
- const errJSON = safeJSON(errText);
295
- const errMessage = errJSON ? undefined : errText;
296
- debug('response', response.status, url, responseHeaders, errMessage);
297
- const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
298
- throw err;
299
- }
300
- return { response, options, controller };
301
- }
302
- requestAPIList(Page, options) {
303
- const request = this.makeRequest(options, null);
304
- return new PagePromise(this, request, Page);
305
- }
306
- buildURL(path, query) {
307
- const url =
308
- isAbsoluteURL(path) ?
309
- new URL(path)
310
- : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
311
- const defaultQuery = this.defaultQuery();
312
- if (!isEmptyObj(defaultQuery)) {
313
- query = { ...defaultQuery, ...query };
314
- }
315
- if (query) {
316
- url.search = this.stringifyQuery(query);
317
- }
318
- return url.toString();
319
- }
320
- stringifyQuery(query) {
321
- return Object.entries(query)
322
- .filter(([_, value]) => typeof value !== 'undefined')
323
- .map(([key, value]) => {
324
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
325
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
108
+ authHeaders(opts) {
109
+ return {};
110
+ }
111
+ /**
112
+ * Override this to add your own default headers, for example:
113
+ *
114
+ * {
115
+ * ...super.defaultHeaders(),
116
+ * Authorization: 'Bearer 123',
117
+ * }
118
+ */
119
+ defaultHeaders(opts) {
120
+ return {
121
+ Accept: 'application/json',
122
+ 'Content-Type': 'application/json',
123
+ 'User-Agent': this.getUserAgent(),
124
+ ...getPlatformHeaders(),
125
+ ...this.authHeaders(opts),
126
+ };
127
+ }
128
+ /**
129
+ * Override this to add your own headers validation:
130
+ */
131
+ validateHeaders(headers, customHeaders) { }
132
+ defaultIdempotencyKey() {
133
+ return `stainless-node-retry-${uuid4()}`;
134
+ }
135
+ get(path, opts) {
136
+ return this.methodRequest('get', path, opts);
137
+ }
138
+ post(path, opts) {
139
+ return this.methodRequest('post', path, opts);
140
+ }
141
+ patch(path, opts) {
142
+ return this.methodRequest('patch', path, opts);
143
+ }
144
+ put(path, opts) {
145
+ return this.methodRequest('put', path, opts);
146
+ }
147
+ delete(path, opts) {
148
+ return this.methodRequest('delete', path, opts);
149
+ }
150
+ methodRequest(method, path, opts) {
151
+ return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
152
+ }
153
+ getAPIList(path, Page, opts) {
154
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
155
+ }
156
+ calculateContentLength(body) {
157
+ if (typeof body === 'string') {
158
+ if (typeof Buffer !== 'undefined') {
159
+ return Buffer.byteLength(body, 'utf8').toString();
160
+ }
161
+ if (typeof TextEncoder !== 'undefined') {
162
+ const encoder = new TextEncoder();
163
+ const encoded = encoder.encode(body);
164
+ return encoded.length.toString();
165
+ }
166
+ }
167
+ return null;
168
+ }
169
+ buildRequest(options) {
170
+ const { method, path, query, headers: headers = {} } = options;
171
+ const body = isMultipartBody(options.body) ? options.body.body
172
+ : options.body ? JSON.stringify(options.body, null, 2)
173
+ : null;
174
+ const contentLength = this.calculateContentLength(body);
175
+ const url = this.buildURL(path, query);
176
+ if ('timeout' in options)
177
+ validatePositiveInteger('timeout', options.timeout);
178
+ const timeout = options.timeout ?? this.timeout;
179
+ const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
180
+ const minAgentTimeout = timeout + 1000;
181
+ if (typeof httpAgent?.options?.timeout === 'number' &&
182
+ minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
183
+ // Allow any given request to bump our agent active socket timeout.
184
+ // This may seem strange, but leaking active sockets should be rare and not particularly problematic,
185
+ // and without mutating agent we would need to create more of them.
186
+ // This tradeoff optimizes for performance.
187
+ httpAgent.options.timeout = minAgentTimeout;
188
+ }
189
+ if (this.idempotencyHeader && method !== 'get') {
190
+ if (!options.idempotencyKey)
191
+ options.idempotencyKey = this.defaultIdempotencyKey();
192
+ headers[this.idempotencyHeader] = options.idempotencyKey;
193
+ }
194
+ const reqHeaders = {
195
+ ...(contentLength && { 'Content-Length': contentLength }),
196
+ ...this.defaultHeaders(options),
197
+ ...headers,
198
+ };
199
+ // let builtin fetch set the Content-Type for multipart bodies
200
+ if (isMultipartBody(options.body) && shimsKind !== 'node') {
201
+ delete reqHeaders['Content-Type'];
202
+ }
203
+ // Strip any headers being explicitly omitted with null
204
+ Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]);
205
+ const req = {
206
+ method,
207
+ ...(body && { body: body }),
208
+ headers: reqHeaders,
209
+ ...(httpAgent && { agent: httpAgent }),
210
+ // @ts-ignore node-fetch uses a custom AbortSignal type that is
211
+ // not compatible with standard web types
212
+ signal: options.signal ?? null,
213
+ };
214
+ this.validateHeaders(reqHeaders, headers);
215
+ return { req, url, timeout };
216
+ }
217
+ /**
218
+ * Used as a callback for mutating the given `RequestInit` object.
219
+ *
220
+ * This is useful for cases where you want to add certain headers based off of
221
+ * the request properties, e.g. `method` or `url`.
222
+ */
223
+ async prepareRequest(request, { url, options }) { }
224
+ parseHeaders(headers) {
225
+ return (!headers ? {}
226
+ : Symbol.iterator in headers ?
227
+ Object.fromEntries(Array.from(headers).map((header) => [...header]))
228
+ : { ...headers });
229
+ }
230
+ makeStatusError(status, error, message, headers) {
231
+ return APIError.generate(status, error, message, headers);
232
+ }
233
+ request(options, remainingRetries = null) {
234
+ return new APIPromise(this.makeRequest(options, remainingRetries));
235
+ }
236
+ async makeRequest(optionsInput, retriesRemaining) {
237
+ const options = await optionsInput;
238
+ if (retriesRemaining == null) {
239
+ retriesRemaining = options.maxRetries ?? this.maxRetries;
240
+ }
241
+ const { req, url, timeout } = this.buildRequest(options);
242
+ await this.prepareRequest(req, { url, options });
243
+ debug('request', url, options, req.headers);
244
+ if (options.signal?.aborted) {
245
+ throw new APIUserAbortError();
326
246
  }
327
- if (value === null) {
328
- return `${encodeURIComponent(key)}=`;
247
+ const controller = new AbortController();
248
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
249
+ if (response instanceof Error) {
250
+ if (options.signal?.aborted) {
251
+ throw new APIUserAbortError();
252
+ }
253
+ if (retriesRemaining) {
254
+ return this.retryRequest(options, retriesRemaining);
255
+ }
256
+ if (response.name === 'AbortError') {
257
+ throw new APIConnectionTimeoutError();
258
+ }
259
+ throw new APIConnectionError({ cause: response });
329
260
  }
330
- throw new Error(
331
- `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`,
332
- );
333
- })
334
- .join('&');
335
- }
336
- async fetchWithTimeout(url, init, ms, controller) {
337
- const { signal, ...options } = init || {};
338
- if (signal) signal.addEventListener('abort', () => controller.abort());
339
- const timeout = setTimeout(() => controller.abort(), ms);
340
- return this.getRequestClient()
341
- .fetch(url, { signal: controller.signal, ...options })
342
- .finally(() => {
343
- clearTimeout(timeout);
344
- });
345
- }
346
- getRequestClient() {
347
- return { fetch: this.fetch };
348
- }
349
- shouldRetry(response) {
350
- // Note this is not a standard header.
351
- const shouldRetryHeader = response.headers.get('x-should-retry');
352
- // If the server explicitly says whether or not to retry, obey.
353
- if (shouldRetryHeader === 'true') return true;
354
- if (shouldRetryHeader === 'false') return false;
355
- // Retry on request timeouts.
356
- if (response.status === 408) return true;
357
- // Retry on lock timeouts.
358
- if (response.status === 409) return true;
359
- // Retry on rate limits.
360
- if (response.status === 429) return true;
361
- // Retry internal errors.
362
- if (response.status >= 500) return true;
363
- return false;
364
- }
365
- async retryRequest(options, retriesRemaining, responseHeaders) {
366
- var _a;
367
- retriesRemaining -= 1;
368
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
369
- //
370
- // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
371
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
372
- const retryAfter = parseInt(
373
- (responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) ||
374
- '',
375
- );
376
- const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
377
- const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
378
- await sleep(timeout);
379
- return this.makeRequest(options, retriesRemaining);
380
- }
381
- calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) {
382
- const initialRetryDelay = 0.5;
383
- const maxRetryDelay = 2;
384
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
385
- // just do what it says.
386
- if (Number.isInteger(retryAfter) && retryAfter <= 60) {
387
- return retryAfter;
388
- }
389
- const numRetries = maxRetries - retriesRemaining;
390
- // Apply exponential backoff, but not more than the max.
391
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
392
- // Apply some jitter, plus-or-minus half a second.
393
- const jitter = Math.random() - 0.5;
394
- return sleepSeconds + jitter;
395
- }
396
- getUserAgent() {
397
- return `${this.constructor.name}/JS ${VERSION}`;
398
- }
261
+ const responseHeaders = createResponseHeaders(response.headers);
262
+ if (!response.ok) {
263
+ if (retriesRemaining && this.shouldRetry(response)) {
264
+ return this.retryRequest(options, retriesRemaining, responseHeaders);
265
+ }
266
+ const errText = await response.text().catch((e) => castToError(e).message);
267
+ const errJSON = safeJSON(errText);
268
+ const errMessage = errJSON ? undefined : errText;
269
+ debug('response', response.status, url, responseHeaders, errMessage);
270
+ const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
271
+ throw err;
272
+ }
273
+ return { response, options, controller };
274
+ }
275
+ requestAPIList(Page, options) {
276
+ const request = this.makeRequest(options, null);
277
+ return new PagePromise(this, request, Page);
278
+ }
279
+ buildURL(path, query) {
280
+ const url = isAbsoluteURL(path) ?
281
+ new URL(path)
282
+ : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
283
+ const defaultQuery = this.defaultQuery();
284
+ if (!isEmptyObj(defaultQuery)) {
285
+ query = { ...defaultQuery, ...query };
286
+ }
287
+ if (query) {
288
+ url.search = this.stringifyQuery(query);
289
+ }
290
+ return url.toString();
291
+ }
292
+ stringifyQuery(query) {
293
+ return Object.entries(query)
294
+ .filter(([_, value]) => typeof value !== 'undefined')
295
+ .map(([key, value]) => {
296
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
297
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
298
+ }
299
+ if (value === null) {
300
+ return `${encodeURIComponent(key)}=`;
301
+ }
302
+ throw new ModernTreasuryError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
303
+ })
304
+ .join('&');
305
+ }
306
+ async fetchWithTimeout(url, init, ms, controller) {
307
+ const { signal, ...options } = init || {};
308
+ if (signal)
309
+ signal.addEventListener('abort', () => controller.abort());
310
+ const timeout = setTimeout(() => controller.abort(), ms);
311
+ return (this.getRequestClient()
312
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
313
+ .fetch.call(undefined, url, { signal: controller.signal, ...options })
314
+ .finally(() => {
315
+ clearTimeout(timeout);
316
+ }));
317
+ }
318
+ getRequestClient() {
319
+ return { fetch: this.fetch };
320
+ }
321
+ shouldRetry(response) {
322
+ // Note this is not a standard header.
323
+ const shouldRetryHeader = response.headers.get('x-should-retry');
324
+ // If the server explicitly says whether or not to retry, obey.
325
+ if (shouldRetryHeader === 'true')
326
+ return true;
327
+ if (shouldRetryHeader === 'false')
328
+ return false;
329
+ // Retry on request timeouts.
330
+ if (response.status === 408)
331
+ return true;
332
+ // Retry on lock timeouts.
333
+ if (response.status === 409)
334
+ return true;
335
+ // Retry on rate limits.
336
+ if (response.status === 429)
337
+ return true;
338
+ // Retry internal errors.
339
+ if (response.status >= 500)
340
+ return true;
341
+ return false;
342
+ }
343
+ async retryRequest(options, retriesRemaining, responseHeaders) {
344
+ retriesRemaining -= 1;
345
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
346
+ let timeoutMillis;
347
+ const retryAfterHeader = responseHeaders?.['retry-after'];
348
+ if (retryAfterHeader) {
349
+ const timeoutSeconds = parseInt(retryAfterHeader);
350
+ if (!Number.isNaN(timeoutSeconds)) {
351
+ timeoutMillis = timeoutSeconds * 1000;
352
+ }
353
+ else {
354
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
355
+ }
356
+ }
357
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
358
+ // just do what it says, but otherwise calculate a default
359
+ if (!timeoutMillis ||
360
+ !Number.isInteger(timeoutMillis) ||
361
+ timeoutMillis <= 0 ||
362
+ timeoutMillis > 60 * 1000) {
363
+ const maxRetries = options.maxRetries ?? this.maxRetries;
364
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
365
+ }
366
+ await sleep(timeoutMillis);
367
+ return this.makeRequest(options, retriesRemaining);
368
+ }
369
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
370
+ const initialRetryDelay = 0.5;
371
+ const maxRetryDelay = 2;
372
+ const numRetries = maxRetries - retriesRemaining;
373
+ // Apply exponential backoff, but not more than the max.
374
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
375
+ // Apply some jitter, plus-or-minus half a second.
376
+ const jitter = Math.random() - 0.5;
377
+ return (sleepSeconds + jitter) * 1000;
378
+ }
379
+ getUserAgent() {
380
+ return `${this.constructor.name}/JS ${VERSION}`;
381
+ }
399
382
  }
400
383
  export class APIResource {
401
- constructor(client) {
402
- this.client = client;
403
- this.get = client.get.bind(client);
404
- this.post = client.post.bind(client);
405
- this.patch = client.patch.bind(client);
406
- this.put = client.put.bind(client);
407
- this.delete = client.delete.bind(client);
408
- this.getAPIList = client.getAPIList.bind(client);
409
- }
384
+ constructor(client) {
385
+ this.client = client;
386
+ this.get = client.get.bind(client);
387
+ this.post = client.post.bind(client);
388
+ this.patch = client.patch.bind(client);
389
+ this.put = client.put.bind(client);
390
+ this.delete = client.delete.bind(client);
391
+ this.getAPIList = client.getAPIList.bind(client);
392
+ }
410
393
  }
411
394
  export class AbstractPage {
412
- constructor(client, response, body, options) {
413
- _AbstractPage_client.set(this, void 0);
414
- __classPrivateFieldSet(this, _AbstractPage_client, client, 'f');
415
- this.options = options;
416
- this.response = response;
417
- this.body = body;
418
- }
419
- hasNextPage() {
420
- const items = this.getPaginatedItems();
421
- if (!items.length) return false;
422
- return this.nextPageInfo() != null;
423
- }
424
- async getNextPage() {
425
- const nextInfo = this.nextPageInfo();
426
- if (!nextInfo) {
427
- throw new Error(
428
- 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
429
- );
430
- }
431
- const nextOptions = { ...this.options };
432
- if ('params' in nextInfo) {
433
- nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
434
- } else if ('url' in nextInfo) {
435
- const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
436
- for (const [key, value] of params) {
437
- nextInfo.url.searchParams.set(key, value);
438
- }
439
- nextOptions.query = undefined;
440
- nextOptions.path = nextInfo.url.toString();
441
- }
442
- return await __classPrivateFieldGet(this, _AbstractPage_client, 'f').requestAPIList(
443
- this.constructor,
444
- nextOptions,
445
- );
446
- }
447
- async *iterPages() {
448
- // eslint-disable-next-line @typescript-eslint/no-this-alias
449
- let page = this;
450
- yield page;
451
- while (page.hasNextPage()) {
452
- page = await page.getNextPage();
453
- yield page;
454
- }
455
- }
456
- async *[((_AbstractPage_client = new WeakMap()), Symbol.asyncIterator)]() {
457
- for await (const page of this.iterPages()) {
458
- for (const item of page.getPaginatedItems()) {
459
- yield item;
460
- }
461
- }
462
- }
395
+ constructor(client, response, body, options) {
396
+ _AbstractPage_client.set(this, void 0);
397
+ __classPrivateFieldSet(this, _AbstractPage_client, client, "f");
398
+ this.options = options;
399
+ this.response = response;
400
+ this.body = body;
401
+ }
402
+ hasNextPage() {
403
+ const items = this.getPaginatedItems();
404
+ if (!items.length)
405
+ return false;
406
+ return this.nextPageInfo() != null;
407
+ }
408
+ async getNextPage() {
409
+ const nextInfo = this.nextPageInfo();
410
+ if (!nextInfo) {
411
+ throw new ModernTreasuryError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
412
+ }
413
+ const nextOptions = { ...this.options };
414
+ if ('params' in nextInfo) {
415
+ nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
416
+ }
417
+ else if ('url' in nextInfo) {
418
+ const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
419
+ for (const [key, value] of params) {
420
+ nextInfo.url.searchParams.set(key, value);
421
+ }
422
+ nextOptions.query = undefined;
423
+ nextOptions.path = nextInfo.url.toString();
424
+ }
425
+ return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
426
+ }
427
+ async *iterPages() {
428
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
429
+ let page = this;
430
+ yield page;
431
+ while (page.hasNextPage()) {
432
+ page = await page.getNextPage();
433
+ yield page;
434
+ }
435
+ }
436
+ async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
437
+ for await (const page of this.iterPages()) {
438
+ for (const item of page.getPaginatedItems()) {
439
+ yield item;
440
+ }
441
+ }
442
+ }
463
443
  }
464
444
  /**
465
445
  * This subclass of Promise will resolve to an instantiated Page once the request completes.
@@ -471,211 +451,216 @@ export class AbstractPage {
471
451
  * }
472
452
  */
473
453
  export class PagePromise extends APIPromise {
474
- constructor(client, request, Page) {
475
- super(
476
- request,
477
- async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options),
478
- );
479
- }
480
- /**
481
- * Allow auto-paginating iteration on an unawaited list call, eg:
482
- *
483
- * for await (const item of client.items.list()) {
484
- * console.log(item)
485
- * }
486
- */
487
- async *[Symbol.asyncIterator]() {
488
- const page = await this;
489
- for await (const item of page) {
490
- yield item;
491
- }
492
- }
454
+ constructor(client, request, Page) {
455
+ super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
456
+ }
457
+ /**
458
+ * Allow auto-paginating iteration on an unawaited list call, eg:
459
+ *
460
+ * for await (const item of client.items.list()) {
461
+ * console.log(item)
462
+ * }
463
+ */
464
+ async *[Symbol.asyncIterator]() {
465
+ const page = await this;
466
+ for await (const item of page) {
467
+ yield item;
468
+ }
469
+ }
493
470
  }
494
471
  export const createResponseHeaders = (headers) => {
495
- return new Proxy(
496
- Object.fromEntries(
497
- // @ts-ignore
498
- headers.entries(),
499
- ),
500
- {
501
- get(target, name) {
502
- const key = name.toString();
503
- return target[key.toLowerCase()] || target[key];
504
- },
505
- },
506
- );
472
+ return new Proxy(Object.fromEntries(
473
+ // @ts-ignore
474
+ headers.entries()), {
475
+ get(target, name) {
476
+ const key = name.toString();
477
+ return target[key.toLowerCase()] || target[key];
478
+ },
479
+ });
507
480
  };
508
481
  // This is required so that we can determine if a given object matches the RequestOptions
509
482
  // type at runtime. While this requires duplication, it is enforced by the TypeScript
510
483
  // compiler such that any missing / extraneous keys will cause an error.
511
484
  const requestOptionsKeys = {
512
- method: true,
513
- path: true,
514
- query: true,
515
- body: true,
516
- headers: true,
517
- maxRetries: true,
518
- stream: true,
519
- timeout: true,
520
- httpAgent: true,
521
- signal: true,
522
- idempotencyKey: true,
485
+ method: true,
486
+ path: true,
487
+ query: true,
488
+ body: true,
489
+ headers: true,
490
+ maxRetries: true,
491
+ stream: true,
492
+ timeout: true,
493
+ httpAgent: true,
494
+ signal: true,
495
+ idempotencyKey: true,
523
496
  };
524
497
  export const isRequestOptions = (obj) => {
525
- return (
526
- typeof obj === 'object' &&
527
- obj !== null &&
528
- !isEmptyObj(obj) &&
529
- Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
530
- );
498
+ return (typeof obj === 'object' &&
499
+ obj !== null &&
500
+ !isEmptyObj(obj) &&
501
+ Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
531
502
  };
532
503
  const getPlatformProperties = () => {
533
- if (typeof Deno !== 'undefined' && Deno.build != null) {
534
- return {
535
- 'X-Stainless-Lang': 'js',
536
- 'X-Stainless-Package-Version': VERSION,
537
- 'X-Stainless-OS': normalizePlatform(Deno.build.os),
538
- 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
539
- 'X-Stainless-Runtime': 'deno',
540
- 'X-Stainless-Runtime-Version': Deno.version,
541
- };
542
- }
543
- if (typeof EdgeRuntime !== 'undefined') {
544
- return {
545
- 'X-Stainless-Lang': 'js',
546
- 'X-Stainless-Package-Version': VERSION,
547
- 'X-Stainless-OS': 'Unknown',
548
- 'X-Stainless-Arch': `other:${EdgeRuntime}`,
549
- 'X-Stainless-Runtime': 'edge',
550
- 'X-Stainless-Runtime-Version': process.version,
551
- };
552
- }
553
- // Check if Node.js
554
- if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
555
- return {
556
- 'X-Stainless-Lang': 'js',
557
- 'X-Stainless-Package-Version': VERSION,
558
- 'X-Stainless-OS': normalizePlatform(process.platform),
559
- 'X-Stainless-Arch': normalizeArch(process.arch),
560
- 'X-Stainless-Runtime': 'node',
561
- 'X-Stainless-Runtime-Version': process.version,
562
- };
563
- }
564
- const browserInfo = getBrowserInfo();
565
- if (browserInfo) {
504
+ if (typeof Deno !== 'undefined' && Deno.build != null) {
505
+ return {
506
+ 'X-Stainless-Lang': 'js',
507
+ 'X-Stainless-Package-Version': VERSION,
508
+ 'X-Stainless-OS': normalizePlatform(Deno.build.os),
509
+ 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
510
+ 'X-Stainless-Runtime': 'deno',
511
+ 'X-Stainless-Runtime-Version': Deno.version,
512
+ };
513
+ }
514
+ if (typeof EdgeRuntime !== 'undefined') {
515
+ return {
516
+ 'X-Stainless-Lang': 'js',
517
+ 'X-Stainless-Package-Version': VERSION,
518
+ 'X-Stainless-OS': 'Unknown',
519
+ 'X-Stainless-Arch': `other:${EdgeRuntime}`,
520
+ 'X-Stainless-Runtime': 'edge',
521
+ 'X-Stainless-Runtime-Version': process.version,
522
+ };
523
+ }
524
+ // Check if Node.js
525
+ if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
526
+ return {
527
+ 'X-Stainless-Lang': 'js',
528
+ 'X-Stainless-Package-Version': VERSION,
529
+ 'X-Stainless-OS': normalizePlatform(process.platform),
530
+ 'X-Stainless-Arch': normalizeArch(process.arch),
531
+ 'X-Stainless-Runtime': 'node',
532
+ 'X-Stainless-Runtime-Version': process.version,
533
+ };
534
+ }
535
+ const browserInfo = getBrowserInfo();
536
+ if (browserInfo) {
537
+ return {
538
+ 'X-Stainless-Lang': 'js',
539
+ 'X-Stainless-Package-Version': VERSION,
540
+ 'X-Stainless-OS': 'Unknown',
541
+ 'X-Stainless-Arch': 'unknown',
542
+ 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
543
+ 'X-Stainless-Runtime-Version': browserInfo.version,
544
+ };
545
+ }
546
+ // TODO add support for Cloudflare workers, etc.
566
547
  return {
567
- 'X-Stainless-Lang': 'js',
568
- 'X-Stainless-Package-Version': VERSION,
569
- 'X-Stainless-OS': 'Unknown',
570
- 'X-Stainless-Arch': 'unknown',
571
- 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
572
- 'X-Stainless-Runtime-Version': browserInfo.version,
548
+ 'X-Stainless-Lang': 'js',
549
+ 'X-Stainless-Package-Version': VERSION,
550
+ 'X-Stainless-OS': 'Unknown',
551
+ 'X-Stainless-Arch': 'unknown',
552
+ 'X-Stainless-Runtime': 'unknown',
553
+ 'X-Stainless-Runtime-Version': 'unknown',
573
554
  };
574
- }
575
- // TODO add support for Cloudflare workers, etc.
576
- return {
577
- 'X-Stainless-Lang': 'js',
578
- 'X-Stainless-Package-Version': VERSION,
579
- 'X-Stainless-OS': 'Unknown',
580
- 'X-Stainless-Arch': 'unknown',
581
- 'X-Stainless-Runtime': 'unknown',
582
- 'X-Stainless-Runtime-Version': 'unknown',
583
- };
584
555
  };
585
556
  // Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
586
557
  function getBrowserInfo() {
587
- if (typeof navigator === 'undefined' || !navigator) {
558
+ if (typeof navigator === 'undefined' || !navigator) {
559
+ return null;
560
+ }
561
+ // NOTE: The order matters here!
562
+ const browserPatterns = [
563
+ { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
564
+ { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
565
+ { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
566
+ { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
567
+ { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
568
+ { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
569
+ ];
570
+ // Find the FIRST matching browser
571
+ for (const { key, pattern } of browserPatterns) {
572
+ const match = pattern.exec(navigator.userAgent);
573
+ if (match) {
574
+ const major = match[1] || 0;
575
+ const minor = match[2] || 0;
576
+ const patch = match[3] || 0;
577
+ return { browser: key, version: `${major}.${minor}.${patch}` };
578
+ }
579
+ }
588
580
  return null;
589
- }
590
- // NOTE: The order matters here!
591
- const browserPatterns = [
592
- { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
593
- { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
594
- { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
595
- { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
596
- { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
597
- { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
598
- ];
599
- // Find the FIRST matching browser
600
- for (const { key, pattern } of browserPatterns) {
601
- const match = pattern.exec(navigator.userAgent);
602
- if (match) {
603
- const major = match[1] || 0;
604
- const minor = match[2] || 0;
605
- const patch = match[3] || 0;
606
- return { browser: key, version: `${major}.${minor}.${patch}` };
607
- }
608
- }
609
- return null;
610
581
  }
611
582
  const normalizeArch = (arch) => {
612
- // Node docs:
613
- // - https://nodejs.org/api/process.html#processarch
614
- // Deno docs:
615
- // - https://doc.deno.land/deno/stable/~/Deno.build
616
- if (arch === 'x32') return 'x32';
617
- if (arch === 'x86_64' || arch === 'x64') return 'x64';
618
- if (arch === 'arm') return 'arm';
619
- if (arch === 'aarch64' || arch === 'arm64') return 'arm64';
620
- if (arch) return `other:${arch}`;
621
- return 'unknown';
583
+ // Node docs:
584
+ // - https://nodejs.org/api/process.html#processarch
585
+ // Deno docs:
586
+ // - https://doc.deno.land/deno/stable/~/Deno.build
587
+ if (arch === 'x32')
588
+ return 'x32';
589
+ if (arch === 'x86_64' || arch === 'x64')
590
+ return 'x64';
591
+ if (arch === 'arm')
592
+ return 'arm';
593
+ if (arch === 'aarch64' || arch === 'arm64')
594
+ return 'arm64';
595
+ if (arch)
596
+ return `other:${arch}`;
597
+ return 'unknown';
622
598
  };
623
599
  const normalizePlatform = (platform) => {
624
- // Node platforms:
625
- // - https://nodejs.org/api/process.html#processplatform
626
- // Deno platforms:
627
- // - https://doc.deno.land/deno/stable/~/Deno.build
628
- // - https://github.com/denoland/deno/issues/14799
629
- platform = platform.toLowerCase();
630
- // NOTE: this iOS check is untested and may not work
631
- // Node does not work natively on IOS, there is a fork at
632
- // https://github.com/nodejs-mobile/nodejs-mobile
633
- // however it is unknown at the time of writing how to detect if it is running
634
- if (platform.includes('ios')) return 'iOS';
635
- if (platform === 'android') return 'Android';
636
- if (platform === 'darwin') return 'MacOS';
637
- if (platform === 'win32') return 'Windows';
638
- if (platform === 'freebsd') return 'FreeBSD';
639
- if (platform === 'openbsd') return 'OpenBSD';
640
- if (platform === 'linux') return 'Linux';
641
- if (platform) return `Other:${platform}`;
642
- return 'Unknown';
600
+ // Node platforms:
601
+ // - https://nodejs.org/api/process.html#processplatform
602
+ // Deno platforms:
603
+ // - https://doc.deno.land/deno/stable/~/Deno.build
604
+ // - https://github.com/denoland/deno/issues/14799
605
+ platform = platform.toLowerCase();
606
+ // NOTE: this iOS check is untested and may not work
607
+ // Node does not work natively on IOS, there is a fork at
608
+ // https://github.com/nodejs-mobile/nodejs-mobile
609
+ // however it is unknown at the time of writing how to detect if it is running
610
+ if (platform.includes('ios'))
611
+ return 'iOS';
612
+ if (platform === 'android')
613
+ return 'Android';
614
+ if (platform === 'darwin')
615
+ return 'MacOS';
616
+ if (platform === 'win32')
617
+ return 'Windows';
618
+ if (platform === 'freebsd')
619
+ return 'FreeBSD';
620
+ if (platform === 'openbsd')
621
+ return 'OpenBSD';
622
+ if (platform === 'linux')
623
+ return 'Linux';
624
+ if (platform)
625
+ return `Other:${platform}`;
626
+ return 'Unknown';
643
627
  };
644
628
  let _platformHeaders;
645
629
  const getPlatformHeaders = () => {
646
- return _platformHeaders !== null && _platformHeaders !== void 0 ?
647
- _platformHeaders
648
- : (_platformHeaders = getPlatformProperties());
630
+ return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
649
631
  };
650
632
  export const safeJSON = (text) => {
651
- try {
652
- return JSON.parse(text);
653
- } catch (err) {
654
- return undefined;
655
- }
633
+ try {
634
+ return JSON.parse(text);
635
+ }
636
+ catch (err) {
637
+ return undefined;
638
+ }
656
639
  };
657
640
  // https://stackoverflow.com/a/19709846
658
641
  const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
659
642
  const isAbsoluteURL = (url) => {
660
- return startsWithSchemeRegexp.test(url);
643
+ return startsWithSchemeRegexp.test(url);
661
644
  };
662
645
  export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
663
646
  const validatePositiveInteger = (name, n) => {
664
- if (typeof n !== 'number' || !Number.isInteger(n)) {
665
- throw new Error(`${name} must be an integer`);
666
- }
667
- if (n < 0) {
668
- throw new Error(`${name} must be a positive integer`);
669
- }
670
- return n;
647
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
648
+ throw new ModernTreasuryError(`${name} must be an integer`);
649
+ }
650
+ if (n < 0) {
651
+ throw new ModernTreasuryError(`${name} must be a positive integer`);
652
+ }
653
+ return n;
671
654
  };
672
655
  export const castToError = (err) => {
673
- if (err instanceof Error) return err;
674
- return new Error(err);
656
+ if (err instanceof Error)
657
+ return err;
658
+ return new Error(err);
675
659
  };
676
660
  export const ensurePresent = (value) => {
677
- if (value == null) throw new Error(`Expected a value to be given but received ${value} instead.`);
678
- return value;
661
+ if (value == null)
662
+ throw new ModernTreasuryError(`Expected a value to be given but received ${value} instead.`);
663
+ return value;
679
664
  };
680
665
  /**
681
666
  * Read an environment variable.
@@ -683,112 +668,117 @@ export const ensurePresent = (value) => {
683
668
  * Will return undefined if the environment variable doesn't exist or cannot be accessed.
684
669
  */
685
670
  export const readEnv = (env) => {
686
- var _a, _b, _c, _d;
687
- if (typeof process !== 'undefined') {
688
- return (_b = (_a = process.env) === null || _a === void 0 ? void 0 : _a[env]) !== null && _b !== void 0 ?
689
- _b
690
- : undefined;
691
- }
692
- if (typeof Deno !== 'undefined') {
693
- return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ?
694
- void 0
695
- : _d.call(_c, env);
696
- }
697
- return undefined;
671
+ if (typeof process !== 'undefined') {
672
+ return process.env?.[env] ?? undefined;
673
+ }
674
+ if (typeof Deno !== 'undefined') {
675
+ return Deno.env?.get?.(env);
676
+ }
677
+ return undefined;
698
678
  };
699
679
  export const coerceInteger = (value) => {
700
- if (typeof value === 'number') return Math.round(value);
701
- if (typeof value === 'string') return parseInt(value, 10);
702
- throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
680
+ if (typeof value === 'number')
681
+ return Math.round(value);
682
+ if (typeof value === 'string')
683
+ return parseInt(value, 10);
684
+ throw new ModernTreasuryError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
703
685
  };
704
686
  export const coerceFloat = (value) => {
705
- if (typeof value === 'number') return value;
706
- if (typeof value === 'string') return parseFloat(value);
707
- throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
687
+ if (typeof value === 'number')
688
+ return value;
689
+ if (typeof value === 'string')
690
+ return parseFloat(value);
691
+ throw new ModernTreasuryError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
708
692
  };
709
693
  export const coerceBoolean = (value) => {
710
- if (typeof value === 'boolean') return value;
711
- if (typeof value === 'string') return value === 'true';
712
- return Boolean(value);
694
+ if (typeof value === 'boolean')
695
+ return value;
696
+ if (typeof value === 'string')
697
+ return value === 'true';
698
+ return Boolean(value);
713
699
  };
714
700
  export const maybeCoerceInteger = (value) => {
715
- if (value === undefined) {
716
- return undefined;
717
- }
718
- return coerceInteger(value);
701
+ if (value === undefined) {
702
+ return undefined;
703
+ }
704
+ return coerceInteger(value);
719
705
  };
720
706
  export const maybeCoerceFloat = (value) => {
721
- if (value === undefined) {
722
- return undefined;
723
- }
724
- return coerceFloat(value);
707
+ if (value === undefined) {
708
+ return undefined;
709
+ }
710
+ return coerceFloat(value);
725
711
  };
726
712
  export const maybeCoerceBoolean = (value) => {
727
- if (value === undefined) {
728
- return undefined;
729
- }
730
- return coerceBoolean(value);
713
+ if (value === undefined) {
714
+ return undefined;
715
+ }
716
+ return coerceBoolean(value);
731
717
  };
732
718
  // https://stackoverflow.com/a/34491287
733
719
  export function isEmptyObj(obj) {
734
- if (!obj) return true;
735
- for (const _k in obj) return false;
736
- return true;
720
+ if (!obj)
721
+ return true;
722
+ for (const _k in obj)
723
+ return false;
724
+ return true;
737
725
  }
738
726
  // https://eslint.org/docs/latest/rules/no-prototype-builtins
739
727
  export function hasOwn(obj, key) {
740
- return Object.prototype.hasOwnProperty.call(obj, key);
728
+ return Object.prototype.hasOwnProperty.call(obj, key);
741
729
  }
742
730
  export function debug(action, ...args) {
743
- if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
744
- console.log(`ModernTreasury:DEBUG:${action}`, ...args);
745
- }
731
+ if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
732
+ console.log(`ModernTreasury:DEBUG:${action}`, ...args);
733
+ }
746
734
  }
747
735
  /**
748
736
  * https://stackoverflow.com/a/2117523
749
737
  */
750
738
  const uuid4 = () => {
751
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
752
- const r = (Math.random() * 16) | 0;
753
- const v = c === 'x' ? r : (r & 0x3) | 0x8;
754
- return v.toString(16);
755
- });
739
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
740
+ const r = (Math.random() * 16) | 0;
741
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
742
+ return v.toString(16);
743
+ });
756
744
  };
757
745
  export const isRunningInBrowser = () => {
758
- return (
746
+ return (
759
747
  // @ts-ignore
760
748
  typeof window !== 'undefined' &&
761
- // @ts-ignore
762
- typeof window.document !== 'undefined' &&
763
- // @ts-ignore
764
- typeof navigator !== 'undefined'
765
- );
749
+ // @ts-ignore
750
+ typeof window.document !== 'undefined' &&
751
+ // @ts-ignore
752
+ typeof navigator !== 'undefined');
766
753
  };
767
754
  export const isHeadersProtocol = (headers) => {
768
- return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function';
755
+ return typeof headers?.get === 'function';
769
756
  };
770
757
  export const getHeader = (headers, key) => {
771
- const lowerKey = key.toLowerCase();
772
- if (isHeadersProtocol(headers)) return headers.get(key) || headers.get(lowerKey);
773
- const value = headers[key] || headers[lowerKey];
774
- if (Array.isArray(value)) {
775
- if (value.length <= 1) return value[0];
776
- console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
777
- return value[0];
778
- }
779
- return value;
758
+ const lowerKey = key.toLowerCase();
759
+ if (isHeadersProtocol(headers))
760
+ return headers.get(key) || headers.get(lowerKey);
761
+ const value = headers[key] || headers[lowerKey];
762
+ if (Array.isArray(value)) {
763
+ if (value.length <= 1)
764
+ return value[0];
765
+ console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
766
+ return value[0];
767
+ }
768
+ return value;
780
769
  };
781
770
  /**
782
771
  * Encodes a string to Base64 format.
783
772
  */
784
773
  export const toBase64 = (str) => {
785
- if (!str) return '';
786
- if (typeof Buffer !== 'undefined') {
787
- return Buffer.from(str).toString('base64');
788
- }
789
- if (typeof btoa !== 'undefined') {
790
- return btoa(str);
791
- }
792
- throw new Error('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
774
+ if (!str)
775
+ return '';
776
+ if (typeof Buffer !== 'undefined') {
777
+ return Buffer.from(str).toString('base64');
778
+ }
779
+ if (typeof btoa !== 'undefined') {
780
+ return btoa(str);
781
+ }
782
+ throw new ModernTreasuryError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
793
783
  };
794
- //# sourceMappingURL=core.mjs.map
784
+ //# sourceMappingURL=core.mjs.map