openai 4.7.1 → 4.9.0

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