@anthropic-ai/sdk 0.6.2 → 0.6.8

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