@anthropic-ai/sdk 0.6.1 → 0.6.7

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 +127 -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 +89 -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 -216
  74. package/core.d.ts.map +1 -1
  75. package/core.js +701 -729
  76. package/core.js.map +1 -1
  77. package/core.mjs +694 -681
  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 -160
  89. package/index.js.map +1 -1
  90. package/index.mjs +84 -105
  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 +81 -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 +124 -61
  149. package/src/error.ts +20 -8
  150. package/src/index.ts +27 -22
  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 +166 -56
  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 -59
  195. package/_shims/fetch.js +0 -13
  196. package/_shims/fetch.mjs +0 -15
  197. package/_shims/fetch.node.d.ts +0 -63
  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 -59
  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 -63
  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,462 +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() {
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() {
138
- return {
139
- Accept: 'application/json',
140
- 'Content-Type': 'application/json',
141
- 'User-Agent': this.getUserAgent(),
142
- ...getPlatformHeaders(),
143
- ...this.authHeaders(),
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(),
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 }) {}
255
- makeStatusError(status, error, message, headers) {
256
- return APIError.generate(status, error, message, headers);
257
- }
258
- request(options, remainingRetries = null) {
259
- return new APIPromise(this.makeRequest(options, remainingRetries));
260
- }
261
- async makeRequest(optionsInput, retriesRemaining) {
262
- var _a, _b, _c;
263
- const options = await optionsInput;
264
- if (retriesRemaining == null) {
265
- retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
266
- }
267
- const { req, url, timeout } = this.buildRequest(options);
268
- await this.prepareRequest(req, { url });
269
- debug('request', url, options, req.headers);
270
- if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) {
271
- throw new APIUserAbortError();
272
- }
273
- const controller = new AbortController();
274
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
275
- if (response instanceof Error) {
276
- if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
277
- throw new APIUserAbortError();
278
- }
279
- if (retriesRemaining) {
280
- return this.retryRequest(options, retriesRemaining);
281
- }
282
- if (response.name === 'AbortError') {
283
- throw new APIConnectionTimeoutError();
284
- }
285
- throw new APIConnectionError({ cause: response });
286
- }
287
- const responseHeaders = createResponseHeaders(response.headers);
288
- if (!response.ok) {
289
- if (retriesRemaining && this.shouldRetry(response)) {
290
- return this.retryRequest(options, retriesRemaining, responseHeaders);
291
- }
292
- const errText = await response.text().catch(() => 'Unknown');
293
- const errJSON = safeJSON(errText);
294
- const errMessage = errJSON ? undefined : errText;
295
- debug('response', response.status, url, responseHeaders, errMessage);
296
- const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
297
- throw err;
298
- }
299
- return { response, options, controller };
300
- }
301
- requestAPIList(Page, options) {
302
- const request = this.makeRequest(options, null);
303
- return new PagePromise(this, request, Page);
304
- }
305
- buildURL(path, query) {
306
- const url =
307
- isAbsoluteURL(path) ?
308
- new URL(path)
309
- : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
310
- const defaultQuery = this.defaultQuery();
311
- if (!isEmptyObj(defaultQuery)) {
312
- query = { ...defaultQuery, ...query };
313
- }
314
- if (query) {
315
- url.search = this.stringifyQuery(query);
316
- }
317
- return url.toString();
318
- }
319
- stringifyQuery(query) {
320
- return Object.entries(query)
321
- .filter(([_, value]) => typeof value !== 'undefined')
322
- .map(([key, value]) => {
323
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
324
- 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();
253
+ }
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 });
325
267
  }
326
- if (value === null) {
327
- return `${encodeURIComponent(key)}=`;
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;
328
279
  }
