mirror of
https://github.com/Onewon/claude-code.git
synced 2026-04-25 22:31:15 +03:00
Add all the original files from the deleted 0.2.8 npm package
This commit is contained in:
3
LICENSE.md
Normal file
3
LICENSE.md
Normal file
@@ -0,0 +1,3 @@
|
||||
Claude Code is a Beta research preview per our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms). If Customer chooses to send us feedback about Claude Code, such as transcripts of Customer Claude Code usage, Anthropic may use that feedback to debug related issues or to improve Claude Code’s functionality (e.g., to reduce the risk of similar bugs occurring in the future). Anthropic will not train models using feedback from Claude Code.
|
||||
|
||||
© Anthropic PBC. All rights reserved. Use is subject to Anthropic's [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms).
|
||||
55
README.md
55
README.md
@@ -1,4 +1,55 @@
|
||||
# claude-code
|
||||
# Claude Code (Research Preview)
|
||||
|
||||
Extracted from the source maps of the @anthropic-ai/claude-code package
|
||||

|
||||
|
||||
Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.
|
||||
|
||||
Some of its key capabilities include:
|
||||
|
||||
- Edit files and fix bugs across your codebase
|
||||
- Answer questions about your code's architecture and logic
|
||||
- Execute and fix tests, lint, and other commands
|
||||
- Search through git history, resolve merge conflicts, and create commits and PRs
|
||||
|
||||
**Learn more in the [official documentation](https://docs.anthropic.com/en/docs/agents/claude-code/introduction)**.
|
||||
|
||||
## Get started
|
||||
|
||||
<ol>
|
||||
<li>
|
||||
Run the following command in your terminal: <br />
|
||||
<code>npm install -g @anthropic-ai/claude-code</code>
|
||||
</li>
|
||||
<li>
|
||||
Navigate to your project directory and run <code>claude</code>
|
||||
</li>
|
||||
<li>
|
||||
Complete the one-time OAuth process with your Anthropic Console account.
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
### Research Preview
|
||||
|
||||
We're launching Claude Code as a beta product in research preview to learn directly from developers about their experiences collaborating with AI agents. Our aim is to learn more about how developers prefer to collaborate with AI tools, which development workflows benefit most from working with the agent, and how we can make the agent experience more intuitive.
|
||||
|
||||
This is an early version of the product experience, and it's likely to evolve as we learn more about developer preferences. Claude Code is an early look into what's possible with agentic coding, and we know there are areas to improve. We plan to enhance tool execution reliability, support for long-running commands, terminal rendering, and Claude's self-knowledge of its capabilities -- as well as many other product experiences -- over the coming weeks.
|
||||
|
||||
### Reporting Bugs
|
||||
|
||||
We welcome feedback during this beta period. Use the `/bug` command to report issues directly within Claude Code, or file a [GitHub issue](https://github.com/anthropics/claude-code/issues).
|
||||
|
||||
### Data collection, usage, and retention
|
||||
|
||||
When you use Claude Code, we collect feedback, which includes usage data (such as code acceptance or rejections), associated conversation data, and user feedback submitted via the `/bug` command.
|
||||
|
||||
#### How we use your data
|
||||
|
||||
We may use feedback to improve our products and services, but we will not train generative models using your feedback from Claude Code. Given their potentially sensitive nature, we store user feedback transcripts for only 30 days.
|
||||
|
||||
If you choose to send us feedback about Claude Code, such as transcripts of your usage, Anthropic may use that feedback to debug related issues and improve Claude Code's functionality (e.g., to reduce the risk of similar bugs occurring in the future).
|
||||
|
||||
### Privacy safeguards
|
||||
|
||||
We have implemented several safeguards to protect your data, including limited retention periods for sensitive information, restricted access to user session data, and clear policies against using feedback for model training.
|
||||
|
||||
For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) and [Privacy Policy](https://www.anthropic.com/legal/privacy).
|
||||
|
||||
3
vendor/ripgrep/COPYING
vendored
Normal file
3
vendor/ripgrep/COPYING
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
This project is dual-licensed under the Unlicense and MIT licenses.
|
||||
|
||||
You may use this code under the terms of either license.
|
||||
BIN
vendor/ripgrep/arm64-darwin/rg
vendored
Executable file
BIN
vendor/ripgrep/arm64-darwin/rg
vendored
Executable file
Binary file not shown.
BIN
vendor/ripgrep/arm64-linux/rg
vendored
Executable file
BIN
vendor/ripgrep/arm64-linux/rg
vendored
Executable file
Binary file not shown.
BIN
vendor/ripgrep/x64-darwin/rg
vendored
Executable file
BIN
vendor/ripgrep/x64-darwin/rg
vendored
Executable file
Binary file not shown.
BIN
vendor/ripgrep/x64-linux/rg
vendored
Executable file
BIN
vendor/ripgrep/x64-linux/rg
vendored
Executable file
Binary file not shown.
BIN
vendor/ripgrep/x64-win32/rg.exe
vendored
Normal file
BIN
vendor/ripgrep/x64-win32/rg.exe
vendored
Normal file
Binary file not shown.
1421
vendor/sdk/CHANGELOG.md
vendored
Normal file
1421
vendor/sdk/CHANGELOG.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
8
vendor/sdk/LICENSE
vendored
Normal file
8
vendor/sdk/LICENSE
vendored
Normal 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.
|
||||
|
||||
536
vendor/sdk/README.md
vendored
Normal file
536
vendor/sdk/README.md
vendored
Normal file
@@ -0,0 +1,536 @@
|
||||
> [!IMPORTANT]
|
||||
> We're actively working on a new alpha version that migrates from `node-fetch` to builtin fetch.
|
||||
>
|
||||
> Please try it out and let us know if you run into any issues!
|
||||
> https://github.com/anthropics/anthropic-sdk-typescript/issues/645
|
||||
|
||||
# Anthropic TypeScript API Library
|
||||
|
||||
[](https://npmjs.org/package/@anthropic-ai/sdk) 
|
||||
|
||||
This library provides convenient access to the Anthropic REST API from server-side TypeScript or JavaScript.
|
||||
|
||||
The REST API documentation can be found on [docs.anthropic.com](https://docs.anthropic.com/claude/reference/). The full API of this library can be found in [api.md](api.md).
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
npm install @anthropic-ai/sdk
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The full API of this library can be found in [api.md](api.md).
|
||||
|
||||
<!-- prettier-ignore -->
|
||||
```js
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
|
||||
const client = new Anthropic({
|
||||
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const message = await client.messages.create({
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
});
|
||||
|
||||
console.log(message.content);
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
## Streaming responses
|
||||
|
||||
We provide support for streaming responses using Server Sent Events (SSE).
|
||||
|
||||
```ts
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
|
||||
const client = new Anthropic();
|
||||
|
||||
const stream = await client.messages.create({
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
stream: true,
|
||||
});
|
||||
for await (const messageStreamEvent of stream) {
|
||||
console.log(messageStreamEvent.type);
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
<!-- prettier-ignore -->
|
||||
```ts
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
|
||||
const client = new Anthropic({
|
||||
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const params: Anthropic.MessageCreateParams = {
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
};
|
||||
const message: Anthropic.Message = await client.messages.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
|
||||
|
||||
You can see the exact usage for a given request through the `usage` response property, e.g.
|
||||
|
||||
```ts
|
||||
const message = await client.messages.create(...)
|
||||
console.log(message.usage)
|
||||
// { input_tokens: 25, output_tokens: 13 }
|
||||
```
|
||||
|
||||
## Streaming Helpers
|
||||
|
||||
This library provides several conveniences for streaming messages, for example:
|
||||
|
||||
```ts
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
|
||||
const anthropic = new Anthropic();
|
||||
|
||||
async function main() {
|
||||
const stream = anthropic.messages
|
||||
.stream({
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
max_tokens: 1024,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: 'Say hello there!',
|
||||
},
|
||||
],
|
||||
})
|
||||
.on('text', (text) => {
|
||||
console.log(text);
|
||||
});
|
||||
|
||||
const message = await stream.finalMessage();
|
||||
console.log(message);
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
Streaming with `client.messages.stream(...)` exposes [various helpers for your convenience](helpers.md) including event handlers and accumulation.
|
||||
|
||||
Alternatively, you can use `client.messages.create({ ..., stream: true })` which only returns an async iterable of the events in the stream and thus uses less memory (it does not build up a final message object for you).
|
||||
|
||||
## Message Batches
|
||||
|
||||
This SDK provides beta support for the [Message Batches API](https://docs.anthropic.com/en/docs/build-with-claude/message-batches) under the `client.beta.messages.batches` namespace.
|
||||
|
||||
### Creating a batch
|
||||
|
||||
Message Batches takes an array of requests, where each object has a `custom_id` identifier, and the exact same request `params` as the standard Messages API:
|
||||
|
||||
```ts
|
||||
await anthropic.beta.messages.batches.create({
|
||||
requests: [
|
||||
{
|
||||
custom_id: 'my-first-request',
|
||||
params: {
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, world' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
custom_id: 'my-second-request',
|
||||
params: {
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hi again, friend' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
### Getting results from a batch
|
||||
|
||||
Once a Message Batch has been processed, indicated by `.processing_status === 'ended'`, you can access the results with `.batches.results()`
|
||||
|
||||
```ts
|
||||
const results = await anthropic.beta.messages.batches.results(batch_id);
|
||||
for await (const entry of results) {
|
||||
if (entry.result.type === 'succeeded') {
|
||||
console.log(entry.result.message.content)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Tool use beta
|
||||
|
||||
This SDK provides beta support for tool use, aka function calling. More details can be found in [the documentation](https://docs.anthropic.com/claude/docs/tool-use).
|
||||
|
||||
## AWS Bedrock
|
||||
|
||||
We provide support for the [Anthropic Bedrock API](https://aws.amazon.com/bedrock/claude/) through a [separate package](https://github.com/anthropics/anthropic-sdk-typescript/tree/main/packages/bedrock-sdk).
|
||||
|
||||
## 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:
|
||||
|
||||
<!-- prettier-ignore -->
|
||||
```ts
|
||||
async function main() {
|
||||
const message = await client.messages
|
||||
.create({
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
})
|
||||
.catch(async (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` |
|
||||
|
||||
## Request IDs
|
||||
|
||||
> For more information on debugging requests, see [these docs](https://docs.anthropic.com/en/api/errors#request-id)
|
||||
|
||||
All object responses in the SDK provide a `_request_id` property which is added from the `request-id` response header so that you can quickly log failing requests and report them back to Anthropic.
|
||||
|
||||
```ts
|
||||
const message = await client.messages.create({ max_tokens: 1024, messages: [{ role: 'user', content: 'Hello, Claude' }], model: 'claude-3-5-sonnet-latest' });
|
||||
console.log(message._request_id) // req_018EeWyXxfu5pfWkrYcMdjWG
|
||||
```
|
||||
|
||||
|
||||
### 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 client = new Anthropic({
|
||||
maxRetries: 0, // default is 2
|
||||
});
|
||||
|
||||
// Or, configure per-request:
|
||||
await client.messages.create({ max_tokens: 1024, messages: [{ role: 'user', content: 'Hello, Claude' }], model: 'claude-3-5-sonnet-latest' }, {
|
||||
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 client = new Anthropic({
|
||||
timeout: 20 * 1000, // 20 seconds (default is 10 minutes)
|
||||
});
|
||||
|
||||
// Override per-request:
|
||||
await client.messages.create({ max_tokens: 1024, messages: [{ role: 'user', content: 'Hello, Claude' }], model: 'claude-3-5-sonnet-latest' }, {
|
||||
timeout: 5 * 1000,
|
||||
});
|
||||
```
|
||||
|
||||
On timeout, an `APIConnectionTimeoutError` is thrown.
|
||||
|
||||
Note that requests which time out will be [retried twice by default](#retries).
|
||||
|
||||
## Auto-pagination
|
||||
|
||||
List methods in the Anthropic API are paginated.
|
||||
You can use the `for await … of` syntax to iterate through items across all pages:
|
||||
|
||||
```ts
|
||||
async function fetchAllBetaMessagesBatches(params) {
|
||||
const allBetaMessagesBatches = [];
|
||||
// Automatically fetches more pages as needed.
|
||||
for await (const betaMessageBatch of client.beta.messages.batches.list({ limit: 20 })) {
|
||||
allBetaMessagesBatches.push(betaMessageBatch);
|
||||
}
|
||||
return allBetaMessagesBatches;
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, you can request a single page at a time:
|
||||
|
||||
```ts
|
||||
let page = await client.beta.messages.batches.list({ limit: 20 });
|
||||
for (const betaMessageBatch of page.data) {
|
||||
console.log(betaMessageBatch);
|
||||
}
|
||||
|
||||
// Convenience methods are provided for manually paginating:
|
||||
while (page.hasNextPage()) {
|
||||
page = await page.getNextPage();
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Default Headers
|
||||
|
||||
We automatically send the `anthropic-version` header set to `2023-06-01`.
|
||||
|
||||
If you need to, you can override it by setting default headers on a per-request basis.
|
||||
|
||||
Be aware that doing so may result in incorrect types and other unexpected or undefined behavior in the SDK.
|
||||
|
||||
```ts
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
|
||||
const client = new Anthropic();
|
||||
|
||||
const message = await client.messages.create(
|
||||
{
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
},
|
||||
{ headers: { 'anthropic-version': 'My-Custom-Value' } },
|
||||
);
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
<!-- prettier-ignore -->
|
||||
```ts
|
||||
const client = new Anthropic();
|
||||
|
||||
const response = await client.messages
|
||||
.create({
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
})
|
||||
.asResponse();
|
||||
console.log(response.headers.get('X-My-Header'));
|
||||
console.log(response.statusText); // access the underlying Response object
|
||||
|
||||
const { data: message, response: raw } = await client.messages
|
||||
.create({
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
})
|
||||
.withResponse();
|
||||
console.log(raw.headers.get('X-My-Header'));
|
||||
console.log(message.content);
|
||||
```
|
||||
|
||||
### Making custom/undocumented requests
|
||||
|
||||
This library is typed for convenient access to the documented API. If you need to access undocumented
|
||||
endpoints, params, or response properties, the library can still be used.
|
||||
|
||||
#### Undocumented endpoints
|
||||
|
||||
To make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs.
|
||||
Options on the client, such as retries, will be respected when making these requests.
|
||||
|
||||
```ts
|
||||
await client.post('/some/path', {
|
||||
body: { some_prop: 'foo' },
|
||||
query: { some_query_arg: 'bar' },
|
||||
});
|
||||
```
|
||||
|
||||
#### Undocumented request params
|
||||
|
||||
To make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented
|
||||
parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you
|
||||
send will be sent as-is.
|
||||
|
||||
```ts
|
||||
client.foo.create({
|
||||
foo: 'my_param',
|
||||
bar: 12,
|
||||
// @ts-expect-error baz is not yet public
|
||||
baz: 'undocumented option',
|
||||
});
|
||||
```
|
||||
|
||||
For requests with the `GET` verb, any extra params will be in the query, all other requests will send the
|
||||
extra param in the body.
|
||||
|
||||
If you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request
|
||||
options.
|
||||
|
||||
#### Undocumented response properties
|
||||
|
||||
To access undocumented response properties, you may access the response object with `// @ts-expect-error` on
|
||||
the response object, or cast the response object to the requisite type. Like the request params, we do not
|
||||
validate or strip extra properties from the response from the API.
|
||||
|
||||
### Customizing the fetch client
|
||||
|
||||
By default, this library uses `node-fetch` in Node, and expects a global `fetch` function in other environments.
|
||||
|
||||
If you would prefer to use a global, web-standards-compliant `fetch` function even in a Node environment,
|
||||
(for example, if you are running Node with `--experimental-fetch` or using NextJS which polyfills with `undici`),
|
||||
add the following import before your first import `from "Anthropic"`:
|
||||
|
||||
```ts
|
||||
// Tell TypeScript and the package to use the global web fetch instead of node-fetch.
|
||||
// Note, despite the name, this does not add any polyfills, but expects them to be provided if needed.
|
||||
import '@anthropic-ai/sdk/shims/web';
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
```
|
||||
|
||||
To do the inverse, add `import "@anthropic-ai/sdk/shims/node"` (which does import polyfills).
|
||||
This can also be useful if you are getting the wrong TypeScript types for `Response` ([more details](https://github.com/anthropics/anthropic-sdk-typescript/tree/main/src/_shims#readme)).
|
||||
|
||||
### Logging and middleware
|
||||
|
||||
You may also provide a custom `fetch` function when instantiating the client,
|
||||
which can be used to inspect or alter the `Request` or `Response` before/after each request:
|
||||
|
||||
```ts
|
||||
import { fetch } from 'undici'; // as one example
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
|
||||
const client = new Anthropic({
|
||||
fetch: async (url: RequestInfo, init?: RequestInit): Promise<Response> => {
|
||||
console.log('About to make a request', url, init);
|
||||
const response = await fetch(url, init);
|
||||
console.log('Got response', response);
|
||||
return response;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Note that if given a `DEBUG=true` environment variable, this library will log all requests and responses automatically.
|
||||
This is intended for debugging purposes only and may change in the future without notice.
|
||||
|
||||
### 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 { HttpsProxyAgent } from 'https-proxy-agent';
|
||||
|
||||
// Configure the default for all requests:
|
||||
const client = new Anthropic({
|
||||
httpAgent: new HttpsProxyAgent(process.env.PROXY_URL),
|
||||
});
|
||||
|
||||
// Override per-request:
|
||||
await client.messages.create(
|
||||
{
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: 'Hello, Claude' }],
|
||||
model: 'claude-3-5-sonnet-latest',
|
||||
},
|
||||
{
|
||||
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.
|
||||
- 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.
|
||||
- Web browsers: disabled by default to avoid exposing your secret API credentials (see our help center for [best practices](https://support.anthropic.com/en/articles/9767949-api-key-best-practices-keeping-your-keys-safe-and-secure)). Enable browser support by explicitly setting `dangerouslyAllowBrowser` to `true`.
|
||||
|
||||
<details>
|
||||
<summary><b>More explanation</b></summary>
|
||||
<h3>Why is this dangerous?</h3>
|
||||
Enabling the <code>dangerouslyAllowBrowser</code> option can be dangerous because it exposes your secret API credentials in the client-side code. Web browsers are inherently less secure than server environments,
|
||||
any user with access to the browser can potentially inspect, extract, and misuse these credentials. This could lead to unauthorized access using your credentials and potentially compromise sensitive data or functionality.
|
||||
<h3>When might this not be dangerous?</h3>
|
||||
In certain scenarios where enabling browser support might not pose significant risks:
|
||||
<ul>
|
||||
<li>Internal Tools: If the application is used solely within a controlled internal environment where the users are trusted, the risk of credential exposure can be mitigated.</li>
|
||||
<li>Development or debugging purpose: Enabling this feature temporarily might be acceptable, provided the credentials are short-lived, aren't also used in production environments, or are frequently rotated.</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
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.
|
||||
|
||||
## Contributing
|
||||
|
||||
See [the contributing documentation](./CONTRIBUTING.md).
|
||||
9
vendor/sdk/_shims/MultipartBody.d.ts
vendored
Normal file
9
vendor/sdk/_shims/MultipartBody.d.ts
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/MultipartBody.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/MultipartBody.d.ts.map
vendored
Normal 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
vendor/sdk/_shims/MultipartBody.js
vendored
Normal file
16
vendor/sdk/_shims/MultipartBody.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/MultipartBody.js.map
vendored
Normal file
1
vendor/sdk/_shims/MultipartBody.js.map
vendored
Normal 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"}
|
||||
12
vendor/sdk/_shims/MultipartBody.mjs
vendored
Normal file
12
vendor/sdk/_shims/MultipartBody.mjs
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/MultipartBody.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/MultipartBody.mjs.map
vendored
Normal 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
vendor/sdk/_shims/README.md
vendored
Normal file
46
vendor/sdk/_shims/README.md
vendored
Normal 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"`.
|
||||
5
vendor/sdk/_shims/auto/runtime-bun.d.ts
vendored
Normal file
5
vendor/sdk/_shims/auto/runtime-bun.d.ts
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/runtime-bun.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime-bun.d.ts.map
vendored
Normal 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"}
|
||||
21
vendor/sdk/_shims/auto/runtime-bun.js
vendored
Normal file
21
vendor/sdk/_shims/auto/runtime-bun.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/runtime-bun.js.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime-bun.js.map
vendored
Normal 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"}
|
||||
2
vendor/sdk/_shims/auto/runtime-bun.mjs
vendored
Normal file
2
vendor/sdk/_shims/auto/runtime-bun.mjs
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "../bun-runtime.mjs";
|
||||
//# sourceMappingURL=runtime-bun.mjs.map
|
||||
1
vendor/sdk/_shims/auto/runtime-bun.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime-bun.mjs.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"runtime-bun.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":""}
|
||||
5
vendor/sdk/_shims/auto/runtime-node.d.ts
vendored
Normal file
5
vendor/sdk/_shims/auto/runtime-node.d.ts
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/runtime-node.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime-node.d.ts.map
vendored
Normal 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"}
|
||||
21
vendor/sdk/_shims/auto/runtime-node.js
vendored
Normal file
21
vendor/sdk/_shims/auto/runtime-node.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/runtime-node.js.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime-node.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"runtime-node.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,qDAAgC"}
|
||||
2
vendor/sdk/_shims/auto/runtime-node.mjs
vendored
Normal file
2
vendor/sdk/_shims/auto/runtime-node.mjs
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "../node-runtime.mjs";
|
||||
//# sourceMappingURL=runtime-node.mjs.map
|
||||
1
vendor/sdk/_shims/auto/runtime-node.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime-node.mjs.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"runtime-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":""}
|
||||
5
vendor/sdk/_shims/auto/runtime.d.ts
vendored
Normal file
5
vendor/sdk/_shims/auto/runtime.d.ts
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/runtime.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime.d.ts.map
vendored
Normal 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
vendor/sdk/_shims/auto/runtime.js
vendored
Normal file
21
vendor/sdk/_shims/auto/runtime.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/runtime.js.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,oDAA+B"}
|
||||
2
vendor/sdk/_shims/auto/runtime.mjs
vendored
Normal file
2
vendor/sdk/_shims/auto/runtime.mjs
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "../web-runtime.mjs";
|
||||
//# sourceMappingURL=runtime.mjs.map
|
||||
1
vendor/sdk/_shims/auto/runtime.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/auto/runtime.mjs.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"runtime.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":""}
|
||||
5
vendor/sdk/_shims/auto/types-node.d.ts
vendored
Normal file
5
vendor/sdk/_shims/auto/types-node.d.ts
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/types-node.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/auto/types-node.d.ts.map
vendored
Normal 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"}
|
||||
21
vendor/sdk/_shims/auto/types-node.js
vendored
Normal file
21
vendor/sdk/_shims/auto/types-node.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/auto/types-node.js.map
vendored
Normal file
1
vendor/sdk/_shims/auto/types-node.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"types-node.js","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,mDAA8B"}
|
||||
2
vendor/sdk/_shims/auto/types-node.mjs
vendored
Normal file
2
vendor/sdk/_shims/auto/types-node.mjs
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "../node-types.mjs";
|
||||
//# sourceMappingURL=types-node.mjs.map
|
||||
1
vendor/sdk/_shims/auto/types-node.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/auto/types-node.mjs.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"types-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":""}
|
||||
101
vendor/sdk/_shims/auto/types.d.ts
vendored
Normal file
101
vendor/sdk/_shims/auto/types.d.ts
vendored
Normal 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
vendor/sdk/_shims/auto/types.js
vendored
Normal file
3
vendor/sdk/_shims/auto/types.js
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
3
vendor/sdk/_shims/auto/types.mjs
vendored
Normal file
3
vendor/sdk/_shims/auto/types.mjs
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
6
vendor/sdk/_shims/bun-runtime.d.ts
vendored
Normal file
6
vendor/sdk/_shims/bun-runtime.d.ts
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/bun-runtime.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/bun-runtime.d.ts.map
vendored
Normal 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
vendor/sdk/_shims/bun-runtime.js
vendored
Normal file
14
vendor/sdk/_shims/bun-runtime.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/bun-runtime.js.map
vendored
Normal file
1
vendor/sdk/_shims/bun-runtime.js.map
vendored
Normal 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
vendor/sdk/_shims/bun-runtime.mjs
vendored
Normal file
10
vendor/sdk/_shims/bun-runtime.mjs
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/bun-runtime.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/bun-runtime.mjs.map
vendored
Normal 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
vendor/sdk/_shims/index.d.ts
vendored
Normal file
81
vendor/sdk/_shims/index.d.ts
vendored
Normal 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 = 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
vendor/sdk/_shims/index.js
vendored
Normal file
13
vendor/sdk/_shims/index.js
vendored
Normal 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
vendor/sdk/_shims/index.mjs
vendored
Normal file
7
vendor/sdk/_shims/index.mjs
vendored
Normal 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';
|
||||
12
vendor/sdk/_shims/manual-types.d.ts
vendored
Normal file
12
vendor/sdk/_shims/manual-types.d.ts
vendored
Normal 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 {}
|
||||
3
vendor/sdk/_shims/manual-types.js
vendored
Normal file
3
vendor/sdk/_shims/manual-types.js
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
3
vendor/sdk/_shims/manual-types.mjs
vendored
Normal file
3
vendor/sdk/_shims/manual-types.mjs
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
3
vendor/sdk/_shims/node-runtime.d.ts
vendored
Normal file
3
vendor/sdk/_shims/node-runtime.d.ts
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import { type Shims } from "./registry.js";
|
||||
export declare function getRuntime(): Shims;
|
||||
//# sourceMappingURL=node-runtime.d.ts.map
|
||||
1
vendor/sdk/_shims/node-runtime.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/node-runtime.d.ts.map
vendored
Normal 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;AA6CxC,wBAAgB,UAAU,IAAI,KAAK,CAqBlC"}
|
||||
89
vendor/sdk/_shims/node-runtime.js
vendored
Normal file
89
vendor/sdk/_shims/node-runtime.js
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
"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");
|
||||
const web_1 = require("node:stream/web");
|
||||
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: web_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
|
||||
1
vendor/sdk/_shims/node-runtime.js.map
vendored
Normal file
1
vendor/sdk/_shims/node-runtime.js.map
vendored
Normal 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;AAEhD,yCAAiD;AAIjD,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;QACrG,kBAAkB,GAAG,IAAI,CAAC;KAC3B;IACD,aAAa;IACb,OAAO,MAAM,aAAa,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,gBAAgB,GAAU,IAAI,wBAAc,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAChG,MAAM,iBAAiB,GAAU,IAAI,wBAAc,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAE5G,KAAK,UAAU,0BAA0B,CACvC,IAAiB,EACjB,IAAuB;IAEvB,MAAM,OAAO,GAAG,IAAI,mCAAe,CAAC,IAAI,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG,sBAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxC,MAAM,IAAI,GAAG,IAAI,6BAAa,CAAC,QAAQ,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,CAAC,OAAO;QACf,GAAG,OAAO,CAAC,OAAO;QAClB,gBAAgB,EAAE,OAAO,CAAC,aAAa;KACxC,CAAC;IAEF,OAAO,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,IAAW,EAAE,OAAO,EAAE,CAAC;AACjD,CAAC;AAED,SAAgB,UAAU;IACxB,oCAAoC;IACpC,IAAI,OAAO,eAAe,KAAK,WAAW,EAAE;QAC1C,gFAAgF;QAChF,UAAU,CAAC,eAAe,GAAG,kCAAuB,CAAC;KACtD;IACD,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,EAAE,CAAC,OAAO;QACjB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,cAAc,EAAd,oBAAc;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
vendor/sdk/_shims/node-runtime.mjs
vendored
Normal file
56
vendor/sdk/_shims/node-runtime.mjs
vendored
Normal 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 'node:stream/web';
|
||||
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
|
||||
1
vendor/sdk/_shims/node-runtime.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/node-runtime.mjs.map
vendored
Normal 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;OAEjB,EAAE,cAAc,EAAE,MAAM,iBAAiB;AAIhD,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;AAC5C,CAAC;AAED,MAAM,gBAAgB,GAAU,IAAI,cAAc,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAChG,MAAM,iBAAiB,GAAU,IAAI,cAAc,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAE5G,KAAK,UAAU,0BAA0B,CACvC,IAAiB,EACjB,IAAuB;IAEvB,MAAM,OAAO,GAAG,IAAI,eAAe,CAAC,IAAI,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxC,MAAM,IAAI,GAAG,IAAI,aAAa,CAAC,QAAQ,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,CAAC,OAAO;QACf,GAAG,OAAO,CAAC,OAAO;QAClB,gBAAgB,EAAE,OAAO,CAAC,aAAa;KACxC,CAAC;IAEF,OAAO,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,IAAW,EAAE,OAAO,EAAE,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,UAAU;IACxB,oCAAoC;IACpC,IAAI,OAAO,eAAe,KAAK,WAAW,EAAE;QAC1C,gFAAgF;QAChF,UAAU,CAAC,eAAe,GAAG,uBAAuB,CAAC;KACtD;IACD,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,EAAE,CAAC,OAAO;QACjB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,cAAc;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,YAAY;KACrF,CAAC;AACJ,CAAC"}
|
||||
42
vendor/sdk/_shims/node-types.d.ts
vendored
Normal file
42
vendor/sdk/_shims/node-types.d.ts
vendored
Normal 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 'node:stream/web';
|
||||
|
||||
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
vendor/sdk/_shims/node-types.js
vendored
Normal file
3
vendor/sdk/_shims/node-types.js
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
3
vendor/sdk/_shims/node-types.mjs
vendored
Normal file
3
vendor/sdk/_shims/node-types.mjs
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
37
vendor/sdk/_shims/registry.d.ts
vendored
Normal file
37
vendor/sdk/_shims/registry.d.ts
vendored
Normal 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 = 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
|
||||
1
vendor/sdk/_shims/registry.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/registry.d.ts.map
vendored
Normal 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,CAAC;IACV,IAAI,EAAE,GAAG,CAAC;IACV,cAAc,EAAE,GAAG,CAAC;IACpB,0BAA0B,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACtD,IAAI,EAAE,KAAK,CAAC,UAAU,CAAC,EACvB,IAAI,EAAE,cAAc,CAAC,CAAC,CAAC,KACpB,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;IAChC,eAAe,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,GAAG,CAAC;IACtC,YAAY,EACR,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,GAC3E,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC7D,cAAc,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,OAAO,CAAC;CACzC;AAED,eAAO,IAAI,IAAI,SAAQ,CAAC;AACxB,eAAO,IAAI,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,SAAqB,CAAC;AACvD,eAAO,IAAI,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,SAAqB,CAAC;AACzD,eAAO,IAAI,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,GAAG,SAAqB,CAAC;AAC7D,eAAO,IAAI,QAAQ,EAAE,KAAK,CAAC,UAAU,CAAC,GAAG,SAAqB,CAAC;AAC/D,eAAO,IAAI,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,GAAG,SAAqB,CAAC;AAC7D,eAAO,IAAI,QAAQ,EAAE,KAAK,CAAC,UAAU,CAAC,GAAG,SAAqB,CAAC;AAC/D,eAAO,IAAI,IAAI,EAAE,KAAK,CAAC,MAAM,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
vendor/sdk/_shims/registry.js
vendored
Normal file
41
vendor/sdk/_shims/registry.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/registry.js.map
vendored
Normal file
1
vendor/sdk/_shims/registry.js.map
vendored
Normal 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
vendor/sdk/_shims/registry.mjs
vendored
Normal file
37
vendor/sdk/_shims/registry.mjs
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/registry.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/registry.mjs.map
vendored
Normal 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"}
|
||||
5
vendor/sdk/_shims/web-runtime.d.ts
vendored
Normal file
5
vendor/sdk/_shims/web-runtime.d.ts
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/web-runtime.d.ts.map
vendored
Normal file
1
vendor/sdk/_shims/web-runtime.d.ts.map
vendored
Normal 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
vendor/sdk/_shims/web-runtime.js
vendored
Normal file
78
vendor/sdk/_shims/web-runtime.js
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/web-runtime.js.map
vendored
Normal file
1
vendor/sdk/_shims/web-runtime.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"web-runtime.js","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,sDAAgD;AAIhD,SAAgB,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,GAAG,OAAO,CAAC;KACpB;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CACb,iEACG,KAAa,CAAC,OACjB,KAAK,cAAc,EAAE,CACtB,CAAC;KACH;IAED,OAAO;QACL,IAAI,EAAE,KAAK;QACX,KAAK,EAAE,MAAM;QACb,OAAO,EAAE,QAAQ;QACjB,QAAQ,EAAE,SAAS;QACnB,OAAO,EAAE,QAAQ;QACjB,QAAQ;QACN,aAAa;QACb,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAC3C,MAAM,QAAQ;YACZ,aAAa;YACb;gBACE,MAAM,IAAI,KAAK,CACb,qFAAqF,cAAc,EAAE,CACtG,CAAC;YACJ,CAAC;SACF,CACF;QACH,IAAI,EACF,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CACnC,MAAM,IAAI;YACR;gBACE,MAAM,IAAI,KAAK,CACb,iFAAiF,cAAc,EAAE,CAClG,CAAC;YACJ,CAAC;SACF,CACF;QACH,IAAI;QACF,aAAa;QACb,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,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
vendor/sdk/_shims/web-runtime.mjs
vendored
Normal file
71
vendor/sdk/_shims/web-runtime.mjs
vendored
Normal 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
|
||||
1
vendor/sdk/_shims/web-runtime.mjs.map
vendored
Normal file
1
vendor/sdk/_shims/web-runtime.mjs.map
vendored
Normal 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,GAAG,OAAO,CAAC;KACpB;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CACb,iEACG,KAAa,CAAC,OACjB,KAAK,cAAc,EAAE,CACtB,CAAC;KACH;IAED,OAAO;QACL,IAAI,EAAE,KAAK;QACX,KAAK,EAAE,MAAM;QACb,OAAO,EAAE,QAAQ;QACjB,QAAQ,EAAE,SAAS;QACnB,OAAO,EAAE,QAAQ;QACjB,QAAQ;QACN,aAAa;QACb,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAC3C,MAAM,QAAQ;YACZ,aAAa;YACb;gBACE,MAAM,IAAI,KAAK,CACb,qFAAqF,cAAc,EAAE,CACtG,CAAC;YACJ,CAAC;SACF,CACF;QACH,IAAI,EACF,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CACnC,MAAM,IAAI;YACR;gBACE,MAAM,IAAI,KAAK,CACb,iFAAiF,cAAc,EAAE,CAClG,CAAC;YACJ,CAAC;SACF,CACF;QACH,IAAI;QACF,aAAa;QACb,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,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,aAAa,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"}
|
||||
83
vendor/sdk/_shims/web-types.d.ts
vendored
Normal file
83
vendor/sdk/_shims/web-types.d.ts
vendored
Normal 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
vendor/sdk/_shims/web-types.js
vendored
Normal file
3
vendor/sdk/_shims/web-types.js
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
3
vendor/sdk/_shims/web-types.mjs
vendored
Normal file
3
vendor/sdk/_shims/web-types.mjs
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
||||
*/
|
||||
3
vendor/sdk/_vendor/partial-json-parser/parser.d.ts
vendored
Normal file
3
vendor/sdk/_vendor/partial-json-parser/parser.d.ts
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
declare const partialParse: (input: string) => unknown;
|
||||
export { partialParse };
|
||||
//# sourceMappingURL=parser.d.ts.map
|
||||
1
vendor/sdk/_vendor/partial-json-parser/parser.d.ts.map
vendored
Normal file
1
vendor/sdk/_vendor/partial-json-parser/parser.d.ts.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/_vendor/partial-json-parser/parser.ts"],"names":[],"mappings":"AAKA,QAAA,MAgQE,YAAY,UAAW,MAAM,KAAG,OAAgE,CAAC;AAEnG,OAAO,EAAE,YAAY,EAAE,CAAC"}
|
||||
226
vendor/sdk/_vendor/partial-json-parser/parser.js
vendored
Normal file
226
vendor/sdk/_vendor/partial-json-parser/parser.js
vendored
Normal file
@@ -0,0 +1,226 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.partialParse = void 0;
|
||||
const tokenize = (input) => {
|
||||
let current = 0;
|
||||
let tokens = [];
|
||||
while (current < input.length) {
|
||||
let char = input[current];
|
||||
if (char === '\\') {
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '{') {
|
||||
tokens.push({
|
||||
type: 'brace',
|
||||
value: '{',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '}') {
|
||||
tokens.push({
|
||||
type: 'brace',
|
||||
value: '}',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '[') {
|
||||
tokens.push({
|
||||
type: 'paren',
|
||||
value: '[',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === ']') {
|
||||
tokens.push({
|
||||
type: 'paren',
|
||||
value: ']',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === ':') {
|
||||
tokens.push({
|
||||
type: 'separator',
|
||||
value: ':',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === ',') {
|
||||
tokens.push({
|
||||
type: 'delimiter',
|
||||
value: ',',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '"') {
|
||||
let value = '';
|
||||
let danglingQuote = false;
|
||||
char = input[++current];
|
||||
while (char !== '"') {
|
||||
if (current === input.length) {
|
||||
danglingQuote = true;
|
||||
break;
|
||||
}
|
||||
if (char === '\\') {
|
||||
current++;
|
||||
if (current === input.length) {
|
||||
danglingQuote = true;
|
||||
break;
|
||||
}
|
||||
value += char + input[current];
|
||||
char = input[++current];
|
||||
}
|
||||
else {
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
}
|
||||
char = input[++current];
|
||||
if (!danglingQuote) {
|
||||
tokens.push({
|
||||
type: 'string',
|
||||
value,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let WHITESPACE = /\s/;
|
||||
if (char && WHITESPACE.test(char)) {
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
let NUMBERS = /[0-9]/;
|
||||
if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {
|
||||
let value = '';
|
||||
if (char === '-') {
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
while ((char && NUMBERS.test(char)) || char === '.') {
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
tokens.push({
|
||||
type: 'number',
|
||||
value,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let LETTERS = /[a-z]/i;
|
||||
if (char && LETTERS.test(char)) {
|
||||
let value = '';
|
||||
while (char && LETTERS.test(char)) {
|
||||
if (current === input.length) {
|
||||
break;
|
||||
}
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
if (value == 'true' || value == 'false' || value === 'null') {
|
||||
tokens.push({
|
||||
type: 'name',
|
||||
value,
|
||||
});
|
||||
}
|
||||
else {
|
||||
// unknown token, e.g. `nul` which isn't quite `null`
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
current++;
|
||||
}
|
||||
return tokens;
|
||||
}, strip = (tokens) => {
|
||||
if (tokens.length === 0) {
|
||||
return tokens;
|
||||
}
|
||||
let lastToken = tokens[tokens.length - 1];
|
||||
switch (lastToken.type) {
|
||||
case 'separator':
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
break;
|
||||
case 'number':
|
||||
let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
|
||||
if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
}
|
||||
case 'string':
|
||||
let tokenBeforeTheLastToken = tokens[tokens.length - 2];
|
||||
if (tokenBeforeTheLastToken?.type === 'delimiter') {
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
}
|
||||
else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
}
|
||||
break;
|
||||
case 'delimiter':
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
break;
|
||||
}
|
||||
return tokens;
|
||||
}, unstrip = (tokens) => {
|
||||
let tail = [];
|
||||
tokens.map((token) => {
|
||||
if (token.type === 'brace') {
|
||||
if (token.value === '{') {
|
||||
tail.push('}');
|
||||
}
|
||||
else {
|
||||
tail.splice(tail.lastIndexOf('}'), 1);
|
||||
}
|
||||
}
|
||||
if (token.type === 'paren') {
|
||||
if (token.value === '[') {
|
||||
tail.push(']');
|
||||
}
|
||||
else {
|
||||
tail.splice(tail.lastIndexOf(']'), 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (tail.length > 0) {
|
||||
tail.reverse().map((item) => {
|
||||
if (item === '}') {
|
||||
tokens.push({
|
||||
type: 'brace',
|
||||
value: '}',
|
||||
});
|
||||
}
|
||||
else if (item === ']') {
|
||||
tokens.push({
|
||||
type: 'paren',
|
||||
value: ']',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
return tokens;
|
||||
}, generate = (tokens) => {
|
||||
let output = '';
|
||||
tokens.map((token) => {
|
||||
switch (token.type) {
|
||||
case 'string':
|
||||
output += '"' + token.value + '"';
|
||||
break;
|
||||
default:
|
||||
output += token.value;
|
||||
break;
|
||||
}
|
||||
});
|
||||
return output;
|
||||
}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
|
||||
exports.partialParse = partialParse;
|
||||
//# sourceMappingURL=parser.js.map
|
||||
1
vendor/sdk/_vendor/partial-json-parser/parser.js.map
vendored
Normal file
1
vendor/sdk/_vendor/partial-json-parser/parser.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
223
vendor/sdk/_vendor/partial-json-parser/parser.mjs
vendored
Normal file
223
vendor/sdk/_vendor/partial-json-parser/parser.mjs
vendored
Normal file
@@ -0,0 +1,223 @@
|
||||
const tokenize = (input) => {
|
||||
let current = 0;
|
||||
let tokens = [];
|
||||
while (current < input.length) {
|
||||
let char = input[current];
|
||||
if (char === '\\') {
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '{') {
|
||||
tokens.push({
|
||||
type: 'brace',
|
||||
value: '{',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '}') {
|
||||
tokens.push({
|
||||
type: 'brace',
|
||||
value: '}',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '[') {
|
||||
tokens.push({
|
||||
type: 'paren',
|
||||
value: '[',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === ']') {
|
||||
tokens.push({
|
||||
type: 'paren',
|
||||
value: ']',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === ':') {
|
||||
tokens.push({
|
||||
type: 'separator',
|
||||
value: ':',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === ',') {
|
||||
tokens.push({
|
||||
type: 'delimiter',
|
||||
value: ',',
|
||||
});
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
if (char === '"') {
|
||||
let value = '';
|
||||
let danglingQuote = false;
|
||||
char = input[++current];
|
||||
while (char !== '"') {
|
||||
if (current === input.length) {
|
||||
danglingQuote = true;
|
||||
break;
|
||||
}
|
||||
if (char === '\\') {
|
||||
current++;
|
||||
if (current === input.length) {
|
||||
danglingQuote = true;
|
||||
break;
|
||||
}
|
||||
value += char + input[current];
|
||||
char = input[++current];
|
||||
}
|
||||
else {
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
}
|
||||
char = input[++current];
|
||||
if (!danglingQuote) {
|
||||
tokens.push({
|
||||
type: 'string',
|
||||
value,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let WHITESPACE = /\s/;
|
||||
if (char && WHITESPACE.test(char)) {
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
let NUMBERS = /[0-9]/;
|
||||
if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {
|
||||
let value = '';
|
||||
if (char === '-') {
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
while ((char && NUMBERS.test(char)) || char === '.') {
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
tokens.push({
|
||||
type: 'number',
|
||||
value,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let LETTERS = /[a-z]/i;
|
||||
if (char && LETTERS.test(char)) {
|
||||
let value = '';
|
||||
while (char && LETTERS.test(char)) {
|
||||
if (current === input.length) {
|
||||
break;
|
||||
}
|
||||
value += char;
|
||||
char = input[++current];
|
||||
}
|
||||
if (value == 'true' || value == 'false' || value === 'null') {
|
||||
tokens.push({
|
||||
type: 'name',
|
||||
value,
|
||||
});
|
||||
}
|
||||
else {
|
||||
// unknown token, e.g. `nul` which isn't quite `null`
|
||||
current++;
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
current++;
|
||||
}
|
||||
return tokens;
|
||||
}, strip = (tokens) => {
|
||||
if (tokens.length === 0) {
|
||||
return tokens;
|
||||
}
|
||||
let lastToken = tokens[tokens.length - 1];
|
||||
switch (lastToken.type) {
|
||||
case 'separator':
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
break;
|
||||
case 'number':
|
||||
let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
|
||||
if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
}
|
||||
case 'string':
|
||||
let tokenBeforeTheLastToken = tokens[tokens.length - 2];
|
||||
if (tokenBeforeTheLastToken?.type === 'delimiter') {
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
}
|
||||
else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
}
|
||||
break;
|
||||
case 'delimiter':
|
||||
tokens = tokens.slice(0, tokens.length - 1);
|
||||
return strip(tokens);
|
||||
break;
|
||||
}
|
||||
return tokens;
|
||||
}, unstrip = (tokens) => {
|
||||
let tail = [];
|
||||
tokens.map((token) => {
|
||||
if (token.type === 'brace') {
|
||||
if (token.value === '{') {
|
||||
tail.push('}');
|
||||
}
|
||||
else {
|
||||
tail.splice(tail.lastIndexOf('}'), 1);
|
||||
}
|
||||
}
|
||||
if (token.type === 'paren') {
|
||||
if (token.value === '[') {
|
||||
tail.push(']');
|
||||
}
|
||||
else {
|
||||
tail.splice(tail.lastIndexOf(']'), 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (tail.length > 0) {
|
||||
tail.reverse().map((item) => {
|
||||
if (item === '}') {
|
||||
tokens.push({
|
||||
type: 'brace',
|
||||
value: '}',
|
||||
});
|
||||
}
|
||||
else if (item === ']') {
|
||||
tokens.push({
|
||||
type: 'paren',
|
||||
value: ']',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
return tokens;
|
||||
}, generate = (tokens) => {
|
||||
let output = '';
|
||||
tokens.map((token) => {
|
||||
switch (token.type) {
|
||||
case 'string':
|
||||
output += '"' + token.value + '"';
|
||||
break;
|
||||
default:
|
||||
output += token.value;
|
||||
break;
|
||||
}
|
||||
});
|
||||
return output;
|
||||
}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
|
||||
export { partialParse };
|
||||
//# sourceMappingURL=parser.mjs.map
|
||||
1
vendor/sdk/_vendor/partial-json-parser/parser.mjs.map
vendored
Normal file
1
vendor/sdk/_vendor/partial-json-parser/parser.mjs.map
vendored
Normal file
File diff suppressed because one or more lines are too long
248
vendor/sdk/core.d.ts
vendored
Normal file
248
vendor/sdk/core.d.ts
vendored
Normal file
@@ -0,0 +1,248 @@
|
||||
|
||||
|
||||
import { Stream } from "./streaming.js";
|
||||
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 };
|
||||
import { BlobLike } from "./uploads.js";
|
||||
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;
|
||||
};
|
||||
type WithRequestID<T> = T extends Array<any> | Response | AbstractPage<any> ? T : T extends Record<string, any> ? T & {
|
||||
_request_id?: string | null;
|
||||
} : T;
|
||||
/**
|
||||
* A subclass of `Promise` providing additional helper methods
|
||||
* for interacting with the SDK.
|
||||
*/
|
||||
export declare class APIPromise<T> extends Promise<WithRequestID<T>> {
|
||||
private responsePromise;
|
||||
private parseResponse;
|
||||
private parsedPromise;
|
||||
constructor(responsePromise: Promise<APIResponseProps>, parseResponse?: (props: APIResponseProps) => PromiseOrValue<WithRequestID<T>>);
|
||||
_thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => 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, the raw `Response` instance and the ID of the request,
|
||||
* returned vie the `request-id` header which is useful for debugging requests and resporting
|
||||
* issues to Anthropic.
|
||||
*
|
||||
* 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;
|
||||
request_id: string | null | undefined;
|
||||
}>;
|
||||
private parse;
|
||||
then<TResult1 = WithRequestID<T>, TResult2 = never>(onfulfilled?: ((value: WithRequestID<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<WithRequestID<T> | TResult>;
|
||||
finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<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: overriddenFetch, }: {
|
||||
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, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
|
||||
post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
|
||||
patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
|
||||
put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
|
||||
delete<Req, 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>(options: FinalRequestOptions<Req>, { retryCount }?: {
|
||||
retryCount?: number;
|
||||
}): {
|
||||
req: RequestInit;
|
||||
url: string;
|
||||
timeout: number;
|
||||
};
|
||||
private buildHeaders;
|
||||
/**
|
||||
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
||||
*/
|
||||
protected prepareOptions(options: FinalRequestOptions): Promise<void>;
|
||||
/**
|
||||
* 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, 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>(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>;
|
||||
private shouldRetry;
|
||||
private retryRequest;
|
||||
private calculateDefaultRetryTimeoutMillis;
|
||||
private getUserAgent;
|
||||
}
|
||||
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<this>;
|
||||
[Symbol.asyncIterator](): AsyncGenerator<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 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<Item>;
|
||||
}
|
||||
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 = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer> = {
|
||||
method?: HTTPMethod;
|
||||
path?: string;
|
||||
query?: Req | undefined;
|
||||
body?: Req | null | undefined;
|
||||
headers?: Headers | undefined;
|
||||
maxRetries?: number;
|
||||
stream?: boolean | undefined;
|
||||
timeout?: number;
|
||||
httpAgent?: Agent;
|
||||
signal?: AbortSignal | undefined | null;
|
||||
idempotencyKey?: string;
|
||||
__binaryRequest?: boolean | undefined;
|
||||
__binaryResponse?: boolean | undefined;
|
||||
__streamClass?: typeof Stream;
|
||||
};
|
||||
export declare const isRequestOptions: (obj: unknown) => obj is RequestOptions<unknown>;
|
||||
export type FinalRequestOptions<Req = unknown | Record<string, unknown> | Readable | DataView> = 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.
|
||||
*
|
||||
* Trims beginning and trailing whitespace.
|
||||
*
|
||||
* 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 | Headers, header: string) => string;
|
||||
export declare const getHeader: (headers: HeadersLike | Headers, header: string) => string | undefined;
|
||||
/**
|
||||
* Encodes a string to Base64 format.
|
||||
*/
|
||||
export declare const toBase64: (str: string | null | undefined) => string;
|
||||
export declare function isObj(obj: unknown): obj is Record<string, unknown>;
|
||||
//# sourceMappingURL=core.d.ts.map
|
||||
1
vendor/sdk/core.d.ts.map
vendored
Normal file
1
vendor/sdk/core.d.ts.map
vendored
Normal file
File diff suppressed because one or more lines are too long
935
vendor/sdk/core.js
vendored
Normal file
935
vendor/sdk/core.js
vendored
Normal file
@@ -0,0 +1,935 @@
|
||||
"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.isObj = exports.toBase64 = exports.getHeader = 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.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>`
|
||||
if (props.options.__streamClass) {
|
||||
return props.options.__streamClass.fromSSEResponse(response, props.controller);
|
||||
}
|
||||
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;
|
||||
}
|
||||
if (props.options.__binaryResponse) {
|
||||
return response;
|
||||
}
|
||||
const contentType = response.headers.get('content-type');
|
||||
const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
|
||||
if (isJSON) {
|
||||
const json = await response.json();
|
||||
debug('response', response.status, response.url, response.headers, json);
|
||||
return _addRequestID(json, response);
|
||||
}
|
||||
const text = await response.text();
|
||||
debug('response', response.status, response.url, response.headers, text);
|
||||
// TODO handle blob, arraybuffer, other content types, etc.
|
||||
return text;
|
||||
}
|
||||
function _addRequestID(value, response) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return value;
|
||||
}
|
||||
return Object.defineProperty(value, '_request_id', {
|
||||
value: response.headers.get('request-id'),
|
||||
enumerable: false,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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) => _addRequestID(transform(await this.parseResponse(props), props), props.response));
|
||||
}
|
||||
/**
|
||||
* 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, the raw `Response` instance and the ID of the request,
|
||||
* returned vie the `request-id` header which is useful for debugging requests and resporting
|
||||
* issues to Anthropic.
|
||||
*
|
||||
* 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, request_id: response.headers.get('request-id') };
|
||||
}
|
||||
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: overriddenFetch, }) {
|
||||
this.baseURL = baseURL;
|
||||
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
|
||||
this.timeout = validatePositiveInteger('timeout', timeout);
|
||||
this.httpAgent = httpAgent;
|
||||
this.fetch = overriddenFetch ?? 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(async (opts) => {
|
||||
const body = opts && (0, uploads_1.isBlobLike)(opts?.body) ? new DataView(await opts.body.arrayBuffer())
|
||||
: opts?.body instanceof DataView ? opts.body
|
||||
: opts?.body instanceof ArrayBuffer ? new DataView(opts.body)
|
||||
: opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)
|
||||
: opts?.body;
|
||||
return { method, path, ...opts, body };
|
||||
}));
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
else if (ArrayBuffer.isView(body)) {
|
||||
return body.byteLength.toString();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
buildRequest(options, { retryCount = 0 } = {}) {
|
||||
options = { ...options };
|
||||
const { method, path, query, headers: headers = {} } = options;
|
||||
const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
|
||||
options.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);
|
||||
options.timeout = options.timeout ?? this.timeout;
|
||||
const httpAgent = options.httpAgent ?? this.httpAgent ?? (0, index_1.getDefaultAgent)(url);
|
||||
const minAgentTimeout = options.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 = this.buildHeaders({ options, headers, contentLength, retryCount });
|
||||
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,
|
||||
};
|
||||
return { req, url, timeout: options.timeout };
|
||||
}
|
||||
buildHeaders({ options, headers, contentLength, retryCount, }) {
|
||||
const reqHeaders = {};
|
||||
if (contentLength) {
|
||||
reqHeaders['content-length'] = contentLength;
|
||||
}
|
||||
const defaultHeaders = this.defaultHeaders(options);
|
||||
applyHeadersMut(reqHeaders, defaultHeaders);
|
||||
applyHeadersMut(reqHeaders, 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'];
|
||||
}
|
||||
// Don't set theses headers if they were already set or removed through default headers or by the caller.
|
||||
// We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account
|
||||
// for the removal case.
|
||||
if ((0, exports.getHeader)(defaultHeaders, 'x-stainless-retry-count') === undefined &&
|
||||
(0, exports.getHeader)(headers, 'x-stainless-retry-count') === undefined) {
|
||||
reqHeaders['x-stainless-retry-count'] = String(retryCount);
|
||||
}
|
||||
if ((0, exports.getHeader)(defaultHeaders, 'x-stainless-timeout') === undefined &&
|
||||
(0, exports.getHeader)(headers, 'x-stainless-timeout') === undefined &&
|
||||
options.timeout) {
|
||||
reqHeaders['x-stainless-timeout'] = String(options.timeout);
|
||||
}
|
||||
this.validateHeaders(reqHeaders, headers);
|
||||
return reqHeaders;
|
||||
}
|
||||
/**
|
||||
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
||||
*/
|
||||
async prepareOptions(options) { }
|
||||
/**
|
||||
* 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;
|
||||
const maxRetries = options.maxRetries ?? this.maxRetries;
|
||||
if (retriesRemaining == null) {
|
||||
retriesRemaining = maxRetries;
|
||||
}
|
||||
await this.prepareOptions(options);
|
||||
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
|
||||
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)) {
|
||||
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
||||
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);
|
||||
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;
|
||||
const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
|
||||
debug(`response (error; ${retryMessage})`, 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 (typeof query === 'object' && query && !Array.isArray(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);
|
||||
const fetchOptions = {
|
||||
signal: controller.signal,
|
||||
...options,
|
||||
};
|
||||
if (fetchOptions.method) {
|
||||
// Custom methods like 'patch' need to be uppercased
|
||||
// See https://github.com/nodejs/undici/issues/2294
|
||||
fetchOptions.method = fetchOptions.method.toUpperCase();
|
||||
}
|
||||
return (
|
||||
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
||||
this.fetch.call(undefined, url, fetchOptions).finally(() => {
|
||||
clearTimeout(timeout);
|
||||
}));
|
||||
}
|
||||
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) {
|
||||
let timeoutMillis;
|
||||
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
||||
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
|
||||
if (retryAfterMillisHeader) {
|
||||
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
||||
if (!Number.isNaN(timeoutMs)) {
|
||||
timeoutMillis = timeoutMs;
|
||||
}
|
||||
}
|
||||
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
||||
const retryAfterHeader = responseHeaders?.['retry-after'];
|
||||
if (retryAfterHeader && !timeoutMillis) {
|
||||
const timeoutSeconds = parseFloat(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 && 0 <= timeoutMillis && 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 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 && typeof nextOptions.query === 'object') {
|
||||
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,
|
||||
__binaryRequest: true,
|
||||
__binaryResponse: true,
|
||||
__streamClass: 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': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
|
||||
};
|
||||
}
|
||||
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://url.spec.whatwg.org/#url-scheme-string
|
||||
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/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;
|
||||
if (typeof err === 'object' && err !== null) {
|
||||
try {
|
||||
return new Error(JSON.stringify(err));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return new Error(String(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.
|
||||
*
|
||||
* Trims beginning and trailing whitespace.
|
||||
*
|
||||
* 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]?.trim() ?? undefined;
|
||||
}
|
||||
if (typeof Deno !== 'undefined') {
|
||||
return Deno.env?.get?.(env)?.trim();
|
||||
}
|
||||
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;
|
||||
/**
|
||||
* Copies headers from "newHeaders" onto "targetHeaders",
|
||||
* using lower-case for all properties,
|
||||
* ignoring any keys with undefined values,
|
||||
* and deleting any keys with null values.
|
||||
*/
|
||||
function applyHeadersMut(targetHeaders, newHeaders) {
|
||||
for (const k in newHeaders) {
|
||||
if (!hasOwn(newHeaders, k))
|
||||
continue;
|
||||
const lowerKey = k.toLowerCase();
|
||||
if (!lowerKey)
|
||||
continue;
|
||||
const val = newHeaders[k];
|
||||
if (val === null) {
|
||||
delete targetHeaders[lowerKey];
|
||||
}
|
||||
else if (val !== undefined) {
|
||||
targetHeaders[lowerKey] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
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 foundHeader = (0, exports.getHeader)(headers, header);
|
||||
if (foundHeader === undefined) {
|
||||
throw new Error(`Could not find ${header} header`);
|
||||
}
|
||||
return foundHeader;
|
||||
};
|
||||
exports.getRequiredHeader = getRequiredHeader;
|
||||
const getHeader = (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;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
exports.getHeader = getHeader;
|
||||
/**
|
||||
* 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;
|
||||
function isObj(obj) {
|
||||
return obj != null && typeof obj === 'object' && !Array.isArray(obj);
|
||||
}
|
||||
exports.isObj = isObj;
|
||||
//# sourceMappingURL=core.js.map
|
||||
1
vendor/sdk/core.js.map
vendored
Normal file
1
vendor/sdk/core.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
903
vendor/sdk/core.mjs
vendored
Normal file
903
vendor/sdk/core.mjs
vendored
Normal file
@@ -0,0 +1,903 @@
|
||||
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 { isBlobLike, 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>`
|
||||
if (props.options.__streamClass) {
|
||||
return props.options.__streamClass.fromSSEResponse(response, props.controller);
|
||||
}
|
||||
return Stream.fromSSEResponse(response, props.controller);
|
||||
}
|
||||
// fetch refuses to read the body when the status code is 204.
|
||||
if (response.status === 204) {
|
||||
return null;
|
||||
}
|
||||
if (props.options.__binaryResponse) {
|
||||
return response;
|
||||
}
|
||||
const contentType = response.headers.get('content-type');
|
||||
const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
|
||||
if (isJSON) {
|
||||
const json = await response.json();
|
||||
debug('response', response.status, response.url, response.headers, json);
|
||||
return _addRequestID(json, response);
|
||||
}
|
||||
const text = await response.text();
|
||||
debug('response', response.status, response.url, response.headers, text);
|
||||
// TODO handle blob, arraybuffer, other content types, etc.
|
||||
return text;
|
||||
}
|
||||
function _addRequestID(value, response) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return value;
|
||||
}
|
||||
return Object.defineProperty(value, '_request_id', {
|
||||
value: response.headers.get('request-id'),
|
||||
enumerable: false,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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) => _addRequestID(transform(await this.parseResponse(props), props), props.response));
|
||||
}
|
||||
/**
|
||||
* 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, the raw `Response` instance and the ID of the request,
|
||||
* returned vie the `request-id` header which is useful for debugging requests and resporting
|
||||
* issues to Anthropic.
|
||||
*
|
||||
* 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, request_id: response.headers.get('request-id') };
|
||||
}
|
||||
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: overriddenFetch, }) {
|
||||
this.baseURL = baseURL;
|
||||
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
|
||||
this.timeout = validatePositiveInteger('timeout', timeout);
|
||||
this.httpAgent = httpAgent;
|
||||
this.fetch = overriddenFetch ?? 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(async (opts) => {
|
||||
const body = opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())
|
||||
: opts?.body instanceof DataView ? opts.body
|
||||
: opts?.body instanceof ArrayBuffer ? new DataView(opts.body)
|
||||
: opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)
|
||||
: opts?.body;
|
||||
return { method, path, ...opts, body };
|
||||
}));
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
else if (ArrayBuffer.isView(body)) {
|
||||
return body.byteLength.toString();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
buildRequest(options, { retryCount = 0 } = {}) {
|
||||
options = { ...options };
|
||||
const { method, path, query, headers: headers = {} } = options;
|
||||
const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
|
||||
options.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);
|
||||
options.timeout = options.timeout ?? this.timeout;
|
||||
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
|
||||
const minAgentTimeout = options.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 = this.buildHeaders({ options, headers, contentLength, retryCount });
|
||||
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,
|
||||
};
|
||||
return { req, url, timeout: options.timeout };
|
||||
}
|
||||
buildHeaders({ options, headers, contentLength, retryCount, }) {
|
||||
const reqHeaders = {};
|
||||
if (contentLength) {
|
||||
reqHeaders['content-length'] = contentLength;
|
||||
}
|
||||
const defaultHeaders = this.defaultHeaders(options);
|
||||
applyHeadersMut(reqHeaders, defaultHeaders);
|
||||
applyHeadersMut(reqHeaders, headers);
|
||||
// let builtin fetch set the Content-Type for multipart bodies
|
||||
if (isMultipartBody(options.body) && shimsKind !== 'node') {
|
||||
delete reqHeaders['content-type'];
|
||||
}
|
||||
// Don't set theses headers if they were already set or removed through default headers or by the caller.
|
||||
// We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account
|
||||
// for the removal case.
|
||||
if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
|
||||
getHeader(headers, 'x-stainless-retry-count') === undefined) {
|
||||
reqHeaders['x-stainless-retry-count'] = String(retryCount);
|
||||
}
|
||||
if (getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&
|
||||
getHeader(headers, 'x-stainless-timeout') === undefined &&
|
||||
options.timeout) {
|
||||
reqHeaders['x-stainless-timeout'] = String(options.timeout);
|
||||
}
|
||||
this.validateHeaders(reqHeaders, headers);
|
||||
return reqHeaders;
|
||||
}
|
||||
/**
|
||||
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
||||
*/
|
||||
async prepareOptions(options) { }
|
||||
/**
|
||||
* 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;
|
||||
const maxRetries = options.maxRetries ?? this.maxRetries;
|
||||
if (retriesRemaining == null) {
|
||||
retriesRemaining = maxRetries;
|
||||
}
|
||||
await this.prepareOptions(options);
|
||||
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
|
||||
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)) {
|
||||
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
||||
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);
|
||||
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;
|
||||
const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
|
||||
debug(`response (error; ${retryMessage})`, 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 (typeof query === 'object' && query && !Array.isArray(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);
|
||||
const fetchOptions = {
|
||||
signal: controller.signal,
|
||||
...options,
|
||||
};
|
||||
if (fetchOptions.method) {
|
||||
// Custom methods like 'patch' need to be uppercased
|
||||
// See https://github.com/nodejs/undici/issues/2294
|
||||
fetchOptions.method = fetchOptions.method.toUpperCase();
|
||||
}
|
||||
return (
|
||||
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
||||
this.fetch.call(undefined, url, fetchOptions).finally(() => {
|
||||
clearTimeout(timeout);
|
||||
}));
|
||||
}
|
||||
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) {
|
||||
let timeoutMillis;
|
||||
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
||||
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
|
||||
if (retryAfterMillisHeader) {
|
||||
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
||||
if (!Number.isNaN(timeoutMs)) {
|
||||
timeoutMillis = timeoutMs;
|
||||
}
|
||||
}
|
||||
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
||||
const retryAfterHeader = responseHeaders?.['retry-after'];
|
||||
if (retryAfterHeader && !timeoutMillis) {
|
||||
const timeoutSeconds = parseFloat(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 && 0 <= timeoutMillis && 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 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 && typeof nextOptions.query === 'object') {
|
||||
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,
|
||||
__binaryRequest: true,
|
||||
__binaryResponse: true,
|
||||
__streamClass: 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': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
|
||||
};
|
||||
}
|
||||
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://url.spec.whatwg.org/#url-scheme-string
|
||||
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/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;
|
||||
if (typeof err === 'object' && err !== null) {
|
||||
try {
|
||||
return new Error(JSON.stringify(err));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return new Error(String(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.
|
||||
*
|
||||
* Trims beginning and trailing whitespace.
|
||||
*
|
||||
* 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]?.trim() ?? undefined;
|
||||
}
|
||||
if (typeof Deno !== 'undefined') {
|
||||
return Deno.env?.get?.(env)?.trim();
|
||||
}
|
||||
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);
|
||||
}
|
||||
/**
|
||||
* Copies headers from "newHeaders" onto "targetHeaders",
|
||||
* using lower-case for all properties,
|
||||
* ignoring any keys with undefined values,
|
||||
* and deleting any keys with null values.
|
||||
*/
|
||||
function applyHeadersMut(targetHeaders, newHeaders) {
|
||||
for (const k in newHeaders) {
|
||||
if (!hasOwn(newHeaders, k))
|
||||
continue;
|
||||
const lowerKey = k.toLowerCase();
|
||||
if (!lowerKey)
|
||||
continue;
|
||||
const val = newHeaders[k];
|
||||
if (val === null) {
|
||||
delete targetHeaders[lowerKey];
|
||||
}
|
||||
else if (val !== undefined) {
|
||||
targetHeaders[lowerKey] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
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 foundHeader = getHeader(headers, header);
|
||||
if (foundHeader === undefined) {
|
||||
throw new Error(`Could not find ${header} header`);
|
||||
}
|
||||
return foundHeader;
|
||||
};
|
||||
export const getHeader = (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;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
/**
|
||||
* 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');
|
||||
};
|
||||
export function isObj(obj) {
|
||||
return obj != null && typeof obj === 'object' && !Array.isArray(obj);
|
||||
}
|
||||
//# sourceMappingURL=core.mjs.map
|
||||
1
vendor/sdk/core.mjs.map
vendored
Normal file
1
vendor/sdk/core.mjs.map
vendored
Normal file
File diff suppressed because one or more lines are too long
48
vendor/sdk/error.d.ts
vendored
Normal file
48
vendor/sdk/error.d.ts
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Headers } from "./core.js";
|
||||
export declare class AnthropicError extends Error {
|
||||
}
|
||||
export declare class APIError<TStatus extends number | undefined = number | undefined, THeaders extends Headers | undefined = Headers | undefined, TError extends Object | undefined = Object | undefined> extends AnthropicError {
|
||||
/** HTTP status for the response that caused the error */
|
||||
readonly status: TStatus;
|
||||
/** HTTP headers for the response that caused the error */
|
||||
readonly headers: THeaders;
|
||||
/** JSON body of the response that caused the error */
|
||||
readonly error: TError;
|
||||
readonly request_id: string | null | undefined;
|
||||
constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders);
|
||||
private static makeMessage;
|
||||
static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
|
||||
}
|
||||
export declare class APIUserAbortError extends APIError<undefined, undefined, undefined> {
|
||||
constructor({ message }?: {
|
||||
message?: string;
|
||||
});
|
||||
}
|
||||
export declare class APIConnectionError extends APIError<undefined, undefined, undefined> {
|
||||
constructor({ message, cause }: {
|
||||
message?: string | undefined;
|
||||
cause?: Error | undefined;
|
||||
});
|
||||
}
|
||||
export declare class APIConnectionTimeoutError extends APIConnectionError {
|
||||
constructor({ message }?: {
|
||||
message?: string;
|
||||
});
|
||||
}
|
||||
export declare class BadRequestError extends APIError<400, Headers> {
|
||||
}
|
||||
export declare class AuthenticationError extends APIError<401, Headers> {
|
||||
}
|
||||
export declare class PermissionDeniedError extends APIError<403, Headers> {
|
||||
}
|
||||
export declare class NotFoundError extends APIError<404, Headers> {
|
||||
}
|
||||
export declare class ConflictError extends APIError<409, Headers> {
|
||||
}
|
||||
export declare class UnprocessableEntityError extends APIError<422, Headers> {
|
||||
}
|
||||
export declare class RateLimitError extends APIError<429, Headers> {
|
||||
}
|
||||
export declare class InternalServerError extends APIError<number, Headers> {
|
||||
}
|
||||
//# sourceMappingURL=error.d.ts.map
|
||||
1
vendor/sdk/error.d.ts.map
vendored
Normal file
1
vendor/sdk/error.d.ts.map
vendored
Normal 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,QAAQ,CACnB,OAAO,SAAS,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,EACvD,QAAQ,SAAS,OAAO,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,EAC1D,MAAM,SAAS,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CACtD,SAAQ,cAAc;IACtB,yDAAyD;IACzD,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,0DAA0D;IAC1D,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;IAC3B,sDAAsD;IACtD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;gBAEnC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,QAAQ;IAQ1F,OAAO,CAAC,MAAM,CAAC,WAAW;IAqB1B,MAAM,CAAC,QAAQ,CACb,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,aAAa,EAAE,MAAM,GAAG,SAAS,EACjC,OAAO,EAAE,MAAM,GAAG,SAAS,EAC3B,OAAO,EAAE,OAAO,GAAG,SAAS,GAC3B,QAAQ;CAyCZ;AAED,qBAAa,iBAAkB,SAAQ,QAAQ,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC;gBAClE,EAAE,OAAO,EAAE,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAO;CAGnD;AAED,qBAAa,kBAAmB,SAAQ,QAAQ,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC;gBACnE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAAC,KAAK,CAAC,EAAE,KAAK,GAAG,SAAS,CAAA;KAAE;CAM5F;AAED,qBAAa,yBAA0B,SAAQ,kBAAkB;gBACnD,EAAE,OAAO,EAAE,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAO;CAGnD;AAED,qBAAa,eAAgB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE9D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAElE,qBAAa,qBAAsB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAEpE,qBAAa,aAAc,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,aAAc,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,wBAAyB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAEvE,qBAAa,cAAe,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE7D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAAG"}
|
||||
114
vendor/sdk/error.js
vendored
Normal file
114
vendor/sdk/error.js
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
"use strict";
|
||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
||||
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.request_id = headers?.['request-id'];
|
||||
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 || !headers) {
|
||||
return new APIConnectionError({ message, 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);
|
||||
}
|
||||
}
|
||||
exports.APIUserAbortError = APIUserAbortError;
|
||||
class APIConnectionError extends APIError {
|
||||
constructor({ message, cause }) {
|
||||
super(undefined, undefined, message || 'Connection error.', 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 {
|
||||
}
|
||||
exports.BadRequestError = BadRequestError;
|
||||
class AuthenticationError extends APIError {
|
||||
}
|
||||
exports.AuthenticationError = AuthenticationError;
|
||||
class PermissionDeniedError extends APIError {
|
||||
}
|
||||
exports.PermissionDeniedError = PermissionDeniedError;
|
||||
class NotFoundError extends APIError {
|
||||
}
|
||||
exports.NotFoundError = NotFoundError;
|
||||
class ConflictError extends APIError {
|
||||
}
|
||||
exports.ConflictError = ConflictError;
|
||||
class UnprocessableEntityError extends APIError {
|
||||
}
|
||||
exports.UnprocessableEntityError = UnprocessableEntityError;
|
||||
class RateLimitError extends APIError {
|
||||
}
|
||||
exports.RateLimitError = RateLimitError;
|
||||
class InternalServerError extends APIError {
|
||||
}
|
||||
exports.InternalServerError = InternalServerError;
|
||||
//# sourceMappingURL=error.js.map
|
||||
1
vendor/sdk/error.js.map
vendored
Normal file
1
vendor/sdk/error.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error.js","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,oCAA8C;AAE9C,MAAa,cAAe,SAAQ,KAAK;CAAG;AAA5C,wCAA4C;AAE5C,MAAa,QAIX,SAAQ,cAAc;IAUtB,YAAY,MAAe,EAAE,KAAa,EAAE,OAA2B,EAAE,OAAiB;QACxF,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,UAAU,GAAG,OAAO,EAAE,CAAC,YAAY,CAAC,CAAC;QAC1C,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;gBACjC,KAAK,CAAC,OAAO;gBACf,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,MAAM,IAAI,GAAG,EAAE,CAAC;SAC3B;QACD,IAAI,MAAM,EAAE;YACV,OAAO,GAAG,MAAM,wBAAwB,CAAC;SAC1C;QACD,IAAI,GAAG,EAAE;YACP,OAAO,GAAG,CAAC;SACZ;QACD,OAAO,0BAA0B,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,MAA0B,EAC1B,aAAiC,EACjC,OAA2B,EAC3B,OAA4B;QAE5B,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE;YACvB,OAAO,IAAI,kBAAkB,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,IAAA,kBAAW,EAAC,aAAa,CAAC,EAAE,CAAC,CAAC;SAC/E;QAED,MAAM,KAAK,GAAG,aAAoC,CAAC;QAEnD,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,eAAe,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC7D;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,mBAAmB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACjE;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,qBAAqB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACnE;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC3D;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC3D;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,wBAAwB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACtE;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC5D;QAED,IAAI,MAAM,IAAI,GAAG,EAAE;YACjB,OAAO,IAAI,mBAAmB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACjE;QAED,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;CACF;AAzFD,4BAyFC;AAED,MAAa,iBAAkB,SAAQ,QAAyC;IAC9E,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,IAAI,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAC5E,CAAC;CACF;AAJD,8CAIC;AAED,MAAa,kBAAmB,SAAQ,QAAyC;IAC/E,YAAY,EAAE,OAAO,EAAE,KAAK,EAA+D;QACzF,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,IAAI,mBAAmB,EAAE,SAAS,CAAC,CAAC;QACvE,gEAAgE;QAChE,aAAa;QACb,IAAI,KAAK;YAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAChC,CAAC;CACF;AAPD,gDAOC;AAED,MAAa,yBAA0B,SAAQ,kBAAkB;IAC/D,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACtD,CAAC;CACF;AAJD,8DAIC;AAED,MAAa,eAAgB,SAAQ,QAAsB;CAAG;AAA9D,0CAA8D;AAE9D,MAAa,mBAAoB,SAAQ,QAAsB;CAAG;AAAlE,kDAAkE;AAElE,MAAa,qBAAsB,SAAQ,QAAsB;CAAG;AAApE,sDAAoE;AAEpE,MAAa,aAAc,SAAQ,QAAsB;CAAG;AAA5D,sCAA4D;AAE5D,MAAa,aAAc,SAAQ,QAAsB;CAAG;AAA5D,sCAA4D;AAE5D,MAAa,wBAAyB,SAAQ,QAAsB;CAAG;AAAvE,4DAAuE;AAEvE,MAAa,cAAe,SAAQ,QAAsB;CAAG;AAA7D,wCAA6D;AAE7D,MAAa,mBAAoB,SAAQ,QAAyB;CAAG;AAArE,kDAAqE"}
|
||||
98
vendor/sdk/error.mjs
vendored
Normal file
98
vendor/sdk/error.mjs
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
||||
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.request_id = headers?.['request-id'];
|
||||
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 || !headers) {
|
||||
return new APIConnectionError({ message, 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);
|
||||
}
|
||||
}
|
||||
export class APIConnectionError extends APIError {
|
||||
constructor({ message, cause }) {
|
||||
super(undefined, undefined, message || 'Connection error.', 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 {
|
||||
}
|
||||
export class AuthenticationError extends APIError {
|
||||
}
|
||||
export class PermissionDeniedError extends APIError {
|
||||
}
|
||||
export class NotFoundError extends APIError {
|
||||
}
|
||||
export class ConflictError extends APIError {
|
||||
}
|
||||
export class UnprocessableEntityError extends APIError {
|
||||
}
|
||||
export class RateLimitError extends APIError {
|
||||
}
|
||||
export class InternalServerError extends APIError {
|
||||
}
|
||||
//# sourceMappingURL=error.mjs.map
|
||||
1
vendor/sdk/error.mjs.map
vendored
Normal file
1
vendor/sdk/error.mjs.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error.mjs","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAW;AAE/B,MAAM,OAAO,cAAe,SAAQ,KAAK;CAAG;AAE5C,MAAM,OAAO,QAIX,SAAQ,cAAc;IAUtB,YAAY,MAAe,EAAE,KAAa,EAAE,OAA2B,EAAE,OAAiB;QACxF,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,UAAU,GAAG,OAAO,EAAE,CAAC,YAAY,CAAC,CAAC;QAC1C,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;gBACjC,KAAK,CAAC,OAAO;gBACf,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,MAAM,IAAI,GAAG,EAAE,CAAC;SAC3B;QACD,IAAI,MAAM,EAAE;YACV,OAAO,GAAG,MAAM,wBAAwB,CAAC;SAC1C;QACD,IAAI,GAAG,EAAE;YACP,OAAO,GAAG,CAAC;SACZ;QACD,OAAO,0BAA0B,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,MAA0B,EAC1B,aAAiC,EACjC,OAA2B,EAC3B,OAA4B;QAE5B,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE;YACvB,OAAO,IAAI,kBAAkB,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;SAC/E;QAED,MAAM,KAAK,GAAG,aAAoC,CAAC;QAEnD,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,eAAe,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC7D;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,mBAAmB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACjE;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,qBAAqB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACnE;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC3D;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC3D;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,wBAAwB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACtE;QAED,IAAI,MAAM,KAAK,GAAG,EAAE;YAClB,OAAO,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SAC5D;QAED,IAAI,MAAM,IAAI,GAAG,EAAE;YACjB,OAAO,IAAI,mBAAmB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;SACjE;QAED,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;CACF;AAED,MAAM,OAAO,iBAAkB,SAAQ,QAAyC;IAC9E,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,IAAI,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAC5E,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,QAAyC;IAC/E,YAAY,EAAE,OAAO,EAAE,KAAK,EAA+D;QACzF,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,IAAI,mBAAmB,EAAE,SAAS,CAAC,CAAC;QACvE,gEAAgE;QAChE,aAAa;QACb,IAAI,KAAK;YAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAChC,CAAC;CACF;AAED,MAAM,OAAO,yBAA0B,SAAQ,kBAAkB;IAC/D,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACtD,CAAC;CACF;AAED,MAAM,OAAO,eAAgB,SAAQ,QAAsB;CAAG;AAE9D,MAAM,OAAO,mBAAoB,SAAQ,QAAsB;CAAG;AAElE,MAAM,OAAO,qBAAsB,SAAQ,QAAsB;CAAG;AAEpE,MAAM,OAAO,aAAc,SAAQ,QAAsB;CAAG;AAE5D,MAAM,OAAO,aAAc,SAAQ,QAAsB;CAAG;AAE5D,MAAM,OAAO,wBAAyB,SAAQ,QAAsB;CAAG;AAEvE,MAAM,OAAO,cAAe,SAAQ,QAAsB;CAAG;AAE7D,MAAM,OAAO,mBAAoB,SAAQ,QAAyB;CAAG"}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user