Update test framework: fix run_tests.py to support all test files, add auto-import-check for test files

This commit is contained in:
qiaoxinjiu
2026-05-09 15:11:30 +08:00
parent eb053a347f
commit eaba8328da
21739 changed files with 2236758 additions and 719 deletions

329
node_modules/@anthropic-ai/sdk/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,329 @@
# Changelog
## 0.8.1 (2023-10-25)
Full Changelog: [v0.8.0...v0.8.1](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.8.0...v0.8.1)
### Bug Fixes
* typo in build script ([#197](https://github.com/anthropics/anthropic-sdk-typescript/issues/197)) ([212e990](https://github.com/anthropics/anthropic-sdk-typescript/commit/212e9903e9b72b3169f450d8ab11ebd384951dba))
## 0.8.0 (2023-10-24)
Full Changelog: [v0.7.0...v0.8.0](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.7.0...v0.8.0)
### Features
* **client:** adjust retry behavior to be exponential backoff ([#192](https://github.com/anthropics/anthropic-sdk-typescript/issues/192)) ([747afe2](https://github.com/anthropics/anthropic-sdk-typescript/commit/747afe2bdbbe3a5489e9b9bc6ed4fcf2a276e40b))
## 0.7.0 (2023-10-19)
Full Changelog: [v0.6.8...v0.7.0](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.8...v0.7.0)
### Features
* handle 204 No Content gracefully ([#190](https://github.com/anthropics/anthropic-sdk-typescript/issues/190)) ([c8a8bec](https://github.com/anthropics/anthropic-sdk-typescript/commit/c8a8becd127e5275333900c3bb76955605ae0f02))
## 0.6.8 (2023-10-17)
Full Changelog: [v0.6.7...v0.6.8](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.7...v0.6.8)
### Bug Fixes
* import web-streams-polyfill without overriding globals ([#186](https://github.com/anthropics/anthropic-sdk-typescript/issues/186)) ([e774e17](https://github.com/anthropics/anthropic-sdk-typescript/commit/e774e1774642668e080de5233aeaa33cf5f1b3ae))
## 0.6.7 (2023-10-16)
Full Changelog: [v0.6.6...v0.6.7](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.6...v0.6.7)
### Bug Fixes
* improve status code in error messages ([#183](https://github.com/anthropics/anthropic-sdk-typescript/issues/183)) ([7d3bbd4](https://github.com/anthropics/anthropic-sdk-typescript/commit/7d3bbd485c9628bb7c3fb5d1660934198981fcc7))
### Chores
* add case insensitive get header function ([#178](https://github.com/anthropics/anthropic-sdk-typescript/issues/178)) ([13c398d](https://github.com/anthropics/anthropic-sdk-typescript/commit/13c398dee3ff2eaa3b6046630eda9831580348f4))
* **internal:** add debug logs for stream responses ([#182](https://github.com/anthropics/anthropic-sdk-typescript/issues/182)) ([a1fa1b7](https://github.com/anthropics/anthropic-sdk-typescript/commit/a1fa1b7766248f3178cb55ac5342409a57c1dbb8))
* update comment ([#179](https://github.com/anthropics/anthropic-sdk-typescript/issues/179)) ([27a425e](https://github.com/anthropics/anthropic-sdk-typescript/commit/27a425ee64dcdc569b92ac27b501bca0dadf2dea))
### Documentation
* organisation -> organization (UK to US English) ([#185](https://github.com/anthropics/anthropic-sdk-typescript/issues/185)) ([70257d4](https://github.com/anthropics/anthropic-sdk-typescript/commit/70257d43296f5b448b5649a34b67a3a3a26704ab))
### Refactors
* **streaming:** change Stream constructor signature ([#174](https://github.com/anthropics/anthropic-sdk-typescript/issues/174)) ([1951824](https://github.com/anthropics/anthropic-sdk-typescript/commit/195182432c41a2a8a4fc425788267e60f36f5820))
* **test:** refactor authentication tests ([#176](https://github.com/anthropics/anthropic-sdk-typescript/issues/176)) ([f59daad](https://github.com/anthropics/anthropic-sdk-typescript/commit/f59daad06cab4c5df3068ea7f71ecbb20d8af141))
## 0.6.6 (2023-10-11)
Full Changelog: [v0.6.5...v0.6.6](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.5...v0.6.6)
### Chores
* update README ([#173](https://github.com/anthropics/anthropic-sdk-typescript/issues/173)) ([5f50c1b](https://github.com/anthropics/anthropic-sdk-typescript/commit/5f50c1b2f160610c89f158a10d83029c356d925a))
## 0.6.5 (2023-10-11)
Full Changelog: [v0.6.4...v0.6.5](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.4...v0.6.5)
### Features
* **client:** handle retry-after with a date ([#162](https://github.com/anthropics/anthropic-sdk-typescript/issues/162)) ([31bd609](https://github.com/anthropics/anthropic-sdk-typescript/commit/31bd60905858a6532414665a1368ae9f5fd29370))
* **client:** retry on 408 Request Timeout ([#151](https://github.com/anthropics/anthropic-sdk-typescript/issues/151)) ([3523ffe](https://github.com/anthropics/anthropic-sdk-typescript/commit/3523ffe5647448d5a5960b1339c9a17374e85dd5))
* **client:** support importing node or web shims manually ([#157](https://github.com/anthropics/anthropic-sdk-typescript/issues/157)) ([c1237fe](https://github.com/anthropics/anthropic-sdk-typescript/commit/c1237feaea9ca2d244720f2f75e023450a78019f))
* **errors:** add status code to error message ([#155](https://github.com/anthropics/anthropic-sdk-typescript/issues/155)) ([76cf128](https://github.com/anthropics/anthropic-sdk-typescript/commit/76cf128b68f206038945ac4f54f6f50e8a6a2c1b))
* **package:** export a root error type ([#160](https://github.com/anthropics/anthropic-sdk-typescript/issues/160)) ([51d8d60](https://github.com/anthropics/anthropic-sdk-typescript/commit/51d8d60b72fbe99dcb4d5a9ec32abbcb21ba1460))
### Bug Fixes
* **client:** eliminate circular imports, which cause runtime errors in webpack dev bundles ([#170](https://github.com/anthropics/anthropic-sdk-typescript/issues/170)) ([4a86733](https://github.com/anthropics/anthropic-sdk-typescript/commit/4a86733b9d11349fca041683ac9d89685133557d))
* fix namespace exports regression ([#171](https://github.com/anthropics/anthropic-sdk-typescript/issues/171)) ([0689a91](https://github.com/anthropics/anthropic-sdk-typescript/commit/0689a9196619d968870b7fd2e1a0f037a1aee282))
* prevent ReferenceError, update compatibility to ES2020 and Node 18+ ([#169](https://github.com/anthropics/anthropic-sdk-typescript/issues/169)) ([9753314](https://github.com/anthropics/anthropic-sdk-typescript/commit/9753314b7e36a270bb4c29f2981c521ec9c17773))
### Chores
* **internal:** bump lock file ([#159](https://github.com/anthropics/anthropic-sdk-typescript/issues/159)) ([e6030fa](https://github.com/anthropics/anthropic-sdk-typescript/commit/e6030fa915f26569f9c48c478a5e6c01910a6557))
* **internal:** minor formatting improvement ([#168](https://github.com/anthropics/anthropic-sdk-typescript/issues/168)) ([6447608](https://github.com/anthropics/anthropic-sdk-typescript/commit/644760883802bc2769a916fa477f2c6491f018fd))
* **internal:** update lock file ([#161](https://github.com/anthropics/anthropic-sdk-typescript/issues/161)) ([370ce3c](https://github.com/anthropics/anthropic-sdk-typescript/commit/370ce3c34b87591071fefc8b53977078603b6ca4))
* **internal:** update lock file ([#163](https://github.com/anthropics/anthropic-sdk-typescript/issues/163)) ([4a37181](https://github.com/anthropics/anthropic-sdk-typescript/commit/4a37181e0ceada13e3ed61d6df7aa34492dc57a7))
* **internal:** update lock file ([#164](https://github.com/anthropics/anthropic-sdk-typescript/issues/164)) ([939c155](https://github.com/anthropics/anthropic-sdk-typescript/commit/939c155277e67c19f7b2ff956f7cf0d40d4671cd))
### Documentation
* **api.md:** add shared models ([#158](https://github.com/anthropics/anthropic-sdk-typescript/issues/158)) ([33e5518](https://github.com/anthropics/anthropic-sdk-typescript/commit/33e5518bdeca83bbbde0e144e444609f569f1477))
* declare Bun 1.0 officially supported ([#154](https://github.com/anthropics/anthropic-sdk-typescript/issues/154)) ([429d8f4](https://github.com/anthropics/anthropic-sdk-typescript/commit/429d8f44b113a91599f0ebb69128636da82a5050))
* **readme:** remove incorrect wording in opening ([#156](https://github.com/anthropics/anthropic-sdk-typescript/issues/156)) ([01973fe](https://github.com/anthropics/anthropic-sdk-typescript/commit/01973fe50b13ce2981656f8c13603975e7c43efd))
## 0.6.4 (2023-09-08)
Full Changelog: [v0.6.3...v0.6.4](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.3...v0.6.4)
### Features
* **package:** add Bun export map ([#139](https://github.com/anthropics/anthropic-sdk-typescript/issues/139)) ([ba3310d](https://github.com/anthropics/anthropic-sdk-typescript/commit/ba3310d903cd5fda91168266335f4e445e60cad4))
### Bug Fixes
* **client:** fix TS errors that appear when users Go to Source in VSCode ([#142](https://github.com/anthropics/anthropic-sdk-typescript/issues/142)) ([f7bfbea](https://github.com/anthropics/anthropic-sdk-typescript/commit/f7bfbeaa54d364201bbe5cddf3132875ae2a3ccf))
* **client:** handle case where the client is instantiated with a undefined baseURL ([#143](https://github.com/anthropics/anthropic-sdk-typescript/issues/143)) ([10e5203](https://github.com/anthropics/anthropic-sdk-typescript/commit/10e52034990d90dcdaf26672ea384545b88ddf35))
* **client:** use explicit file extensions in _shims imports ([#141](https://github.com/anthropics/anthropic-sdk-typescript/issues/141)) ([10fd687](https://github.com/anthropics/anthropic-sdk-typescript/commit/10fd68742a202c5c0a8b520db190c239dce9b676))
* fix module not found errors in Vercel edge ([#148](https://github.com/anthropics/anthropic-sdk-typescript/issues/148)) ([72e51a1](https://github.com/anthropics/anthropic-sdk-typescript/commit/72e51a170855281a8d099b00c6fb1e9ccb276212))
* **readme:** update link to api.md to use the correct branch ([#145](https://github.com/anthropics/anthropic-sdk-typescript/issues/145)) ([5db78ed](https://github.com/anthropics/anthropic-sdk-typescript/commit/5db78edec4826f86b2fc21ee3f470b49a4987029))
### Chores
* **internal:** export helper from core ([#147](https://github.com/anthropics/anthropic-sdk-typescript/issues/147)) ([7e79de1](https://github.com/anthropics/anthropic-sdk-typescript/commit/7e79de14edeab8110d740e996653e9f9cc2299a4))
### Documentation
* **readme:** add link to api.md ([#144](https://github.com/anthropics/anthropic-sdk-typescript/issues/144)) ([716c9f0](https://github.com/anthropics/anthropic-sdk-typescript/commit/716c9f0714c0e9c26cb6cdcb007457aff1284cf4))
## 0.6.3 (2023-08-28)
Full Changelog: [v0.6.2...v0.6.3](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.2...v0.6.3)
### Bug Fixes
* **types:** improve getNextPage() return type ([#137](https://github.com/anthropics/anthropic-sdk-typescript/issues/137)) ([713d603](https://github.com/anthropics/anthropic-sdk-typescript/commit/713d6032c2c3b3630314a9625a1672147ef19258))
### Chores
* **ci:** setup workflows to create releases and release PRs ([#135](https://github.com/anthropics/anthropic-sdk-typescript/issues/135)) ([56229d9](https://github.com/anthropics/anthropic-sdk-typescript/commit/56229d964733a8b00625dac4ff138b3ade7e4202))
## [0.6.2](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.1...v0.6.2) (2023-08-26)
### Bug Fixes
* **stream:** declare Stream.controller as public ([#132](https://github.com/anthropics/anthropic-sdk-typescript/issues/132)) ([ff33a89](https://github.com/anthropics/anthropic-sdk-typescript/commit/ff33a893747aa708133bab14e97fba34ec776303))
### Refactors
* remove unnecessary line in constructor ([#131](https://github.com/anthropics/anthropic-sdk-typescript/issues/131)) ([dcdf5e5](https://github.com/anthropics/anthropic-sdk-typescript/commit/dcdf5e5183e99ae91d170ca09cc6da5e5637783f))
### Chores
* **internal:** add helper method ([#133](https://github.com/anthropics/anthropic-sdk-typescript/issues/133)) ([4c6950a](https://github.com/anthropics/anthropic-sdk-typescript/commit/4c6950a489b818151127aa1a39c239e4fd58a06e))
* **internal:** export HeadersInit type shim ([#129](https://github.com/anthropics/anthropic-sdk-typescript/issues/129)) ([bcd51bd](https://github.com/anthropics/anthropic-sdk-typescript/commit/bcd51bd12ad0854baf28b59dcada871889032515))
## [0.6.1](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.6.0...v0.6.1) (2023-08-23)
### Features
* allow a default timeout to be set for clients ([#113](https://github.com/anthropics/anthropic-sdk-typescript/issues/113)) ([1c5b2e2](https://github.com/anthropics/anthropic-sdk-typescript/commit/1c5b2e29926100a6e4a6176f0943e2c98991175d))
* **client:** improve compatibility with Bun ([#119](https://github.com/anthropics/anthropic-sdk-typescript/issues/119)) ([fe4f5d5](https://github.com/anthropics/anthropic-sdk-typescript/commit/fe4f5d5e35e35cab2a62388eb595519e9c14635c))
* **docs:** add documentation to the client constructor ([#118](https://github.com/anthropics/anthropic-sdk-typescript/issues/118)) ([79303f9](https://github.com/anthropics/anthropic-sdk-typescript/commit/79303f9c46a8248abd05fedbedbbed6e735c046d))
* **types:** export RequestOptions type ([#127](https://github.com/anthropics/anthropic-sdk-typescript/issues/127)) ([9769751](https://github.com/anthropics/anthropic-sdk-typescript/commit/9769751b84853822e3e6596110ecb2c367f07438))
* **types:** remove footgun with streaming params ([#125](https://github.com/anthropics/anthropic-sdk-typescript/issues/125)) ([3ed67b6](https://github.com/anthropics/anthropic-sdk-typescript/commit/3ed67b670bae14bc586df224aa57dd4dfa6e71f5))
### Bug Fixes
* **client:** fix TypeError when a request gets retried ([#117](https://github.com/anthropics/anthropic-sdk-typescript/issues/117)) ([0ade979](https://github.com/anthropics/anthropic-sdk-typescript/commit/0ade979a322c07f9a8f5322407b38352fe99b3ce))
* **core:** fix navigator check for strange environments ([#124](https://github.com/anthropics/anthropic-sdk-typescript/issues/124)) ([c783604](https://github.com/anthropics/anthropic-sdk-typescript/commit/c7836040017d5ce35204c07be0b018e87e827fdb))
* **types:** add catch-all overload to streaming methods ([#123](https://github.com/anthropics/anthropic-sdk-typescript/issues/123)) ([7c229a2](https://github.com/anthropics/anthropic-sdk-typescript/commit/7c229a24e6751bad22acb8c544113713140120fd))
### Documentation
* **readme:** fix typo ([#121](https://github.com/anthropics/anthropic-sdk-typescript/issues/121)) ([c5dbc3f](https://github.com/anthropics/anthropic-sdk-typescript/commit/c5dbc3fe89c84a728b6a4d7a4f6eadb228ac5688))
### Chores
* assign default reviewers to release PRs ([#115](https://github.com/anthropics/anthropic-sdk-typescript/issues/115)) ([1df3965](https://github.com/anthropics/anthropic-sdk-typescript/commit/1df3965a10256d30f8ce2af8d9890a26522117a9))
* **internal:** add missing eslint-plugin-prettier ([#122](https://github.com/anthropics/anthropic-sdk-typescript/issues/122)) ([66bede0](https://github.com/anthropics/anthropic-sdk-typescript/commit/66bede0ae3ed7b5baa002bbb0c87b4156306f982))
* **internal:** fix error happening in CloudFlare pages ([#116](https://github.com/anthropics/anthropic-sdk-typescript/issues/116)) ([b0dc7b3](https://github.com/anthropics/anthropic-sdk-typescript/commit/b0dc7b3b14520ce1f66c2b9d6a0f5aae4028985b))
* **internal:** minor reformatting of code ([#120](https://github.com/anthropics/anthropic-sdk-typescript/issues/120)) ([4bcaf9e](https://github.com/anthropics/anthropic-sdk-typescript/commit/4bcaf9e30a312284cb22c2084e8242ad7d181ba8))
## [0.6.0](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.10...v0.6.0) (2023-08-12)
### Features
* **client:** add support for accessing the raw response object ([#105](https://github.com/anthropics/anthropic-sdk-typescript/issues/105)) ([c86b059](https://github.com/anthropics/anthropic-sdk-typescript/commit/c86b0593a630f3adafc5c329019ea7028b6a41cd))
* **client:** detect browser usage ([#101](https://github.com/anthropics/anthropic-sdk-typescript/issues/101)) ([f4cae3f](https://github.com/anthropics/anthropic-sdk-typescript/commit/f4cae3f63c2e65e087a7bf27dac1eeb8200e0a36))
* **types:** improve streaming params types ([#102](https://github.com/anthropics/anthropic-sdk-typescript/issues/102)) ([cdf808c](https://github.com/anthropics/anthropic-sdk-typescript/commit/cdf808ca2a18cd744a5d1840e5e2adb3015e8d1d))
### Documentation
* **readme:** minor updates ([#107](https://github.com/anthropics/anthropic-sdk-typescript/issues/107)) ([406fd97](https://github.com/anthropics/anthropic-sdk-typescript/commit/406fd97d4cee0dd363ad548c9a251f78091a70e3))
* **readme:** remove beta status + document versioning policy ([#100](https://github.com/anthropics/anthropic-sdk-typescript/issues/100)) ([e9ef3d2](https://github.com/anthropics/anthropic-sdk-typescript/commit/e9ef3d21a25e355d8bf94b7a941ad82ec5eafec8))
### Chores
* **docs:** remove trailing spaces ([#108](https://github.com/anthropics/anthropic-sdk-typescript/issues/108)) ([4ba2c6f](https://github.com/anthropics/anthropic-sdk-typescript/commit/4ba2c6f181521ed9a60ed45c35d2276129cd7a0b))
* **internal:** conditionally include bin during build output ([#109](https://github.com/anthropics/anthropic-sdk-typescript/issues/109)) ([58ac305](https://github.com/anthropics/anthropic-sdk-typescript/commit/58ac305d752d6b5c378f91b988ddfb97231c003c))
* **internal:** fix deno build ([#98](https://github.com/anthropics/anthropic-sdk-typescript/issues/98)) ([f011e04](https://github.com/anthropics/anthropic-sdk-typescript/commit/f011e041f2f9cabb12951013825c0f0a2a569053))
* **internal:** remove deno build ([#103](https://github.com/anthropics/anthropic-sdk-typescript/issues/103)) ([9af1527](https://github.com/anthropics/anthropic-sdk-typescript/commit/9af152707a9bcf3027afc64f027566be25da2eb9))
### Refactors
* **client:** remove Stream.toReadableStream() ([#110](https://github.com/anthropics/anthropic-sdk-typescript/issues/110)) ([c370412](https://github.com/anthropics/anthropic-sdk-typescript/commit/c37041285ed9cccf6d980a953e14ffd4006a8acc))
## [0.5.10](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.9...v0.5.10) (2023-08-01)
### Refactors
* create build for deno.land ([#93](https://github.com/anthropics/anthropic-sdk-typescript/issues/93)) ([2ea741a](https://github.com/anthropics/anthropic-sdk-typescript/commit/2ea741a4d4a3123b2eaafb87b73d7884c69ae23b))
### Documentation
* **readme:** add token counting reference ([#94](https://github.com/anthropics/anthropic-sdk-typescript/issues/94)) ([2c6a699](https://github.com/anthropics/anthropic-sdk-typescript/commit/2c6a699d499a3468fc4312a6b6c9493ffd1806a2))
### Chores
* **internal:** allow the build script to be run without yarn installed ([#91](https://github.com/anthropics/anthropic-sdk-typescript/issues/91)) ([9bd2b28](https://github.com/anthropics/anthropic-sdk-typescript/commit/9bd2b2871ca8a3b5f2466a904153d5c234094372))
* **internal:** fix deno build ([#96](https://github.com/anthropics/anthropic-sdk-typescript/issues/96)) ([3fdab4e](https://github.com/anthropics/anthropic-sdk-typescript/commit/3fdab4e33b4c8668d17b8cddabbb09a22adf4124))
## [0.5.9](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.8...v0.5.9) (2023-07-29)
### Bug Fixes
* **client:** handle undefined process in more places ([#87](https://github.com/anthropics/anthropic-sdk-typescript/issues/87)) ([d950c25](https://github.com/anthropics/anthropic-sdk-typescript/commit/d950c25469a6c6b0dd3cfecd282db078826366ba))
* **examples:** avoid swallowing errors in example scripts ([#82](https://github.com/anthropics/anthropic-sdk-typescript/issues/82)) ([b27cfe9](https://github.com/anthropics/anthropic-sdk-typescript/commit/b27cfe9323bce983bb49f57dece98f1d9e507034))
* fix undefined message in errors ([#86](https://github.com/anthropics/anthropic-sdk-typescript/issues/86)) ([5714a14](https://github.com/anthropics/anthropic-sdk-typescript/commit/5714a14d9af282a3d308b8694e6e03309d4b5642))
### Chores
* **internal:** minor refactoring of client instantiation ([#88](https://github.com/anthropics/anthropic-sdk-typescript/issues/88)) ([2c53e1c](https://github.com/anthropics/anthropic-sdk-typescript/commit/2c53e1ca28a444a48e5f1041d9eb9077608b3fc7))
### Refactors
* use destructuring arguments in client constructor and respect false values ([#89](https://github.com/anthropics/anthropic-sdk-typescript/issues/89)) ([8d4c686](https://github.com/anthropics/anthropic-sdk-typescript/commit/8d4c6860273bbd16027023700d521a5e48db76f7))
## [0.5.8](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.7...v0.5.8) (2023-07-22)
### Features
* **streaming:** make requests immediately throw an error if an aborted signal is passed in ([#79](https://github.com/anthropics/anthropic-sdk-typescript/issues/79)) ([5c86597](https://github.com/anthropics/anthropic-sdk-typescript/commit/5c865979a21d18db87df43a9bdb27b701815f4bb))
## [0.5.7](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.6...v0.5.7) (2023-07-19)
### Features
* add flexible enum to model param ([#73](https://github.com/anthropics/anthropic-sdk-typescript/issues/73)) ([a6bbcad](https://github.com/anthropics/anthropic-sdk-typescript/commit/a6bbcadb447060f3c2e60881d31d7b7fb7a50512))
* **client:** export ClientOptions interface ([#75](https://github.com/anthropics/anthropic-sdk-typescript/issues/75)) ([0315ce1](https://github.com/anthropics/anthropic-sdk-typescript/commit/0315ce170db463ad900384ab7e4f62885cb471a2))
* **deps:** remove unneeded qs dep ([#72](https://github.com/anthropics/anthropic-sdk-typescript/issues/72)) ([0aea5a6](https://github.com/anthropics/anthropic-sdk-typescript/commit/0aea5a6f4852f351ecbe9f46d6857a6fafc7e864))
### Bug Fixes
* **client:** fix errors with file uploads in the browser ([#76](https://github.com/anthropics/anthropic-sdk-typescript/issues/76)) ([ac48fa7](https://github.com/anthropics/anthropic-sdk-typescript/commit/ac48fa72bb764b2abed95f200bc658f65725e2b3))
* fix error in environments without `TextEncoder` ([#70](https://github.com/anthropics/anthropic-sdk-typescript/issues/70)) ([5b78e05](https://github.com/anthropics/anthropic-sdk-typescript/commit/5b78e0586fd351258ccc05c8ba89a2ba66681b0d))
* fix export map order ([#74](https://github.com/anthropics/anthropic-sdk-typescript/issues/74)) ([51e70cb](https://github.com/anthropics/anthropic-sdk-typescript/commit/51e70cb9b55128d4de1b0597fad475d0f4bc836c))
## [0.5.6](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.5...v0.5.6) (2023-07-15)
### Bug Fixes
* fix errors with "named" client export in CJS ([#67](https://github.com/anthropics/anthropic-sdk-typescript/issues/67)) ([08ef69c](https://github.com/anthropics/anthropic-sdk-typescript/commit/08ef69cca87bbdf82440d163611f45e04e894234))
## [0.5.5](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.4...v0.5.5) (2023-07-13)
### Features
* **client:** add support for passing a `signal` request option ([#55](https://github.com/anthropics/anthropic-sdk-typescript/issues/55)) ([09604e9](https://github.com/anthropics/anthropic-sdk-typescript/commit/09604e9990e13dd703f4bcfd0a241b8ec2ebbc71))
### Bug Fixes
* **streaming:** do not abort successfully completed streams ([#53](https://github.com/anthropics/anthropic-sdk-typescript/issues/53)) ([950dd49](https://github.com/anthropics/anthropic-sdk-typescript/commit/950dd4930429010d89ae31eef9ebb193be9517ad))
### Documentation
* **examples:** bump model to claude-2 in example scripts ([#57](https://github.com/anthropics/anthropic-sdk-typescript/issues/57)) ([f85c05d](https://github.com/anthropics/anthropic-sdk-typescript/commit/f85c05d49a7a9db1deb8eed9124934da763b721b))
* **readme:** improvements to formatting code snippets ([#58](https://github.com/anthropics/anthropic-sdk-typescript/issues/58)) ([67bae64](https://github.com/anthropics/anthropic-sdk-typescript/commit/67bae64d5388e7e71ea3a891b3579c072b743f38))
### Chores
* **internal:** add helper function for b64 ([#62](https://github.com/anthropics/anthropic-sdk-typescript/issues/62)) ([04e303c](https://github.com/anthropics/anthropic-sdk-typescript/commit/04e303c5cc7b14a862b81379d547b3dc6e908720))
* **internal:** let `toFile` helper accept promises to objects with name/type properties ([#63](https://github.com/anthropics/anthropic-sdk-typescript/issues/63)) ([93f9af2](https://github.com/anthropics/anthropic-sdk-typescript/commit/93f9af29a91cfced533d309d1816c58bc2efa355))
* **internal:** remove unneeded type var usage ([#59](https://github.com/anthropics/anthropic-sdk-typescript/issues/59)) ([42fc4a9](https://github.com/anthropics/anthropic-sdk-typescript/commit/42fc4a90cc267f077b26d2bafebe487a74cae067))
## [0.5.4](https://github.com/anthropics/anthropic-sdk-typescript/compare/v0.5.3...v0.5.4) (2023-07-11)
### Features
* **api:** reference claude-2 in examples ([#50](https://github.com/anthropics/anthropic-sdk-typescript/issues/50)) ([7c53ded](https://github.com/anthropics/anthropic-sdk-typescript/commit/7c53ded6b7f5f3efec0df295181f18469c37e09d))
* **client:** support passing a custom `fetch` function ([#46](https://github.com/anthropics/anthropic-sdk-typescript/issues/46)) ([7d54366](https://github.com/anthropics/anthropic-sdk-typescript/commit/7d54366fcefa0267e831a0cca4d10c9a146d9f6c))
### Bug Fixes
* **client:** properly handle multi-byte characters in Content-Length ([#47](https://github.com/anthropics/anthropic-sdk-typescript/issues/47)) ([8dfff26](https://github.com/anthropics/anthropic-sdk-typescript/commit/8dfff2691a3ebd5721462c055d8da638ac77e571))
### Refactors
* **streaming:** make response body streaming polyfill more spec-compliant ([#44](https://github.com/anthropics/anthropic-sdk-typescript/issues/44)) ([047d328](https://github.com/anthropics/anthropic-sdk-typescript/commit/047d328cb0968fb1926e41326d35b595ba3fb3bc))

8
node_modules/@anthropic-ai/sdk/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,8 @@
Copyright 2023 Anthropic, PBC.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

351
node_modules/@anthropic-ai/sdk/README.md generated vendored Normal file
View File

@@ -0,0 +1,351 @@
# Anthropic TypeScript API Library
[![NPM version](https://img.shields.io/npm/v/@anthropic-ai/sdk.svg)](https://npmjs.org/package/@anthropic-ai/sdk)
This library provides convenient access to the Anthropic REST API from server-side TypeScript or JavaScript.
For the AWS Bedrock API, see [`@anthropic-ai/bedrock-sdk`](github.com/anthropics/anthropic-bedrock-typescript).
## Migration from v0.4.x and below
In `v0.5.0`, we introduced a fully rewritten SDK. The new version offers better error handling, a more robust and intuitive streaming implementation, and more.
Key interface changes:
1. `new Client(apiKey)``new Anthropic({ apiKey })`
2. `client.complete()``client.completions.create()`
3. `client.completeStream()``client.completions.create({ stream: true })`
1. `onUpdate` callback → `for await (const x of stream)`
2. full message in stream → delta of message in stream
<details>
<summary>Example diff</summary>
```diff ts
// Import "Anthropic" instead of "Client":
- import { Client, HUMAN_PROMPT, AI_PROMPT } from '@anthropic-ai/sdk';
+ import Anthropic, { HUMAN_PROMPT, AI_PROMPT } from '@anthropic-ai/sdk';
// Instantiate with "apiKey" as an object property:
- const client = new Client(apiKey);
+ const client = new Anthropic({ apiKey });
// or, simply provide an ANTHROPIC_API_KEY environment variable:
+ const client = new Anthropic();
async function main() {
// Request & response types are the same as before, but better-typed.
const params = {
prompt: `${HUMAN_PROMPT} How many toes do dogs have?${AI_PROMPT}`,
max_tokens_to_sample: 200,
model: "claude-1",
};
// Instead of "client.complete()", you now call "client.completions.create()":
- await client.complete(params);
+ await client.completions.create(params);
// Streaming requests now use async iterators instead of callbacks:
- client.completeStream(params, {
- onUpdate: (completion) => {
- console.log(completion.completion); // full text
- },
- });
+ const stream = await client.completions.create({ ...params, stream: true });
+ for await (const completion of stream) {
+ process.stdout.write(completion.completion); // incremental text
+ }
// And, since this library uses `Anthropic-Version: 2023-06-01`,
// completion streams are now incremental diffs of text
// rather than sending the whole message every time:
let text = '';
- await client.completeStream(params, {
- onUpdate: (completion) => {
- const diff = completion.completion.replace(text, "");
- text = completion.completion;
- process.stdout.write(diff);
- },
- });
+ const stream = await client.completions.create({ ...params, stream: true });
+ for await (const completion of stream) {
+ const diff = completion.completion;
+ text += diff;
+ process.stdout.write(diff);
+ }
console.log('Done; final text is:')
console.log(text)
}
main();
```
</details>
The API documentation can be found [here](https://docs.anthropic.com/claude/reference/).
## Installation
```sh
npm install --save @anthropic-ai/sdk
# or
yarn add @anthropic-ai/sdk
```
## Usage
The full API of this library can be found in [api.md](https://www.github.com/anthropics/anthropic-sdk-typescript/blob/main/api.md).
```js
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: 'my api key', // defaults to process.env["ANTHROPIC_API_KEY"]
});
async function main() {
const completion = await anthropic.completions.create({
model: 'claude-2',
max_tokens_to_sample: 300,
prompt: `${Anthropic.HUMAN_PROMPT} how does a court case get to the Supreme Court?${Anthropic.AI_PROMPT}`,
});
}
main();
```
## Streaming Responses
We provide support for streaming responses using Server Sent Events (SSE).
```ts
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const stream = await anthropic.completions.create({
prompt: `${Anthropic.HUMAN_PROMPT} Your prompt here${Anthropic.AI_PROMPT}`,
model: 'claude-2',
stream: true,
max_tokens_to_sample: 300,
});
for await (const completion of stream) {
console.log(completion.completion);
}
```
If you need to cancel a stream, you can `break` from the loop
or call `stream.controller.abort()`.
### Request & Response types
This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:
```ts
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: 'my api key', // defaults to process.env["ANTHROPIC_API_KEY"]
});
async function main() {
const params: Anthropic.CompletionCreateParams = {
prompt: `${Anthropic.HUMAN_PROMPT} how does a court case get to the Supreme Court?${Anthropic.AI_PROMPT}`,
max_tokens_to_sample: 300,
model: 'claude-2',
};
const completion: Anthropic.Completion = await anthropic.completions.create(params);
}
main();
```
Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.
## Counting Tokens
We provide a [separate package](https://github.com/anthropics/anthropic-tokenizer-typescript) for counting how many tokens a given piece of text contains.
See the [repository documentation](https://github.com/anthropics/anthropic-tokenizer-typescript) for more details.
## Handling errors
When the library is unable to connect to the API,
or if the API returns a non-success status code (i.e., 4xx or 5xx response),
a subclass of `APIError` will be thrown:
```ts
async function main() {
const completion = await anthropic.completions
.create({
prompt: `${Anthropic.HUMAN_PROMPT} Your prompt here${Anthropic.AI_PROMPT}`,
max_tokens_to_sample: 300,
model: 'claude-2',
})
.catch((err) => {
if (err instanceof Anthropic.APIError) {
console.log(err.status); // 400
console.log(err.name); // BadRequestError
console.log(err.headers); // {server: 'nginx', ...}
} else {
throw err;
}
});
}
main();
```
Error codes are as followed:
| Status Code | Error Type |
| ----------- | -------------------------- |
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| >=500 | `InternalServerError` |
| N/A | `APIConnectionError` |
### Retries
Certain errors will be automatically retried 2 times by default, with a short exponential backoff.
Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
429 Rate Limit, and >=500 Internal errors will all be retried by default.
You can use the `maxRetries` option to configure or disable this:
<!-- prettier-ignore -->
```js
// Configure the default for all requests:
const anthropic = new Anthropic({
maxRetries: 0, // default is 2
});
// Or, configure per-request:
await anthropic.completions.create(
{
prompt: `${Anthropic.HUMAN_PROMPT} Can you help me effectively ask for a raise at work?${Anthropic.AI_PROMPT}`,
max_tokens_to_sample: 300,
model: 'claude-2',
},
{
maxRetries: 5,
},
);
```
### Timeouts
Requests time out after 10 minutes by default. You can configure this with a `timeout` option:
<!-- prettier-ignore -->
```ts
// Configure the default for all requests:
const anthropic = new Anthropic({
timeout: 20 * 1000, // 20 seconds (default is 10 minutes)
});
// Override per-request:
await anthropic.completions.create(
{
prompt: `${Anthropic.HUMAN_PROMPT} Where can I get a good coffee in my neighbourhood?${Anthropic.AI_PROMPT}`,
max_tokens_to_sample: 300,
model: 'claude-2',
},
{
timeout: 5 * 1000,
},
);
```
On timeout, an `APIConnectionTimeoutError` is thrown.
Note that requests which time out will be [retried twice by default](#retries).
## Advanced Usage
### Accessing raw Response data (e.g., headers)
The "raw" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return.
You can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.
```ts
const anthropic = new Anthropic();
const response = await anthropic.completions
.create({
prompt: `${Anthropic.HUMAN_PROMPT} Can you help me effectively ask for a raise at work?${Anthropic.AI_PROMPT}`,
max_tokens_to_sample: 300,
model: 'claude-2',
})
.asResponse();
console.log(response.headers.get('X-My-Header'));
console.log(response.raw.statusText); // access the underlying Response object
// parses the response body, returning an object if the API responds with JSON
const completion: Completions.Completion = await response.parse();
console.log(completion.completion);
```
## Configuring an HTTP(S) Agent (e.g., for proxies)
By default, this library uses a stable agent for all http/https requests to reuse TCP connections, eliminating many TCP & TLS handshakes and shaving around 100ms off most requests.
If you would like to disable or customize this behavior, for example to use the API behind a proxy, you can pass an `httpAgent` which is used for all requests (be they http or https), for example:
<!-- prettier-ignore -->
```ts
import http from 'http';
import Anthropic from '@anthropic-ai/sdk';
import HttpsProxyAgent from 'https-proxy-agent';
// Configure the default for all requests:
const anthropic = new Anthropic({
httpAgent: new HttpsProxyAgent(process.env.PROXY_URL),
});
// Override per-request:
await anthropic.completions.create(
{
prompt: `${Anthropic.HUMAN_PROMPT} How does a court case get to the Supreme Court?${Anthropic.AI_PROMPT}`,
max_tokens_to_sample: 300,
model: 'claude-2',
},
{
baseURL: 'http://localhost:8080/test-api',
httpAgent: new http.Agent({ keepAlive: false }),
},
);
```
## Semantic Versioning
This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
1. Changes that only affect static types, without breaking runtime behavior.
2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals)_.
3. Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an [issue](https://www.github.com/anthropics/anthropic-sdk-typescript/issues) with questions, bugs, or suggestions.
## Requirements
TypeScript >= 4.5 is supported.
The following runtimes are supported:
- Node.js 18 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.
- Deno v1.28.0 or higher, using `import Anthropic from "npm:@anthropic-ai/sdk"`.
- Bun 1.0 or later.
- Cloudflare Workers.
- Vercel Edge Runtime.
- Jest 28 or greater with the `"node"` environment (`"jsdom"` is not supported at this time).
- Nitro v2.6 or greater.
Note that React Native is not supported at this time.
If you are interested in other runtime environments, please open or upvote an issue on GitHub.

View File

@@ -0,0 +1,9 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export declare class MultipartBody {
body: any;
constructor(body: any);
get [Symbol.toStringTag](): string;
}
//# sourceMappingURL=MultipartBody.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MultipartBody.d.ts","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,aAAa;IACL,IAAI,EAAE,GAAG;gBAAT,IAAI,EAAE,GAAG;IAC5B,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,MAAM,CAEjC;CACF"}

16
node_modules/@anthropic-ai/sdk/_shims/MultipartBody.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultipartBody = void 0;
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
class MultipartBody {
constructor(body) {
this.body = body;
}
get [Symbol.toStringTag]() {
return 'MultipartBody';
}
}
exports.MultipartBody = MultipartBody;
//# sourceMappingURL=MultipartBody.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MultipartBody.js","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,aAAa;IACxB,YAAmB,IAAS;QAAT,SAAI,GAAJ,IAAI,CAAK;IAAG,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AALD,sCAKC"}

View File

@@ -0,0 +1,12 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export class MultipartBody {
constructor(body) {
this.body = body;
}
get [Symbol.toStringTag]() {
return 'MultipartBody';
}
}
//# sourceMappingURL=MultipartBody.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MultipartBody.mjs","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,OAAO,aAAa;IACxB,YAAmB,IAAS;QAAT,SAAI,GAAJ,IAAI,CAAK;IAAG,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF"}

46
node_modules/@anthropic-ai/sdk/_shims/README.md generated vendored Normal file
View File

@@ -0,0 +1,46 @@
# 👋 Wondering what everything in here does?
`@anthropic-ai/sdk` supports a wide variety of runtime environments like Node.js, Deno, Bun, browsers, and various
edge runtimes, as well as both CommonJS (CJS) and EcmaScript Modules (ESM).
To do this, `@anthropic-ai/sdk` provides shims for either using `node-fetch` when in Node (because `fetch` is still experimental there) or the global `fetch` API built into the environment when not in Node.
It uses [conditional exports](https://nodejs.org/api/packages.html#conditional-exports) to
automatically select the correct shims for each environment. However, conditional exports are a fairly new
feature and not supported everywhere. For instance, the TypeScript `"moduleResolution": "node"`
setting doesn't consult the `exports` map, compared to `"moduleResolution": "nodeNext"`, which does.
Unfortunately that's still the default setting, and it can result in errors like
getting the wrong raw `Response` type from `.asResponse()`, for example.
The user can work around these issues by manually importing one of:
- `import '@anthropic-ai/sdk/shims/node'`
- `import '@anthropic-ai/sdk/shims/web'`
All of the code here in `_shims` handles selecting the automatic default shims or manual overrides.
### How it works - Runtime
Runtime shims get installed by calling `setShims` exported by `@anthropic-ai/sdk/_shims/registry`.
Manually importing `@anthropic-ai/sdk/shims/node` or `@anthropic-ai/sdk/shims/web`, calls `setShims` with the respective runtime shims.
All client code imports shims from `@anthropic-ai/sdk/_shims/index`, which:
- checks if shims have been set manually
- if not, calls `setShims` with the shims from `@anthropic-ai/sdk/_shims/auto/runtime`
- re-exports the installed shims from `@anthropic-ai/sdk/_shims/registry`.
`@anthropic-ai/sdk/_shims/auto/runtime` exports web runtime shims.
If the `node` export condition is set, the export map replaces it with `@anthropic-ai/sdk/_shims/auto/runtime-node`.
### How it works - Type time
All client code imports shim types from `@anthropic-ai/sdk/_shims/index`, which selects the manual types from `@anthropic-ai/sdk/_shims/manual-types` if they have been declared, otherwise it exports the auto types from `@anthropic-ai/sdk/_shims/auto/types`.
`@anthropic-ai/sdk/_shims/manual-types` exports an empty namespace.
Manually importing `@anthropic-ai/sdk/shims/node` or `@anthropic-ai/sdk/shims/web` merges declarations into this empty namespace, so they get picked up by `@anthropic-ai/sdk/_shims/index`.
`@anthropic-ai/sdk/_shims/auto/types` exports web type definitions.
If the `node` export condition is set, the export map replaces it with `@anthropic-ai/sdk/_shims/auto/types-node`, though TS only picks this up if `"moduleResolution": "nodenext"` or `"moduleResolution": "bundler"`.

View File

@@ -0,0 +1,5 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export * from "../bun-runtime.js";
//# sourceMappingURL=runtime-bun.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime-bun.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,gBAAgB,CAAC"}

View File

@@ -0,0 +1,21 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
__exportStar(require("../bun-runtime.js"), exports);
//# sourceMappingURL=runtime-bun.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime-bun.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,oDAA+B"}

View File

@@ -0,0 +1,2 @@
export * from "../bun-runtime.mjs";
//# sourceMappingURL=runtime-bun.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime-bun.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,5 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export * from "../node-runtime.js";
//# sourceMappingURL=runtime-node.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime-node.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,iBAAiB,CAAC"}

View File

@@ -0,0 +1,21 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
__exportStar(require("../node-runtime.js"), exports);
//# sourceMappingURL=runtime-node.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime-node.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,qDAAgC"}

View File

@@ -0,0 +1,2 @@
export * from "../node-runtime.mjs";
//# sourceMappingURL=runtime-node.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,5 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export * from "../web-runtime.js";
//# sourceMappingURL=runtime.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,gBAAgB,CAAC"}

21
node_modules/@anthropic-ai/sdk/_shims/auto/runtime.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
__exportStar(require("../web-runtime.js"), exports);
//# sourceMappingURL=runtime.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,oDAA+B"}

View File

@@ -0,0 +1,2 @@
export * from "../web-runtime.mjs";
//# sourceMappingURL=runtime.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"runtime.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,5 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export * from "../node-types.js";
//# sourceMappingURL=types-node.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types-node.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,eAAe,CAAC"}

View File

@@ -0,0 +1,21 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
__exportStar(require("../node-types.js"), exports);
//# sourceMappingURL=types-node.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types-node.js","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,mDAA8B"}

View File

@@ -0,0 +1,2 @@
export * from "../node-types.mjs";
//# sourceMappingURL=types-node.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":""}

101
node_modules/@anthropic-ai/sdk/_shims/auto/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,101 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export type Agent = any;
// @ts-ignore
declare const _fetch: unknown extends typeof fetch ? never : typeof fetch;
export { _fetch as fetch };
// @ts-ignore
type _Request = unknown extends Request ? never : Request;
export { _Request as Request };
// @ts-ignore
type _RequestInfo = unknown extends RequestInfo ? never : RequestInfo;
export { type _RequestInfo as RequestInfo };
// @ts-ignore
type _RequestInit = unknown extends RequestInit ? never : RequestInit;
export { type _RequestInit as RequestInit };
// @ts-ignore
type _Response = unknown extends Response ? never : Response;
export { _Response as Response };
// @ts-ignore
type _ResponseInit = unknown extends ResponseInit ? never : ResponseInit;
export { type _ResponseInit as ResponseInit };
// @ts-ignore
type _ResponseType = unknown extends ResponseType ? never : ResponseType;
export { type _ResponseType as ResponseType };
// @ts-ignore
type _BodyInit = unknown extends BodyInit ? never : BodyInit;
export { type _BodyInit as BodyInit };
// @ts-ignore
type _Headers = unknown extends Headers ? never : Headers;
export { _Headers as Headers };
// @ts-ignore
type _HeadersInit = unknown extends HeadersInit ? never : HeadersInit;
export { type _HeadersInit as HeadersInit };
type EndingType = 'native' | 'transparent';
export interface BlobPropertyBag {
endings?: EndingType;
type?: string;
}
export interface FilePropertyBag extends BlobPropertyBag {
lastModified?: number;
}
export type FileFromPathOptions = Omit<FilePropertyBag, 'lastModified'>;
// @ts-ignore
type _FormData = unknown extends FormData ? never : FormData;
// @ts-ignore
declare const _FormData: unknown extends typeof FormData ? never : typeof FormData;
export { _FormData as FormData };
// @ts-ignore
type _File = unknown extends File ? never : File;
// @ts-ignore
declare const _File: unknown extends typeof File ? never : typeof File;
export { _File as File };
// @ts-ignore
type _Blob = unknown extends Blob ? never : Blob;
// @ts-ignore
declare const _Blob: unknown extends typeof Blob ? never : typeof Blob;
export { _Blob as Blob };
export declare class Readable {
readable: boolean;
readonly readableEnded: boolean;
readonly readableFlowing: boolean | null;
readonly readableHighWaterMark: number;
readonly readableLength: number;
readonly readableObjectMode: boolean;
destroyed: boolean;
read(size?: number): any;
pause(): this;
resume(): this;
isPaused(): boolean;
destroy(error?: Error): this;
[Symbol.asyncIterator](): AsyncIterableIterator<any>;
}
export declare class FsReadStream extends Readable {
path: {}; // node type is string | Buffer
}
// @ts-ignore
type _ReadableStream<R = any> = unknown extends ReadableStream<R> ? never : ReadableStream<R>;
// @ts-ignore
declare const _ReadableStream: unknown extends typeof ReadableStream ? never : typeof ReadableStream;
export { _ReadableStream as ReadableStream };

3
node_modules/@anthropic-ai/sdk/_shims/auto/types.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

3
node_modules/@anthropic-ai/sdk/_shims/auto/types.mjs generated vendored Normal file
View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

View File

@@ -0,0 +1,6 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
import { type Shims } from "./registry.js";
export declare function getRuntime(): Shims;
//# sourceMappingURL=bun-runtime.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"bun-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAIxC,wBAAgB,UAAU,IAAI,KAAK,CAMlC"}

14
node_modules/@anthropic-ai/sdk/_shims/bun-runtime.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRuntime = void 0;
const web_runtime_1 = require("./web-runtime.js");
const node_fs_1 = require("node:fs");
function getRuntime() {
const runtime = (0, web_runtime_1.getRuntime)();
function isFsReadStream(value) {
return value instanceof node_fs_1.ReadStream;
}
return { ...runtime, isFsReadStream };
}
exports.getRuntime = getRuntime;
//# sourceMappingURL=bun-runtime.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"bun-runtime.js","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":";;;AAIA,kDAA4D;AAC5D,qCAAqD;AAErD,SAAgB,UAAU;IACxB,MAAM,OAAO,GAAG,IAAA,wBAAa,GAAE,CAAC;IAChC,SAAS,cAAc,CAAC,KAAU;QAChC,OAAO,KAAK,YAAY,oBAAY,CAAC;IACvC,CAAC;IACD,OAAO,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,CAAC;AACxC,CAAC;AAND,gCAMC"}

10
node_modules/@anthropic-ai/sdk/_shims/bun-runtime.mjs generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { getRuntime as getWebRuntime } from "./web-runtime.mjs";
import { ReadStream as FsReadStream } from 'node:fs';
export function getRuntime() {
const runtime = getWebRuntime();
function isFsReadStream(value) {
return value instanceof FsReadStream;
}
return { ...runtime, isFsReadStream };
}
//# sourceMappingURL=bun-runtime.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"bun-runtime.mjs","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":"OAIO,EAAE,UAAU,IAAI,aAAa,EAAE;OAC/B,EAAE,UAAU,IAAI,YAAY,EAAE,MAAM,SAAS;AAEpD,MAAM,UAAU,UAAU;IACxB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAC;IAChC,SAAS,cAAc,CAAC,KAAU;QAChC,OAAO,KAAK,YAAY,YAAY,CAAC;IACvC,CAAC;IACD,OAAO,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,CAAC;AACxC,CAAC"}

81
node_modules/@anthropic-ai/sdk/_shims/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,81 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
import { manual } from "./manual-types.js";
import * as auto from '@anthropic-ai/sdk/_shims/auto/types';
import { type RequestOptions } from "../core.js";
type SelectType<Manual, Auto> = unknown extends Manual ? Auto : Manual;
export const kind: string;
// @ts-ignore
export type Agent = SelectType<manual.Agent, auto.Agent>;
// @ts-ignore
export const fetch: SelectType<typeof manual.fetch, typeof auto.fetch>;
// @ts-ignore
export type Request = SelectType<manual.Request, auto.Request>;
// @ts-ignore
export type RequestInfo = SelectType<manual.RequestInfo, auto.RequestInfo>;
// @ts-ignore
export type RequestInit = SelectType<manual.RequestInit, auto.RequestInit>;
// @ts-ignore
export type Response = SelectType<manual.Response, auto.Response>;
// @ts-ignore
export type ResponseInit = SelectType<manual.ResponseInit, auto.ResponseInit>;
// @ts-ignore
export type ResponseType = SelectType<manual.ResponseType, auto.ResponseType>;
// @ts-ignore
export type BodyInit = SelectType<manual.BodyInit, auto.BodyInit>;
// @ts-ignore
export type Headers = SelectType<manual.Headers, auto.Headers>;
// @ts-ignore
export const Headers: SelectType<typeof manual.Headers, typeof auto.Headers>;
// @ts-ignore
export type HeadersInit = SelectType<manual.HeadersInit, auto.HeadersInit>;
// @ts-ignore
export type BlobPropertyBag = SelectType<manual.BlobPropertyBag, auto.BlobPropertyBag>;
// @ts-ignore
export type FilePropertyBag = SelectType<manual.FilePropertyBag, auto.FilePropertyBag>;
// @ts-ignore
export type FileFromPathOptions = SelectType<manual.FileFromPathOptions, auto.FileFromPathOptions>;
// @ts-ignore
export type FormData = SelectType<manual.FormData, auto.FormData>;
// @ts-ignore
export const FormData: SelectType<typeof manual.FormData, typeof auto.FormData>;
// @ts-ignore
export type File = SelectType<manual.File, auto.File>;
// @ts-ignore
export const File: SelectType<typeof manual.File, typeof auto.File>;
// @ts-ignore
export type Blob = SelectType<manual.Blob, auto.Blob>;
// @ts-ignore
export const Blob: SelectType<typeof manual.Blob, typeof auto.Blob>;
// @ts-ignore
export type Readable = SelectType<manual.Readable, auto.Readable>;
// @ts-ignore
export type FsReadStream = SelectType<manual.FsReadStream, auto.FsReadStream>;
// @ts-ignore
export type ReadableStream = SelectType<manual.ReadableStream, auto.ReadableStream>;
// @ts-ignore
export const ReadableStream: SelectType<typeof manual.ReadableStream, typeof auto.ReadableStream>;
export function getMultipartRequestOptions<T extends {} = Record<string, unknown>>(
form: FormData,
opts: RequestOptions<T>,
): Promise<RequestOptions<T>>;
export function getDefaultAgent(url: string): any;
// @ts-ignore
export type FileFromPathOptions = SelectType<manual.FileFromPathOptions, auto.FileFromPathOptions>;
export function fileFromPath(path: string, options?: FileFromPathOptions): Promise<File>;
export function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise<File>;
export function isFsReadStream(value: any): value is FsReadStream;

13
node_modules/@anthropic-ai/sdk/_shims/index.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
const shims = require('./registry');
const auto = require('@anthropic-ai/sdk/_shims/auto/runtime');
if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });
for (const property of Object.keys(shims)) {
Object.defineProperty(exports, property, {
get() {
return shims[property];
},
});
}

7
node_modules/@anthropic-ai/sdk/_shims/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,7 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
import * as shims from './registry.mjs';
import * as auto from '@anthropic-ai/sdk/_shims/auto/runtime';
if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });
export * from './registry.mjs';

View File

@@ -0,0 +1,12 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
/**
* Types will get added to this namespace when you import one of the following:
*
* import '@anthropic-ai/sdk/shims/node'
* import '@anthropic-ai/sdk/shims/web'
*
* Importing more than one will cause type and runtime errors.
*/
export namespace manual {}

View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

View File

@@ -0,0 +1,3 @@
import { type Shims } from "./registry.js";
export declare function getRuntime(): Shims;
//# sourceMappingURL=node-runtime.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"node-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/node-runtime.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AA+CxC,wBAAgB,UAAU,IAAI,KAAK,CAqBlC"}

90
node_modules/@anthropic-ai/sdk/_shims/node-runtime.js generated vendored Normal file
View File

@@ -0,0 +1,90 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRuntime = void 0;
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
const nf = __importStar(require("node-fetch"));
const fd = __importStar(require("formdata-node"));
const agentkeepalive_1 = __importDefault(require("agentkeepalive"));
const abort_controller_1 = require("abort-controller");
const node_fs_1 = require("node:fs");
const form_data_encoder_1 = require("form-data-encoder");
const node_stream_1 = require("node:stream");
const MultipartBody_1 = require("./MultipartBody.js");
// @ts-ignore (this package does not have proper export maps for this export)
const ponyfill_es2018_js_1 = require("web-streams-polyfill/dist/ponyfill.es2018.js");
let fileFromPathWarned = false;
async function fileFromPath(path, ...args) {
// this import fails in environments that don't handle export maps correctly, like old versions of Jest
const { fileFromPath: _fileFromPath } = await Promise.resolve().then(() => __importStar(require('formdata-node/file-from-path')));
if (!fileFromPathWarned) {
console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`);
fileFromPathWarned = true;
}
// @ts-ignore
return await _fileFromPath(path, ...args);
}
const defaultHttpAgent = new agentkeepalive_1.default({ keepAlive: true, timeout: 5 * 60 * 1000 });
const defaultHttpsAgent = new agentkeepalive_1.default.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 });
async function getMultipartRequestOptions(form, opts) {
const encoder = new form_data_encoder_1.FormDataEncoder(form);
const readable = node_stream_1.Readable.from(encoder);
const body = new MultipartBody_1.MultipartBody(readable);
const headers = {
...opts.headers,
...encoder.headers,
'Content-Length': encoder.contentLength,
};
return { ...opts, body: body, headers };
}
function getRuntime() {
// Polyfill global object if needed.
if (typeof AbortController === 'undefined') {
// @ts-expect-error (the types are subtly different, but compatible in practice)
globalThis.AbortController = abort_controller_1.AbortController;
}
return {
kind: 'node',
fetch: nf.default,
Request: nf.Request,
Response: nf.Response,
Headers: nf.Headers,
FormData: fd.FormData,
Blob: fd.Blob,
File: fd.File,
ReadableStream: ponyfill_es2018_js_1.ReadableStream,
getMultipartRequestOptions,
getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent),
fileFromPath,
isFsReadStream: (value) => value instanceof node_fs_1.ReadStream,
};
}
exports.getRuntime = getRuntime;
//# sourceMappingURL=node-runtime.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"node-runtime.js","sourceRoot":"","sources":["../src/_shims/node-runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,+CAAiC;AACjC,kDAAoC;AAEpC,oEAA4C;AAC5C,uDAA8E;AAC9E,qCAAqD;AAErD,yDAAoD;AACpD,6CAAuC;AAEvC,sDAAgD;AAGhD,6EAA6E;AAC7E,qFAA8E;AAI9E,IAAI,kBAAkB,GAAG,KAAK,CAAC;AAS/B,KAAK,UAAU,YAAY,CAAC,IAAY,EAAE,GAAG,IAAW;IACtD,uGAAuG;IACvG,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,wDAAa,8BAA8B,GAAC,CAAC;IAErF,IAAI,CAAC,kBAAkB,EAAE;QACvB,OAAO,CAAC,IAAI,CAAC,uDAAuD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;Q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AC,QAAQ;QACrB,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,cAAc,EAAd,mCAAc;QACd,0BAA0B;QAC1B,eAAe,EAAE,CAAC,GAAW,EAAS,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACzG,YAAY;QACZ,cAAc,EAAE,CAAC,KAAU,EAAyB,EAAE,CAAC,KAAK,YAAY,oBAAY;KACrF,CAAC;AACJ,CAAC;AArBD,gCAqBC"}

56
node_modules/@anthropic-ai/sdk/_shims/node-runtime.mjs generated vendored Normal file
View File

@@ -0,0 +1,56 @@
import * as nf from 'node-fetch';
import * as fd from 'formdata-node';
import KeepAliveAgent from 'agentkeepalive';
import { AbortController as AbortControllerPolyfill } from 'abort-controller';
import { ReadStream as FsReadStream } from 'node:fs';
import { FormDataEncoder } from 'form-data-encoder';
import { Readable } from 'node:stream';
import { MultipartBody } from "./MultipartBody.mjs";
import { ReadableStream } from 'web-streams-polyfill/dist/ponyfill.es2018.js';
let fileFromPathWarned = false;
async function fileFromPath(path, ...args) {
// this import fails in environments that don't handle export maps correctly, like old versions of Jest
const { fileFromPath: _fileFromPath } = await import('formdata-node/file-from-path');
if (!fileFromPathWarned) {
console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`);
fileFromPathWarned = true;
}
// @ts-ignore
return await _fileFromPath(path, ...args);
}
const defaultHttpAgent = new KeepAliveAgent({ keepAlive: true, timeout: 5 * 60 * 1000 });
const defaultHttpsAgent = new KeepAliveAgent.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 });
async function getMultipartRequestOptions(form, opts) {
const encoder = new FormDataEncoder(form);
const readable = Readable.from(encoder);
const body = new MultipartBody(readable);
const headers = {
...opts.headers,
...encoder.headers,
'Content-Length': encoder.contentLength,
};
return { ...opts, body: body, headers };
}
export function getRuntime() {
// Polyfill global object if needed.
if (typeof AbortController === 'undefined') {
// @ts-expect-error (the types are subtly different, but compatible in practice)
globalThis.AbortController = AbortControllerPolyfill;
}
return {
kind: 'node',
fetch: nf.default,
Request: nf.Request,
Response: nf.Response,
Headers: nf.Headers,
FormData: fd.FormData,
Blob: fd.Blob,
File: fd.File,
ReadableStream,
getMultipartRequestOptions,
getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent),
fileFromPath,
isFsReadStream: (value) => value instanceof FsReadStream,
};
}
//# sourceMappingURL=node-runtime.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"node-runtime.mjs","sourceRoot":"","sources":["../src/_shims/node-runtime.ts"],"names":[],"mappings":"OAGO,KAAK,EAAE,MAAM,YAAY;OACzB,KAAK,EAAE,MAAM,eAAe;OAE5B,cAAc,MAAM,gBAAgB;OACpC,EAAE,eAAe,IAAI,uBAAuB,EAAE,MAAM,kBAAkB;OACtE,EAAE,UAAU,IAAI,YAAY,EAAE,MAAM,SAAS;OAE7C,EAAE,eAAe,EAAE,MAAM,mBAAmB;OAC5C,EAAE,QAAQ,EAAE,MAAM,aAAa;OAE/B,EAAE,aAAa,EAAE;OAIjB,EAAE,cAAc,EAAE,MAAM,8CAA8C;AAI7E,IAAI,kBAAkB,GAAG,KAAK,CAAC;AAS/B,KAAK,UAAU,YAAY,CAAC,IAAY,EAAE,GAAG,IAAW;IACtD,uGAAuG;IACvG,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,8BAA8B,CAAC,CAAC;IAErF,IAAI,CAAC,kBAAkB,EAAE;QACvB,OAAO,CAAC,IAAI,CAAC,uDAAuD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACrG,kBAAkB,GAAG,IAAI,CAAC;KAC3B;IACD,aAAa;IACb,OAAO,MAAM,aAAa,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC;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Ae,EAAE,CAAC,GAAW,EAAS,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACzG,YAAY;QACZ,cAAc,EAAE,CAAC,KAAU,EAAyB,EAAE,CAAC,KAAK,YAAY,YAAY;KACrF,CAAC;AACJ,CAAC"}

42
node_modules/@anthropic-ai/sdk/_shims/node-types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
import * as nf from 'node-fetch';
import * as fd from 'formdata-node';
export { type Agent } from 'node:http';
export { type Readable } from 'node:stream';
export { type ReadStream as FsReadStream } from 'node:fs';
export { ReadableStream } from 'web-streams-polyfill';
export const fetch: typeof nf.default;
export type Request = nf.Request;
export type RequestInfo = nf.RequestInfo;
export type RequestInit = nf.RequestInit;
export type Response = nf.Response;
export type ResponseInit = nf.ResponseInit;
export type ResponseType = nf.ResponseType;
export type BodyInit = nf.BodyInit;
export type Headers = nf.Headers;
export type HeadersInit = nf.HeadersInit;
type EndingType = 'native' | 'transparent';
export interface BlobPropertyBag {
endings?: EndingType;
type?: string;
}
export interface FilePropertyBag extends BlobPropertyBag {
lastModified?: number;
}
export type FileFromPathOptions = Omit<FilePropertyBag, 'lastModified'>;
export type FormData = fd.FormData;
export const FormData: typeof fd.FormData;
export type File = fd.File;
export const File: typeof fd.File;
export type Blob = fd.Blob;
export const Blob: typeof fd.Blob;

3
node_modules/@anthropic-ai/sdk/_shims/node-types.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

3
node_modules/@anthropic-ai/sdk/_shims/node-types.mjs generated vendored Normal file
View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

37
node_modules/@anthropic-ai/sdk/_shims/registry.d.ts generated vendored Normal file
View File

@@ -0,0 +1,37 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
import { type RequestOptions } from "../core.js";
export interface Shims {
kind: string;
fetch: any;
Request: any;
Response: any;
Headers: any;
FormData: any;
Blob: any;
File: any;
ReadableStream: any;
getMultipartRequestOptions: <T extends {} = Record<string, unknown>>(form: Shims['FormData'], opts: RequestOptions<T>) => Promise<RequestOptions<T>>;
getDefaultAgent: (url: string) => any;
fileFromPath: ((path: string, filename?: string, options?: {}) => Promise<Shims['File']>) | ((path: string, options?: {}) => Promise<Shims['File']>);
isFsReadStream: (value: any) => boolean;
}
export declare let auto: boolean;
export declare let kind: Shims['kind'] | undefined;
export declare let fetch: Shims['fetch'] | undefined;
export declare let Request: Shims['Request'] | undefined;
export declare let Response: Shims['Response'] | undefined;
export declare let Headers: Shims['Headers'] | undefined;
export declare let FormData: Shims['FormData'] | undefined;
export declare let Blob: Shims['Blob'] | undefined;
export declare let File: Shims['File'] | undefined;
export declare let ReadableStream: Shims['ReadableStream'] | undefined;
export declare let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined;
export declare let getDefaultAgent: Shims['getDefaultAgent'] | undefined;
export declare let fileFromPath: Shims['fileFromPath'] | undefined;
export declare let isFsReadStream: Shims['isFsReadStream'] | undefined;
export declare function setShims(shims: Shims, options?: {
auto: boolean;
}): void;
//# sourceMappingURL=registry.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,GAAG,CAAC;IACX,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,GAAG,CAAC;IACd,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,GAAG,C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AAM,CAAC,GAAG,SAAqB,CAAC;AACvD,eAAO,IAAI,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,SAAqB,CAAC;AACvD,eAAO,IAAI,cAAc,EAAE,KAAK,CAAC,gBAAgB,CAAC,GAAG,SAAqB,CAAC;AAC3E,eAAO,IAAI,0BAA0B,EAAE,KAAK,CAAC,4BAA4B,CAAC,GAAG,SAAqB,CAAC;AACnG,eAAO,IAAI,eAAe,EAAE,KAAK,CAAC,iBAAiB,CAAC,GAAG,SAAqB,CAAC;AAC7E,eAAO,IAAI,YAAY,EAAE,KAAK,CAAC,cAAc,CAAC,GAAG,SAAqB,CAAC;AACvE,eAAO,IAAI,cAAc,EAAE,KAAK,CAAC,gBAAgB,CAAC,GAAG,SAAqB,CAAC;AAE3E,wBAAgB,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,GAAE;IAAE,IAAI,EAAE,OAAO,CAAA;CAAoB,QAyBlF"}

41
node_modules/@anthropic-ai/sdk/_shims/registry.js generated vendored Normal file
View File

@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setShims = exports.isFsReadStream = exports.fileFromPath = exports.getDefaultAgent = exports.getMultipartRequestOptions = exports.ReadableStream = exports.File = exports.Blob = exports.FormData = exports.Headers = exports.Response = exports.Request = exports.fetch = exports.kind = exports.auto = void 0;
exports.auto = false;
exports.kind = undefined;
exports.fetch = undefined;
exports.Request = undefined;
exports.Response = undefined;
exports.Headers = undefined;
exports.FormData = undefined;
exports.Blob = undefined;
exports.File = undefined;
exports.ReadableStream = undefined;
exports.getMultipartRequestOptions = undefined;
exports.getDefaultAgent = undefined;
exports.fileFromPath = undefined;
exports.isFsReadStream = undefined;
function setShims(shims, options = { auto: false }) {
if (exports.auto) {
throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` before importing anything else from @anthropic-ai/sdk`);
}
if (exports.kind) {
throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` after \`import '@anthropic-ai/sdk/shims/${exports.kind}'\``);
}
exports.auto = options.auto;
exports.kind = shims.kind;
exports.fetch = shims.fetch;
exports.Request = shims.Request;
exports.Response = shims.Response;
exports.Headers = shims.Headers;
exports.FormData = shims.FormData;
exports.Blob = shims.Blob;
exports.File = shims.File;
exports.ReadableStream = shims.ReadableStream;
exports.getMultipartRequestOptions = shims.getMultipartRequestOptions;
exports.getDefaultAgent = shims.getDefaultAgent;
exports.fileFromPath = shims.fileFromPath;
exports.isFsReadStream = shims.isFsReadStream;
}
exports.setShims = setShims;
//# sourceMappingURL=registry.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":";;;AA0BW,QAAA,IAAI,GAAG,KAAK,CAAC;AACb,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,KAAK,GAA+B,SAAS,CAAC;AAC9C,QAAA,OAAO,GAAiC,SAAS,CAAC;AAClD,QAAA,QAAQ,GAAkC,SAAS,CAAC;AACpD,QAAA,OAAO,GAAiC,SAAS,CAAC;AAClD,QAAA,QAAQ,GAAkC,SAAS,CAAC;AACpD,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,cAAc,GAAwC,SAAS,CAAC;AAChE,QAAA,0BAA0B,GAAoD,SAAS,CAAC;AACxF,QAAA,eAAe,GAAyC,SAAS,CAAC;AAClE,QAAA,YAAY,GAAsC,SAAS,CAAC;AAC5D,QAAA,cAAc,GAAwC,SAAS,CAAC;AAE3E,SAAgB,QAAQ,CAAC,KAAY,EAAE,UAA6B,EAAE,IAAI,EAAE,KAAK,EAAE;IACjF,IAAI,YAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,8CAA8C,KAAK,CAAC,IAAI,2DAA2D,CACpH,CAAC;KACH;IACD,IAAI,YAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,2CAA2C,KAAK,CAAC,IAAI,+CAA+C,YAAI,KAAK,CAC9G,CAAC;KACH;IACD,YAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,aAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IACpB,eAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,gBAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,eAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,gBAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,sBAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IACtC,kCAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAC9D,uBAAe,GAAG,KAAK,CAAC,eAAe,CAAC;IACxC,oBAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IAClC,sBAAc,GAAG,KAAK,CAAC,cAAc,CAAC;AACxC,CAAC;AAzBD,4BAyBC"}

37
node_modules/@anthropic-ai/sdk/_shims/registry.mjs generated vendored Normal file
View File

@@ -0,0 +1,37 @@
export let auto = false;
export let kind = undefined;
export let fetch = undefined;
export let Request = undefined;
export let Response = undefined;
export let Headers = undefined;
export let FormData = undefined;
export let Blob = undefined;
export let File = undefined;
export let ReadableStream = undefined;
export let getMultipartRequestOptions = undefined;
export let getDefaultAgent = undefined;
export let fileFromPath = undefined;
export let isFsReadStream = undefined;
export function setShims(shims, options = { auto: false }) {
if (auto) {
throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` before importing anything else from @anthropic-ai/sdk`);
}
if (kind) {
throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` after \`import '@anthropic-ai/sdk/shims/${kind}'\``);
}
auto = options.auto;
kind = shims.kind;
fetch = shims.fetch;
Request = shims.Request;
Response = shims.Response;
Headers = shims.Headers;
FormData = shims.FormData;
Blob = shims.Blob;
File = shims.File;
ReadableStream = shims.ReadableStream;
getMultipartRequestOptions = shims.getMultipartRequestOptions;
getDefaultAgent = shims.getDefaultAgent;
fileFromPath = shims.fileFromPath;
isFsReadStream = shims.isFsReadStream;
}
//# sourceMappingURL=registry.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"registry.mjs","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":"AA0BA,MAAM,CAAC,IAAI,IAAI,GAAG,KAAK,CAAC;AACxB,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,KAAK,GAA+B,SAAS,CAAC;AACzD,MAAM,CAAC,IAAI,OAAO,GAAiC,SAAS,CAAC;AAC7D,MAAM,CAAC,IAAI,QAAQ,GAAkC,SAAS,CAAC;AAC/D,MAAM,CAAC,IAAI,OAAO,GAAiC,SAAS,CAAC;AAC7D,MAAM,CAAC,IAAI,QAAQ,GAAkC,SAAS,CAAC;AAC/D,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,cAAc,GAAwC,SAAS,CAAC;AAC3E,MAAM,CAAC,IAAI,0BAA0B,GAAoD,SAAS,CAAC;AACnG,MAAM,CAAC,IAAI,eAAe,GAAyC,SAAS,CAAC;AAC7E,MAAM,CAAC,IAAI,YAAY,GAAsC,SAAS,CAAC;AACvE,MAAM,CAAC,IAAI,cAAc,GAAwC,SAAS,CAAC;AAE3E,MAAM,UAAU,QAAQ,CAAC,KAAY,EAAE,UAA6B,EAAE,IAAI,EAAE,KAAK,EAAE;IACjF,IAAI,IAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,8CAA8C,KAAK,CAAC,IAAI,2DAA2D,CACpH,CAAC;KACH;IACD,IAAI,IAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,2CAA2C,KAAK,CAAC,IAAI,+CAA+C,IAAI,KAAK,CAC9G,CAAC;KACH;IACD,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IACpB,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IACtC,0BAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAC9D,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;IACxC,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IAClC,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;AACxC,CAAC"}

View File

@@ -0,0 +1,5 @@
import { type Shims } from "./registry.js";
export declare function getRuntime({ manuallyImported }?: {
manuallyImported?: boolean;
}): Shims;
//# sourceMappingURL=web-runtime.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"web-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,wBAAgB,UAAU,CAAC,EAAE,gBAAgB,EAAE,GAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,KAAK,CA+F3F"}

78
node_modules/@anthropic-ai/sdk/_shims/web-runtime.js generated vendored Normal file
View File

@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRuntime = void 0;
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
const MultipartBody_1 = require("./MultipartBody.js");
function getRuntime({ manuallyImported } = {}) {
const recommendation = manuallyImported ?
`You may need to use polyfills`
: `Add one of these imports before your first \`import … from '@anthropic-ai/sdk'\`:
- \`import '@anthropic-ai/sdk/shims/node'\` (if you're running on Node)
- \`import '@anthropic-ai/sdk/shims/web'\` (otherwise)
`;
let _fetch, _Request, _Response, _Headers;
try {
// @ts-ignore
_fetch = fetch;
// @ts-ignore
_Request = Request;
// @ts-ignore
_Response = Response;
// @ts-ignore
_Headers = Headers;
}
catch (error) {
throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
}
return {
kind: 'web',
fetch: _fetch,
Request: _Request,
Response: _Response,
Headers: _Headers,
FormData:
// @ts-ignore
typeof FormData !== 'undefined' ? FormData : (class FormData {
// @ts-ignore
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
}
}),
Blob: typeof Blob !== 'undefined' ? Blob : (class Blob {
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
}
}),
File:
// @ts-ignore
typeof File !== 'undefined' ? File : (class File {
// @ts-ignore
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
}
}),
ReadableStream:
// @ts-ignore
typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream {
// @ts-ignore
constructor() {
throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
}
}),
getMultipartRequestOptions: async (
// @ts-ignore
form, opts) => ({
...opts,
body: new MultipartBody_1.MultipartBody(form),
}),
getDefaultAgent: (url) => undefined,
fileFromPath: () => {
throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads');
},
isFsReadStream: (value) => false,
};
}
exports.getRuntime = getRuntime;
//# sourceMappingURL=web-runtime.js.map

View File

@@ -0,0 +1 @@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,CACnC,MAAM,IAAI;YACR,aAAa;YACb;gBACE,MAAM,IAAI,KAAK,CACb,iFAAiF,cAAc,EAAE,CAClG,CAAC;YACJ,CAAC;SACF,CACF;QACH,cAAc;QACZ,aAAa;QACb,OAAO,cAAc,KAAK,WAAW,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CACvD,MAAM,cAAc;YAClB,aAAa;YACb;gBACE,MAAM,IAAI,KAAK,CACb,uFAAuF,cAAc,EAAE,CACxG,CAAC;YACJ,CAAC;SACF,CACF;QACH,0BAA0B,EAAE,KAAK;QAC/B,aAAa;QACb,IAAc,EACd,IAAuB,EACK,EAAE,CAAC,CAAC;YAChC,GAAG,IAAI;YACP,IAAI,EAAE,IAAI,6BAAa,CAAC,IAAI,CAAQ;SACrC,CAAC;QACF,eAAe,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,SAAS;QAC3C,YAAY,EAAE,GAAG,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,iKAAiK,CAClK,CAAC;QACJ,CAAC;QACD,cAAc,EAAE,CAAC,KAAU,EAAE,EAAE,CAAC,KAAK;KACtC,CAAC;AACJ,CAAC;AA/FD,gCA+FC"}

71
node_modules/@anthropic-ai/sdk/_shims/web-runtime.mjs generated vendored Normal file
View File

@@ -0,0 +1,71 @@
import { MultipartBody } from "./MultipartBody.mjs";
export function getRuntime({ manuallyImported } = {}) {
const recommendation = manuallyImported ?
`You may need to use polyfills`
: `Add one of these imports before your first \`import … from '@anthropic-ai/sdk'\`:
- \`import '@anthropic-ai/sdk/shims/node'\` (if you're running on Node)
- \`import '@anthropic-ai/sdk/shims/web'\` (otherwise)
`;
let _fetch, _Request, _Response, _Headers;
try {
// @ts-ignore
_fetch = fetch;
// @ts-ignore
_Request = Request;
// @ts-ignore
_Response = Response;
// @ts-ignore
_Headers = Headers;
}
catch (error) {
throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
}
return {
kind: 'web',
fetch: _fetch,
Request: _Request,
Response: _Response,
Headers: _Headers,
FormData:
// @ts-ignore
typeof FormData !== 'undefined' ? FormData : (class FormData {
// @ts-ignore
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
}
}),
Blob: typeof Blob !== 'undefined' ? Blob : (class Blob {
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
}
}),
File:
// @ts-ignore
typeof File !== 'undefined' ? File : (class File {
// @ts-ignore
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
}
}),
ReadableStream:
// @ts-ignore
typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream {
// @ts-ignore
constructor() {
throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
}
}),
getMultipartRequestOptions: async (
// @ts-ignore
form, opts) => ({
...opts,
body: new MultipartBody(form),
}),
getDefaultAgent: (url) => undefined,
fileFromPath: () => {
throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads');
},
isFsReadStream: (value) => false,
};
}
//# sourceMappingURL=web-runtime.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"web-runtime.mjs","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":"OAGO,EAAE,aAAa,EAAE;AAIxB,MAAM,UAAU,UAAU,CAAC,EAAE,gBAAgB,KAAqC,EAAE;IAClF,MAAM,cAAc,GAClB,gBAAgB,CAAC,CAAC;QAChB,+BAA+B;QACjC,CAAC,CAAC;;;CAGL,CAAC;IAEA,IAAI,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC;IAC1C,IAAI;QACF,aAAa;QACb,MAAM,GAAG,KAAK,CAAC;QACf,aAAa;QACb,QAAQ,GAAG,OAAO,CAAC;QACnB,aAAa;QACb,SAAS,GAAG,QAAQ,CAAC;QACrB,aAAa;QACb,QAAQ,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AI,CAAQ;SACrC,CAAC;QACF,eAAe,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,SAAS;QAC3C,YAAY,EAAE,GAAG,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,iKAAiK,CAClK,CAAC;QACJ,CAAC;QACD,cAAc,EAAE,CAAC,KAAU,EAAE,EAAE,CAAC,KAAK;KACtC,CAAC;AACJ,CAAC"}

83
node_modules/@anthropic-ai/sdk/_shims/web-types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,83 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
export type Agent = any;
declare const _fetch: typeof fetch;
export { _fetch as fetch };
type _Request = Request;
export { _Request as Request };
type _RequestInfo = RequestInfo;
export { type _RequestInfo as RequestInfo };
type _RequestInit = RequestInit;
export { type _RequestInit as RequestInit };
type _Response = Response;
export { _Response as Response };
type _ResponseInit = ResponseInit;
export { type _ResponseInit as ResponseInit };
type _ResponseType = ResponseType;
export { type _ResponseType as ResponseType };
type _BodyInit = BodyInit;
export { type _BodyInit as BodyInit };
type _Headers = Headers;
export { _Headers as Headers };
type _HeadersInit = HeadersInit;
export { type _HeadersInit as HeadersInit };
type EndingType = 'native' | 'transparent';
export interface BlobPropertyBag {
endings?: EndingType;
type?: string;
}
export interface FilePropertyBag extends BlobPropertyBag {
lastModified?: number;
}
export type FileFromPathOptions = Omit<FilePropertyBag, 'lastModified'>;
type _FormData = FormData;
declare const _FormData: typeof FormData;
export { _FormData as FormData };
type _File = File;
declare const _File: typeof File;
export { _File as File };
type _Blob = Blob;
declare const _Blob: typeof Blob;
export { _Blob as Blob };
export declare class Readable {
readable: boolean;
readonly readableEnded: boolean;
readonly readableFlowing: boolean | null;
readonly readableHighWaterMark: number;
readonly readableLength: number;
readonly readableObjectMode: boolean;
destroyed: boolean;
read(size?: number): any;
pause(): this;
resume(): this;
isPaused(): boolean;
destroy(error?: Error): this;
[Symbol.asyncIterator](): AsyncIterableIterator<any>;
}
export declare class FsReadStream extends Readable {
path: {}; // node type is string | Buffer
}
type _ReadableStream<R = any> = ReadableStream<R>;
declare const _ReadableStream: typeof ReadableStream;
export { _ReadableStream as ReadableStream };

3
node_modules/@anthropic-ai/sdk/_shims/web-types.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

3
node_modules/@anthropic-ai/sdk/_shims/web-types.mjs generated vendored Normal file
View File

@@ -0,0 +1,3 @@
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/

239
node_modules/@anthropic-ai/sdk/core.d.ts generated vendored Normal file
View File

@@ -0,0 +1,239 @@
import { APIError } from "./error.js";
import { type Readable, type Agent, type RequestInfo, type RequestInit, type Response, type HeadersInit } from "./_shims/index.js";
export { type Response };
export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, type Uploadable, } from "./uploads.js";
export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
type PromiseOrValue<T> = T | Promise<T>;
type APIResponseProps = {
response: Response;
options: FinalRequestOptions;
controller: AbortController;
};
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export declare class APIPromise<T> extends Promise<T> {
private responsePromise;
private parseResponse;
private parsedPromise;
constructor(responsePromise: Promise<APIResponseProps>, parseResponse?: (props: APIResponseProps) => PromiseOrValue<T>);
_thenUnwrap<U>(transform: (data: T) => U): APIPromise<U>;
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
*/
asResponse(): Promise<Response>;
/**
* Gets the parsed response data and the raw `Response` instance.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
*/
withResponse(): Promise<{
data: T;
response: Response;
}>;
private parse;
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<T>;
}
export declare abstract class APIClient {
baseURL: string;
maxRetries: number;
timeout: number;
httpAgent: Agent | undefined;
private fetch;
protected idempotencyHeader?: string;
constructor({ baseURL, maxRetries, timeout, // 10 minutes
httpAgent, fetch: overridenFetch, }: {
baseURL: string;
maxRetries?: number | undefined;
timeout: number | undefined;
httpAgent: Agent | undefined;
fetch: Fetch | undefined;
});
protected authHeaders(opts: FinalRequestOptions): Headers;
/**
* Override this to add your own default headers, for example:
*
* {
* ...super.defaultHeaders(),
* Authorization: 'Bearer 123',
* }
*/
protected defaultHeaders(opts: FinalRequestOptions): Headers;
protected abstract defaultQuery(): DefaultQuery | undefined;
/**
* Override this to add your own headers validation:
*/
protected validateHeaders(headers: Headers, customHeaders: Headers): void;
protected defaultIdempotencyKey(): string;
get<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
post<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
patch<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
put<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
delete<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
private methodRequest;
getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(path: string, Page: new (...args: any[]) => PageClass, opts?: RequestOptions<any>): PagePromise<PageClass, Item>;
private calculateContentLength;
buildRequest<Req extends {}>(options: FinalRequestOptions<Req>): {
req: RequestInit;
url: string;
timeout: number;
};
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
protected prepareRequest(request: RequestInit, { url, options }: {
url: string;
options: FinalRequestOptions;
}): Promise<void>;
protected parseHeaders(headers: HeadersInit | null | undefined): Record<string, string>;
protected makeStatusError(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
request<Req extends {}, Rsp>(options: PromiseOrValue<FinalRequestOptions<Req>>, remainingRetries?: number | null): APIPromise<Rsp>;
private makeRequest;
requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass, options: FinalRequestOptions): PagePromise<PageClass, Item>;
buildURL<Req extends Record<string, unknown>>(path: string, query: Req | null | undefined): string;
protected stringifyQuery(query: Record<string, unknown>): string;
fetchWithTimeout(url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController): Promise<Response>;
protected getRequestClient(): RequestClient;
private shouldRetry;
private retryRequest;
private calculateDefaultRetryTimeoutMillis;
private getUserAgent;
}
export declare class APIResource {
protected client: APIClient;
constructor(client: APIClient);
protected get: APIClient['get'];
protected post: APIClient['post'];
protected patch: APIClient['patch'];
protected put: APIClient['put'];
protected delete: APIClient['delete'];
protected getAPIList: APIClient['getAPIList'];
}
export type PageInfo = {
url: URL;
} | {
params: Record<string, unknown> | null;
};
export declare abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#private;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions);
/**
* @deprecated Use nextPageInfo instead
*/
abstract nextPageParams(): Partial<Record<string, unknown>> | null;
abstract nextPageInfo(): PageInfo | null;
abstract getPaginatedItems(): Item[];
hasNextPage(): boolean;
getNextPage(): Promise<this>;
iterPages(): AsyncGenerator<AbstractPage<Item>, void, unknown>;
[Symbol.asyncIterator](): AsyncGenerator<Awaited<Item>, void, unknown>;
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export declare class PagePromise<PageClass extends AbstractPage<Item>, Item = ReturnType<PageClass['getPaginatedItems']>[number]> extends APIPromise<PageClass> implements AsyncIterable<Item> {
constructor(client: APIClient, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass);
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
[Symbol.asyncIterator](): AsyncGenerator<Awaited<Item>, void, unknown>;
}
export declare const createResponseHeaders: (headers: Awaited<ReturnType<Fetch>>['headers']) => Record<string, string>;
type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
export type RequestClient = {
fetch: Fetch;
};
export type Headers = Record<string, string | null | undefined>;
export type DefaultQuery = Record<string, string | undefined>;
export type KeysEnum<T> = {
[P in keyof Required<T>]: true;
};
export type RequestOptions<Req extends {} = Record<string, unknown> | Readable> = {
method?: HTTPMethod;
path?: string;
query?: Req | undefined;
body?: Req | undefined;
headers?: Headers | undefined;
maxRetries?: number;
stream?: boolean | undefined;
timeout?: number;
httpAgent?: Agent;
signal?: AbortSignal | undefined | null;
idempotencyKey?: string;
};
export declare const isRequestOptions: (obj: unknown) => obj is RequestOptions<Readable | Record<string, unknown>>;
export type FinalRequestOptions<Req extends {} = Record<string, unknown> | Readable> = RequestOptions<Req> & {
method: HTTPMethod;
path: string;
};
export declare const safeJSON: (text: string) => any;
export declare const sleep: (ms: number) => Promise<unknown>;
export declare const castToError: (err: any) => Error;
export declare const ensurePresent: <T>(value: T | null | undefined) => T;
/**
* Read an environment variable.
*
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
*/
export declare const readEnv: (env: string) => string | undefined;
export declare const coerceInteger: (value: unknown) => number;
export declare const coerceFloat: (value: unknown) => number;
export declare const coerceBoolean: (value: unknown) => boolean;
export declare const maybeCoerceInteger: (value: unknown) => number | undefined;
export declare const maybeCoerceFloat: (value: unknown) => number | undefined;
export declare const maybeCoerceBoolean: (value: unknown) => boolean | undefined;
export declare function isEmptyObj(obj: Object | null | undefined): boolean;
export declare function hasOwn(obj: Object, key: string): boolean;
export declare function debug(action: string, ...args: any[]): void;
export declare const isRunningInBrowser: () => boolean;
export interface HeadersProtocol {
get: (header: string) => string | null | undefined;
}
export type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;
export declare const isHeadersProtocol: (headers: any) => headers is HeadersProtocol;
export declare const getRequiredHeader: (headers: HeadersLike, header: string) => string;
/**
* Encodes a string to Base64 format.
*/
export declare const toBase64: (str: string | null | undefined) => string;
//# sourceMappingURL=core.d.ts.map

1
node_modules/@anthropic-ai/sdk/core.d.ts.map generated vendored Normal file

File diff suppressed because one or more lines are too long

837
node_modules/@anthropic-ai/sdk/core.js generated vendored Normal file
View File

@@ -0,0 +1,837 @@
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
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");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _AbstractPage_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBase64 = exports.getRequiredHeader = exports.isHeadersProtocol = exports.isRunningInBrowser = exports.debug = exports.hasOwn = exports.isEmptyObj = exports.maybeCoerceBoolean = exports.maybeCoerceFloat = exports.maybeCoerceInteger = exports.coerceBoolean = exports.coerceFloat = exports.coerceInteger = exports.readEnv = exports.ensurePresent = exports.castToError = exports.sleep = exports.safeJSON = exports.isRequestOptions = exports.createResponseHeaders = exports.PagePromise = exports.AbstractPage = exports.APIResource = exports.APIClient = exports.APIPromise = exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = void 0;
const version_1 = require("./version.js");
const streaming_1 = require("./streaming.js");
const error_1 = require("./error.js");
const index_1 = require("./_shims/index.js");
const uploads_1 = require("./uploads.js");
var uploads_2 = require("./uploads.js");
Object.defineProperty(exports, "maybeMultipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.maybeMultipartFormRequestOptions; } });
Object.defineProperty(exports, "multipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.multipartFormRequestOptions; } });
Object.defineProperty(exports, "createForm", { enumerable: true, get: function () { return uploads_2.createForm; } });
async function defaultParseResponse(props) {
const { response } = props;
if (props.options.stream) {
debug('response', response.status, response.url, response.headers, response.body);
// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`
return streaming_1.Stream.fromSSEResponse(response, props.controller);
}
// fetch refuses to read the body when the status code is 204.
if (response.status === 204) {
return null;
}
const contentType = response.headers.get('content-type');
if (contentType?.includes('application/json')) {
const json = await response.json();
debug('response', response.status, response.url, response.headers, json);
return json;
}
// TODO handle blob, arraybuffer, other content types, etc.
const text = await response.text();
debug('response', response.status, response.url, response.headers, text);
return text;
}
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
class APIPromise extends Promise {
constructor(responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
}
_thenUnwrap(transform) {
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data and the raw `Response` instance.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then(this.parseResponse);
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
exports.APIPromise = APIPromise;
class APIClient {
constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes
httpAgent, fetch: overridenFetch, }) {
this.baseURL = baseURL;
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
this.timeout = validatePositiveInteger('timeout', timeout);
this.httpAgent = httpAgent;
this.fetch = overridenFetch ?? index_1.fetch;
}
authHeaders(opts) {
return {};
}
/**
* Override this to add your own default headers, for example:
*
* {
* ...super.defaultHeaders(),
* Authorization: 'Bearer 123',
* }
*/
defaultHeaders(opts) {
return {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': this.getUserAgent(),
...getPlatformHeaders(),
...this.authHeaders(opts),
};
}
/**
* Override this to add your own headers validation:
*/
validateHeaders(headers, customHeaders) { }
defaultIdempotencyKey() {
return `stainless-node-retry-${uuid4()}`;
}
get(path, opts) {
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
}
getAPIList(path, Page, opts) {
return this.requestAPIList(Page, { method: 'get', path, ...opts });
}
calculateContentLength(body) {
if (typeof body === 'string') {
if (typeof Buffer !== 'undefined') {
return Buffer.byteLength(body, 'utf8').toString();
}
if (typeof TextEncoder !== 'undefined') {
const encoder = new TextEncoder();
const encoded = encoder.encode(body);
return encoded.length.toString();
}
}
return null;
}
buildRequest(options) {
const { method, path, query, headers: headers = {} } = options;
const body = (0, uploads_1.isMultipartBody)(options.body) ? options.body.body
: options.body ? JSON.stringify(options.body, null, 2)
: null;
const contentLength = this.calculateContentLength(body);
const url = this.buildURL(path, query);
if ('timeout' in options)
validatePositiveInteger('timeout', options.timeout);
const timeout = options.timeout ?? this.timeout;
const httpAgent = options.httpAgent ?? this.httpAgent ?? (0, index_1.getDefaultAgent)(url);
const minAgentTimeout = timeout + 1000;
if (typeof httpAgent?.options?.timeout === 'number' &&
minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
// Allow any given request to bump our agent active socket timeout.
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
// and without mutating agent we would need to create more of them.
// This tradeoff optimizes for performance.
httpAgent.options.timeout = minAgentTimeout;
}
if (this.idempotencyHeader && method !== 'get') {
if (!options.idempotencyKey)
options.idempotencyKey = this.defaultIdempotencyKey();
headers[this.idempotencyHeader] = options.idempotencyKey;
}
const reqHeaders = {
...(contentLength && { 'Content-Length': contentLength }),
...this.defaultHeaders(options),
...headers,
};
// let builtin fetch set the Content-Type for multipart bodies
if ((0, uploads_1.isMultipartBody)(options.body) && index_1.kind !== 'node') {
delete reqHeaders['Content-Type'];
}
// Strip any headers being explicitly omitted with null
Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]);
const req = {
method,
...(body && { body: body }),
headers: reqHeaders,
...(httpAgent && { agent: httpAgent }),
// @ts-ignore node-fetch uses a custom AbortSignal type that is
// not compatible with standard web types
signal: options.signal ?? null,
};
this.validateHeaders(reqHeaders, headers);
return { req, url, timeout };
}
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
async prepareRequest(request, { url, options }) { }
parseHeaders(headers) {
return (!headers ? {}
: Symbol.iterator in headers ?
Object.fromEntries(Array.from(headers).map((header) => [...header]))
: { ...headers });
}
makeStatusError(status, error, message, headers) {
return error_1.APIError.generate(status, error, message, headers);
}
request(options, remainingRetries = null) {
return new APIPromise(this.makeRequest(options, remainingRetries));
}
async makeRequest(optionsInput, retriesRemaining) {
const options = await optionsInput;
if (retriesRemaining == null) {
retriesRemaining = options.maxRetries ?? this.maxRetries;
}
const { req, url, timeout } = this.buildRequest(options);
await this.prepareRequest(req, { url, options });
debug('request', url, options, req.headers);
if (options.signal?.aborted) {
throw new error_1.APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(exports.castToError);
if (response instanceof Error) {
if (options.signal?.aborted) {
throw new error_1.APIUserAbortError();
}
if (retriesRemaining) {
return this.retryRequest(options, retriesRemaining);
}
if (response.name === 'AbortError') {
throw new error_1.APIConnectionTimeoutError();
}
throw new error_1.APIConnectionError({ cause: response });
}
const responseHeaders = (0, exports.createResponseHeaders)(response.headers);
if (!response.ok) {
if (retriesRemaining && this.shouldRetry(response)) {
return this.retryRequest(options, retriesRemaining, responseHeaders);
}
const errText = await response.text().catch((e) => (0, exports.castToError)(e).message);
const errJSON = (0, exports.safeJSON)(errText);
const errMessage = errJSON ? undefined : errText;
debug('response', response.status, url, responseHeaders, errMessage);
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
throw err;
}
return { response, options, controller };
}
requestAPIList(Page, options) {
const request = this.makeRequest(options, null);
return new PagePromise(this, request, Page);
}
buildURL(path, query) {
const url = isAbsoluteURL(path) ?
new URL(path)
: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
if (!isEmptyObj(defaultQuery)) {
query = { ...defaultQuery, ...query };
}
if (query) {
url.search = this.stringifyQuery(query);
}
return url.toString();
}
stringifyQuery(query) {
return Object.entries(query)
.filter(([_, value]) => typeof value !== 'undefined')
.map(([key, value]) => {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}
if (value === null) {
return `${encodeURIComponent(key)}=`;
}
throw new error_1.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.`);
})
.join('&');
}
async fetchWithTimeout(url, init, ms, controller) {
const { signal, ...options } = init || {};
if (signal)
signal.addEventListener('abort', () => controller.abort());
const timeout = setTimeout(() => controller.abort(), ms);
return (this.getRequestClient()
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
.fetch.call(undefined, url, { signal: controller.signal, ...options })
.finally(() => {
clearTimeout(timeout);
}));
}
getRequestClient() {
return { fetch: this.fetch };
}
shouldRetry(response) {
// Note this is not a standard header.
const shouldRetryHeader = response.headers.get('x-should-retry');
// If the server explicitly says whether or not to retry, obey.
if (shouldRetryHeader === 'true')
return true;
if (shouldRetryHeader === 'false')
return false;
// Retry on request timeouts.
if (response.status === 408)
return true;
// Retry on lock timeouts.
if (response.status === 409)
return true;
// Retry on rate limits.
if (response.status === 429)
return true;
// Retry internal errors.
if (response.status >= 500)
return true;
return false;
}
async retryRequest(options, retriesRemaining, responseHeaders) {
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
let timeoutMillis;
const retryAfterHeader = responseHeaders?.['retry-after'];
if (retryAfterHeader) {
const timeoutSeconds = parseInt(retryAfterHeader);
if (!Number.isNaN(timeoutSeconds)) {
timeoutMillis = timeoutSeconds * 1000;
}
else {
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
}
}
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
// just do what it says, but otherwise calculate a default
if (!timeoutMillis ||
!Number.isInteger(timeoutMillis) ||
timeoutMillis <= 0 ||
timeoutMillis > 60 * 1000) {
const maxRetries = options.maxRetries ?? this.maxRetries;
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
}
await (0, exports.sleep)(timeoutMillis);
return this.makeRequest(options, retriesRemaining - 1);
}
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
const initialRetryDelay = 0.5;
const maxRetryDelay = 8.0;
const numRetries = maxRetries - retriesRemaining;
// Apply exponential backoff, but not more than the max.
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
// Apply some jitter, take up to at most 25 percent of the retry time.
const jitter = 1 - Math.random() * 0.25;
return sleepSeconds * jitter * 1000;
}
getUserAgent() {
return `${this.constructor.name}/JS ${version_1.VERSION}`;
}
}
exports.APIClient = APIClient;
class APIResource {
constructor(client) {
this.client = client;
this.get = client.get.bind(client);
this.post = client.post.bind(client);
this.patch = client.patch.bind(client);
this.put = client.put.bind(client);
this.delete = client.delete.bind(client);
this.getAPIList = client.getAPIList.bind(client);
}
}
exports.APIResource = APIResource;
class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageInfo() != null;
}
async getNextPage() {
const nextInfo = this.nextPageInfo();
if (!nextInfo) {
throw new error_1.AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
const nextOptions = { ...this.options };
if ('params' in nextInfo) {
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
}
else if ('url' in nextInfo) {
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
for (const [key, value] of params) {
nextInfo.url.searchParams.set(key, value);
}
nextOptions.query = undefined;
nextOptions.path = nextInfo.url.toString();
}
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
exports.AbstractPage = AbstractPage;
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
class PagePromise extends APIPromise {
constructor(client, request, Page) {
super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
exports.PagePromise = PagePromise;
const createResponseHeaders = (headers) => {
return new Proxy(Object.fromEntries(
// @ts-ignore
headers.entries()), {
get(target, name) {
const key = name.toString();
return target[key.toLowerCase()] || target[key];
},
});
};
exports.createResponseHeaders = createResponseHeaders;
// This is required so that we can determine if a given object matches the RequestOptions
// type at runtime. While this requires duplication, it is enforced by the TypeScript
// compiler such that any missing / extraneous keys will cause an error.
const requestOptionsKeys = {
method: true,
path: true,
query: true,
body: true,
headers: true,
maxRetries: true,
stream: true,
timeout: true,
httpAgent: true,
signal: true,
idempotencyKey: true,
};
const isRequestOptions = (obj) => {
return (typeof obj === 'object' &&
obj !== null &&
!isEmptyObj(obj) &&
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
};
exports.isRequestOptions = isRequestOptions;
const getPlatformProperties = () => {
if (typeof Deno !== 'undefined' && Deno.build != null) {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': version_1.VERSION,
'X-Stainless-OS': normalizePlatform(Deno.build.os),
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
'X-Stainless-Runtime': 'deno',
'X-Stainless-Runtime-Version': Deno.version,
};
}
if (typeof EdgeRuntime !== 'undefined') {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': version_1.VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': `other:${EdgeRuntime}`,
'X-Stainless-Runtime': 'edge',
'X-Stainless-Runtime-Version': process.version,
};
}
// Check if Node.js
if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': version_1.VERSION,
'X-Stainless-OS': normalizePlatform(process.platform),
'X-Stainless-Arch': normalizeArch(process.arch),
'X-Stainless-Runtime': 'node',
'X-Stainless-Runtime-Version': process.version,
};
}
const browserInfo = getBrowserInfo();
if (browserInfo) {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': version_1.VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': 'unknown',
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
'X-Stainless-Runtime-Version': browserInfo.version,
};
}
// TODO add support for Cloudflare workers, etc.
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': version_1.VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': 'unknown',
'X-Stainless-Runtime': 'unknown',
'X-Stainless-Runtime-Version': 'unknown',
};
};
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
function getBrowserInfo() {
if (typeof navigator === 'undefined' || !navigator) {
return null;
}
// NOTE: The order matters here!
const browserPatterns = [
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
];
// Find the FIRST matching browser
for (const { key, pattern } of browserPatterns) {
const match = pattern.exec(navigator.userAgent);
if (match) {
const major = match[1] || 0;
const minor = match[2] || 0;
const patch = match[3] || 0;
return { browser: key, version: `${major}.${minor}.${patch}` };
}
}
return null;
}
const normalizeArch = (arch) => {
// Node docs:
// - https://nodejs.org/api/process.html#processarch
// Deno docs:
// - https://doc.deno.land/deno/stable/~/Deno.build
if (arch === 'x32')
return 'x32';
if (arch === 'x86_64' || arch === 'x64')
return 'x64';
if (arch === 'arm')
return 'arm';
if (arch === 'aarch64' || arch === 'arm64')
return 'arm64';
if (arch)
return `other:${arch}`;
return 'unknown';
};
const normalizePlatform = (platform) => {
// Node platforms:
// - https://nodejs.org/api/process.html#processplatform
// Deno platforms:
// - https://doc.deno.land/deno/stable/~/Deno.build
// - https://github.com/denoland/deno/issues/14799
platform = platform.toLowerCase();
// NOTE: this iOS check is untested and may not work
// Node does not work natively on IOS, there is a fork at
// https://github.com/nodejs-mobile/nodejs-mobile
// however it is unknown at the time of writing how to detect if it is running
if (platform.includes('ios'))
return 'iOS';
if (platform === 'android')
return 'Android';
if (platform === 'darwin')
return 'MacOS';
if (platform === 'win32')
return 'Windows';
if (platform === 'freebsd')
return 'FreeBSD';
if (platform === 'openbsd')
return 'OpenBSD';
if (platform === 'linux')
return 'Linux';
if (platform)
return `Other:${platform}`;
return 'Unknown';
};
let _platformHeaders;
const getPlatformHeaders = () => {
return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
};
const safeJSON = (text) => {
try {
return JSON.parse(text);
}
catch (err) {
return undefined;
}
};
exports.safeJSON = safeJSON;
// https://stackoverflow.com/a/19709846
const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
const isAbsoluteURL = (url) => {
return startsWithSchemeRegexp.test(url);
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
exports.sleep = sleep;
const validatePositiveInteger = (name, n) => {
if (typeof n !== 'number' || !Number.isInteger(n)) {
throw new error_1.AnthropicError(`${name} must be an integer`);
}
if (n < 0) {
throw new error_1.AnthropicError(`${name} must be a positive integer`);
}
return n;
};
const castToError = (err) => {
if (err instanceof Error)
return err;
return new Error(err);
};
exports.castToError = castToError;
const ensurePresent = (value) => {
if (value == null)
throw new error_1.AnthropicError(`Expected a value to be given but received ${value} instead.`);
return value;
};
exports.ensurePresent = ensurePresent;
/**
* Read an environment variable.
*
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
*/
const readEnv = (env) => {
if (typeof process !== 'undefined') {
return process.env?.[env] ?? undefined;
}
if (typeof Deno !== 'undefined') {
return Deno.env?.get?.(env);
}
return undefined;
};
exports.readEnv = readEnv;
const coerceInteger = (value) => {
if (typeof value === 'number')
return Math.round(value);
if (typeof value === 'string')
return parseInt(value, 10);
throw new error_1.AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
exports.coerceInteger = coerceInteger;
const coerceFloat = (value) => {
if (typeof value === 'number')
return value;
if (typeof value === 'string')
return parseFloat(value);
throw new error_1.AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
exports.coerceFloat = coerceFloat;
const coerceBoolean = (value) => {
if (typeof value === 'boolean')
return value;
if (typeof value === 'string')
return value === 'true';
return Boolean(value);
};
exports.coerceBoolean = coerceBoolean;
const maybeCoerceInteger = (value) => {
if (value === undefined) {
return undefined;
}
return (0, exports.coerceInteger)(value);
};
exports.maybeCoerceInteger = maybeCoerceInteger;
const maybeCoerceFloat = (value) => {
if (value === undefined) {
return undefined;
}
return (0, exports.coerceFloat)(value);
};
exports.maybeCoerceFloat = maybeCoerceFloat;
const maybeCoerceBoolean = (value) => {
if (value === undefined) {
return undefined;
}
return (0, exports.coerceBoolean)(value);
};
exports.maybeCoerceBoolean = maybeCoerceBoolean;
// https://stackoverflow.com/a/34491287
function isEmptyObj(obj) {
if (!obj)
return true;
for (const _k in obj)
return false;
return true;
}
exports.isEmptyObj = isEmptyObj;
// https://eslint.org/docs/latest/rules/no-prototype-builtins
function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
exports.hasOwn = hasOwn;
function debug(action, ...args) {
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
console.log(`Anthropic:DEBUG:${action}`, ...args);
}
}
exports.debug = debug;
/**
* https://stackoverflow.com/a/2117523
*/
const uuid4 = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
const isRunningInBrowser = () => {
return (
// @ts-ignore
typeof window !== 'undefined' &&
// @ts-ignore
typeof window.document !== 'undefined' &&
// @ts-ignore
typeof navigator !== 'undefined');
};
exports.isRunningInBrowser = isRunningInBrowser;
const isHeadersProtocol = (headers) => {
return typeof headers?.get === 'function';
};
exports.isHeadersProtocol = isHeadersProtocol;
const getRequiredHeader = (headers, header) => {
const lowerCasedHeader = header.toLowerCase();
if ((0, exports.isHeadersProtocol)(headers)) {
// to deal with the case where the header looks like Stainless-Event-Id
const intercapsHeader = header[0]?.toUpperCase() +
header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
const value = headers.get(key);
if (value) {
return value;
}
}
}
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === lowerCasedHeader) {
if (Array.isArray(value)) {
if (value.length <= 1)
return value[0];
console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
return value[0];
}
return value;
}
}
throw new Error(`Could not find ${header} header`);
};
exports.getRequiredHeader = getRequiredHeader;
/**
* Encodes a string to Base64 format.
*/
const toBase64 = (str) => {
if (!str)
return '';
if (typeof Buffer !== 'undefined') {
return Buffer.from(str).toString('base64');
}
if (typeof btoa !== 'undefined') {
return btoa(str);
}
throw new error_1.AnthropicError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
};
exports.toBase64 = toBase64;
//# sourceMappingURL=core.js.map

1
node_modules/@anthropic-ai/sdk/core.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

806
node_modules/@anthropic-ai/sdk/core.mjs generated vendored Normal file
View File

@@ -0,0 +1,806 @@
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
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");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _AbstractPage_client;
import { VERSION } from "./version.mjs";
import { Stream } from "./streaming.mjs";
import { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from "./error.mjs";
import { kind as shimsKind, getDefaultAgent, fetch, } from "./_shims/index.mjs";
import { isMultipartBody } from "./uploads.mjs";
export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from "./uploads.mjs";
async function defaultParseResponse(props) {
const { response } = props;
if (props.options.stream) {
debug('response', response.status, response.url, response.headers, response.body);
// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`
return Stream.fromSSEResponse(response, props.controller);
}
// fetch refuses to read the body when the status code is 204.
if (response.status === 204) {
return null;
}
const contentType = response.headers.get('content-type');
if (contentType?.includes('application/json')) {
const json = await response.json();
debug('response', response.status, response.url, response.headers, json);
return json;
}
// TODO handle blob, arraybuffer, other content types, etc.
const text = await response.text();
debug('response', response.status, response.url, response.headers, text);
return text;
}
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export class APIPromise extends Promise {
constructor(responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
}
_thenUnwrap(transform) {
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data and the raw `Response` instance.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then(this.parseResponse);
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
export class APIClient {
constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes
httpAgent, fetch: overridenFetch, }) {
this.baseURL = baseURL;
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
this.timeout = validatePositiveInteger('timeout', timeout);
this.httpAgent = httpAgent;
this.fetch = overridenFetch ?? fetch;
}
authHeaders(opts) {
return {};
}
/**
* Override this to add your own default headers, for example:
*
* {
* ...super.defaultHeaders(),
* Authorization: 'Bearer 123',
* }
*/
defaultHeaders(opts) {
return {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': this.getUserAgent(),
...getPlatformHeaders(),
...this.authHeaders(opts),
};
}
/**
* Override this to add your own headers validation:
*/
validateHeaders(headers, customHeaders) { }
defaultIdempotencyKey() {
return `stainless-node-retry-${uuid4()}`;
}
get(path, opts) {
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
}
getAPIList(path, Page, opts) {
return this.requestAPIList(Page, { method: 'get', path, ...opts });
}
calculateContentLength(body) {
if (typeof body === 'string') {
if (typeof Buffer !== 'undefined') {
return Buffer.byteLength(body, 'utf8').toString();
}
if (typeof TextEncoder !== 'undefined') {
const encoder = new TextEncoder();
const encoded = encoder.encode(body);
return encoded.length.toString();
}
}
return null;
}
buildRequest(options) {
const { method, path, query, headers: headers = {} } = options;
const body = isMultipartBody(options.body) ? options.body.body
: options.body ? JSON.stringify(options.body, null, 2)
: null;
const contentLength = this.calculateContentLength(body);
const url = this.buildURL(path, query);
if ('timeout' in options)
validatePositiveInteger('timeout', options.timeout);
const timeout = options.timeout ?? this.timeout;
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
const minAgentTimeout = timeout + 1000;
if (typeof httpAgent?.options?.timeout === 'number' &&
minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
// Allow any given request to bump our agent active socket timeout.
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
// and without mutating agent we would need to create more of them.
// This tradeoff optimizes for performance.
httpAgent.options.timeout = minAgentTimeout;
}
if (this.idempotencyHeader && method !== 'get') {
if (!options.idempotencyKey)
options.idempotencyKey = this.defaultIdempotencyKey();
headers[this.idempotencyHeader] = options.idempotencyKey;
}
const reqHeaders = {
...(contentLength && { 'Content-Length': contentLength }),
...this.defaultHeaders(options),
...headers,
};
// let builtin fetch set the Content-Type for multipart bodies
if (isMultipartBody(options.body) && shimsKind !== 'node') {
delete reqHeaders['Content-Type'];
}
// Strip any headers being explicitly omitted with null
Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]);
const req = {
method,
...(body && { body: body }),
headers: reqHeaders,
...(httpAgent && { agent: httpAgent }),
// @ts-ignore node-fetch uses a custom AbortSignal type that is
// not compatible with standard web types
signal: options.signal ?? null,
};
this.validateHeaders(reqHeaders, headers);
return { req, url, timeout };
}
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
async prepareRequest(request, { url, options }) { }
parseHeaders(headers) {
return (!headers ? {}
: Symbol.iterator in headers ?
Object.fromEntries(Array.from(headers).map((header) => [...header]))
: { ...headers });
}
makeStatusError(status, error, message, headers) {
return APIError.generate(status, error, message, headers);
}
request(options, remainingRetries = null) {
return new APIPromise(this.makeRequest(options, remainingRetries));
}
async makeRequest(optionsInput, retriesRemaining) {
const options = await optionsInput;
if (retriesRemaining == null) {
retriesRemaining = options.maxRetries ?? this.maxRetries;
}
const { req, url, timeout } = this.buildRequest(options);
await this.prepareRequest(req, { url, options });
debug('request', url, options, req.headers);
if (options.signal?.aborted) {
throw new APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
if (response instanceof Error) {
if (options.signal?.aborted) {
throw new APIUserAbortError();
}
if (retriesRemaining) {
return this.retryRequest(options, retriesRemaining);
}
if (response.name === 'AbortError') {
throw new APIConnectionTimeoutError();
}
throw new APIConnectionError({ cause: response });
}
const responseHeaders = createResponseHeaders(response.headers);
if (!response.ok) {
if (retriesRemaining && this.shouldRetry(response)) {
return this.retryRequest(options, retriesRemaining, responseHeaders);
}
const errText = await response.text().catch((e) => castToError(e).message);
const errJSON = safeJSON(errText);
const errMessage = errJSON ? undefined : errText;
debug('response', response.status, url, responseHeaders, errMessage);
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
throw err;
}
return { response, options, controller };
}
requestAPIList(Page, options) {
const request = this.makeRequest(options, null);
return new PagePromise(this, request, Page);
}
buildURL(path, query) {
const url = isAbsoluteURL(path) ?
new URL(path)
: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
if (!isEmptyObj(defaultQuery)) {
query = { ...defaultQuery, ...query };
}
if (query) {
url.search = this.stringifyQuery(query);
}
return url.toString();
}
stringifyQuery(query) {
return Object.entries(query)
.filter(([_, value]) => typeof value !== 'undefined')
.map(([key, value]) => {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}
if (value === null) {
return `${encodeURIComponent(key)}=`;
}
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.`);
})
.join('&');
}
async fetchWithTimeout(url, init, ms, controller) {
const { signal, ...options } = init || {};
if (signal)
signal.addEventListener('abort', () => controller.abort());
const timeout = setTimeout(() => controller.abort(), ms);
return (this.getRequestClient()
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
.fetch.call(undefined, url, { signal: controller.signal, ...options })
.finally(() => {
clearTimeout(timeout);
}));
}
getRequestClient() {
return { fetch: this.fetch };
}
shouldRetry(response) {
// Note this is not a standard header.
const shouldRetryHeader = response.headers.get('x-should-retry');
// If the server explicitly says whether or not to retry, obey.
if (shouldRetryHeader === 'true')
return true;
if (shouldRetryHeader === 'false')
return false;
// Retry on request timeouts.
if (response.status === 408)
return true;
// Retry on lock timeouts.
if (response.status === 409)
return true;
// Retry on rate limits.
if (response.status === 429)
return true;
// Retry internal errors.
if (response.status >= 500)
return true;
return false;
}
async retryRequest(options, retriesRemaining, responseHeaders) {
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
let timeoutMillis;
const retryAfterHeader = responseHeaders?.['retry-after'];
if (retryAfterHeader) {
const timeoutSeconds = parseInt(retryAfterHeader);
if (!Number.isNaN(timeoutSeconds)) {
timeoutMillis = timeoutSeconds * 1000;
}
else {
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
}
}
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
// just do what it says, but otherwise calculate a default
if (!timeoutMillis ||
!Number.isInteger(timeoutMillis) ||
timeoutMillis <= 0 ||
timeoutMillis > 60 * 1000) {
const maxRetries = options.maxRetries ?? this.maxRetries;
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
}
await sleep(timeoutMillis);
return this.makeRequest(options, retriesRemaining - 1);
}
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
const initialRetryDelay = 0.5;
const maxRetryDelay = 8.0;
const numRetries = maxRetries - retriesRemaining;
// Apply exponential backoff, but not more than the max.
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
// Apply some jitter, take up to at most 25 percent of the retry time.
const jitter = 1 - Math.random() * 0.25;
return sleepSeconds * jitter * 1000;
}
getUserAgent() {
return `${this.constructor.name}/JS ${VERSION}`;
}
}
export class APIResource {
constructor(client) {
this.client = client;
this.get = client.get.bind(client);
this.post = client.post.bind(client);
this.patch = client.patch.bind(client);
this.put = client.put.bind(client);
this.delete = client.delete.bind(client);
this.getAPIList = client.getAPIList.bind(client);
}
}
export class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageInfo() != null;
}
async getNextPage() {
const nextInfo = this.nextPageInfo();
if (!nextInfo) {
throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
const nextOptions = { ...this.options };
if ('params' in nextInfo) {
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
}
else if ('url' in nextInfo) {
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
for (const [key, value] of params) {
nextInfo.url.searchParams.set(key, value);
}
nextOptions.query = undefined;
nextOptions.path = nextInfo.url.toString();
}
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export class PagePromise extends APIPromise {
constructor(client, request, Page) {
super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
export const createResponseHeaders = (headers) => {
return new Proxy(Object.fromEntries(
// @ts-ignore
headers.entries()), {
get(target, name) {
const key = name.toString();
return target[key.toLowerCase()] || target[key];
},
});
};
// This is required so that we can determine if a given object matches the RequestOptions
// type at runtime. While this requires duplication, it is enforced by the TypeScript
// compiler such that any missing / extraneous keys will cause an error.
const requestOptionsKeys = {
method: true,
path: true,
query: true,
body: true,
headers: true,
maxRetries: true,
stream: true,
timeout: true,
httpAgent: true,
signal: true,
idempotencyKey: true,
};
export const isRequestOptions = (obj) => {
return (typeof obj === 'object' &&
obj !== null &&
!isEmptyObj(obj) &&
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
};
const getPlatformProperties = () => {
if (typeof Deno !== 'undefined' && Deno.build != null) {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': normalizePlatform(Deno.build.os),
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
'X-Stainless-Runtime': 'deno',
'X-Stainless-Runtime-Version': Deno.version,
};
}
if (typeof EdgeRuntime !== 'undefined') {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': `other:${EdgeRuntime}`,
'X-Stainless-Runtime': 'edge',
'X-Stainless-Runtime-Version': process.version,
};
}
// Check if Node.js
if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': normalizePlatform(process.platform),
'X-Stainless-Arch': normalizeArch(process.arch),
'X-Stainless-Runtime': 'node',
'X-Stainless-Runtime-Version': process.version,
};
}
const browserInfo = getBrowserInfo();
if (browserInfo) {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': 'unknown',
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
'X-Stainless-Runtime-Version': browserInfo.version,
};
}
// TODO add support for Cloudflare workers, etc.
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': 'unknown',
'X-Stainless-Runtime': 'unknown',
'X-Stainless-Runtime-Version': 'unknown',
};
};
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
function getBrowserInfo() {
if (typeof navigator === 'undefined' || !navigator) {
return null;
}
// NOTE: The order matters here!
const browserPatterns = [
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
];
// Find the FIRST matching browser
for (const { key, pattern } of browserPatterns) {
const match = pattern.exec(navigator.userAgent);
if (match) {
const major = match[1] || 0;
const minor = match[2] || 0;
const patch = match[3] || 0;
return { browser: key, version: `${major}.${minor}.${patch}` };
}
}
return null;
}
const normalizeArch = (arch) => {
// Node docs:
// - https://nodejs.org/api/process.html#processarch
// Deno docs:
// - https://doc.deno.land/deno/stable/~/Deno.build
if (arch === 'x32')
return 'x32';
if (arch === 'x86_64' || arch === 'x64')
return 'x64';
if (arch === 'arm')
return 'arm';
if (arch === 'aarch64' || arch === 'arm64')
return 'arm64';
if (arch)
return `other:${arch}`;
return 'unknown';
};
const normalizePlatform = (platform) => {
// Node platforms:
// - https://nodejs.org/api/process.html#processplatform
// Deno platforms:
// - https://doc.deno.land/deno/stable/~/Deno.build
// - https://github.com/denoland/deno/issues/14799
platform = platform.toLowerCase();
// NOTE: this iOS check is untested and may not work
// Node does not work natively on IOS, there is a fork at
// https://github.com/nodejs-mobile/nodejs-mobile
// however it is unknown at the time of writing how to detect if it is running
if (platform.includes('ios'))
return 'iOS';
if (platform === 'android')
return 'Android';
if (platform === 'darwin')
return 'MacOS';
if (platform === 'win32')
return 'Windows';
if (platform === 'freebsd')
return 'FreeBSD';
if (platform === 'openbsd')
return 'OpenBSD';
if (platform === 'linux')
return 'Linux';
if (platform)
return `Other:${platform}`;
return 'Unknown';
};
let _platformHeaders;
const getPlatformHeaders = () => {
return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
};
export const safeJSON = (text) => {
try {
return JSON.parse(text);
}
catch (err) {
return undefined;
}
};
// https://stackoverflow.com/a/19709846
const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
const isAbsoluteURL = (url) => {
return startsWithSchemeRegexp.test(url);
};
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const validatePositiveInteger = (name, n) => {
if (typeof n !== 'number' || !Number.isInteger(n)) {
throw new AnthropicError(`${name} must be an integer`);
}
if (n < 0) {
throw new AnthropicError(`${name} must be a positive integer`);
}
return n;
};
export const castToError = (err) => {
if (err instanceof Error)
return err;
return new Error(err);
};
export const ensurePresent = (value) => {
if (value == null)
throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);
return value;
};
/**
* Read an environment variable.
*
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
*/
export const readEnv = (env) => {
if (typeof process !== 'undefined') {
return process.env?.[env] ?? undefined;
}
if (typeof Deno !== 'undefined') {
return Deno.env?.get?.(env);
}
return undefined;
};
export const coerceInteger = (value) => {
if (typeof value === 'number')
return Math.round(value);
if (typeof value === 'string')
return parseInt(value, 10);
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
export const coerceFloat = (value) => {
if (typeof value === 'number')
return value;
if (typeof value === 'string')
return parseFloat(value);
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
export const coerceBoolean = (value) => {
if (typeof value === 'boolean')
return value;
if (typeof value === 'string')
return value === 'true';
return Boolean(value);
};
export const maybeCoerceInteger = (value) => {
if (value === undefined) {
return undefined;
}
return coerceInteger(value);
};
export const maybeCoerceFloat = (value) => {
if (value === undefined) {
return undefined;
}
return coerceFloat(value);
};
export const maybeCoerceBoolean = (value) => {
if (value === undefined) {
return undefined;
}
return coerceBoolean(value);
};
// https://stackoverflow.com/a/34491287
export function isEmptyObj(obj) {
if (!obj)
return true;
for (const _k in obj)
return false;
return true;
}
// https://eslint.org/docs/latest/rules/no-prototype-builtins
export function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
export function debug(action, ...args) {
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
console.log(`Anthropic:DEBUG:${action}`, ...args);
}
}
/**
* https://stackoverflow.com/a/2117523
*/
const uuid4 = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
export const isRunningInBrowser = () => {
return (
// @ts-ignore
typeof window !== 'undefined' &&
// @ts-ignore
typeof window.document !== 'undefined' &&
// @ts-ignore
typeof navigator !== 'undefined');
};
export const isHeadersProtocol = (headers) => {
return typeof headers?.get === 'function';
};
export const getRequiredHeader = (headers, header) => {
const lowerCasedHeader = header.toLowerCase();
if (isHeadersProtocol(headers)) {
// to deal with the case where the header looks like Stainless-Event-Id
const intercapsHeader = header[0]?.toUpperCase() +
header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
const value = headers.get(key);
if (value) {
return value;
}
}
}
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === lowerCasedHeader) {
if (Array.isArray(value)) {
if (value.length <= 1)
return value[0];
console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
return value[0];
}
return value;
}
}
throw new Error(`Could not find ${header} header`);
};
/**
* Encodes a string to Base64 format.
*/
export const toBase64 = (str) => {
if (!str)
return '';
if (typeof Buffer !== 'undefined') {
return Buffer.from(str).toString('base64');
}
if (typeof btoa !== 'undefined') {
return btoa(str);
}
throw new AnthropicError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
};
//# sourceMappingURL=core.mjs.map

1
node_modules/@anthropic-ai/sdk/core.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

53
node_modules/@anthropic-ai/sdk/error.d.ts generated vendored Normal file
View File

@@ -0,0 +1,53 @@
import { Headers } from "./core.js";
export declare class AnthropicError extends Error {
}
export declare class APIError extends AnthropicError {
readonly status: number | undefined;
readonly headers: Headers | undefined;
readonly error: Object | undefined;
constructor(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined);
private static makeMessage;
static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
}
export declare class APIUserAbortError extends APIError {
readonly status: undefined;
constructor({ message }?: {
message?: string;
});
}
export declare class APIConnectionError extends APIError {
readonly status: undefined;
constructor({ message, cause }: {
message?: string;
cause?: Error | undefined;
});
}
export declare class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message }?: {
message?: string;
});
}
export declare class BadRequestError extends APIError {
readonly status: 400;
}
export declare class AuthenticationError extends APIError {
readonly status: 401;
}
export declare class PermissionDeniedError extends APIError {
readonly status: 403;
}
export declare class NotFoundError extends APIError {
readonly status: 404;
}
export declare class ConflictError extends APIError {
readonly status: 409;
}
export declare class UnprocessableEntityError extends APIError {
readonly status: 422;
}
export declare class RateLimitError extends APIError {
readonly status: 429;
}
export declare class InternalServerError extends APIError {
}
//# sourceMappingURL=error.d.ts.map

1
node_modules/@anthropic-ai/sdk/error.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,OAAO,EAAE,MAAM,QAAQ,CAAC;AAE9C,qBAAa,cAAe,SAAQ,KAAK;CAAG;AAE5C,qBAAa,QAAS,SAAQ,cAAc;IAC1C,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,CAAC;IACtC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;gBAGjC,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,OAAO,EAAE,MA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BAAa,cAAe,SAAQ,QAAQ;IAC1C,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,mBAAoB,SAAQ,QAAQ;CAAG"}

142
node_modules/@anthropic-ai/sdk/error.js generated vendored Normal file
View File

@@ -0,0 +1,142 @@
"use strict";
// File generated from our OpenAPI spec by Stainless.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalServerError = exports.RateLimitError = exports.UnprocessableEntityError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIUserAbortError = exports.APIError = exports.AnthropicError = void 0;
const core_1 = require("./core.js");
class AnthropicError extends Error {
}
exports.AnthropicError = AnthropicError;
class APIError extends AnthropicError {
constructor(status, error, message, headers) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.error = error;
}
static makeMessage(status, error, message) {
const msg = error?.message ?
typeof error.message === 'string' ? error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
if (status && msg) {
return `${status} ${msg}`;
}
if (status) {
return `${status} status code (no body)`;
}
if (msg) {
return msg;
}
return '(no status code or body)';
}
static generate(status, errorResponse, message, headers) {
if (!status) {
return new APIConnectionError({ cause: (0, core_1.castToError)(errorResponse) });
}
const error = errorResponse;
if (status === 400) {
return new BadRequestError(status, error, message, headers);
}
if (status === 401) {
return new AuthenticationError(status, error, message, headers);
}
if (status === 403) {
return new PermissionDeniedError(status, error, message, headers);
}
if (status === 404) {
return new NotFoundError(status, error, message, headers);
}
if (status === 409) {
return new ConflictError(status, error, message, headers);
}
if (status === 422) {
return new UnprocessableEntityError(status, error, message, headers);
}
if (status === 429) {
return new RateLimitError(status, error, message, headers);
}
if (status >= 500) {
return new InternalServerError(status, error, message, headers);
}
return new APIError(status, error, message, headers);
}
}
exports.APIError = APIError;
class APIUserAbortError extends APIError {
constructor({ message } = {}) {
super(undefined, undefined, message || 'Request was aborted.', undefined);
this.status = undefined;
}
}
exports.APIUserAbortError = APIUserAbortError;
class APIConnectionError extends APIError {
constructor({ message, cause }) {
super(undefined, undefined, message || 'Connection error.', undefined);
this.status = undefined;
// in some environments the 'cause' property is already declared
// @ts-ignore
if (cause)
this.cause = cause;
}
}
exports.APIConnectionError = APIConnectionError;
class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? 'Request timed out.' });
}
}
exports.APIConnectionTimeoutError = APIConnectionTimeoutError;
class BadRequestError extends APIError {
constructor() {
super(...arguments);
this.status = 400;
}
}
exports.BadRequestError = BadRequestError;
class AuthenticationError extends APIError {
constructor() {
super(...arguments);
this.status = 401;
}
}
exports.AuthenticationError = AuthenticationError;
class PermissionDeniedError extends APIError {
constructor() {
super(...arguments);
this.status = 403;
}
}
exports.PermissionDeniedError = PermissionDeniedError;
class NotFoundError extends APIError {
constructor() {
super(...arguments);
this.status = 404;
}
}
exports.NotFoundError = NotFoundError;
class ConflictError extends APIError {
constructor() {
super(...arguments);
this.status = 409;
}
}
exports.ConflictError = ConflictError;
class UnprocessableEntityError extends APIError {
constructor() {
super(...arguments);
this.status = 422;
}
}
exports.UnprocessableEntityError = UnprocessableEntityError;
class RateLimitError extends APIError {
constructor() {
super(...arguments);
this.status = 429;
}
}
exports.RateLimitError = RateLimitError;
class InternalServerError extends APIError {
}
exports.InternalServerError = InternalServerError;
//# sourceMappingURL=error.js.map

1
node_modules/@anthropic-ai/sdk/error.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"error.js","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":";AAAA,qDAAqD;;;AAErD,oCAA8C;AAE9C,MAAa,cAAe,SAAQ,KAAK;CAAG;AAA5C,wCAA4C;AAE5C,MAAa,QAAS,SAAQ,cAAc;IAK1C,YACE,MAA0B,EAC1B,KAAyB,EACzB,OAA2B,EAC3B,OAA4B;QAE5B,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,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ules/@anthropic-ai/sdk/error.mjs generated vendored Normal file
View File

@@ -0,0 +1,126 @@
// File generated from our OpenAPI spec by Stainless.
import { castToError } from "./core.mjs";
export class AnthropicError extends Error {
}
export class APIError extends AnthropicError {
constructor(status, error, message, headers) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.error = error;
}
static makeMessage(status, error, message) {
const msg = error?.message ?
typeof error.message === 'string' ? error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
if (status && msg) {
return `${status} ${msg}`;
}
if (status) {
return `${status} status code (no body)`;
}
if (msg) {
return msg;
}
return '(no status code or body)';
}
static generate(status, errorResponse, message, headers) {
if (!status) {
return new APIConnectionError({ cause: castToError(errorResponse) });
}
const error = errorResponse;
if (status === 400) {
return new BadRequestError(status, error, message, headers);
}
if (status === 401) {
return new AuthenticationError(status, error, message, headers);
}
if (status === 403) {
return new PermissionDeniedError(status, error, message, headers);
}
if (status === 404) {
return new NotFoundError(status, error, message, headers);
}
if (status === 409) {
return new ConflictError(status, error, message, headers);
}
if (status === 422) {
return new UnprocessableEntityError(status, error, message, headers);
}
if (status === 429) {
return new RateLimitError(status, error, message, headers);
}
if (status >= 500) {
return new InternalServerError(status, error, message, headers);
}
return new APIError(status, error, message, headers);
}
}
export class APIUserAbortError extends APIError {
constructor({ message } = {}) {
super(undefined, undefined, message || 'Request was aborted.', undefined);
this.status = undefined;
}
}
export class APIConnectionError extends APIError {
constructor({ message, cause }) {
super(undefined, undefined, message || 'Connection error.', undefined);
this.status = undefined;
// in some environments the 'cause' property is already declared
// @ts-ignore
if (cause)
this.cause = cause;
}
}
export class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? 'Request timed out.' });
}
}
export class BadRequestError extends APIError {
constructor() {
super(...arguments);
this.status = 400;
}
}
export class AuthenticationError extends APIError {
constructor() {
super(...arguments);
this.status = 401;
}
}
export class PermissionDeniedError extends APIError {
constructor() {
super(...arguments);
this.status = 403;
}
}
export class NotFoundError extends APIError {
constructor() {
super(...arguments);
this.status = 404;
}
}
export class ConflictError extends APIError {
constructor() {
super(...arguments);
this.status = 409;
}
}
export class UnprocessableEntityError extends APIError {
constructor() {
super(...arguments);
this.status = 422;
}
}
export class RateLimitError extends APIError {
constructor() {
super(...arguments);
this.status = 429;
}
}
export class InternalServerError extends APIError {
}
//# sourceMappingURL=error.mjs.map

1
node_modules/@anthropic-ai/sdk/error.mjs.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"error.mjs","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":"AAAA,qDAAqD;OAE9C,EAAE,WAAW,EAAW;AAE/B,MAAM,OAAO,cAAe,SAAQ,KAAK;CAAG;AAE5C,MAAM,OAAO,QAAS,SAAQ,cAAc;IAK1C,YACE,MAA0B,EAC1B,KAAyB,EACzB,OAA2B,EAC3B,OAA4B;QAE5B,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAEO,MAAM,CAAC,WAAW,CAAC,MAA0B,EAAE,KAAU,EAAE,OAA2B;QAC5F,MAAM,GAAG,GACP,KAAK,EAAE,OAAO,CAAC,CAAC;YACd,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO;gBACjD,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC;YACjC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;gBAC/B,CAAC,CAAC,OAAO,CAAC;QAEZ,IAAI,MAAM,IAAI,GAAG,EAAE;YACjB,OAAO,GAAG,MAA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AAQ,QAAQ;IAAnD;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,aAAc,SAAQ,QAAQ;IAA3C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,aAAc,SAAQ,QAAQ;IAA3C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,wBAAyB,SAAQ,QAAQ;IAAtD;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAA5C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,mBAAoB,SAAQ,QAAQ;CAAG"}

121
node_modules/@anthropic-ai/sdk/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,121 @@
import * as Core from "./core.js";
import * as Errors from "./error.js";
import { type Agent } from "./_shims/index.js";
import * as Uploads from "./uploads.js";
import * as API from '@anthropic-ai/sdk/resources/index';
export interface ClientOptions {
/**
* Defaults to process.env['ANTHROPIC_API_KEY'].
*/
apiKey?: string | null;
/**
* Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].
*/
authToken?: string | null;
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*/
baseURL?: string;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*/
timeout?: number;
/**
* An HTTP agent used to manage HTTP(S) connections.
*
* If not provided, an agent will be constructed by default in the Node.js environment,
* otherwise no agent is used.
*/
httpAgent?: Agent;
/**
* Specify a custom `fetch` function implementation.
*
* If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
* defined globally.
*/
fetch?: Core.Fetch | undefined;
/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
*
* @default 2
*/
maxRetries?: number;
/**
* Default headers to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* header to `undefined` or `null` in request options.
*/
defaultHeaders?: Core.Headers;
/**
* Default query parameters to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* param to `undefined` in request options.
*/
defaultQuery?: Core.DefaultQuery;
}
/** API Client for interfacing with the Anthropic API. */
export declare class Anthropic extends Core.APIClient {
apiKey: string | null;
authToken: string | null;
private _options;
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null} [opts.apiKey==process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null} [opts.authToken==process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
*/
constructor({ apiKey, authToken, ...opts }?: ClientOptions);
completions: API.Completions;
protected defaultQuery(): Core.DefaultQuery | undefined;
protected defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers;
protected validateHeaders(headers: Core.Headers, customHeaders: Core.Headers): void;
protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers;
protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers;
protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers;
static Anthropic: typeof Anthropic;
static HUMAN_PROMPT: string;
static AI_PROMPT: string;
static AnthropicError: typeof Errors.AnthropicError;
static APIError: typeof Errors.APIError;
static APIConnectionError: typeof Errors.APIConnectionError;
static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError;
static APIUserAbortError: typeof Errors.APIUserAbortError;
static NotFoundError: typeof Errors.NotFoundError;
static ConflictError: typeof Errors.ConflictError;
static RateLimitError: typeof Errors.RateLimitError;
static BadRequestError: typeof Errors.BadRequestError;
static AuthenticationError: typeof Errors.AuthenticationError;
static InternalServerError: typeof Errors.InternalServerError;
static PermissionDeniedError: typeof Errors.PermissionDeniedError;
static UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
}
export declare const HUMAN_PROMPT: string, AI_PROMPT: string;
export declare const AnthropicError: typeof Errors.AnthropicError, APIError: typeof Errors.APIError, APIConnectionError: typeof Errors.APIConnectionError, APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError, APIUserAbortError: typeof Errors.APIUserAbortError, NotFoundError: typeof Errors.NotFoundError, ConflictError: typeof Errors.ConflictError, RateLimitError: typeof Errors.RateLimitError, BadRequestError: typeof Errors.BadRequestError, AuthenticationError: typeof Errors.AuthenticationError, InternalServerError: typeof Errors.InternalServerError, PermissionDeniedError: typeof Errors.PermissionDeniedError, UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
export import toFile = Uploads.toFile;
export import fileFromPath = Uploads.fileFromPath;
export declare namespace Anthropic {
export import toFile = Uploads.toFile;
export import fileFromPath = Uploads.fileFromPath;
export import RequestOptions = Core.RequestOptions;
export import Completions = API.Completions;
export import Completion = API.Completion;
export import CompletionCreateParams = API.CompletionCreateParams;
export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming;
export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming;
}
export default Anthropic;
//# sourceMappingURL=index.d.ts.map

121
node_modules/@anthropic-ai/sdk/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,121 @@
import * as Core from "./core.js";
import * as Errors from "./error.js";
import { type Agent } from "./_shims/index.js";
import * as Uploads from "./uploads.js";
import * as API from '@anthropic-ai/sdk/resources/index';
export interface ClientOptions {
/**
* Defaults to process.env['ANTHROPIC_API_KEY'].
*/
apiKey?: string | null;
/**
* Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].
*/
authToken?: string | null;
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*/
baseURL?: string;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*/
timeout?: number;
/**
* An HTTP agent used to manage HTTP(S) connections.
*
* If not provided, an agent will be constructed by default in the Node.js environment,
* otherwise no agent is used.
*/
httpAgent?: Agent;
/**
* Specify a custom `fetch` function implementation.
*
* If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
* defined globally.
*/
fetch?: Core.Fetch | undefined;
/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
*
* @default 2
*/
maxRetries?: number;
/**
* Default headers to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* header to `undefined` or `null` in request options.
*/
defaultHeaders?: Core.Headers;
/**
* Default query parameters to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* param to `undefined` in request options.
*/
defaultQuery?: Core.DefaultQuery;
}
/** API Client for interfacing with the Anthropic API. */
export declare class Anthropic extends Core.APIClient {
apiKey: string | null;
authToken: string | null;
private _options;
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null} [opts.apiKey==process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null} [opts.authToken==process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
*/
constructor({ apiKey, authToken, ...opts }?: ClientOptions);
completions: API.Completions;
protected defaultQuery(): Core.DefaultQuery | undefined;
protected defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers;
protected validateHeaders(headers: Core.Headers, customHeaders: Core.Headers): void;
protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers;
protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers;
protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers;
static Anthropic: typeof Anthropic;
static HUMAN_PROMPT: string;
static AI_PROMPT: string;
static AnthropicError: typeof Errors.AnthropicError;
static APIError: typeof Errors.APIError;
static APIConnectionError: typeof Errors.APIConnectionError;
static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError;
static APIUserAbortError: typeof Errors.APIUserAbortError;
static NotFoundError: typeof Errors.NotFoundError;
static ConflictError: typeof Errors.ConflictError;
static RateLimitError: typeof Errors.RateLimitError;
static BadRequestError: typeof Errors.BadRequestError;
static AuthenticationError: typeof Errors.AuthenticationError;
static InternalServerError: typeof Errors.InternalServerError;
static PermissionDeniedError: typeof Errors.PermissionDeniedError;
static UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
}
export declare const HUMAN_PROMPT: string, AI_PROMPT: string;
export declare const AnthropicError: typeof Errors.AnthropicError, APIError: typeof Errors.APIError, APIConnectionError: typeof Errors.APIConnectionError, APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError, APIUserAbortError: typeof Errors.APIUserAbortError, NotFoundError: typeof Errors.NotFoundError, ConflictError: typeof Errors.ConflictError, RateLimitError: typeof Errors.RateLimitError, BadRequestError: typeof Errors.BadRequestError, AuthenticationError: typeof Errors.AuthenticationError, InternalServerError: typeof Errors.InternalServerError, PermissionDeniedError: typeof Errors.PermissionDeniedError, UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
export import toFile = Uploads.toFile;
export import fileFromPath = Uploads.fileFromPath;
export declare namespace Anthropic {
export import toFile = Uploads.toFile;
export import fileFromPath = Uploads.fileFromPath;
export import RequestOptions = Core.RequestOptions;
export import Completions = API.Completions;
export import Completion = API.Completion;
export import CompletionCreateParams = API.CompletionCreateParams;
export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming;
export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming;
}
export default Anthropic;
//# sourceMappingURL=index.d.ts.map

1
node_modules/@anthropic-ai/sdk/index.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,MAAM,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,GAAG,MAAM,mCAAmC,CAAC;AAEzD,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,KAAK,CAAC;IAElB;;;;;OAKG;IACH,KAAK,CAAC,EAAE,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;IAE/B;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;OAKG;IACH,cAAc,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC;IAE9B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,IAAI,CAAC,YAAY,CAAC;CAClC;AAED,yDAAyD;AACzD,qBAAa,SAAU,SAAQ,IAAI,CAAC,SAAS;IAC3C,MAAM,EAAE,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BAAwB,yCAAmC;CACnE;AAED,eAAO,MAAQ,YAAY,UAAE,SAAS,QAAc,CAAC;AAErD,eAAO,MACL,cAAc,gCACd,QAAQ,0BACR,kBAAkB,oCAClB,yBAAyB,2CACzB,iBAAiB,mCACjB,aAAa,+BACb,aAAa,+BACb,cAAc,gCACd,eAAe,iCACf,mBAAmB,qCACnB,mBAAmB,qCACnB,qBAAqB,uCACrB,wBAAwB,wCAChB,CAAC;AAEX,MAAM,QAAQ,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;AACtC,MAAM,QAAQ,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;AAElD,yBAAiB,SAAS,CAAC;IAEzB,MAAM,QAAQ,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IACtC,MAAM,QAAQ,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAElD,MAAM,QAAQ,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IAEnD,MAAM,QAAQ,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAC5C,MAAM,QAAQ,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAC1C,MAAM,QAAQ,sBAAsB,GAAG,GAAG,CAAC,sBAAsB,CAAC;IAClE,MAAM,QAAQ,kCAAkC,GAAG,GAAG,CAAC,kCAAkC,CAAC;IAC1F,MAAM,QAAQ,+BAA+B,GAAG,GAAG,CAAC,+BAA+B,CAAC;CACrF;AAED,eAAe,SAAS,CAAC"}

146
node_modules/@anthropic-ai/sdk/index.js generated vendored Normal file
View File

@@ -0,0 +1,146 @@
"use strict";
// File generated from our OpenAPI spec by Stainless.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileFromPath = exports.toFile = exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.AnthropicError = exports.AI_PROMPT = exports.HUMAN_PROMPT = exports.Anthropic = void 0;
const Core = __importStar(require("./core.js"));
const Errors = __importStar(require("./error.js"));
const Uploads = __importStar(require("./uploads.js"));
const API = __importStar(require("@anthropic-ai/sdk/resources/index"));
/** API Client for interfacing with the Anthropic API. */
class Anthropic extends Core.APIClient {
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null} [opts.apiKey==process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null} [opts.authToken==process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
*/
constructor({ apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null, authToken = Core.readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) {
const options = {
apiKey,
authToken,
...opts,
baseURL: opts.baseURL ?? `https://api.anthropic.com`,
};
super({
baseURL: options.baseURL,
timeout: options.timeout ?? 600000 /* 10 minutes */,
httpAgent: options.httpAgent,
maxRetries: options.maxRetries,
fetch: options.fetch,
});
this.completions = new API.Completions(this);
this._options = options;
this.apiKey = apiKey;
this.authToken = authToken;
}
defaultQuery() {
return this._options.defaultQuery;
}
defaultHeaders(opts) {
return {
...super.defaultHeaders(opts),
'anthropic-version': '2023-06-01',
...this._options.defaultHeaders,
};
}
validateHeaders(headers, customHeaders) {
if (this.apiKey && headers['X-Api-Key']) {
return;
}
if (customHeaders['X-Api-Key'] === null) {
return;
}
if (this.authToken && headers['Authorization']) {
return;
}
if (customHeaders['Authorization'] === null) {
return;
}
throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
}
authHeaders(opts) {
const apiKeyAuth = this.apiKeyAuth(opts);
const bearerAuth = this.bearerAuth(opts);
if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {
return apiKeyAuth;
}
if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
return bearerAuth;
}
return {};
}
apiKeyAuth(opts) {
if (this.apiKey == null) {
return {};
}
return { 'X-Api-Key': this.apiKey };
}
bearerAuth(opts) {
if (this.authToken == null) {
return {};
}
return { Authorization: `Bearer ${this.authToken}` };
}
}
exports.Anthropic = Anthropic;
_a = Anthropic;
Anthropic.Anthropic = _a;
Anthropic.HUMAN_PROMPT = '\n\nHuman:';
Anthropic.AI_PROMPT = '\n\nAssistant:';
Anthropic.AnthropicError = Errors.AnthropicError;
Anthropic.APIError = Errors.APIError;
Anthropic.APIConnectionError = Errors.APIConnectionError;
Anthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
Anthropic.APIUserAbortError = Errors.APIUserAbortError;
Anthropic.NotFoundError = Errors.NotFoundError;
Anthropic.ConflictError = Errors.ConflictError;
Anthropic.RateLimitError = Errors.RateLimitError;
Anthropic.BadRequestError = Errors.BadRequestError;
Anthropic.AuthenticationError = Errors.AuthenticationError;
Anthropic.InternalServerError = Errors.InternalServerError;
Anthropic.PermissionDeniedError = Errors.PermissionDeniedError;
Anthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
exports.HUMAN_PROMPT = Anthropic.HUMAN_PROMPT, exports.AI_PROMPT = Anthropic.AI_PROMPT;
exports.AnthropicError = Errors.AnthropicError, exports.APIError = Errors.APIError, exports.APIConnectionError = Errors.APIConnectionError, exports.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError, exports.APIUserAbortError = Errors.APIUserAbortError, exports.NotFoundError = Errors.NotFoundError, exports.ConflictError = Errors.ConflictError, exports.RateLimitError = Errors.RateLimitError, exports.BadRequestError = Errors.BadRequestError, exports.AuthenticationError = Errors.AuthenticationError, exports.InternalServerError = Errors.InternalServerError, exports.PermissionDeniedError = Errors.PermissionDeniedError, exports.UnprocessableEntityError = Errors.UnprocessableEntityError;
exports.toFile = Uploads.toFile;
exports.fileFromPath = Uploads.fileFromPath;
(function (Anthropic) {
// Helper functions
Anthropic.toFile = Uploads.toFile;
Anthropic.fileFromPath = Uploads.fileFromPath;
Anthropic.Completions = API.Completions;
})(Anthropic = exports.Anthropic || (exports.Anthropic = {}));
exports = module.exports = Anthropic;
exports.default = Anthropic;
//# sourceMappingURL=index.js.map

1
node_modules/@anthropic-ai/sdk/index.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,qDAAqD;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErD,gDAA+B;AAC/B,mDAAkC;AAElC,sDAAqC;AACrC,uEAAyD;AAoEzD,yDAAyD;AACzD,MAAa,SAAU,SAAQ,IAAI,CAAC,SAAS;IAM3C;;;;;;;;;;;;OAYG;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@anthropic-ai/sdk/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,118 @@
// File generated from our OpenAPI spec by Stainless.
var _a;
import * as Core from "./core.mjs";
import * as Errors from "./error.mjs";
import * as Uploads from "./uploads.mjs";
import * as API from '@anthropic-ai/sdk/resources/index';
/** API Client for interfacing with the Anthropic API. */
export class Anthropic extends Core.APIClient {
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null} [opts.apiKey==process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null} [opts.authToken==process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
*/
constructor({ apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null, authToken = Core.readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) {
const options = {
apiKey,
authToken,
...opts,
baseURL: opts.baseURL ?? `https://api.anthropic.com`,
};
super({
baseURL: options.baseURL,
timeout: options.timeout ?? 600000 /* 10 minutes */,
httpAgent: options.httpAgent,
maxRetries: options.maxRetries,
fetch: options.fetch,
});
this.completions = new API.Completions(this);
this._options = options;
this.apiKey = apiKey;
this.authToken = authToken;
}
defaultQuery() {
return this._options.defaultQuery;
}
defaultHeaders(opts) {
return {
...super.defaultHeaders(opts),
'anthropic-version': '2023-06-01',
...this._options.defaultHeaders,
};
}
validateHeaders(headers, customHeaders) {
if (this.apiKey && headers['X-Api-Key']) {
return;
}
if (customHeaders['X-Api-Key'] === null) {
return;
}
if (this.authToken && headers['Authorization']) {
return;
}
if (customHeaders['Authorization'] === null) {
return;
}
throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
}
authHeaders(opts) {
const apiKeyAuth = this.apiKeyAuth(opts);
const bearerAuth = this.bearerAuth(opts);
if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {
return apiKeyAuth;
}
if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
return bearerAuth;
}
return {};
}
apiKeyAuth(opts) {
if (this.apiKey == null) {
return {};
}
return { 'X-Api-Key': this.apiKey };
}
bearerAuth(opts) {
if (this.authToken == null) {
return {};
}
return { Authorization: `Bearer ${this.authToken}` };
}
}
_a = Anthropic;
Anthropic.Anthropic = _a;
Anthropic.HUMAN_PROMPT = '\n\nHuman:';
Anthropic.AI_PROMPT = '\n\nAssistant:';
Anthropic.AnthropicError = Errors.AnthropicError;
Anthropic.APIError = Errors.APIError;
Anthropic.APIConnectionError = Errors.APIConnectionError;
Anthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
Anthropic.APIUserAbortError = Errors.APIUserAbortError;
Anthropic.NotFoundError = Errors.NotFoundError;
Anthropic.ConflictError = Errors.ConflictError;
Anthropic.RateLimitError = Errors.RateLimitError;
Anthropic.BadRequestError = Errors.BadRequestError;
Anthropic.AuthenticationError = Errors.AuthenticationError;
Anthropic.InternalServerError = Errors.InternalServerError;
Anthropic.PermissionDeniedError = Errors.PermissionDeniedError;
Anthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
export const { HUMAN_PROMPT, AI_PROMPT } = Anthropic;
export const { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } = Errors;
export var toFile = Uploads.toFile;
export var fileFromPath = Uploads.fileFromPath;
(function (Anthropic) {
// Helper functions
Anthropic.toFile = Uploads.toFile;
Anthropic.fileFromPath = Uploads.fileFromPath;
Anthropic.Completions = API.Completions;
})(Anthropic || (Anthropic = {}));
export default Anthropic;
//# sourceMappingURL=index.mjs.map

1
node_modules/@anthropic-ai/sdk/index.mjs.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA,qDAAqD;;OAE9C,KAAK,IAAI;OACT,KAAK,MAAM;OAEX,KAAK,OAAO;OACZ,KAAK,GAAG,MAAM,mCAAmC;AAoExD,yDAAyD;AACzD,MAAM,OAAO,SAAU,SAAQ,IAAI,CAAC,SAAS;IAM3C;;;;;;;;;;;;OAYG;IACH,YAAY,EACV,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,IAAI,IAAI,EAClD,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,IAAI,IAAI,EACxD,GAAG,IAAI,KACU,EAAE;QACnB,MAAM,OAAO,GAAkB;YAC7B,MAAM;YACN,SAAS;YACT,GAAG,IAAI;YACP,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,2BAA2B;SACrD,CAAC;QAEF,KAAK,CAAC;YACJ,OAAO,EAAE,OAAO,CAAC,OAAQ;YACzB,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC,gBAAgB;YACnD,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,UAAU,EAAE,OAAO,CAAC,UAAU;YAC9B,KAAK,EAAE,OAAO,CAAC,KAAK;SACrB,CAAC,CAAC;QAOL,gBAAW,GAAoB,IAAI,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QANvD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QAExB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAIkB,YAAY;QAC7B,OAAO,IAAI,CAAC,QAAQ,C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GAAG,OAAO,CAAC,YAAY,CAAC;AAElD,WAAiB,SAAS;IACxB,mBAAmB;IACL,gBAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IACxB,sBAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAIpC,qBAAW,GAAG,GAAG,CAAC,WAAW,CAAC;AAK9C,CAAC,EAZgB,SAAS,KAAT,SAAS,QAYzB;AAED,eAAe,SAAS,CAAC"}

97
node_modules/@anthropic-ai/sdk/package.json generated vendored Normal file
View File

@@ -0,0 +1,97 @@
{
"name": "@anthropic-ai/sdk",
"version": "0.8.1",
"description": "Client library for the Anthropic API",
"author": "Anthropic <support@anthropic.com>",
"types": "./index.d.ts",
"main": "./index.js",
"type": "commonjs",
"repository": "github:anthropics/anthropic-sdk-typescript",
"license": "MIT",
"private": false,
"sideEffects": [
"./_shims/index.js",
"./_shims/index.mjs",
"./shims/node.js",
"./shims/node.mjs",
"./shims/web.js",
"./shims/web.mjs"
],
"exports": {
"./_shims/auto/*": {
"deno": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"bun": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*-bun.js",
"default": "./_shims/auto/*-bun.mjs"
},
"browser": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"worker": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"workerd": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"node": {
"types": "./_shims/auto/*-node.d.ts",
"require": "./_shims/auto/*-node.js",
"default": "./_shims/auto/*-node.mjs"
},
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
".": {
"require": {
"types": "./index.d.ts",
"default": "./index.js"
},
"types": "./index.d.mts",
"default": "./index.mjs"
},
"./*.mjs": {
"types": "./*.d.ts",
"default": "./*.mjs"
},
"./*.js": {
"types": "./*.d.ts",
"default": "./*.js"
},
"./*": {
"types": "./*.d.ts",
"require": "./*.js",
"default": "./*.mjs"
}
},
"scripts": {
"test": "bin/check-test-server && yarn jest",
"build": "bash ./build",
"format": "prettier --write --cache --cache-strategy metadata . !dist",
"tsn": "ts-node -r tsconfig-paths/register",
"lint": "eslint --ext ts,js .",
"fix": "eslint --fix --ext ts,js ."
},
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"digest-fetch": "^1.3.0",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7",
"web-streams-polyfill": "^3.2.1"
}
}

12
node_modules/@anthropic-ai/sdk/resource.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import type { Anthropic } from "./index.js";
export declare class APIResource {
protected client: Anthropic;
constructor(client: Anthropic);
protected get: Anthropic['get'];
protected post: Anthropic['post'];
protected patch: Anthropic['patch'];
protected put: Anthropic['put'];
protected delete: Anthropic['delete'];
protected getAPIList: Anthropic['getAPIList'];
}
//# sourceMappingURL=resource.d.ts.map

1
node_modules/@anthropic-ai/sdk/resource.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["src/resource.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,qBAAa,WAAW;IACtB,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC;gBAChB,MAAM,EAAE,SAAS;IAW7B,SAAS,CAAC,GAAG,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IAClC,SAAS,CAAC,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC,CAAC;IACpC,SAAS,CAAC,GAAG,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,QAAQ,CAAC,CAAC;IACtC,SAAS,CAAC,UAAU,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;CAC/C"}

17
node_modules/@anthropic-ai/sdk/resource.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
"use strict";
// File generated from our OpenAPI spec by Stainless.
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIResource = void 0;
class APIResource {
constructor(client) {
this.client = client;
this.get = client.get.bind(client);
this.post = client.post.bind(client);
this.patch = client.patch.bind(client);
this.put = client.put.bind(client);
this.delete = client.delete.bind(client);
this.getAPIList = client.getAPIList.bind(client);
}
}
exports.APIResource = APIResource;
//# sourceMappingURL=resource.js.map

1
node_modules/@anthropic-ai/sdk/resource.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"resource.js","sourceRoot":"","sources":["src/resource.ts"],"names":[],"mappings":";AAAA,qDAAqD;;;AAIrD,MAAa,WAAW;IAEtB,YAAY,MAAiB;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACvC,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzC,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACnD,CAAC;CAQF;AAnBD,kCAmBC"}

13
node_modules/@anthropic-ai/sdk/resource.mjs generated vendored Normal file
View File

@@ -0,0 +1,13 @@
// File generated from our OpenAPI spec by Stainless.
export class APIResource {
constructor(client) {
this.client = client;
this.get = client.get.bind(client);
this.post = client.post.bind(client);
this.patch = client.patch.bind(client);
this.put = client.put.bind(client);
this.delete = client.delete.bind(client);
this.getAPIList = client.getAPIList.bind(client);
}
}
//# sourceMappingURL=resource.mjs.map

1
node_modules/@anthropic-ai/sdk/resource.mjs.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"resource.mjs","sourceRoot":"","sources":["src/resource.ts"],"names":[],"mappings":"AAAA,qDAAqD;AAIrD,MAAM,OAAO,WAAW;IAEtB,YAAY,MAAiB;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACvC,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzC,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACnD,CAAC;CAQF"}

View File

@@ -0,0 +1,156 @@
import * as Core from '@anthropic-ai/sdk/core';
import { APIPromise } from '@anthropic-ai/sdk/core';
import { APIResource } from '@anthropic-ai/sdk/resource';
import * as CompletionsAPI from '@anthropic-ai/sdk/resources/completions';
import { Stream } from '@anthropic-ai/sdk/streaming';
export declare class Completions extends APIResource {
/**
* Create a completion
*/
create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(body: CompletionCreateParamsStreaming, options?: Core.RequestOptions): APIPromise<Stream<Completion>>;
create(body: CompletionCreateParamsBase, options?: Core.RequestOptions): APIPromise<Stream<Completion> | Completion>;
}
export interface Completion {
/**
* The resulting completion up to and excluding the stop sequences.
*/
completion: string;
/**
* The model that performed the completion.
*/
model: string;
/**
* The reason that we stopped sampling.
*
* This may be one the following values:
*
* - `"stop_sequence"`: we reached a stop sequence — either provided by you via the
* `stop_sequences` parameter, or a stop sequence built into the model
* - `"max_tokens"`: we exceeded `max_tokens_to_sample` or the model's maximum
*/
stop_reason: string;
}
export type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming;
export interface CompletionCreateParamsBase {
/**
* The maximum number of tokens to generate before stopping.
*
* Note that our models may stop _before_ reaching this maximum. This parameter
* only specifies the absolute maximum number of tokens to generate.
*/
max_tokens_to_sample: number;
/**
* The model that will complete your prompt.
*
* As we improve Claude, we develop new versions of it that you can query. This
* parameter controls which version of Claude answers your request. Right now we
* are offering two model families: Claude, and Claude Instant. You can use them by
* setting `model` to `"claude-2"` or `"claude-instant-1"`, respectively. See
* [models](https://docs.anthropic.com/claude/reference/selecting-a-model) for
* additional details.
*/
model: (string & {}) | 'claude-2' | 'claude-instant-1';
/**
* The prompt that you want Claude to complete.
*
* For proper response generation you will need to format your prompt as follows:
*
* ```javascript
* const userQuestion = r"Why is the sky blue?";
* const prompt = `\n\nHuman: ${userQuestion}\n\nAssistant:`;
* ```
*
* See our
* [comments on prompts](https://docs.anthropic.com/claude/docs/introduction-to-prompt-design)
* for more context.
*/
prompt: string;
/**
* An object describing metadata about the request.
*/
metadata?: CompletionCreateParams.Metadata;
/**
* Sequences that will cause the model to stop generating completion text.
*
* Our models stop on `"\n\nHuman:"`, and may include additional built-in stop
* sequences in the future. By providing the stop_sequences parameter, you may
* include additional strings that will cause the model to stop generating.
*/
stop_sequences?: Array<string>;
/**
* Whether to incrementally stream the response using server-sent events.
*
* See
* [this guide to SSE events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)
* for details.
*/
stream?: boolean;
/**
* Amount of randomness injected into the response.
*
* Defaults to 1. Ranges from 0 to 1. Use temp closer to 0 for analytical /
* multiple choice, and closer to 1 for creative and generative tasks.
*/
temperature?: number;
/**
* Only sample from the top K options for each subsequent token.
*
* Used to remove "long tail" low probability responses.
* [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
*/
top_k?: number;
/**
* Use nucleus sampling.
*
* In nucleus sampling, we compute the cumulative distribution over all the options
* for each subsequent token in decreasing probability order and cut it off once it
* reaches a particular probability specified by `top_p`. You should either alter
* `temperature` or `top_p`, but not both.
*/
top_p?: number;
}
export declare namespace CompletionCreateParams {
/**
* An object describing metadata about the request.
*/
interface Metadata {
/**
* An external identifier for the user who is associated with the request.
*
* This should be a uuid, hash value, or other opaque identifier. Anthropic may use
* this id to help detect abuse. Do not include any identifying information such as
* name, email address, or phone number.
*/
user_id?: string;
}
type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming;
type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming;
}
export interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {
/**
* Whether to incrementally stream the response using server-sent events.
*
* See
* [this guide to SSE events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)
* for details.
*/
stream?: false;
}
export interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {
/**
* Whether to incrementally stream the response using server-sent events.
*
* See
* [this guide to SSE events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)
* for details.
*/
stream: true;
}
export declare namespace Completions {
export import Completion = CompletionsAPI.Completion;
export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams;
export import CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming;
export import CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming;
}
//# sourceMappingURL=completions.d.ts.map

Some files were not shown because too many files have changed in this diff Show More