329
- throw new Error(
330
- `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.`,
331
- );
332
- })
333
- .join('&');
334
- }
335
- async fetchWithTimeout(url, init, ms, controller) {
336
- const { signal, ...options } = init || {};
337
- if (signal) signal.addEventListener('abort', () => controller.abort());
338
- const timeout = setTimeout(() => controller.abort(), ms);
339
- return this.getRequestClient()
340
- .fetch(url, { signal: controller.signal, ...options })
341
- .finally(() => {
342
- clearTimeout(timeout);
343
- });
344
- }
345
- getRequestClient() {
346
- return { fetch: this.fetch };
347
- }
348
- shouldRetry(response) {
349
- // Note this is not a standard header.
350
- const shouldRetryHeader = response.headers.get('x-should-retry');
351
- // If the server explicitly says whether or not to retry, obey.
352
- if (shouldRetryHeader === 'true') return true;
353
- if (shouldRetryHeader === 'false') return false;
354
- // Retry on lock timeouts.
355
- if (response.status === 409) return true;
356
- // Retry on rate limits.
357
- if (response.status === 429) return true;
358
- // Retry internal errors.
359
- if (response.status >= 500) return true;
360
- return false;
361
- }
362
- async retryRequest(options, retriesRemaining, responseHeaders) {
363
- var _a;
364
- retriesRemaining -= 1;
365
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
366
- //
367
- // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
368
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
369
- const retryAfter = parseInt(
370
- (responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) ||
371
- '',
372
- );
373
- const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
374
- const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
375
- await sleep(timeout);
376
- return this.makeRequest(options, retriesRemaining);
377
- }
378
- calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) {
379
- const initialRetryDelay = 0.5;
380
- const maxRetryDelay = 2;
381
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
382
- // just do what it says.
383
- if (Number.isInteger(retryAfter) && retryAfter <= 60) {
384
- return retryAfter;
385
- }
386
- const numRetries = maxRetries - retriesRemaining;
387
- // Apply exponential backoff, but not more than the max.
388
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
389
- // Apply some jitter, plus-or-minus half a second.
390
- const jitter = Math.random() - 0.5;
391
- return sleepSeconds + jitter;
392
- }
393
- getUserAgent() {
394
- return `${this.constructor.name}/JS ${VERSION}`;
395
- }
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
+ }
396
389
  }
397
390
  export class APIResource {
398
- constructor(client) {
399
- this.client = client;
400
- this.get = client.get.bind(client);
401
- this.post = client.post.bind(client);
402
- this.patch = client.patch.bind(client);
403
- this.put = client.put.bind(client);
404
- this.delete = client.delete.bind(client);
405
- this.getAPIList = client.getAPIList.bind(client);
406
- }
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
+ }
407
400
  }
408
401
  export class AbstractPage {
409
- constructor(client, response, body, options) {
410
- _AbstractPage_client.set(this, void 0);
411
- __classPrivateFieldSet(this, _AbstractPage_client, client, 'f');
412
- this.options = options;
413
- this.response = response;
414
- this.body = body;
415
- }
416
- hasNextPage() {
417
- const items = this.getPaginatedItems();
418
- if (!items.length) return false;
419
- return this.nextPageInfo() != null;
420
- }
421
- async getNextPage() {
422
- const nextInfo = this.nextPageInfo();
423
- if (!nextInfo) {
424
- throw new Error(
425
- 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
426
- );
427
- }
428
- const nextOptions = { ...this.options };
429
- if ('params' in nextInfo) {
430
- nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
431
- } else if ('url' in nextInfo) {
432
- const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
433
- for (const [key, value] of params) {
434
- nextInfo.url.searchParams.set(key, value);
435
- }
436
- nextOptions.query = undefined;
437
- nextOptions.path = nextInfo.url.toString();
438
- }
439
- return await __classPrivateFieldGet(this, _AbstractPage_client, 'f').requestAPIList(
440
- this.constructor,
441
- nextOptions,
442
- );
443
- }
444
- async *iterPages() {
445
- // eslint-disable-next-line @typescript-eslint/no-this-alias
446
- let page = this;
447
- yield page;
448
- while (page.hasNextPage()) {
449
- page = await page.getNextPage();
450
- yield page;
451
- }
452
- }
453
- async *[((_AbstractPage_client = new WeakMap()), Symbol.asyncIterator)]() {
454
- for await (const page of this.iterPages()) {
455
- for (const item of page.getPaginatedItems()) {
456
- yield item;
457
- }
458
- }
459
- }
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
+ }
460
450
  }
461
451
  /**
462
452
  * This subclass of Promise will resolve to an instantiated Page once the request completes.
@@ -468,211 +458,216 @@ export class AbstractPage {
468
458
  * }
469
459
  */
470
460
  export class PagePromise extends APIPromise {
471
- constructor(client, request, Page) {
472
- super(
473
- request,
474
- async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options),
475
- );
476
- }
477
- /**
478
- * Allow auto-paginating iteration on an unawaited list call, eg:
479
- *
480
- * for await (const item of client.items.list()) {
481
- * console.log(item)
482
- * }
483
- */
484
- async *[Symbol.asyncIterator]() {
485
- const page = await this;
486
- for await (const item of page) {
487
- yield item;
488
- }
489
- }
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
+ }
490
477
  }
