Add extracted source directory and README navigation

This commit is contained in:
Shawn Bot
2026-03-31 14:56:06 +00:00
parent 6252bb6eb5
commit 91e01d755b
4757 changed files with 984951 additions and 0 deletions

View File

@@ -0,0 +1,72 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _APIPromise_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { defaultParseResponse, addRequestID, } from "../internal/parse.mjs";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export class APIPromise extends Promise {
constructor(client, 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;
_APIPromise_client.set(this, void 0);
__classPrivateFieldSet(this, _APIPromise_client, client, "f");
}
_thenUnwrap(transform) {
return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, 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"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via 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"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
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((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
}
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);
}
}
_APIPromise_client = new WeakMap();
//# sourceMappingURL=api-promise.mjs.map

View File

@@ -0,0 +1,98 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { castToError } from "../internal/errors.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.requestID = headers?.get('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

View File

@@ -0,0 +1,177 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _AbstractPage_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { defaultParseResponse } from "../internal/parse.mjs";
import { APIPromise } from "./api-promise.mjs";
import { maybeObj } from "../internal/utils/values.mjs";
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.nextPageRequestOptions() != null;
}
async getNextPage() {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
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(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, 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 class Page extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.first_id = body.first_id || null;
this.last_id = body.last_id || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
if (this.options.query?.['before_id']) {
// in reverse
const first_id = this.first_id;
if (!first_id) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
before_id: first_id,
},
};
}
const cursor = this.last_id;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
after_id: cursor,
},
};
}
}
export class TokenPage extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page_token: cursor,
},
};
}
}
export class PageCursor extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page: cursor,
},
};
}
}
//# sourceMappingURL=pagination.mjs.map

View File

@@ -0,0 +1,7 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export class APIResource {
constructor(client) {
this._client = client;
}
}
//# sourceMappingURL=resource.mjs.map

View File

@@ -0,0 +1,283 @@
var _Stream_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { makeReadableStream } from "../internal/shims.mjs";
import { findDoubleNewlineIndex, LineDecoder } from "../internal/decoders/line.mjs";
import { ReadableStreamToAsyncIterable } from "../internal/shims.mjs";
import { isAbortError } from "../internal/errors.mjs";
import { safeJSON } from "../internal/utils/values.mjs";
import { encodeUTF8 } from "../internal/utils/bytes.mjs";
import { loggerFor } from "../internal/utils/log.mjs";
import { APIError } from "./error.mjs";
export class Stream {
constructor(iterator, controller, client) {
this.iterator = iterator;
_Stream_client.set(this, void 0);
this.controller = controller;
__classPrivateFieldSet(this, _Stream_client, client, "f");
}
static fromSSEResponse(response, controller, client) {
let consumed = false;
const logger = client ? loggerFor(client) : console;
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const sse of _iterSSEMessages(response, controller)) {
if (sse.event === 'completion') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'message_start' ||
sse.event === 'message_delta' ||
sse.event === 'message_stop' ||
sse.event === 'content_block_start' ||
sse.event === 'content_block_delta' ||
sse.event === 'content_block_stop') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'ping') {
continue;
}
if (sse.event === 'error') {
throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers);
}
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream(readableStream, controller, client) {
let consumed = false;
async function* iterLines() {
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(readableStream);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
yield line;
}
}
for (const line of lineDecoder.flush()) {
yield line;
}
}
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const line of iterLines()) {
if (done)
continue;
if (line)
yield JSON.parse(line);
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
[(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
return this.iterator();
}
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee() {
const left = [];
const right = [];
const iterator = this.iterator();
const teeIterator = (queue) => {
return {
next: () => {
if (queue.length === 0) {
const result = iterator.next();
left.push(result);
right.push(result);
}
return queue.shift();
},
};
};
return [
new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
];
}
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream() {
const self = this;
let iter;
return makeReadableStream({
async start() {
iter = self[Symbol.asyncIterator]();
},
async pull(ctrl) {
try {
const { value, done } = await iter.next();
if (done)
return ctrl.close();
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
ctrl.enqueue(bytes);
}
catch (err) {
ctrl.error(err);
}
},
async cancel() {
await iter.return?.();
},
});
}
}
export async function* _iterSSEMessages(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== 'undefined' &&
globalThis.navigator.product === 'ReactNative') {
throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
}
throw new AnthropicError(`Attempted to iterate over a response with no body`);
}
const sseDecoder = new SSEDecoder();
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(response.body);
for await (const sseChunk of iterSSEChunks(iter)) {
for (const line of lineDecoder.decode(sseChunk)) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
for (const line of lineDecoder.flush()) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
/**
* Given an async iterable iterator, iterates over it and yields full
* SSE chunks, i.e. yields when a double new-line is encountered.
*/
async function* iterSSEChunks(iterator) {
let data = new Uint8Array();
for await (const chunk of iterator) {
if (chunk == null) {
continue;
}
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
: typeof chunk === 'string' ? encodeUTF8(chunk)
: chunk;
let newData = new Uint8Array(data.length + binaryChunk.length);
newData.set(data);
newData.set(binaryChunk, data.length);
data = newData;
let patternIndex;
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
yield data.slice(0, patternIndex);
data = data.slice(patternIndex);
}
}
if (data.length > 0) {
yield data;
}
}
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length)
return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
}
else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
function partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) {
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
}
return [str, '', ''];
}
//# sourceMappingURL=streaming.mjs.map

View File

@@ -0,0 +1,2 @@
export { toFile } from "../internal/to-file.mjs";
//# sourceMappingURL=uploads.mjs.map