491
478
  export const createResponseHeaders = (headers) => {
492
- return new Proxy(
493
- Object.fromEntries(
494
- // @ts-ignore
495
- headers.entries(),
496
- ),
497
- {
498
- get(target, name) {
499
- const key = name.toString();
500
- return target[key.toLowerCase()] || target[key];
501
- },
502
- },
503
- );
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
+ });
504
487
  };
505
488
  // This is required so that we can determine if a given object matches the RequestOptions
506
489
  // type at runtime. While this requires duplication, it is enforced by the TypeScript
507
490
  // compiler such that any missing / extraneous keys will cause an error.
508
491
  const requestOptionsKeys = {
509
- method: true,
510
- path: true,
511
- query: true,
512
- body: true,
513
- headers: true,
514
- maxRetries: true,
515
- stream: true,
516
- timeout: true,
517
- httpAgent: true,
518
- signal: true,
519
- 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,
520
503
  };
521
504
  export const isRequestOptions = (obj) => {
522
- return (
523
- typeof obj === 'object' &&
524
- obj !== null &&
525
- !isEmptyObj(obj) &&
526
- Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
527
- );
505
+ return (typeof obj === 'object' &&
506
+ obj !== null &&
507
+ !isEmptyObj(obj) &&
508
+ Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
528
509
  };
529
510
  const getPlatformProperties = () => {
530
- if (typeof Deno !== 'undefined' && Deno.build != null) {
531
- return {
532
- 'X-Stainless-Lang': 'js',
533
- 'X-Stainless-Package-Version': VERSION,
534
- 'X-Stainless-OS': normalizePlatform(Deno.build.os),
535
- 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
536
- 'X-Stainless-Runtime': 'deno',
537
- 'X-Stainless-Runtime-Version': Deno.version,
538
- };
539
- }
540
- if (typeof EdgeRuntime !== 'undefined') {
541
- return {
542
- 'X-Stainless-Lang': 'js',
543
- 'X-Stainless-Package-Version': VERSION,
544
- 'X-Stainless-OS': 'Unknown',
545
- 'X-Stainless-Arch': `other:${EdgeRuntime}`,
546
- 'X-Stainless-Runtime': 'edge',
547
- 'X-Stainless-Runtime-Version': process.version,
548
- };
549
- }
550
- // Check if Node.js
551
- if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
552
- return {
553
- 'X-Stainless-Lang': 'js',
554
- 'X-Stainless-Package-Version': VERSION,
555
- 'X-Stainless-OS': normalizePlatform(process.platform),
556
- 'X-Stainless-Arch': normalizeArch(process.arch),
557
- 'X-Stainless-Runtime': 'node',
558
- 'X-Stainless-Runtime-Version': process.version,
559
- };
560
- }
561
- const browserInfo = getBrowserInfo();
562
- 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.
563
554
  return {
564
- 'X-Stainless-Lang': 'js',
565
- 'X-Stainless-Package-Version': VERSION,
566
- 'X-Stainless-OS': 'Unknown',
567
- 'X-Stainless-Arch': 'unknown',
568
- 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
569
- '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',
570
561
  };
571
- }
572
- // TODO add support for Cloudflare workers, etc.
573
- return {
574
- 'X-Stainless-Lang': 'js',
575
- 'X-Stainless-Package-Version': VERSION,
576
- 'X-Stainless-OS': 'Unknown',
577
- 'X-Stainless-Arch': 'unknown',
578
- 'X-Stainless-Runtime': 'unknown',
579
- 'X-Stainless-Runtime-Version': 'unknown',
580
- };
581
562
  };
582
563
  // Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
583
564
  function getBrowserInfo() {
584
- 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
+ }
585
587
  return null;
586
- }
587
- // NOTE: The order matters here!
588
- const browserPatterns = [
589
- { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
590
- { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
591
- { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
592
- { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
593
- { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
594
- { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
595
- ];
596
- // Find the FIRST matching browser
597
- for (const { key, pattern } of browserPatterns) {
598
- const match = pattern.exec(navigator.userAgent);
599
- if (match) {
600
- const major = match[1] || 0;
601
- const minor = match[2] || 0;
602
- const patch = match[3] || 0;
603
- return { browser: key, version: `${major}.${minor}.${patch}` };
604
- }
605
- }
606
- return null;
607
588
  }
608
589
  const normalizeArch = (arch) => {
609
- // Node docs:
610
- // - https://nodejs.org/api/process.html#processarch
611
- // Deno docs:
612
- // - https://doc.deno.land/deno/stable/~/Deno.build
613
- if (arch === 'x32') return 'x32';
614
- if (arch === 'x86_64' || arch === 'x64') return 'x64';
615
- if (arch === 'arm') return 'arm';
616
- if (arch === 'aarch64' || arch === 'arm64') return 'arm64';
617
- if (arch) return `other:${arch}`;
618
- 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';
619
605
  };
620
606
  const normalizePlatform = (platform) => {
621
- // Node platforms:
622
- // - https://nodejs.org/api/process.html#processplatform
623
- // Deno platforms:
624
- // - https://doc.deno.land/deno/stable/~/Deno.build
625
- // - https://github.com/denoland/deno/issues/14799
626
- platform = platform.toLowerCase();
627
- // NOTE: this iOS check is untested and may not work
628
- // Node does not work natively on IOS, there is a fork at
629
- // https://github.com/nodejs-mobile/nodejs-mobile
630
- // however it is unknown at the time of writing how to detect if it is running
631
- if (platform.includes('ios')) return 'iOS';
632
- if (platform === 'android') return 'Android';
633
- if (platform === 'darwin') return 'MacOS';
634
- if (platform === 'win32') return 'Windows';
635
- if (platform === 'freebsd') return 'FreeBSD';
636
- if (platform === 'openbsd') return 'OpenBSD';
637
- if (platform === 'linux') return 'Linux';
638
- if (platform) return `Other:${platform}`;
639
- 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';
640
634
  };
641
635
  let _platformHeaders;
642
636
  const getPlatformHeaders = () => {
643
- return _platformHeaders !== null && _platformHeaders !== void 0 ?
644
- _platformHeaders
645
- : (_platformHeaders = getPlatformProperties());
637
+ return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
646
638
  };
647
639
  export const safeJSON = (text) => {
648
- try {
649
- return JSON.parse(text);
650
- } catch (err) {
651
- return undefined;
652
- }
640
+ try {
641
+ return JSON.parse(text);
642
+ }
643
+ catch (err) {
644
+ return undefined;
645
+ }
653
646
  };
654
647
  // https://stackoverflow.com/a/19709846
655
648
  const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
656
649
  const isAbsoluteURL = (url) => {
657
- return startsWithSchemeRegexp.test(url);
650
+ return startsWithSchemeRegexp.test(url);
658
651
  };
659
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
652
+ export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
660
653
  const validatePositiveInteger = (name, n) => {
661
- if (typeof n !== 'number' || !Number.isInteger(n)) {
662
- throw new Error(`${name} must be an integer`);
663
- }
664
- if (n < 0) {
665
- throw new Error(`${name} must be a positive integer`);
666
- }
667
- 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;
668
661
  };
669
662
  export const castToError = (err) => {
670
- if (err instanceof Error) return err;
671
- return new Error(err);
663
+ if (err instanceof Error)
664
+ return err;
665
+ return new Error(err);
672
666
  };
673
667
  export const ensurePresent = (value) => {
674
- if (value == null) throw new Error(`Expected a value to be given but received ${value} instead.`);
675
- return value;
668
+ if (value == null)
669
+ throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);
670
+ return value;
676
671
  };
677
672
  /**
678
673
  * Read an environment variable.
@@ -680,112 +675,130 @@ export const ensurePresent = (value) => {
680
675
  * Will return undefined if the environment variable doesn't exist or cannot be accessed.
681
676
  */
682
677
  export const readEnv = (env) => {
683
- var _a, _b, _c, _d;
684
- if (typeof process !== 'undefined') {
685
- return (_b = (_a = process.env) === null || _a === void 0 ? void 0 : _a[env]) !== null && _b !== void 0 ?
686
- _b
687
- : undefined;
688
- }
689
- if (typeof Deno !== 'undefined') {
690
- return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ?
691
- void 0
692
- : _d.call(_c, env);
693
- }
694
- 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;
695
685
  };
696
686
  export const coerceInteger = (value) => {
697
- if (typeof value === 'number') return Math.round(value);
698
- if (typeof value === 'string') return parseInt(value, 10);
699
- 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`);
700
692
  };
701
693
  export const coerceFloat = (value) => {
702
- if (typeof value === 'number') return value;
703
- if (typeof value === 'string') return parseFloat(value);
704
- 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`);
705
699
  };
706
700
  export const coerceBoolean = (value) => {
707
- if (typeof value === 'boolean') return value;
708
- if (typeof value === 'string') return value === 'true';
709
- return Boolean(value);
701
+ if (typeof value === 'boolean')
702
+ return value;
703
+ if (typeof value === 'string')
704
+ return value === 'true';
705
+ return Boolean(value);
710
706
  };
711
707
  export const maybeCoerceInteger = (value) => {
712
- if (value === undefined) {
713
- return undefined;
714
- }
715
- return coerceInteger(value);
708
+ if (value === undefined) {
709
+ return undefined;
710
+ }
711
+ return coerceInteger(value);
716
712
  };
717
713
  export const maybeCoerceFloat = (value) => {
718
- if (value === undefined) {
719
- return undefined;
720
- }
721
- return coerceFloat(value);
714
+ if (value === undefined) {
715
+ return undefined;
716
+ }
717
+ return coerceFloat(value);
722
718
  };
723
719
  export const maybeCoerceBoolean = (value) => {
724
- if (value === undefined) {
725
- return undefined;
726
- }
727
- return coerceBoolean(value);
720
+ if (value === undefined) {
721
+ return undefined;
722
+ }
723
+ return coerceBoolean(value);
728
724
  };
729
725
  // https://stackoverflow.com/a/34491287
730
726
  export function isEmptyObj(obj) {
731
- if (!obj) return true;
732
- for (const _k in obj) return false;
733
- return true;
727
+ if (!obj)
728
+ return true;
729
+ for (const _k in obj)
730
+ return false;
731
+ return true;
734
732
  }
735
733
  // https://eslint.org/docs/latest/rules/no-prototype-builtins
736
734
  export function hasOwn(obj, key) {
737
- return Object.prototype.hasOwnProperty.call(obj, key);
735
+ return Object.prototype.hasOwnProperty.call(obj, key);
738
736
  }
739
737
  export function debug(action, ...args) {
740
- if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
741
- console.log(`Anthropic:DEBUG:${action}`, ...args);
742
- }
738
+ if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
739
+ console.log(`Anthropic:DEBUG:${action}`, ...args);
740
+ }
743
741
  }
744
742
  /**
745
743
  * https://stackoverflow.com/a/2117523
746
744
  */
747
745
  const uuid4 = () => {
748
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
749
- const r = (Math.random() * 16) | 0;
750
- const v = c === 'x' ? r : (r & 0x3) | 0x8;
751
- return v.toString(16);
752
- });
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
+ });
753
751
  };
754
752
  export const isRunningInBrowser = () => {
755
- return (
753
+ return (
756
754
  // @ts-ignore
757
755
  typeof window !== 'undefined' &&
758
- // @ts-ignore
759
- typeof window.document !== 'undefined' &&
760
- // @ts-ignore
761
- typeof navigator !== 'undefined'
762
- );
756
+ // @ts-ignore
757
+ typeof window.document !== 'undefined' &&
758
+ // @ts-ignore
759
+ typeof navigator !== 'undefined');
763
760
  };
764
761
  export const isHeadersProtocol = (headers) => {
765
- return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function';
762
+ return typeof headers?.get === 'function';
766
763
  };
767
- export const getHeader = (headers, key) => {
768
- const lowerKey = key.toLowerCase();
769
- if (isHeadersProtocol(headers)) return headers.get(key) || headers.get(lowerKey);
770
- const value = headers[key] || headers[lowerKey];
771
- if (Array.isArray(value)) {
772
- if (value.length <= 1) return value[0];
773
- console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
774
- return value[0];
775
- }
776
- 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`);
777
789
  };
778
790
  /**
779
791
  * Encodes a string to Base64 format.
780
792
  */
781
793
  export const toBase64 = (str) => {
782
- if (!str) return '';
783
- if (typeof Buffer !== 'undefined') {
784
- return Buffer.from(str).toString('base64');
785
- }
786
- if (typeof btoa !== 'undefined') {
787
- return btoa(str);
788
- }
789
- 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');
790
803
  };
791
- //# sourceMappingURL=core.mjs.map
804
+ //# sourceMappingURL=core.mjs.map