Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@anthropic-ai/sdk

Package Overview
Dependencies
Maintainers
11
Versions
96
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@anthropic-ai/sdk - npm Package Compare versions

Comparing version 0.33.1 to 0.34.0-alpha.0

_vendor/partial-json-parser/parser.d.mts

4

error.d.ts

@@ -1,2 +0,2 @@

import { Headers } from "./core.js";
export declare class AnthropicError extends Error {

@@ -11,3 +11,3 @@ }

readonly error: TError;
readonly request_id: string | null | undefined;
readonly requestID: string | null | undefined;
constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders);

@@ -14,0 +14,0 @@ private static makeMessage;

@@ -5,3 +5,3 @@ "use strict";

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");
const errors_1 = require("./internal/errors.js");
class AnthropicError extends Error {

@@ -15,3 +15,3 @@ }

this.headers = headers;
this.request_id = headers?.['request-id'];
this.requestID = headers?.get('request-id');
this.error = error;

@@ -39,3 +39,3 @@ }

if (!status || !headers) {
return new APIConnectionError({ message, cause: (0, core_1.castToError)(errorResponse) });
return new APIConnectionError({ message, cause: (0, errors_1.castToError)(errorResponse) });
}

@@ -42,0 +42,0 @@ const error = errorResponse;

@@ -1,152 +0,7 @@

import { type Agent } from "./_shims/index.js";
import * as Core from "./core.js";
import * as Errors from "./error.js";
import * as Pagination from "./pagination.js";
import { type PageParams, PageResponse } from "./pagination.js";
import * as Uploads from "./uploads.js";
import * as API from "./resources/index.js";
import { Completion, CompletionCreateParams, CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming, Completions } from "./resources/completions.js";
import { ModelInfo, ModelInfosPage, ModelListParams, Models } from "./resources/models.js";
import { AnthropicBeta, Beta, BetaAPIError, BetaAuthenticationError, BetaBillingError, BetaError, BetaErrorResponse, BetaGatewayTimeoutError, BetaInvalidRequestError, BetaNotFoundError, BetaOverloadedError, BetaPermissionError, BetaRateLimitError } from "./resources/beta/beta.js";
import { Base64PDFSource, CacheControlEphemeral, ContentBlock, ContentBlockDeltaEvent, ContentBlockParam, ContentBlockStartEvent, ContentBlockStopEvent, DocumentBlockParam, ImageBlockParam, InputJSONDelta, Message, MessageCountTokensParams, MessageCreateParams, MessageCreateParamsNonStreaming, MessageCreateParamsStreaming, MessageDeltaEvent, MessageDeltaUsage, MessageParam, MessageStartEvent, MessageStopEvent, MessageStreamEvent, MessageStreamParams, MessageTokensCount, Messages, Metadata, Model, RawContentBlockDeltaEvent, RawContentBlockStartEvent, RawContentBlockStopEvent, RawMessageDeltaEvent, RawMessageStartEvent, RawMessageStopEvent, RawMessageStreamEvent, TextBlock, TextBlockParam, TextDelta, Tool, ToolChoice, ToolChoiceAny, ToolChoiceAuto, ToolChoiceTool, ToolResultBlockParam, ToolUseBlock, ToolUseBlockParam, Usage } from "./resources/messages/messages.js";
export interface ClientOptions {
/**
* Defaults to process.env['ANTHROPIC_API_KEY'].
*/
apiKey?: string | null | undefined;
/**
* Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].
*/
authToken?: string | null | undefined;
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*
* Defaults to process.env['ANTHROPIC_BASE_URL'].
*/
baseURL?: string | null | undefined;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*/
timeout?: number;
/**
* An HTTP agent used to manage HTTP(S) connections.
*
* If not provided, an agent will be constructed by default in the Node.js environment,
* otherwise no agent is used.
*/
httpAgent?: Agent;
/**
* Specify a custom `fetch` function implementation.
*
* If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
* defined globally.
*/
fetch?: Core.Fetch | undefined;
/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
*
* @default 2
*/
maxRetries?: number;
/**
* Default headers to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* header to `undefined` or `null` in request options.
*/
defaultHeaders?: Core.Headers;
/**
* Default query parameters to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* param to `undefined` in request options.
*/
defaultQuery?: Core.DefaultQuery;
/**
* By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
* Only set this option to `true` if you understand the risks and have appropriate mitigations in place.
*/
dangerouslyAllowBrowser?: boolean;
}
/**
* API Client for interfacing with the Anthropic API.
*/
export declare class Anthropic extends Core.APIClient {
apiKey: string | null;
authToken: string | null;
private _options;
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
*/
constructor({ baseURL, apiKey, authToken, ...opts }?: ClientOptions);
completions: API.Completions;
messages: API.Messages;
models: API.Models;
beta: API.Beta;
protected defaultQuery(): Core.DefaultQuery | undefined;
protected defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers;
protected validateHeaders(headers: Core.Headers, customHeaders: Core.Headers): void;
protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers;
protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers;
protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers;
static Anthropic: typeof Anthropic;
static HUMAN_PROMPT: string;
static AI_PROMPT: string;
static DEFAULT_TIMEOUT: number;
static AnthropicError: typeof Errors.AnthropicError;
static APIError: typeof Errors.APIError;
static APIConnectionError: typeof Errors.APIConnectionError;
static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError;
static APIUserAbortError: typeof Errors.APIUserAbortError;
static NotFoundError: typeof Errors.NotFoundError;
static ConflictError: typeof Errors.ConflictError;
static RateLimitError: typeof Errors.RateLimitError;
static BadRequestError: typeof Errors.BadRequestError;
static AuthenticationError: typeof Errors.AuthenticationError;
static InternalServerError: typeof Errors.InternalServerError;
static PermissionDeniedError: typeof Errors.PermissionDeniedError;
static UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
static toFile: typeof Uploads.toFile;
static fileFromPath: typeof Uploads.fileFromPath;
}
export declare namespace Anthropic {
export type RequestOptions = Core.RequestOptions;
export import Page = Pagination.Page;
export { type PageParams as PageParams, type PageResponse as PageResponse };
export { Completions as Completions, type Completion as Completion, type CompletionCreateParams as CompletionCreateParams, type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming, type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming, };
export { Messages as Messages, type Base64PDFSource as Base64PDFSource, type CacheControlEphemeral as CacheControlEphemeral, type ContentBlock as ContentBlock, type ContentBlockDeltaEvent as ContentBlockDeltaEvent, type ContentBlockParam as ContentBlockParam, type ContentBlockStartEvent as ContentBlockStartEvent, type ContentBlockStopEvent as ContentBlockStopEvent, type DocumentBlockParam as DocumentBlockParam, type ImageBlockParam as ImageBlockParam, type InputJSONDelta as InputJSONDelta, type Message as Message, type MessageDeltaEvent as MessageDeltaEvent, type MessageDeltaUsage as MessageDeltaUsage, type MessageParam as MessageParam, type MessageStartEvent as MessageStartEvent, type MessageStopEvent as MessageStopEvent, type MessageStreamEvent as MessageStreamEvent, type MessageTokensCount as MessageTokensCount, type Metadata as Metadata, type Model as Model, type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent, type RawContentBlockStartEvent as RawContentBlockStartEvent, type RawContentBlockStopEvent as RawContentBlockStopEvent, type RawMessageDeltaEvent as RawMessageDeltaEvent, type RawMessageStartEvent as RawMessageStartEvent, type RawMessageStopEvent as RawMessageStopEvent, type RawMessageStreamEvent as RawMessageStreamEvent, type TextBlock as TextBlock, type TextBlockParam as TextBlockParam, type TextDelta as TextDelta, type Tool as Tool, type ToolChoice as ToolChoice, type ToolChoiceAny as ToolChoiceAny, type ToolChoiceAuto as ToolChoiceAuto, type ToolChoiceTool as ToolChoiceTool, type ToolResultBlockParam as ToolResultBlockParam, type ToolUseBlock as ToolUseBlock, type ToolUseBlockParam as ToolUseBlockParam, type Usage as Usage, type MessageCreateParams as MessageCreateParams, type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming as MessageCreateParamsStreaming, type MessageStreamParams as MessageStreamParams, type MessageCountTokensParams as MessageCountTokensParams, };
export { Models as Models, type ModelInfo as ModelInfo, ModelInfosPage as ModelInfosPage, type ModelListParams as ModelListParams, };
export { Beta as Beta, type AnthropicBeta as AnthropicBeta, type BetaAPIError as BetaAPIError, type BetaAuthenticationError as BetaAuthenticationError, type BetaBillingError as BetaBillingError, type BetaError as BetaError, type BetaErrorResponse as BetaErrorResponse, type BetaGatewayTimeoutError as BetaGatewayTimeoutError, type BetaInvalidRequestError as BetaInvalidRequestError, type BetaNotFoundError as BetaNotFoundError, type BetaOverloadedError as BetaOverloadedError, type BetaPermissionError as BetaPermissionError, type BetaRateLimitError as BetaRateLimitError, };
export type APIErrorObject = API.APIErrorObject;
export type AuthenticationError = API.AuthenticationError;
export type BillingError = API.BillingError;
export type ErrorObject = API.ErrorObject;
export type ErrorResponse = API.ErrorResponse;
export type GatewayTimeoutError = API.GatewayTimeoutError;
export type InvalidRequestError = API.InvalidRequestError;
export type NotFoundError = API.NotFoundError;
export type OverloadedError = API.OverloadedError;
export type PermissionError = API.PermissionError;
export type RateLimitError = API.RateLimitError;
}
export declare const HUMAN_PROMPT: string, AI_PROMPT: string;
export { toFile, fileFromPath } from "./uploads.js";
export { Anthropic as default } from "./client.js";
export { multipartFormRequestOptions, maybeMultipartFormRequestOptions, Uploadable, createForm, toFile, } from "./uploads.js";
export { APIPromise } from "./api-promise.js";
export { BaseAnthropic, Anthropic, ClientOptions, HUMAN_PROMPT, AI_PROMPT } from "./client.js";
export { PagePromise } from "./pagination.js";
export { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "./error.js";
export default Anthropic;
//# sourceMappingURL=index.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var _a;
exports = module.exports = function (...args) {
return new exports.default(...args)
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.AnthropicError = exports.fileFromPath = exports.toFile = exports.AI_PROMPT = exports.HUMAN_PROMPT = exports.Anthropic = void 0;
const Core = __importStar(require("./core.js"));
const Errors = __importStar(require("./error.js"));
const Pagination = __importStar(require("./pagination.js"));
const Uploads = __importStar(require("./uploads.js"));
const API = __importStar(require("./resources/index.js"));
const completions_1 = require("./resources/completions.js");
const models_1 = require("./resources/models.js");
const beta_1 = require("./resources/beta/beta.js");
const messages_1 = require("./resources/messages/messages.js");
/**
* API Client for interfacing with the Anthropic API.
*/
class Anthropic extends Core.APIClient {
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
*/
constructor({ baseURL = Core.readEnv('ANTHROPIC_BASE_URL'), apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null, authToken = Core.readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) {
const options = {
apiKey,
authToken,
...opts,
baseURL: baseURL || `https://api.anthropic.com`,
};
if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {
throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
}
super({
baseURL: options.baseURL,
timeout: options.timeout ?? 600000 /* 10 minutes */,
httpAgent: options.httpAgent,
maxRetries: options.maxRetries,
fetch: options.fetch,
});
this.completions = new API.Completions(this);
this.messages = new API.Messages(this);
this.models = new API.Models(this);
this.beta = new API.Beta(this);
this._options = options;
this.apiKey = apiKey;
this.authToken = authToken;
}
defaultQuery() {
return this._options.defaultQuery;
}
defaultHeaders(opts) {
return {
...super.defaultHeaders(opts),
...(this._options.dangerouslyAllowBrowser ?
{ 'anthropic-dangerous-direct-browser-access': 'true' }
: undefined),
'anthropic-version': '2023-06-01',
...this._options.defaultHeaders,
};
}
validateHeaders(headers, customHeaders) {
if (this.apiKey && headers['x-api-key']) {
return;
}
if (customHeaders['x-api-key'] === null) {
return;
}
if (this.authToken && headers['authorization']) {
return;
}
if (customHeaders['authorization'] === null) {
return;
}
throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
}
authHeaders(opts) {
const apiKeyAuth = this.apiKeyAuth(opts);
const bearerAuth = this.bearerAuth(opts);
if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {
return apiKeyAuth;
}
if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
return bearerAuth;
}
return {};
}
apiKeyAuth(opts) {
if (this.apiKey == null) {
return {};
}
return { 'X-Api-Key': this.apiKey };
}
bearerAuth(opts) {
if (this.authToken == null) {
return {};
}
return { Authorization: `Bearer ${this.authToken}` };
}
}
exports.Anthropic = Anthropic;
_a = Anthropic;
Anthropic.Anthropic = _a;
Anthropic.HUMAN_PROMPT = '\n\nHuman:';
Anthropic.AI_PROMPT = '\n\nAssistant:';
Anthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
Anthropic.AnthropicError = Errors.AnthropicError;
Anthropic.APIError = Errors.APIError;
Anthropic.APIConnectionError = Errors.APIConnectionError;
Anthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
Anthropic.APIUserAbortError = Errors.APIUserAbortError;
Anthropic.NotFoundError = Errors.NotFoundError;
Anthropic.ConflictError = Errors.ConflictError;
Anthropic.RateLimitError = Errors.RateLimitError;
Anthropic.BadRequestError = Errors.BadRequestError;
Anthropic.AuthenticationError = Errors.AuthenticationError;
Anthropic.InternalServerError = Errors.InternalServerError;
Anthropic.PermissionDeniedError = Errors.PermissionDeniedError;
Anthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
Anthropic.toFile = Uploads.toFile;
Anthropic.fileFromPath = Uploads.fileFromPath;
Anthropic.Completions = completions_1.Completions;
Anthropic.Messages = messages_1.Messages;
Anthropic.Models = models_1.Models;
Anthropic.ModelInfosPage = models_1.ModelInfosPage;
Anthropic.Beta = beta_1.Beta;
exports.HUMAN_PROMPT = Anthropic.HUMAN_PROMPT, exports.AI_PROMPT = Anthropic.AI_PROMPT;
exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.AnthropicError = exports.PagePromise = exports.AI_PROMPT = exports.HUMAN_PROMPT = exports.Anthropic = exports.BaseAnthropic = exports.APIPromise = exports.toFile = exports.createForm = exports.maybeMultipartFormRequestOptions = exports.multipartFormRequestOptions = exports.default = void 0;
var client_1 = require("./client.js");
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return client_1.Anthropic; } });
var uploads_1 = require("./uploads.js");
Object.defineProperty(exports, "multipartFormRequestOptions", { enumerable: true, get: function () { return uploads_1.multipartFormRequestOptions; } });
Object.defineProperty(exports, "maybeMultipartFormRequestOptions", { enumerable: true, get: function () { return uploads_1.maybeMultipartFormRequestOptions; } });
Object.defineProperty(exports, "createForm", { enumerable: true, get: function () { return uploads_1.createForm; } });
Object.defineProperty(exports, "toFile", { enumerable: true, get: function () { return uploads_1.toFile; } });
Object.defineProperty(exports, "fileFromPath", { enumerable: true, get: function () { return uploads_1.fileFromPath; } });
var api_promise_1 = require("./api-promise.js");
Object.defineProperty(exports, "APIPromise", { enumerable: true, get: function () { return api_promise_1.APIPromise; } });
var client_2 = require("./client.js");
Object.defineProperty(exports, "BaseAnthropic", { enumerable: true, get: function () { return client_2.BaseAnthropic; } });
Object.defineProperty(exports, "Anthropic", { enumerable: true, get: function () { return client_2.Anthropic; } });
Object.defineProperty(exports, "HUMAN_PROMPT", { enumerable: true, get: function () { return client_2.HUMAN_PROMPT; } });
Object.defineProperty(exports, "AI_PROMPT", { enumerable: true, get: function () { return client_2.AI_PROMPT; } });
var pagination_1 = require("./pagination.js");
Object.defineProperty(exports, "PagePromise", { enumerable: true, get: function () { return pagination_1.PagePromise; } });
var error_1 = require("./error.js");

@@ -177,4 +38,2 @@ Object.defineProperty(exports, "AnthropicError", { enumerable: true, get: function () { return error_1.AnthropicError; } });

Object.defineProperty(exports, "UnprocessableEntityError", { enumerable: true, get: function () { return error_1.UnprocessableEntityError; } });
exports = module.exports = Anthropic;
exports.default = Anthropic;
//# sourceMappingURL=index.js.map
import { type Response } from "../../_shims/index.js";
import { type Bytes } from "./line.js";

@@ -4,0 +3,0 @@ export declare class JSONLDecoder<T> {

export type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;

@@ -3,0 +4,0 @@ /**

import * as Core from '@anthropic-ai/sdk/core';
import { AnthropicError, APIUserAbortError } from '@anthropic-ai/sdk/error';
import { type ContentBlock, Messages, type Message, type MessageStreamEvent, type MessageParam, type MessageCreateParams, type MessageCreateParamsBase } from '@anthropic-ai/sdk/resources/messages';
import { type ReadableStream } from '@anthropic-ai/sdk/_shims/index';
import { AnthropicError, APIUserAbortError } from "../error.js";
import { type ContentBlock, Messages, type Message, type MessageStreamEvent, type MessageParam, type MessageCreateParams, type MessageCreateParamsBase } from "../resources/messages/index.js";
import { RequestOptions } from "../internal/request-options.js";
import { type ReadableStream } from "../internal/shim-types.js";
export interface MessageStreamEvents {

@@ -32,7 +32,7 @@ connect: () => void;

static fromReadableStream(stream: ReadableStream): MessageStream;
static createMessage(messages: Messages, params: MessageCreateParamsBase, options?: Core.RequestOptions): MessageStream;
static createMessage(messages: Messages, params: MessageCreateParamsBase, options?: RequestOptions): MessageStream;
protected _run(executor: () => Promise<any>): void;
protected _addMessageParam(message: MessageParam): void;
protected _addMessage(message: Message, emit?: boolean): void;
protected _createMessage(messages: Messages, params: MessageCreateParams, options?: Core.RequestOptions): Promise<void>;
protected _createMessage(messages: Messages, params: MessageCreateParams, options?: RequestOptions): Promise<void>;
protected _connected(): void;

@@ -92,3 +92,3 @@ get ended(): boolean;

protected _emitFinal(): void;
protected _fromReadableStream(readableStream: ReadableStream, options?: Core.RequestOptions): Promise<void>;
protected _fromReadableStream(readableStream: ReadableStream, options?: RequestOptions): Promise<void>;
[Symbol.asyncIterator](): AsyncIterator<MessageStreamEvent>;

@@ -95,0 +95,0 @@ toReadableStream(): ReadableStream;

@@ -16,4 +16,4 @@ "use strict";

exports.MessageStream = void 0;
const error_1 = require("@anthropic-ai/sdk/error");
const streaming_1 = require("@anthropic-ai/sdk/streaming");
const error_1 = require("../error.js");
const streaming_1 = require("../streaming.js");
const parser_1 = require("../_vendor/partial-json-parser/parser.js");

@@ -20,0 +20,0 @@ const JSON_BUF_PROPERTY = '__json_buf';

{
"name": "@anthropic-ai/sdk",
"version": "0.33.1",
"version": "0.34.0-alpha.0",
"description": "The official TypeScript library for the Anthropic API",

@@ -24,19 +24,3 @@ "author": "Anthropic <support@anthropic.com>",

},
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7"
},
"sideEffects": [
"./_shims/index.js",
"./_shims/index.mjs",
"./shims/node.js",
"./shims/node.mjs",
"./shims/web.js",
"./shims/web.mjs"
],
"dependencies": {},
"imports": {

@@ -47,37 +31,2 @@ "@anthropic-ai/sdk": ".",

"exports": {
"./_shims/auto/*": {
"deno": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"bun": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*-bun.js",
"default": "./_shims/auto/*-bun.mjs"
},
"browser": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"worker": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"workerd": {
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
"node": {
"types": "./_shims/auto/*-node.d.ts",
"require": "./_shims/auto/*-node.js",
"default": "./_shims/auto/*-node.mjs"
},
"types": "./_shims/auto/*.d.ts",
"require": "./_shims/auto/*.js",
"default": "./_shims/auto/*.mjs"
},
".": {

@@ -91,16 +40,123 @@ "require": {

},
"./*.mjs": {
"types": "./*.d.ts",
"default": "./*.mjs"
"./_vendor/*.mjs": {
"default": "./_vendor/*.mjs"
},
"./*.js": {
"types": "./*.d.ts",
"default": "./*.js"
"./_vendor/*.js": {
"default": "./_vendor/*.js"
},
"./*": {
"types": "./*.d.ts",
"require": "./*.js",
"default": "./*.mjs"
"./_vendor/*": {
"import": "./_vendor/*.mjs",
"require": "./_vendor/*.js"
},
"./api-promise": {
"import": "./api-promise.mjs",
"require": "./api-promise.js"
},
"./api-promise.js": {
"default": "./api-promise.js"
},
"./api-promise.mjs": {
"default": "./api-promise.mjs"
},
"./client": {
"import": "./client.mjs",
"require": "./client.js"
},
"./client.js": {
"default": "./client.js"
},
"./client.mjs": {
"default": "./client.mjs"
},
"./error": {
"import": "./error.mjs",
"require": "./error.js"
},
"./error.js": {
"default": "./error.js"
},
"./error.mjs": {
"default": "./error.mjs"
},
"./index": {
"import": "./index.mjs",
"require": "./index.js"
},
"./index.js": {
"default": "./index.js"
},
"./index.mjs": {
"default": "./index.mjs"
},
"./lib/*.mjs": {
"default": "./lib/*.mjs"
},
"./lib/*.js": {
"default": "./lib/*.js"
},
"./lib/*": {
"import": "./lib/*.mjs",
"require": "./lib/*.js"
},
"./pagination": {
"import": "./pagination.mjs",
"require": "./pagination.js"
},
"./pagination.js": {
"default": "./pagination.js"
},
"./pagination.mjs": {
"default": "./pagination.mjs"
},
"./resource": {
"import": "./resource.mjs",
"require": "./resource.js"
},
"./resource.js": {
"default": "./resource.js"
},
"./resource.mjs": {
"default": "./resource.mjs"
},
"./resources/*.mjs": {
"default": "./resources/*.mjs"
},
"./resources/*.js": {
"default": "./resources/*.js"
},
"./resources/*": {
"import": "./resources/*.mjs",
"require": "./resources/*.js"
},
"./streaming": {
"import": "./streaming.mjs",
"require": "./streaming.js"
},
"./streaming.js": {
"default": "./streaming.js"
},
"./streaming.mjs": {
"default": "./streaming.mjs"
},
"./uploads": {
"import": "./uploads.mjs",
"require": "./uploads.js"
},
"./uploads.js": {
"default": "./uploads.js"
},
"./uploads.mjs": {
"default": "./uploads.mjs"
},
"./version": {
"import": "./version.mjs",
"require": "./version.js"
},
"./version.js": {
"default": "./version.js"
},
"./version.mjs": {
"default": "./version.mjs"
}
}
}
}

@@ -1,2 +0,40 @@

import { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from "./core.js";
import type { Anthropic } from "./client.js";
import { FinalRequestOptions } from "./internal/request-options.js";
import { APIPromise } from "./api-promise.js";
import { type APIResponseProps } from "./internal/parse.js";
export type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;
export declare abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#private;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: Anthropic, response: Response, body: unknown, options: FinalRequestOptions);
abstract nextPageRequestOptions(): PageRequestOptions | 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: Anthropic, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass);
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
[Symbol.asyncIterator](): AsyncGenerator<Awaited<Item>, void, unknown>;
}
export interface PageResponse<Item> {

@@ -21,7 +59,6 @@ data: Array<Item>;

last_id: string | null;
constructor(client: APIClient, response: Response, body: PageResponse<Item>, options: FinalRequestOptions);
constructor(client: Anthropic, response: Response, body: PageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
nextPageParams(): Partial<PageParams> | null;
nextPageInfo(): PageInfo | null;
nextPageRequestOptions(): PageRequestOptions | null;
}
//# sourceMappingURL=pagination.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
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.Page = void 0;
const core_1 = require("./core.js");
class Page extends core_1.AbstractPage {
exports.Page = exports.PagePromise = exports.AbstractPage = void 0;
const error_1 = require("./error.js");
const parse_1 = require("./internal/parse.js");
const api_promise_1 = require("./api-promise.js");
const values_1 = require("./internal/utils/values.js");
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 error_1.AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
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 api_promise_1.APIPromise {
constructor(client, request, Page) {
super(request, async (props) => new Page(client, props.response, await (0, parse_1.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;
class Page extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);

@@ -17,24 +99,14 @@ this.data = body.data || [];

}
// @deprecated Please use `nextPageInfo()` instead
nextPageParams() {
const info = this.nextPageInfo();
if (!info)
return null;
if ('params' in info)
return info.params;
const params = Object.fromEntries(info.url.searchParams);
if (!Object.keys(params).length)
return null;
return params;
}
nextPageInfo() {
nextPageRequestOptions() {
if (this.options.query?.['before_id']) {
// in reverse
const firstId = this.first_id;
if (!firstId) {
const first_id = this.first_id;
if (!first_id) {
return null;
}
return {
params: {
before_id: firstId,
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
before_id: first_id,
},

@@ -48,3 +120,5 @@ };

return {
params: {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
after_id: cursor,

@@ -51,0 +125,0 @@ },

@@ -417,18 +417,20 @@ # Anthropic TypeScript API Library

By default, this library uses `node-fetch` in Node, and expects a global `fetch` function in other environments.
By default, this library expects a global `fetch` function is defined.
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"`:
If you want to use a different `fetch` function, you can either polyfill the global:
```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';
import fetch from 'my-fetch';
globalThis.fetch = fetch;
```
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)).
Or pass it to the client:
```ts
import fetch from 'my-fetch';
const client = new Anthropic({ fetch });
```
### Logging and middleware

@@ -485,2 +487,4 @@

## Frequently Asked Questions
## Semantic versioning

@@ -500,3 +504,3 @@

TypeScript >= 4.5 is supported.
TypeScript >= 4.9 is supported.

@@ -503,0 +507,0 @@ The following runtimes are supported:

@@ -1,6 +0,6 @@

import * as Core from "./core.js";
import { BaseAnthropic } from "./client.js";
export declare class APIResource {
protected _client: Core.APIClient;
constructor(client: Core.APIClient);
protected _client: BaseAnthropic;
constructor(client: BaseAnthropic);
}
//# sourceMappingURL=resource.d.ts.map

@@ -54,5 +54,5 @@ import { APIResource } from "../../resource.js";

export { type AnthropicBeta as AnthropicBeta, type BetaAPIError as BetaAPIError, type BetaAuthenticationError as BetaAuthenticationError, type BetaBillingError as BetaBillingError, type BetaError as BetaError, type BetaErrorResponse as BetaErrorResponse, type BetaGatewayTimeoutError as BetaGatewayTimeoutError, type BetaInvalidRequestError as BetaInvalidRequestError, type BetaNotFoundError as BetaNotFoundError, type BetaOverloadedError as BetaOverloadedError, type BetaPermissionError as BetaPermissionError, type BetaRateLimitError as BetaRateLimitError, };
export { Models as Models, type BetaModelInfo as BetaModelInfo, BetaModelInfosPage as BetaModelInfosPage, type ModelListParams as ModelListParams, };
export { Models as Models, type BetaModelInfo as BetaModelInfo, type BetaModelInfosPage as BetaModelInfosPage, type ModelListParams as ModelListParams, };
export { Messages as Messages, type BetaBase64PDFBlock as BetaBase64PDFBlock, type BetaBase64PDFSource as BetaBase64PDFSource, type BetaCacheControlEphemeral as BetaCacheControlEphemeral, type BetaContentBlock as BetaContentBlock, type BetaContentBlockParam as BetaContentBlockParam, type BetaImageBlockParam as BetaImageBlockParam, type BetaInputJSONDelta as BetaInputJSONDelta, type BetaMessage as BetaMessage, type BetaMessageDeltaUsage as BetaMessageDeltaUsage, type BetaMessageParam as BetaMessageParam, type BetaMessageTokensCount as BetaMessageTokensCount, type BetaMetadata as BetaMetadata, type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent, type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent, type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent, type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent, type BetaRawMessageStartEvent as BetaRawMessageStartEvent, type BetaRawMessageStopEvent as BetaRawMessageStopEvent, type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent, type BetaTextBlock as BetaTextBlock, type BetaTextBlockParam as BetaTextBlockParam, type BetaTextDelta as BetaTextDelta, type BetaTool as BetaTool, type BetaToolBash20241022 as BetaToolBash20241022, type BetaToolChoice as BetaToolChoice, type BetaToolChoiceAny as BetaToolChoiceAny, type BetaToolChoiceAuto as BetaToolChoiceAuto, type BetaToolChoiceTool as BetaToolChoiceTool, type BetaToolComputerUse20241022 as BetaToolComputerUse20241022, type BetaToolResultBlockParam as BetaToolResultBlockParam, type BetaToolTextEditor20241022 as BetaToolTextEditor20241022, type BetaToolUnion as BetaToolUnion, type BetaToolUseBlock as BetaToolUseBlock, type BetaToolUseBlockParam as BetaToolUseBlockParam, type BetaUsage as BetaUsage, type MessageCreateParams as MessageCreateParams, type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming as MessageCreateParamsStreaming, type MessageCountTokensParams as MessageCountTokensParams, };
}
//# sourceMappingURL=beta.d.ts.map

@@ -42,4 +42,3 @@ "use strict";

Beta.Models = models_1.Models;
Beta.BetaModelInfosPage = models_1.BetaModelInfosPage;
Beta.Messages = messages_1.Messages;
//# sourceMappingURL=beta.js.map
export { Beta, type AnthropicBeta, type BetaAPIError, type BetaAuthenticationError, type BetaBillingError, type BetaError, type BetaErrorResponse, type BetaGatewayTimeoutError, type BetaInvalidRequestError, type BetaNotFoundError, type BetaOverloadedError, type BetaPermissionError, type BetaRateLimitError, } from "./beta.js";
export { BetaModelInfosPage, Models, type BetaModelInfo, type ModelListParams } from "./models.js";
export { Messages, type BetaBase64PDFBlock, type BetaBase64PDFSource, type BetaCacheControlEphemeral, type BetaContentBlock, type BetaContentBlockParam, type BetaImageBlockParam, type BetaInputJSONDelta, type BetaMessage, type BetaMessageDeltaUsage, type BetaMessageParam, type BetaMessageTokensCount, type BetaMetadata, type BetaRawContentBlockDeltaEvent, type BetaRawContentBlockStartEvent, type BetaRawContentBlockStopEvent, type BetaRawMessageDeltaEvent, type BetaRawMessageStartEvent, type BetaRawMessageStopEvent, type BetaRawMessageStreamEvent, type BetaTextBlock, type BetaTextBlockParam, type BetaTextDelta, type BetaTool, type BetaToolBash20241022, type BetaToolChoice, type BetaToolChoiceAny, type BetaToolChoiceAuto, type BetaToolChoiceTool, type BetaToolComputerUse20241022, type BetaToolResultBlockParam, type BetaToolTextEditor20241022, type BetaToolUnion, type BetaToolUseBlock, type BetaToolUseBlockParam, type BetaUsage, type MessageCreateParams, type MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming, type MessageCountTokensParams, } from "./messages/index.js";
export { Models, type BetaModelInfo, type ModelListParams, type BetaModelInfosPage } from "./models.js";
//# sourceMappingURL=index.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Messages = exports.Models = exports.BetaModelInfosPage = exports.Beta = void 0;
exports.Models = exports.Messages = exports.Beta = void 0;
var beta_1 = require("./beta.js");
Object.defineProperty(exports, "Beta", { enumerable: true, get: function () { return beta_1.Beta; } });
var index_1 = require("./messages/index.js");
Object.defineProperty(exports, "Messages", { enumerable: true, get: function () { return index_1.Messages; } });
var models_1 = require("./models.js");
Object.defineProperty(exports, "BetaModelInfosPage", { enumerable: true, get: function () { return models_1.BetaModelInfosPage; } });
Object.defineProperty(exports, "Models", { enumerable: true, get: function () { return models_1.Models; } });
var index_1 = require("./messages/index.js");
Object.defineProperty(exports, "Messages", { enumerable: true, get: function () { return index_1.Messages; } });
//# sourceMappingURL=index.js.map
import { APIResource } from "../../../resource.js";
import * as Core from "../../../core.js";
import * as BetaAPI from "../beta.js";
import * as BetaMessagesAPI from "./messages.js";
import { Page, type PageParams } from "../../../pagination.js";
import { APIPromise } from "../../../api-promise.js";
import { Page, type PageParams, PagePromise } from "../../../pagination.js";
import { RequestOptions } from "../../../internal/request-options.js";
import { JSONLDecoder } from "../../../internal/decoders/jsonl.js";

@@ -15,3 +16,3 @@ export declare class Batches extends APIResource {

*/
create(params: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;
create(params: BatchCreateParams, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**

@@ -22,4 +23,3 @@ * This endpoint is idempotent and can be used to poll for Message Batch

*/
retrieve(messageBatchId: string, params?: BatchRetrieveParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;
retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;
retrieve(messageBatchID: string, params?: BatchRetrieveParams | null | undefined, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**

@@ -29,5 +29,10 @@ * List all Message Batches within a Workspace. Most recently created batches are

*/
list(params?: BatchListParams, options?: Core.RequestOptions): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;
list(options?: Core.RequestOptions): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;
list(params?: BatchListParams | null | undefined, options?: RequestOptions): PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*/
delete(messageBatchID: string, params?: BatchDeleteParams | null | undefined, options?: RequestOptions): APIPromise<BetaDeletedMessageBatch>;
/**
* Batches may be canceled any time before processing ends. Once cancellation is

@@ -43,4 +48,3 @@ * initiated, the batch enters a `canceling` state, at which time the system may

*/
cancel(messageBatchId: string, params?: BatchCancelParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;
cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;
cancel(messageBatchID: string, params?: BatchCancelParams | null | undefined, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**

@@ -53,6 +57,16 @@ * Streams the results of a Message Batch as a `.jsonl` file.

*/
results(messageBatchId: string, params?: BatchResultsParams, options?: Core.RequestOptions): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
results(messageBatchId: string, options?: Core.RequestOptions): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
results(messageBatchID: string, params?: BatchResultsParams | null | undefined, options?: RequestOptions): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
}
export declare class BetaMessageBatchesPage extends Page<BetaMessageBatch> {
export type BetaMessageBatchesPage = Page<BetaMessageBatch>;
export interface BetaDeletedMessageBatch {
/**
* ID of the Message Batch.
*/
id: string;
/**
* Deleted object type.
*
* For Message Batches, this is always `"message_batch_deleted"`.
*/
type: 'message_batch_deleted';
}

@@ -231,2 +245,8 @@ export interface BetaMessageBatch {

}
export interface BatchDeleteParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchCancelParams {

@@ -245,4 +265,4 @@ /**

export declare namespace Batches {
export { type BetaMessageBatch as BetaMessageBatch, type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts, type BetaMessageBatchResult as BetaMessageBatchResult, type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult, BetaMessageBatchesPage as BetaMessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchRetrieveParams as BatchRetrieveParams, type BatchListParams as BatchListParams, type BatchCancelParams as BatchCancelParams, type BatchResultsParams as BatchResultsParams, };
export { type BetaDeletedMessageBatch as BetaDeletedMessageBatch, type BetaMessageBatch as BetaMessageBatch, type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts, type BetaMessageBatchResult as BetaMessageBatchResult, type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult, type BetaMessageBatchesPage as BetaMessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchRetrieveParams as BatchRetrieveParams, type BatchListParams as BatchListParams, type BatchDeleteParams as BatchDeleteParams, type BatchCancelParams as BatchCancelParams, type BatchResultsParams as BatchResultsParams, };
}
//# sourceMappingURL=batches.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BetaMessageBatchesPage = exports.Batches = void 0;
exports.Batches = void 0;
const resource_1 = require("../../../resource.js");
const core_1 = require("../../../core.js");
const pagination_1 = require("../../../pagination.js");

@@ -29,8 +28,10 @@ const jsonl_1 = require("../../../internal/decoders/jsonl.js");

}
retrieve(messageBatchId, params = {}, options) {
if ((0, core_1.isRequestOptions)(params)) {
return this.retrieve(messageBatchId, {}, params);
}
const { betas } = params;
return this._client.get(`/v1/messages/batches/${messageBatchId}?beta=true`, {
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*/
retrieve(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(`/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,

@@ -43,8 +44,9 @@ headers: {

}
/**
* List all Message Batches within a Workspace. Most recently created batches are
* returned first.
*/
list(params = {}, options) {
if ((0, core_1.isRequestOptions)(params)) {
return this.list({}, params);
}
const { betas, ...query } = params;
return this._client.getAPIList('/v1/messages/batches?beta=true', BetaMessageBatchesPage, {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/messages/batches?beta=true', (pagination_1.Page), {
query,

@@ -58,8 +60,10 @@ ...options,

}
cancel(messageBatchId, params = {}, options) {
if ((0, core_1.isRequestOptions)(params)) {
return this.cancel(messageBatchId, {}, params);
}
const { betas } = params;
return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`, {
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*/
delete(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.delete(`/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,

@@ -72,11 +76,36 @@ headers: {

}
async results(messageBatchId, params = {}, options) {
if ((0, core_1.isRequestOptions)(params)) {
return this.results(messageBatchId, {}, params);
}
const batch = await this.retrieve(messageBatchId);
/**
* Batches may be canceled any time before processing ends. Once cancellation is
* initiated, the batch enters a `canceling` state, at which time the system may
* complete any in-progress, non-interruptible requests before finalizing
* cancellation.
*
* The number of canceled requests is specified in `request_counts`. To determine
* which requests were canceled, check the individual results within the batch.
* Note that cancellation may not result in any canceled requests if they were
* non-interruptible.
*/
cancel(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.post(`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
...options,
headers: {
'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
...options?.headers,
},
});
}
/**
* Streams the results of a Message Batch as a `.jsonl` file.
*
* Each line in the file is a JSON object containing the result of a single request
* in the Message Batch. Results are not guaranteed to be in the same order as
* requests. Use the `custom_id` field to match results to requests.
*/
async results(messageBatchID, params = {}, options) {
const batch = await this.retrieve(messageBatchID);
if (!batch.results_url) {
throw new error_1.AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
}
const { betas } = params;
const { betas } = params ?? {};
return this._client

@@ -95,6 +124,2 @@ .get(batch.results_url, {

exports.Batches = Batches;
class BetaMessageBatchesPage extends pagination_1.Page {
}
exports.BetaMessageBatchesPage = BetaMessageBatchesPage;
Batches.BetaMessageBatchesPage = BetaMessageBatchesPage;
//# sourceMappingURL=batches.js.map

@@ -1,3 +0,3 @@

export { BetaMessageBatchesPage, Batches, type BetaMessageBatch, type BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts, type BetaMessageBatchResult, type BetaMessageBatchSucceededResult, type BatchCreateParams, type BatchRetrieveParams, type BatchListParams, type BatchCancelParams, type BatchResultsParams, } from "./batches.js";
export { Batches, type BetaDeletedMessageBatch, type BetaMessageBatch, type BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts, type BetaMessageBatchResult, type BetaMessageBatchSucceededResult, type BatchCreateParams, type BatchRetrieveParams, type BatchListParams, type BatchDeleteParams, type BatchCancelParams, type BatchResultsParams, type BetaMessageBatchesPage, } from "./batches.js";
export { Messages, type BetaBase64PDFBlock, type BetaBase64PDFSource, type BetaCacheControlEphemeral, type BetaContentBlock, type BetaContentBlockParam, type BetaImageBlockParam, type BetaInputJSONDelta, type BetaMessage, type BetaMessageDeltaUsage, type BetaMessageParam, type BetaMessageTokensCount, type BetaMetadata, type BetaRawContentBlockDeltaEvent, type BetaRawContentBlockStartEvent, type BetaRawContentBlockStopEvent, type BetaRawMessageDeltaEvent, type BetaRawMessageStartEvent, type BetaRawMessageStopEvent, type BetaRawMessageStreamEvent, type BetaTextBlock, type BetaTextBlockParam, type BetaTextDelta, type BetaTool, type BetaToolBash20241022, type BetaToolChoice, type BetaToolChoiceAny, type BetaToolChoiceAuto, type BetaToolChoiceTool, type BetaToolComputerUse20241022, type BetaToolResultBlockParam, type BetaToolTextEditor20241022, type BetaToolUnion, type BetaToolUseBlock, type BetaToolUseBlockParam, type BetaUsage, type MessageCreateParams, type MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming, type MessageCountTokensParams, } from "./messages.js";
//# sourceMappingURL=index.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Messages = exports.Batches = exports.BetaMessageBatchesPage = void 0;
exports.Messages = exports.Batches = void 0;
var batches_1 = require("./batches.js");
Object.defineProperty(exports, "BetaMessageBatchesPage", { enumerable: true, get: function () { return batches_1.BetaMessageBatchesPage; } });
Object.defineProperty(exports, "Batches", { enumerable: true, get: function () { return batches_1.Batches; } });

@@ -8,0 +7,0 @@ var messages_1 = require("./messages.js");

import { APIResource } from "../../../resource.js";
import { APIPromise } from "../../../core.js";
import * as Core from "../../../core.js";
import * as MessagesMessagesAPI from "./messages.js";

@@ -8,4 +6,6 @@ import * as BetaAPI from "../beta.js";

import * as BatchesAPI from "./batches.js";
import { BatchCancelParams, BatchCreateParams, BatchListParams, BatchResultsParams, BatchRetrieveParams, Batches, BetaMessageBatch, BetaMessageBatchCanceledResult, BetaMessageBatchErroredResult, BetaMessageBatchExpiredResult, BetaMessageBatchIndividualResponse, BetaMessageBatchRequestCounts, BetaMessageBatchResult, BetaMessageBatchSucceededResult, BetaMessageBatchesPage } from "./batches.js";
import { BatchCancelParams, BatchCreateParams, BatchDeleteParams, BatchListParams, BatchResultsParams, BatchRetrieveParams, Batches, BetaDeletedMessageBatch, BetaMessageBatch, BetaMessageBatchCanceledResult, BetaMessageBatchErroredResult, BetaMessageBatchExpiredResult, BetaMessageBatchIndividualResponse, BetaMessageBatchRequestCounts, BetaMessageBatchResult, BetaMessageBatchSucceededResult, BetaMessageBatchesPage } from "./batches.js";
import { APIPromise } from "../../../api-promise.js";
import { Stream } from "../../../streaming.js";
import { RequestOptions } from "../../../internal/request-options.js";
export declare class Messages extends APIResource {

@@ -20,5 +20,5 @@ batches: BatchesAPI.Batches;

*/
create(params: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<BetaMessage>;
create(params: MessageCreateParamsStreaming, options?: Core.RequestOptions): APIPromise<Stream<BetaRawMessageStreamEvent>>;
create(params: MessageCreateParamsBase, options?: Core.RequestOptions): APIPromise<Stream<BetaRawMessageStreamEvent> | BetaMessage>;
create(params: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<BetaMessage>;
create(params: MessageCreateParamsStreaming, options?: RequestOptions): APIPromise<Stream<BetaRawMessageStreamEvent>>;
create(params: MessageCreateParamsBase, options?: RequestOptions): APIPromise<Stream<BetaRawMessageStreamEvent> | BetaMessage>;
/**

@@ -30,3 +30,3 @@ * Count the number of tokens in a Message.

*/
countTokens(params: MessageCountTokensParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageTokensCount>;
countTokens(params: MessageCountTokensParams, options?: RequestOptions): APIPromise<BetaMessageTokensCount>;
}

@@ -880,4 +880,4 @@ export interface BetaBase64PDFBlock {

export { type BetaBase64PDFBlock as BetaBase64PDFBlock, type BetaBase64PDFSource as BetaBase64PDFSource, type BetaCacheControlEphemeral as BetaCacheControlEphemeral, type BetaContentBlock as BetaContentBlock, type BetaContentBlockParam as BetaContentBlockParam, type BetaImageBlockParam as BetaImageBlockParam, type BetaInputJSONDelta as BetaInputJSONDelta, type BetaMessage as BetaMessage, type BetaMessageDeltaUsage as BetaMessageDeltaUsage, type BetaMessageParam as BetaMessageParam, type BetaMessageTokensCount as BetaMessageTokensCount, type BetaMetadata as BetaMetadata, type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent, type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent, type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent, type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent, type BetaRawMessageStartEvent as BetaRawMessageStartEvent, type BetaRawMessageStopEvent as BetaRawMessageStopEvent, type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent, type BetaTextBlock as BetaTextBlock, type BetaTextBlockParam as BetaTextBlockParam, type BetaTextDelta as BetaTextDelta, type BetaTool as BetaTool, type BetaToolBash20241022 as BetaToolBash20241022, type BetaToolChoice as BetaToolChoice, type BetaToolChoiceAny as BetaToolChoiceAny, type BetaToolChoiceAuto as BetaToolChoiceAuto, type BetaToolChoiceTool as BetaToolChoiceTool, type BetaToolComputerUse20241022 as BetaToolComputerUse20241022, type BetaToolResultBlockParam as BetaToolResultBlockParam, type BetaToolTextEditor20241022 as BetaToolTextEditor20241022, type BetaToolUnion as BetaToolUnion, type BetaToolUseBlock as BetaToolUseBlock, type BetaToolUseBlockParam as BetaToolUseBlockParam, type BetaUsage as BetaUsage, type MessageCreateParams as MessageCreateParams, type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming as MessageCreateParamsStreaming, type MessageCountTokensParams as MessageCountTokensParams, };
export { Batches as Batches, type BetaMessageBatch as BetaMessageBatch, type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts, type BetaMessageBatchResult as BetaMessageBatchResult, type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult, BetaMessageBatchesPage as BetaMessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchRetrieveParams as BatchRetrieveParams, type BatchListParams as BatchListParams, type BatchCancelParams as BatchCancelParams, type BatchResultsParams as BatchResultsParams, };
export { Batches as Batches, type BetaDeletedMessageBatch as BetaDeletedMessageBatch, type BetaMessageBatch as BetaMessageBatch, type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts, type BetaMessageBatchResult as BetaMessageBatchResult, type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult, type BetaMessageBatchesPage as BetaMessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchRetrieveParams as BatchRetrieveParams, type BatchListParams as BatchListParams, type BatchDeleteParams as BatchDeleteParams, type BatchCancelParams as BatchCancelParams, type BatchResultsParams as BatchResultsParams, };
}
//# sourceMappingURL=messages.d.ts.map

@@ -69,3 +69,2 @@ "use strict";

Messages.Batches = batches_1.Batches;
Messages.BetaMessageBatchesPage = batches_1.BetaMessageBatchesPage;
//# sourceMappingURL=messages.js.map
import { APIResource } from "../../resource.js";
import * as Core from "../../core.js";
import { Page, type PageParams } from "../../pagination.js";
import { APIPromise } from "../../api-promise.js";
import { Page, type PageParams, PagePromise } from "../../pagination.js";
import { RequestOptions } from "../../internal/request-options.js";
export declare class Models extends APIResource {

@@ -11,3 +12,3 @@ /**

*/
retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo>;
retrieve(modelID: string, options?: RequestOptions): APIPromise<BetaModelInfo>;
/**

@@ -19,7 +20,5 @@ * List available models.

*/
list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(query?: ModelListParams | null | undefined, options?: RequestOptions): PagePromise<BetaModelInfosPage, BetaModelInfo>;
}
export declare class BetaModelInfosPage extends Page<BetaModelInfo> {
}
export type BetaModelInfosPage = Page<BetaModelInfo>;
export interface BetaModelInfo {

@@ -49,4 +48,4 @@ /**

export declare namespace Models {
export { type BetaModelInfo as BetaModelInfo, BetaModelInfosPage as BetaModelInfosPage, type ModelListParams as ModelListParams, };
export { type BetaModelInfo as BetaModelInfo, type BetaModelInfosPage as BetaModelInfosPage, type ModelListParams as ModelListParams, };
}
//# sourceMappingURL=models.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BetaModelInfosPage = exports.Models = void 0;
exports.Models = void 0;
const resource_1 = require("../../resource.js");
const core_1 = require("../../core.js");
const pagination_1 = require("../../pagination.js");

@@ -15,17 +14,16 @@ class Models extends resource_1.APIResource {

*/
retrieve(modelId, options) {
return this._client.get(`/v1/models/${modelId}?beta=true`, options);
retrieve(modelID, options) {
return this._client.get(`/v1/models/${modelID}?beta=true`, options);
}
/**
* List available models.
*
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
*/
list(query = {}, options) {
if ((0, core_1.isRequestOptions)(query)) {
return this.list({}, query);
}
return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, { query, ...options });
return this._client.getAPIList('/v1/models?beta=true', (pagination_1.Page), { query, ...options });
}
}
exports.Models = Models;
class BetaModelInfosPage extends pagination_1.Page {
}
exports.BetaModelInfosPage = BetaModelInfosPage;
Models.BetaModelInfosPage = BetaModelInfosPage;
//# sourceMappingURL=models.js.map
import { APIResource } from "../resource.js";
import { APIPromise } from "../core.js";
import * as Core from "../core.js";
import * as CompletionsAPI from "./completions.js";
import * as MessagesAPI from "./messages/messages.js";
import { APIPromise } from "../api-promise.js";
import { Stream } from "../streaming.js";
import { RequestOptions } from "../internal/request-options.js";
export declare class Completions extends APIResource {

@@ -18,5 +18,5 @@ /**

*/
create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(body: CompletionCreateParamsStreaming, options?: Core.RequestOptions): APIPromise<Stream<Completion>>;
create(body: CompletionCreateParamsBase, options?: Core.RequestOptions): APIPromise<Stream<Completion> | Completion>;
create(body: CompletionCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Completion>;
create(body: CompletionCreateParamsStreaming, options?: RequestOptions): APIPromise<Stream<Completion>>;
create(body: CompletionCreateParamsBase, options?: RequestOptions): APIPromise<Stream<Completion> | Completion>;
}

@@ -23,0 +23,0 @@ export interface Completion {

@@ -5,3 +5,3 @@ export * from "./shared.js";

export { Messages, type Base64PDFSource, type CacheControlEphemeral, type ContentBlock, type ContentBlockDeltaEvent, type ContentBlockParam, type ContentBlockStartEvent, type ContentBlockStopEvent, type DocumentBlockParam, type ImageBlockParam, type InputJsonDelta, type InputJSONDelta, type Message, type MessageDeltaEvent, type MessageDeltaUsage, type MessageParam, type MessageStartEvent, type MessageStopEvent, type MessageStreamEvent, type MessageStreamParams, type MessageTokensCount, type Metadata, type Model, type RawContentBlockDeltaEvent, type RawContentBlockStartEvent, type RawContentBlockStopEvent, type RawMessageDeltaEvent, type RawMessageStartEvent, type RawMessageStopEvent, type RawMessageStreamEvent, type TextBlock, type TextBlockParam, type TextDelta, type Tool, type ToolChoice, type ToolChoiceAny, type ToolChoiceAuto, type ToolChoiceTool, type ToolResultBlockParam, type ToolUseBlock, type ToolUseBlockParam, type Usage, type MessageCreateParams, type MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming, type MessageCountTokensParams, } from "./messages/messages.js";
export { ModelInfosPage, Models, type ModelInfo, type ModelListParams } from "./models.js";
export { Models, type ModelInfo, type ModelListParams, type ModelInfosPage } from "./models.js";
//# sourceMappingURL=index.d.ts.map

@@ -18,3 +18,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Models = exports.ModelInfosPage = exports.Messages = exports.Completions = exports.Beta = void 0;
exports.Models = exports.Messages = exports.Completions = exports.Beta = void 0;
__exportStar(require("./shared.js"), exports);

@@ -28,4 +28,3 @@ var beta_1 = require("./beta/beta.js");

var models_1 = require("./models.js");
Object.defineProperty(exports, "ModelInfosPage", { enumerable: true, get: function () { return models_1.ModelInfosPage; } });
Object.defineProperty(exports, "Models", { enumerable: true, get: function () { return models_1.Models; } });
//# sourceMappingURL=index.js.map
import { APIResource } from "../../resource.js";
import * as Core from "../../core.js";
import * as Shared from "../shared.js";
import * as MessagesAPI from "./messages.js";
import { Page, type PageParams } from "../../pagination.js";
import { APIPromise } from "../../api-promise.js";
import { Page, type PageParams, PagePromise } from "../../pagination.js";
import { RequestOptions } from "../../internal/request-options.js";
import { JSONLDecoder } from "../../internal/decoders/jsonl.js";

@@ -15,3 +16,3 @@ export declare class Batches extends APIResource {

*/
create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<MessageBatch>;
create(body: BatchCreateParams, options?: RequestOptions): APIPromise<MessageBatch>;
/**

@@ -22,3 +23,3 @@ * This endpoint is idempotent and can be used to poll for Message Batch

*/
retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch>;
retrieve(messageBatchID: string, options?: RequestOptions): APIPromise<MessageBatch>;
/**

@@ -28,5 +29,10 @@ * List all Message Batches within a Workspace. Most recently created batches are

*/
list(query?: BatchListParams, options?: Core.RequestOptions): Core.PagePromise<MessageBatchesPage, MessageBatch>;
list(options?: Core.RequestOptions): Core.PagePromise<MessageBatchesPage, MessageBatch>;
list(query?: BatchListParams | null | undefined, options?: RequestOptions): PagePromise<MessageBatchesPage, MessageBatch>;
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*/
delete(messageBatchID: string, options?: RequestOptions): APIPromise<DeletedMessageBatch>;
/**
* Batches may be canceled any time before processing ends. Once cancellation is

@@ -42,3 +48,3 @@ * initiated, the batch enters a `canceling` state, at which time the system may

*/
cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch>;
cancel(messageBatchID: string, options?: RequestOptions): APIPromise<MessageBatch>;
/**

@@ -51,5 +57,16 @@ * Streams the results of a Message Batch as a `.jsonl` file.

*/
results(messageBatchId: string, options?: Core.RequestOptions): Promise<JSONLDecoder<MessageBatchIndividualResponse>>;
results(messageBatchID: string, options?: RequestOptions): Promise<JSONLDecoder<MessageBatchIndividualResponse>>;
}
export declare class MessageBatchesPage extends Page<MessageBatch> {
export type MessageBatchesPage = Page<MessageBatch>;
export interface DeletedMessageBatch {
/**
* ID of the Message Batch.
*/
id: string;
/**
* Deleted object type.
*
* For Message Batches, this is always `"message_batch_deleted"`.
*/
type: 'message_batch_deleted';
}

@@ -215,4 +232,4 @@ export interface MessageBatch {

export declare namespace Batches {
export { type MessageBatch as MessageBatch, type MessageBatchCanceledResult as MessageBatchCanceledResult, type MessageBatchErroredResult as MessageBatchErroredResult, type MessageBatchExpiredResult as MessageBatchExpiredResult, type MessageBatchIndividualResponse as MessageBatchIndividualResponse, type MessageBatchRequestCounts as MessageBatchRequestCounts, type MessageBatchResult as MessageBatchResult, type MessageBatchSucceededResult as MessageBatchSucceededResult, MessageBatchesPage as MessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchListParams as BatchListParams, };
export { type DeletedMessageBatch as DeletedMessageBatch, type MessageBatch as MessageBatch, type MessageBatchCanceledResult as MessageBatchCanceledResult, type MessageBatchErroredResult as MessageBatchErroredResult, type MessageBatchExpiredResult as MessageBatchExpiredResult, type MessageBatchIndividualResponse as MessageBatchIndividualResponse, type MessageBatchRequestCounts as MessageBatchRequestCounts, type MessageBatchResult as MessageBatchResult, type MessageBatchSucceededResult as MessageBatchSucceededResult, type MessageBatchesPage as MessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchListParams as BatchListParams, };
}
//# sourceMappingURL=batches.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageBatchesPage = exports.Batches = void 0;
exports.Batches = void 0;
const resource_1 = require("../../resource.js");
const core_1 = require("../../core.js");
const pagination_1 = require("../../pagination.js");

@@ -26,12 +25,21 @@ const jsonl_1 = require("../../internal/decoders/jsonl.js");

*/
retrieve(messageBatchId, options) {
return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);
retrieve(messageBatchID, options) {
return this._client.get(`/v1/messages/batches/${messageBatchID}`, options);
}
/**
* List all Message Batches within a Workspace. Most recently created batches are
* returned first.
*/
list(query = {}, options) {
if ((0, core_1.isRequestOptions)(query)) {
return this.list({}, query);
}
return this._client.getAPIList('/v1/messages/batches', MessageBatchesPage, { query, ...options });
return this._client.getAPIList('/v1/messages/batches', (pagination_1.Page), { query, ...options });
}
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*/
delete(messageBatchID, options) {
return this._client.delete(`/v1/messages/batches/${messageBatchID}`, options);
}
/**
* Batches may be canceled any time before processing ends. Once cancellation is

@@ -47,4 +55,4 @@ * initiated, the batch enters a `canceling` state, at which time the system may

*/
cancel(messageBatchId, options) {
return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);
cancel(messageBatchID, options) {
return this._client.post(`/v1/messages/batches/${messageBatchID}/cancel`, options);
}

@@ -58,4 +66,4 @@ /**

*/
async results(messageBatchId, options) {
const batch = await this.retrieve(messageBatchId);
async results(messageBatchID, options) {
const batch = await this.retrieve(messageBatchID);
if (!batch.results_url) {

@@ -70,6 +78,2 @@ throw new error_1.AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);

exports.Batches = Batches;
class MessageBatchesPage extends pagination_1.Page {
}
exports.MessageBatchesPage = MessageBatchesPage;
Batches.MessageBatchesPage = MessageBatchesPage;
//# sourceMappingURL=batches.js.map

@@ -1,3 +0,3 @@

export { MessageBatchesPage, Batches, type MessageBatch, type MessageBatchCanceledResult, type MessageBatchErroredResult, type MessageBatchExpiredResult, type MessageBatchIndividualResponse, type MessageBatchRequestCounts, type MessageBatchResult, type MessageBatchSucceededResult, type BatchCreateParams, type BatchListParams, } from "./batches.js";
export { Batches, type DeletedMessageBatch, type MessageBatch, type MessageBatchCanceledResult, type MessageBatchErroredResult, type MessageBatchExpiredResult, type MessageBatchIndividualResponse, type MessageBatchRequestCounts, type MessageBatchResult, type MessageBatchSucceededResult, type BatchCreateParams, type BatchListParams, type MessageBatchesPage, } from "./batches.js";
export { Messages, type Base64PDFSource, type CacheControlEphemeral, type ContentBlock, type ContentBlockDeltaEvent, type ContentBlockParam, type ContentBlockStartEvent, type ContentBlockStopEvent, type DocumentBlockParam, type ImageBlockParam, type InputJSONDelta, type Message, type MessageDeltaEvent, type MessageDeltaUsage, type MessageParam, type MessageStartEvent, type MessageStopEvent, type MessageStreamEvent, type MessageTokensCount, type Metadata, type Model, type RawContentBlockDeltaEvent, type RawContentBlockStartEvent, type RawContentBlockStopEvent, type RawMessageDeltaEvent, type RawMessageStartEvent, type RawMessageStopEvent, type RawMessageStreamEvent, type TextBlock, type TextBlockParam, type TextDelta, type Tool, type ToolChoice, type ToolChoiceAny, type ToolChoiceAuto, type ToolChoiceTool, type ToolResultBlockParam, type ToolUseBlock, type ToolUseBlockParam, type Usage, type MessageCreateParams, type MessageCreateParamsBase, type MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming, type MessageCountTokensParams, } from "./messages.js";
//# sourceMappingURL=index.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Messages = exports.Batches = exports.MessageBatchesPage = void 0;
exports.Messages = exports.Batches = void 0;
var batches_1 = require("./batches.js");
Object.defineProperty(exports, "MessageBatchesPage", { enumerable: true, get: function () { return batches_1.MessageBatchesPage; } });
Object.defineProperty(exports, "Batches", { enumerable: true, get: function () { return batches_1.Batches; } });

@@ -8,0 +7,0 @@ var messages_1 = require("./messages.js");

import { APIResource } from "../../resource.js";
import { APIPromise } from "../../core.js";
import * as Core from "../../core.js";
import * as MessagesAPI from "./messages.js";
import * as BatchesAPI from "./batches.js";
import { BatchCreateParams, BatchListParams, Batches, MessageBatch, MessageBatchCanceledResult, MessageBatchErroredResult, MessageBatchExpiredResult, MessageBatchIndividualResponse, MessageBatchRequestCounts, MessageBatchResult, MessageBatchSucceededResult, MessageBatchesPage } from "./batches.js";
import { BatchCreateParams, BatchListParams, Batches, DeletedMessageBatch, MessageBatch, MessageBatchCanceledResult, MessageBatchErroredResult, MessageBatchExpiredResult, MessageBatchIndividualResponse, MessageBatchRequestCounts, MessageBatchResult, MessageBatchSucceededResult, MessageBatchesPage } from "./batches.js";
import { APIPromise } from "../../api-promise.js";
import { Stream } from "../../streaming.js";
import { RequestOptions } from "../../internal/request-options.js";
import { MessageStream } from "../../lib/MessageStream.js";

@@ -19,9 +19,9 @@ export { MessageStream } from "../../lib/MessageStream.js";

*/
create(body: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Message>;
create(body: MessageCreateParamsStreaming, options?: Core.RequestOptions): APIPromise<Stream<RawMessageStreamEvent>>;
create(body: MessageCreateParamsBase, options?: Core.RequestOptions): APIPromise<Stream<RawMessageStreamEvent> | Message>;
create(body: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Message>;
create(body: MessageCreateParamsStreaming, options?: RequestOptions): APIPromise<Stream<RawMessageStreamEvent>>;
create(body: MessageCreateParamsBase, options?: RequestOptions): APIPromise<Stream<RawMessageStreamEvent> | Message>;
/**
* Create a Message stream
*/
stream(body: MessageStreamParams, options?: Core.RequestOptions): MessageStream;
stream(body: MessageStreamParams, options?: RequestOptions): MessageStream;
/**

@@ -33,3 +33,3 @@ * Count the number of tokens in a Message.

*/
countTokens(body: MessageCountTokensParams, options?: Core.RequestOptions): Core.APIPromise<MessageTokensCount>;
countTokens(body: MessageCountTokensParams, options?: RequestOptions): APIPromise<MessageTokensCount>;
}

@@ -859,4 +859,4 @@ export interface Base64PDFSource {

export { type Base64PDFSource as Base64PDFSource, type CacheControlEphemeral as CacheControlEphemeral, type ContentBlock as ContentBlock, type ContentBlockDeltaEvent as ContentBlockDeltaEvent, type ContentBlockParam as ContentBlockParam, type ContentBlockStartEvent as ContentBlockStartEvent, type ContentBlockStopEvent as ContentBlockStopEvent, type DocumentBlockParam as DocumentBlockParam, type ImageBlockParam as ImageBlockParam, type InputJsonDelta as InputJsonDelta, type InputJSONDelta as InputJSONDelta, type Message as Message, type MessageDeltaEvent as MessageDeltaEvent, type MessageDeltaUsage as MessageDeltaUsage, type MessageParam as MessageParam, type MessageStartEvent as MessageStartEvent, type MessageStopEvent as MessageStopEvent, type MessageStreamEvent as MessageStreamEvent, type MessageTokensCount as MessageTokensCount, type Metadata as Metadata, type Model as Model, type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent, type RawContentBlockStartEvent as RawContentBlockStartEvent, type RawContentBlockStopEvent as RawContentBlockStopEvent, type RawMessageDeltaEvent as RawMessageDeltaEvent, type RawMessageStartEvent as RawMessageStartEvent, type RawMessageStopEvent as RawMessageStopEvent, type RawMessageStreamEvent as RawMessageStreamEvent, type TextBlock as TextBlock, type TextBlockParam as TextBlockParam, type TextDelta as TextDelta, type Tool as Tool, type ToolChoice as ToolChoice, type ToolChoiceAny as ToolChoiceAny, type ToolChoiceAuto as ToolChoiceAuto, type ToolChoiceTool as ToolChoiceTool, type ToolResultBlockParam as ToolResultBlockParam, type ToolUseBlock as ToolUseBlock, type ToolUseBlockParam as ToolUseBlockParam, type Usage as Usage, type MessageCreateParams as MessageCreateParams, type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming as MessageCreateParamsStreaming, type MessageStreamParams as MessageStreamParams, type MessageCountTokensParams as MessageCountTokensParams, };
export { Batches as Batches, type MessageBatch as MessageBatch, type MessageBatchCanceledResult as MessageBatchCanceledResult, type MessageBatchErroredResult as MessageBatchErroredResult, type MessageBatchExpiredResult as MessageBatchExpiredResult, type MessageBatchIndividualResponse as MessageBatchIndividualResponse, type MessageBatchRequestCounts as MessageBatchRequestCounts, type MessageBatchResult as MessageBatchResult, type MessageBatchSucceededResult as MessageBatchSucceededResult, MessageBatchesPage as MessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchListParams as BatchListParams, };
export { Batches as Batches, type DeletedMessageBatch as DeletedMessageBatch, type MessageBatch as MessageBatch, type MessageBatchCanceledResult as MessageBatchCanceledResult, type MessageBatchErroredResult as MessageBatchErroredResult, type MessageBatchExpiredResult as MessageBatchExpiredResult, type MessageBatchIndividualResponse as MessageBatchIndividualResponse, type MessageBatchRequestCounts as MessageBatchRequestCounts, type MessageBatchResult as MessageBatchResult, type MessageBatchSucceededResult as MessageBatchSucceededResult, type MessageBatchesPage as MessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchListParams as BatchListParams, };
}
//# sourceMappingURL=messages.d.ts.map

@@ -75,3 +75,2 @@ "use strict";

Messages.Batches = batches_1.Batches;
Messages.MessageBatchesPage = batches_1.MessageBatchesPage;
//# sourceMappingURL=messages.js.map
import { APIResource } from "../resource.js";
import * as Core from "../core.js";
import { Page, type PageParams } from "../pagination.js";
import { APIPromise } from "../api-promise.js";
import { Page, type PageParams, PagePromise } from "../pagination.js";
import { RequestOptions } from "../internal/request-options.js";
export declare class Models extends APIResource {

@@ -11,3 +12,3 @@ /**

*/
retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo>;
retrieve(modelID: string, options?: RequestOptions): APIPromise<ModelInfo>;
/**

@@ -19,7 +20,5 @@ * List available models.

*/
list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(query?: ModelListParams | null | undefined, options?: RequestOptions): PagePromise<ModelInfosPage, ModelInfo>;
}
export declare class ModelInfosPage extends Page<ModelInfo> {
}
export type ModelInfosPage = Page<ModelInfo>;
export interface ModelInfo {

@@ -49,4 +48,4 @@ /**

export declare namespace Models {
export { type ModelInfo as ModelInfo, ModelInfosPage as ModelInfosPage, type ModelListParams as ModelListParams, };
export { type ModelInfo as ModelInfo, type ModelInfosPage as ModelInfosPage, type ModelListParams as ModelListParams, };
}
//# sourceMappingURL=models.d.ts.map
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelInfosPage = exports.Models = void 0;
exports.Models = void 0;
const resource_1 = require("../resource.js");
const core_1 = require("../core.js");
const pagination_1 = require("../pagination.js");

@@ -15,17 +14,16 @@ class Models extends resource_1.APIResource {

*/
retrieve(modelId, options) {
return this._client.get(`/v1/models/${modelId}`, options);
retrieve(modelID, options) {
return this._client.get(`/v1/models/${modelID}`, options);
}
/**
* List available models.
*
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
*/
list(query = {}, options) {
if ((0, core_1.isRequestOptions)(query)) {
return this.list({}, query);
}
return this._client.getAPIList('/v1/models', ModelInfosPage, { query, ...options });
return this._client.getAPIList('/v1/models', (pagination_1.Page), { query, ...options });
}
}
exports.Models = Models;
class ModelInfosPage extends pagination_1.Page {
}
exports.ModelInfosPage = ModelInfosPage;
Models.ModelInfosPage = ModelInfosPage;
//# sourceMappingURL=models.js.map
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { castToError, Headers } from "./core.js";
import { castToError } from './internal/errors';

@@ -19,3 +19,3 @@ export class AnthropicError extends Error {}

readonly request_id: string | null | undefined;
readonly requestID: string | null | undefined;

@@ -26,3 +26,3 @@ constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {

this.headers = headers;
this.request_id = headers?.['request-id'];
this.requestID = headers?.get('request-id');
this.error = error;

@@ -29,0 +29,0 @@ }

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { type Agent } from "./_shims/index.js";
import * as Core from "./core.js";
import * as Errors from "./error.js";
import * as Pagination from "./pagination.js";
import { type PageParams, PageResponse } from "./pagination.js";
import * as Uploads from "./uploads.js";
import * as API from "./resources/index.js";
import {
Completion,
CompletionCreateParams,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
Completions,
} from "./resources/completions.js";
import { ModelInfo, ModelInfosPage, ModelListParams, Models } from "./resources/models.js";
import {
AnthropicBeta,
Beta,
BetaAPIError,
BetaAuthenticationError,
BetaBillingError,
BetaError,
BetaErrorResponse,
BetaGatewayTimeoutError,
BetaInvalidRequestError,
BetaNotFoundError,
BetaOverloadedError,
BetaPermissionError,
BetaRateLimitError,
} from "./resources/beta/beta.js";
import {
Base64PDFSource,
CacheControlEphemeral,
ContentBlock,
ContentBlockDeltaEvent,
ContentBlockParam,
ContentBlockStartEvent,
ContentBlockStopEvent,
DocumentBlockParam,
ImageBlockParam,
InputJSONDelta,
Message,
MessageCountTokensParams,
MessageCreateParams,
MessageCreateParamsNonStreaming,
MessageCreateParamsStreaming,
MessageDeltaEvent,
MessageDeltaUsage,
MessageParam,
MessageStartEvent,
MessageStopEvent,
MessageStreamEvent,
MessageStreamParams,
MessageTokensCount,
Messages,
Metadata,
Model,
RawContentBlockDeltaEvent,
RawContentBlockStartEvent,
RawContentBlockStopEvent,
RawMessageDeltaEvent,
RawMessageStartEvent,
RawMessageStopEvent,
RawMessageStreamEvent,
TextBlock,
TextBlockParam,
TextDelta,
Tool,
ToolChoice,
ToolChoiceAny,
ToolChoiceAuto,
ToolChoiceTool,
ToolResultBlockParam,
ToolUseBlock,
ToolUseBlockParam,
Usage,
} from "./resources/messages/messages.js";
export { Anthropic as default } from './client';
export interface ClientOptions {
/**
* Defaults to process.env['ANTHROPIC_API_KEY'].
*/
apiKey?: string | null | undefined;
/**
* Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].
*/
authToken?: string | null | undefined;
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*
* Defaults to process.env['ANTHROPIC_BASE_URL'].
*/
baseURL?: string | null | undefined;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*/
timeout?: number;
/**
* An HTTP agent used to manage HTTP(S) connections.
*
* If not provided, an agent will be constructed by default in the Node.js environment,
* otherwise no agent is used.
*/
httpAgent?: Agent;
/**
* Specify a custom `fetch` function implementation.
*
* If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
* defined globally.
*/
fetch?: Core.Fetch | undefined;
/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
*
* @default 2
*/
maxRetries?: number;
/**
* Default headers to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* header to `undefined` or `null` in request options.
*/
defaultHeaders?: Core.Headers;
/**
* Default query parameters to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* param to `undefined` in request options.
*/
defaultQuery?: Core.DefaultQuery;
/**
* By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
* Only set this option to `true` if you understand the risks and have appropriate mitigations in place.
*/
dangerouslyAllowBrowser?: boolean;
}
/**
* API Client for interfacing with the Anthropic API.
*/
export class Anthropic extends Core.APIClient {
apiKey: string | null;
authToken: string | null;
private _options: ClientOptions;
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
*/
constructor({
baseURL = Core.readEnv('ANTHROPIC_BASE_URL'),
apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null,
authToken = Core.readEnv('ANTHROPIC_AUTH_TOKEN') ?? null,
...opts
}: ClientOptions = {}) {
const options: ClientOptions = {
apiKey,
authToken,
...opts,
baseURL: baseURL || `https://api.anthropic.com`,
};
if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {
throw new Errors.AnthropicError(
"It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n",
);
}
super({
baseURL: options.baseURL!,
timeout: options.timeout ?? 600000 /* 10 minutes */,
httpAgent: options.httpAgent,
maxRetries: options.maxRetries,
fetch: options.fetch,
});
this._options = options;
this.apiKey = apiKey;
this.authToken = authToken;
}
completions: API.Completions = new API.Completions(this);
messages: API.Messages = new API.Messages(this);
models: API.Models = new API.Models(this);
beta: API.Beta = new API.Beta(this);
protected override defaultQuery(): Core.DefaultQuery | undefined {
return this._options.defaultQuery;
}
protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
return {
...super.defaultHeaders(opts),
...(this._options.dangerouslyAllowBrowser ?
{ 'anthropic-dangerous-direct-browser-access': 'true' }
: undefined),
'anthropic-version': '2023-06-01',
...this._options.defaultHeaders,
};
}
protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) {
if (this.apiKey && headers['x-api-key']) {
return;
}
if (customHeaders['x-api-key'] === null) {
return;
}
if (this.authToken && headers['authorization']) {
return;
}
if (customHeaders['authorization'] === null) {
return;
}
throw new Error(
'Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted',
);
}
protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
const apiKeyAuth = this.apiKeyAuth(opts);
const bearerAuth = this.bearerAuth(opts);
if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {
return apiKeyAuth;
}
if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
return bearerAuth;
}
return {};
}
protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
if (this.apiKey == null) {
return {};
}
return { 'X-Api-Key': this.apiKey };
}
protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers {
if (this.authToken == null) {
return {};
}
return { Authorization: `Bearer ${this.authToken}` };
}
static Anthropic = this;
static HUMAN_PROMPT = '\n\nHuman:';
static AI_PROMPT = '\n\nAssistant:';
static DEFAULT_TIMEOUT = 600000; // 10 minutes
static AnthropicError = Errors.AnthropicError;
static APIError = Errors.APIError;
static APIConnectionError = Errors.APIConnectionError;
static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
static APIUserAbortError = Errors.APIUserAbortError;
static NotFoundError = Errors.NotFoundError;
static ConflictError = Errors.ConflictError;
static RateLimitError = Errors.RateLimitError;
static BadRequestError = Errors.BadRequestError;
static AuthenticationError = Errors.AuthenticationError;
static InternalServerError = Errors.InternalServerError;
static PermissionDeniedError = Errors.PermissionDeniedError;
static UnprocessableEntityError = Errors.UnprocessableEntityError;
static toFile = Uploads.toFile;
static fileFromPath = Uploads.fileFromPath;
}
Anthropic.Completions = Completions;
Anthropic.Messages = Messages;
Anthropic.Models = Models;
Anthropic.ModelInfosPage = ModelInfosPage;
Anthropic.Beta = Beta;
export declare namespace Anthropic {
export type RequestOptions = Core.RequestOptions;
export import Page = Pagination.Page;
export { type PageParams as PageParams, type PageResponse as PageResponse };
export {
Completions as Completions,
type Completion as Completion,
type CompletionCreateParams as CompletionCreateParams,
type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,
type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,
};
export {
Messages as Messages,
type Base64PDFSource as Base64PDFSource,
type CacheControlEphemeral as CacheControlEphemeral,
type ContentBlock as ContentBlock,
type ContentBlockDeltaEvent as ContentBlockDeltaEvent,
type ContentBlockParam as ContentBlockParam,
type ContentBlockStartEvent as ContentBlockStartEvent,
type ContentBlockStopEvent as ContentBlockStopEvent,
type DocumentBlockParam as DocumentBlockParam,
type ImageBlockParam as ImageBlockParam,
type InputJSONDelta as InputJSONDelta,
type Message as Message,
type MessageDeltaEvent as MessageDeltaEvent,
type MessageDeltaUsage as MessageDeltaUsage,
type MessageParam as MessageParam,
type MessageStartEvent as MessageStartEvent,
type MessageStopEvent as MessageStopEvent,
type MessageStreamEvent as MessageStreamEvent,
type MessageTokensCount as MessageTokensCount,
type Metadata as Metadata,
type Model as Model,
type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent,
type RawContentBlockStartEvent as RawContentBlockStartEvent,
type RawContentBlockStopEvent as RawContentBlockStopEvent,
type RawMessageDeltaEvent as RawMessageDeltaEvent,
type RawMessageStartEvent as RawMessageStartEvent,
type RawMessageStopEvent as RawMessageStopEvent,
type RawMessageStreamEvent as RawMessageStreamEvent,
type TextBlock as TextBlock,
type TextBlockParam as TextBlockParam,
type TextDelta as TextDelta,
type Tool as Tool,
type ToolChoice as ToolChoice,
type ToolChoiceAny as ToolChoiceAny,
type ToolChoiceAuto as ToolChoiceAuto,
type ToolChoiceTool as ToolChoiceTool,
type ToolResultBlockParam as ToolResultBlockParam,
type ToolUseBlock as ToolUseBlock,
type ToolUseBlockParam as ToolUseBlockParam,
type Usage as Usage,
type MessageCreateParams as MessageCreateParams,
type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming as MessageCreateParamsStreaming,
type MessageStreamParams as MessageStreamParams,
type MessageCountTokensParams as MessageCountTokensParams,
};
export {
Models as Models,
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
type ModelListParams as ModelListParams,
};
export {
Beta as Beta,
type AnthropicBeta as AnthropicBeta,
type BetaAPIError as BetaAPIError,
type BetaAuthenticationError as BetaAuthenticationError,
type BetaBillingError as BetaBillingError,
type BetaError as BetaError,
type BetaErrorResponse as BetaErrorResponse,
type BetaGatewayTimeoutError as BetaGatewayTimeoutError,
type BetaInvalidRequestError as BetaInvalidRequestError,
type BetaNotFoundError as BetaNotFoundError,
type BetaOverloadedError as BetaOverloadedError,
type BetaPermissionError as BetaPermissionError,
type BetaRateLimitError as BetaRateLimitError,
};
export type APIErrorObject = API.APIErrorObject;
export type AuthenticationError = API.AuthenticationError;
export type BillingError = API.BillingError;
export type ErrorObject = API.ErrorObject;
export type ErrorResponse = API.ErrorResponse;
export type GatewayTimeoutError = API.GatewayTimeoutError;
export type InvalidRequestError = API.InvalidRequestError;
export type NotFoundError = API.NotFoundError;
export type OverloadedError = API.OverloadedError;
export type PermissionError = API.PermissionError;
export type RateLimitError = API.RateLimitError;
}
export const { HUMAN_PROMPT, AI_PROMPT } = Anthropic;
export { toFile, fileFromPath } from "./uploads.js";
export {
multipartFormRequestOptions,
maybeMultipartFormRequestOptions,
Uploadable,
createForm,
toFile,
} from './uploads';
export { APIPromise } from './api-promise';
export { BaseAnthropic, Anthropic, ClientOptions, HUMAN_PROMPT, AI_PROMPT } from './client';
export { PagePromise } from './pagination';
export {
AnthropicError,

@@ -421,4 +29,2 @@ APIError,

UnprocessableEntityError,
} from "./error.js";
export default Anthropic;
} from './error';

@@ -1,5 +0,4 @@

import { AnthropicError } from "../../error.js";
import { readableStreamAsyncIterable } from "../../streaming.js";
import { type Response } from "../../_shims/index.js";
import { LineDecoder, type Bytes } from "./line.js";
import { AnthropicError } from '../../error';
import { readableStreamAsyncIterable } from '../../streaming';
import { LineDecoder, type Bytes } from './line';

@@ -6,0 +5,0 @@ export class JSONLDecoder<T> {

@@ -1,2 +0,2 @@

import { AnthropicError } from "../../error.js";
import { AnthropicError } from '../../error';

@@ -3,0 +3,0 @@ export type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;

@@ -1,3 +0,2 @@

import * as Core from "../core.js";
import { AnthropicError, APIUserAbortError } from "../error.js";
import { AnthropicError, APIUserAbortError } from '../error';
import {

@@ -12,6 +11,7 @@ type ContentBlock,

type TextBlock,
} from "../resources/messages.js";
import { type ReadableStream } from "../_shims/index.js";
import { Stream } from "../streaming.js";
import { partialParse } from "../_vendor/partial-json-parser/parser.js";
} from '../resources/messages';
import { Stream } from '../streaming';
import { partialParse } from '../_vendor/partial-json-parser/parser';
import { RequestOptions } from '../internal/request-options';
import { type ReadableStream } from '../internal/shim-types';

@@ -95,3 +95,3 @@ export interface MessageStreamEvents {

params: MessageCreateParamsBase,
options?: Core.RequestOptions,
options?: RequestOptions,
): MessageStream {

@@ -133,3 +133,3 @@ const runner = new MessageStream();

params: MessageCreateParams,
options?: Core.RequestOptions,
options?: RequestOptions,
): Promise<void> {

@@ -422,3 +422,3 @@ const signal = options?.signal;

readableStream: ReadableStream,
options?: Core.RequestOptions,
options?: RequestOptions,
): Promise<void> {

@@ -425,0 +425,0 @@ const signal = options?.signal;

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from "./core.js";
import type { Anthropic } from './client';
import { AnthropicError } from './error';
import { FinalRequestOptions } from './internal/request-options';
import { defaultParseResponse, type WithRequestID } from './internal/parse';
import { APIPromise } from './api-promise';
import { type APIResponseProps } from './internal/parse';
import { maybeObj } from './internal/utils/values';
export type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;
export abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#client: Anthropic;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: Anthropic, response: Response, body: unknown, options: FinalRequestOptions) {
this.#client = client;
this.options = options;
this.response = response;
this.body = body;
}
abstract nextPageRequestOptions(): PageRequestOptions | null;
abstract getPaginatedItems(): Item[];
hasNextPage(): boolean {
const items = this.getPaginatedItems();
if (!items.length) return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage(): Promise<this> {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new AnthropicError(
'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
);
}
return await this.#client.requestAPIList(this.constructor as any, nextOptions);
}
async *iterPages(): AsyncGenerator<this> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let page: this = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[Symbol.asyncIterator](): AsyncGenerator<Item> {
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<
PageClass extends AbstractPage<Item>,
Item = ReturnType<PageClass['getPaginatedItems']>[number],
>
extends APIPromise<PageClass>
implements AsyncIterable<Item>
{
constructor(
client: Anthropic,
request: Promise<APIResponseProps>,
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
) {
super(
request,
async (props) =>
new Page(
client,
props.response,
await defaultParseResponse(props),
props.options,
) as WithRequestID<PageClass>,
);
}
/**
* 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 interface PageResponse<Item> {

@@ -35,3 +145,3 @@ data: Array<Item>;

constructor(client: APIClient, response: Response, body: PageResponse<Item>, options: FinalRequestOptions) {
constructor(client: Anthropic, response: Response, body: PageResponse<Item>, options: FinalRequestOptions) {
super(client, response, body, options);

@@ -49,17 +159,7 @@

// @deprecated Please use `nextPageInfo()` instead
nextPageParams(): Partial<PageParams> | null {
const info = this.nextPageInfo();
if (!info) return null;
if ('params' in info) return info.params;
const params = Object.fromEntries(info.url.searchParams);
if (!Object.keys(params).length) return null;
return params;
}
nextPageInfo(): PageInfo | null {
nextPageRequestOptions(): PageRequestOptions | null {
if ((this.options.query as Record<string, unknown>)?.['before_id']) {
// in reverse
const firstId = this.first_id;
if (!firstId) {
const first_id = this.first_id;
if (!first_id) {
return null;

@@ -69,4 +169,6 @@ }

return {
params: {
before_id: firstId,
...this.options,
query: {
...maybeObj(this.options.query),
before_id: first_id,
},

@@ -82,3 +184,5 @@ };

return {
params: {
...this.options,
query: {
...maybeObj(this.options.query),
after_id: cursor,

@@ -85,0 +189,0 @@ },

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import * as Core from "./core.js";
import { BaseAnthropic } from './client';
export class APIResource {
protected _client: Core.APIClient;
protected _client: BaseAnthropic;
constructor(client: Core.APIClient) {
constructor(client: BaseAnthropic) {
this._client = client;
}
}
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../resource.js";
import * as ModelsAPI from "./models.js";
import { BetaModelInfo, BetaModelInfosPage, ModelListParams, Models } from "./models.js";
import * as MessagesAPI from "./messages/messages.js";
import { APIResource } from '../../resource';
import * as ModelsAPI from './models';
import { BetaModelInfo, BetaModelInfosPage, ModelListParams, Models } from './models';
import * as MessagesAPI from './messages/messages';
import {

@@ -48,3 +48,3 @@ BetaBase64PDFBlock,

Messages,
} from "./messages/messages.js";
} from './messages/messages';

@@ -136,3 +136,2 @@ export class Beta extends APIResource {

Beta.Models = Models;
Beta.BetaModelInfosPage = BetaModelInfosPage;
Beta.Messages = Messages;

@@ -159,3 +158,3 @@

type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
type BetaModelInfosPage as BetaModelInfosPage,
type ModelListParams as ModelListParams,

@@ -162,0 +161,0 @@ };

@@ -17,4 +17,3 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

type BetaRateLimitError,
} from "./beta.js";
export { BetaModelInfosPage, Models, type BetaModelInfo, type ModelListParams } from "./models.js";
} from './beta';
export {

@@ -61,2 +60,3 @@ Messages,

type MessageCountTokensParams,
} from "./messages/index.js";
} from './messages/index';
export { Models, type BetaModelInfo, type ModelListParams, type BetaModelInfosPage } from './models';
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../../resource.js";
import { isRequestOptions } from "../../../core.js";
import * as Core from "../../../core.js";
import * as BetaAPI from "../beta.js";
import * as BetaMessagesAPI from "./messages.js";
import { Page, type PageParams } from "../../../pagination.js";
import { JSONLDecoder } from "../../../internal/decoders/jsonl.js";
import { AnthropicError } from "../../../error.js";
import { APIResource } from '../../../resource';
import * as BetaAPI from '../beta';
import * as BetaMessagesAPI from './messages';
import { APIPromise } from '../../../api-promise';
import { Page, type PageParams, PagePromise } from '../../../pagination';
import { RequestOptions } from '../../../internal/request-options';
import { JSONLDecoder } from '../../../internal/decoders/jsonl';
import { AnthropicError } from '../../../error';

@@ -20,3 +20,3 @@ export class Batches extends APIResource {

*/
create(params: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch> {
create(params: BatchCreateParams, options?: RequestOptions): APIPromise<BetaMessageBatch> {
const { betas, ...body } = params;

@@ -39,17 +39,8 @@ return this._client.post('/v1/messages/batches?beta=true', {

retrieve(
messageBatchId: string,
params?: BatchRetrieveParams,
options?: Core.RequestOptions,
): Core.APIPromise<BetaMessageBatch>;
retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;
retrieve(
messageBatchId: string,
params: BatchRetrieveParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.APIPromise<BetaMessageBatch> {
if (isRequestOptions(params)) {
return this.retrieve(messageBatchId, {}, params);
}
const { betas } = params;
return this._client.get(`/v1/messages/batches/${messageBatchId}?beta=true`, {
messageBatchID: string,
params: BatchRetrieveParams | null | undefined = {},
options?: RequestOptions,
): APIPromise<BetaMessageBatch> {
const { betas } = params ?? {};
return this._client.get(`/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,

@@ -68,15 +59,7 @@ headers: {

list(
params?: BatchListParams,
options?: Core.RequestOptions,
): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;
list(options?: Core.RequestOptions): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;
list(
params: BatchListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch> {
if (isRequestOptions(params)) {
return this.list({}, params);
}
const { betas, ...query } = params;
return this._client.getAPIList('/v1/messages/batches?beta=true', BetaMessageBatchesPage, {
params: BatchListParams | null | undefined = {},
options?: RequestOptions,
): PagePromise<BetaMessageBatchesPage, BetaMessageBatch> {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/messages/batches?beta=true', Page<BetaMessageBatch>, {
query,

@@ -92,2 +75,22 @@ ...options,

/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*/
delete(
messageBatchID: string,
params: BatchDeleteParams | null | undefined = {},
options?: RequestOptions,
): APIPromise<BetaDeletedMessageBatch> {
const { betas } = params ?? {};
return this._client.delete(`/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,
headers: {
'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
...options?.headers,
},
});
}
/**
* Batches may be canceled any time before processing ends. Once cancellation is

@@ -104,17 +107,8 @@ * initiated, the batch enters a `canceling` state, at which time the system may

cancel(
messageBatchId: string,
params?: BatchCancelParams,
options?: Core.RequestOptions,
): Core.APIPromise<BetaMessageBatch>;
cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;
cancel(
messageBatchId: string,
params: BatchCancelParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.APIPromise<BetaMessageBatch> {
if (isRequestOptions(params)) {
return this.cancel(messageBatchId, {}, params);
}
const { betas } = params;
return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`, {
messageBatchID: string,
params: BatchCancelParams | null | undefined = {},
options?: RequestOptions,
): APIPromise<BetaMessageBatch> {
const { betas } = params ?? {};
return this._client.post(`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
...options,

@@ -136,20 +130,7 @@ headers: {

async results(
messageBatchId: string,
params?: BatchResultsParams,
options?: Core.RequestOptions,
): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
async results(
messageBatchId: string,
options?: Core.RequestOptions,
): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
async results(
messageBatchId: string,
params: BatchResultsParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
messageBatchID: string,
params: BatchResultsParams | null | undefined = {},
options?: RequestOptions,
): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>> {
if (isRequestOptions(params)) {
return this.results(messageBatchId, {}, params);
}
const batch = await this.retrieve(messageBatchId);
const batch = await this.retrieve(messageBatchID);
if (!batch.results_url) {

@@ -161,3 +142,3 @@ throw new AnthropicError(

const { betas } = params;
const { betas } = params ?? {};
return this._client

@@ -176,4 +157,18 @@ .get(batch.results_url, {

export class BetaMessageBatchesPage extends Page<BetaMessageBatch> {}
export type BetaMessageBatchesPage = Page<BetaMessageBatch>;
export interface BetaDeletedMessageBatch {
/**
* ID of the Message Batch.
*/
id: string;
/**
* Deleted object type.
*
* For Message Batches, this is always `"message_batch_deleted"`.
*/
type: 'message_batch_deleted';
}
export interface BetaMessageBatch {

@@ -385,2 +380,9 @@ /**

export interface BatchDeleteParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchCancelParams {

@@ -400,6 +402,5 @@ /**

Batches.BetaMessageBatchesPage = BetaMessageBatchesPage;
export declare namespace Batches {
export {
type BetaDeletedMessageBatch as BetaDeletedMessageBatch,
type BetaMessageBatch as BetaMessageBatch,

@@ -413,6 +414,7 @@ type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,

type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,
BetaMessageBatchesPage as BetaMessageBatchesPage,
type BetaMessageBatchesPage as BetaMessageBatchesPage,
type BatchCreateParams as BatchCreateParams,
type BatchRetrieveParams as BatchRetrieveParams,
type BatchListParams as BatchListParams,
type BatchDeleteParams as BatchDeleteParams,
type BatchCancelParams as BatchCancelParams,

@@ -419,0 +421,0 @@ type BatchResultsParams as BatchResultsParams,

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export {
BetaMessageBatchesPage,
Batches,
type BetaDeletedMessageBatch,
type BetaMessageBatch,

@@ -17,5 +17,7 @@ type BetaMessageBatchCanceledResult,

type BatchListParams,
type BatchDeleteParams,
type BatchCancelParams,
type BatchResultsParams,
} from "./batches.js";
type BetaMessageBatchesPage,
} from './batches';
export {

@@ -62,2 +64,2 @@ Messages,

type MessageCountTokensParams,
} from "./messages.js";
} from './messages';
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../../resource.js";
import { APIPromise } from "../../../core.js";
import * as Core from "../../../core.js";
import * as MessagesMessagesAPI from "./messages.js";
import * as BetaAPI from "../beta.js";
import * as MessagesAPI from "../../messages/messages.js";
import * as BatchesAPI from "./batches.js";
import { APIResource } from '../../../resource';
import * as MessagesMessagesAPI from './messages';
import * as BetaAPI from '../beta';
import * as MessagesAPI from '../../messages/messages';
import * as BatchesAPI from './batches';
import {
BatchCancelParams,
BatchCreateParams,
BatchDeleteParams,
BatchListParams,

@@ -17,2 +16,3 @@ BatchResultsParams,

Batches,
BetaDeletedMessageBatch,
BetaMessageBatch,

@@ -27,4 +27,6 @@ BetaMessageBatchCanceledResult,

BetaMessageBatchesPage,
} from "./batches.js";
import { Stream } from "../../../streaming.js";
} from './batches';
import { APIPromise } from '../../../api-promise';
import { Stream } from '../../../streaming';
import { RequestOptions } from '../../../internal/request-options';

@@ -41,14 +43,14 @@ export class Messages extends APIResource {

*/
create(params: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<BetaMessage>;
create(params: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<BetaMessage>;
create(
params: MessageCreateParamsStreaming,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<Stream<BetaRawMessageStreamEvent>>;
create(
params: MessageCreateParamsBase,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<Stream<BetaRawMessageStreamEvent> | BetaMessage>;
create(
params: MessageCreateParams,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<BetaMessage> | APIPromise<Stream<BetaRawMessageStreamEvent>> {

@@ -76,4 +78,4 @@ const { betas, ...body } = params;

params: MessageCountTokensParams,
options?: Core.RequestOptions,
): Core.APIPromise<BetaMessageTokensCount> {
options?: RequestOptions,
): APIPromise<BetaMessageTokensCount> {
const { betas, ...body } = params;

@@ -1075,3 +1077,2 @@ return this._client.post('/v1/messages/count_tokens?beta=true', {

Messages.Batches = Batches;
Messages.BetaMessageBatchesPage = BetaMessageBatchesPage;

@@ -1123,2 +1124,3 @@ export declare namespace Messages {

Batches as Batches,
type BetaDeletedMessageBatch as BetaDeletedMessageBatch,
type BetaMessageBatch as BetaMessageBatch,

@@ -1132,6 +1134,7 @@ type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,

type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,
BetaMessageBatchesPage as BetaMessageBatchesPage,
type BetaMessageBatchesPage as BetaMessageBatchesPage,
type BatchCreateParams as BatchCreateParams,
type BatchRetrieveParams as BatchRetrieveParams,
type BatchListParams as BatchListParams,
type BatchDeleteParams as BatchDeleteParams,
type BatchCancelParams as BatchCancelParams,

@@ -1138,0 +1141,0 @@ type BatchResultsParams as BatchResultsParams,

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../resource.js";
import { isRequestOptions } from "../../core.js";
import * as Core from "../../core.js";
import { Page, type PageParams } from "../../pagination.js";
import { APIResource } from '../../resource';
import { APIPromise } from '../../api-promise';
import { Page, type PageParams, PagePromise } from '../../pagination';
import { RequestOptions } from '../../internal/request-options';

@@ -15,4 +15,4 @@ export class Models extends APIResource {

*/
retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo> {
return this._client.get(`/v1/models/${modelId}?beta=true`, options);
retrieve(modelID: string, options?: RequestOptions): APIPromise<BetaModelInfo> {
return this._client.get(`/v1/models/${modelID}?beta=true`, options);
}

@@ -27,18 +27,10 @@

list(
query?: ModelListParams,
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(
query: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo> {
if (isRequestOptions(query)) {
return this.list({}, query);
}
return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, { query, ...options });
query: ModelListParams | null | undefined = {},
options?: RequestOptions,
): PagePromise<BetaModelInfosPage, BetaModelInfo> {
return this._client.getAPIList('/v1/models?beta=true', Page<BetaModelInfo>, { query, ...options });
}
}
export class BetaModelInfosPage extends Page<BetaModelInfo> {}
export type BetaModelInfosPage = Page<BetaModelInfo>;

@@ -72,10 +64,8 @@ export interface BetaModelInfo {

Models.BetaModelInfosPage = BetaModelInfosPage;
export declare namespace Models {
export {
type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
type BetaModelInfosPage as BetaModelInfosPage,
type ModelListParams as ModelListParams,
};
}
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../resource.js";
import { APIPromise } from "../core.js";
import * as Core from "../core.js";
import * as CompletionsAPI from "./completions.js";
import * as MessagesAPI from "./messages/messages.js";
import { Stream } from "../streaming.js";
import { APIResource } from '../resource';
import * as CompletionsAPI from './completions';
import * as MessagesAPI from './messages/messages';
import { APIPromise } from '../api-promise';
import { Stream } from '../streaming';
import { RequestOptions } from '../internal/request-options';

@@ -21,14 +21,11 @@ export class Completions extends APIResource {

*/
create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(body: CompletionCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Completion>;
create(body: CompletionCreateParamsStreaming, options?: RequestOptions): APIPromise<Stream<Completion>>;
create(
body: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): APIPromise<Stream<Completion>>;
create(
body: CompletionCreateParamsBase,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<Stream<Completion> | Completion>;
create(
body: CompletionCreateParams,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<Completion> | APIPromise<Stream<Completion>> {

@@ -35,0 +32,0 @@ return this._client.post('/v1/complete', {

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export * from "./shared.js";
export * from './shared';
export {

@@ -18,3 +18,3 @@ Beta,

type BetaRateLimitError,
} from "./beta/beta.js";
} from './beta/beta';
export {

@@ -26,3 +26,3 @@ Completions,

type CompletionCreateParamsStreaming,
} from "./completions.js";
} from './completions';
export {

@@ -75,3 +75,3 @@ Messages,

type MessageCountTokensParams,
} from "./messages/messages.js";
export { ModelInfosPage, Models, type ModelInfo, type ModelListParams } from "./models.js";
} from './messages/messages';
export { Models, type ModelInfo, type ModelListParams, type ModelInfosPage } from './models';
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../resource.js";
import { isRequestOptions } from "../../core.js";
import * as Core from "../../core.js";
import * as Shared from "../shared.js";
import * as MessagesAPI from "./messages.js";
import { Page, type PageParams } from "../../pagination.js";
import { JSONLDecoder } from "../../internal/decoders/jsonl.js";
import { AnthropicError } from "../../error.js";
import { APIResource } from '../../resource';
import * as Shared from '../shared';
import * as MessagesAPI from './messages';
import { APIPromise } from '../../api-promise';
import { Page, type PageParams, PagePromise } from '../../pagination';
import { RequestOptions } from '../../internal/request-options';
import { JSONLDecoder } from '../../internal/decoders/jsonl';
import { AnthropicError } from '../../error';

@@ -20,3 +20,3 @@ export class Batches extends APIResource {

*/
create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
create(body: BatchCreateParams, options?: RequestOptions): APIPromise<MessageBatch> {
return this._client.post('/v1/messages/batches', { body, ...options });

@@ -30,4 +30,4 @@ }

*/
retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);
retrieve(messageBatchID: string, options?: RequestOptions): APIPromise<MessageBatch> {
return this._client.get(`/v1/messages/batches/${messageBatchID}`, options);
}

@@ -40,17 +40,18 @@

list(
query?: BatchListParams,
options?: Core.RequestOptions,
): Core.PagePromise<MessageBatchesPage, MessageBatch>;
list(options?: Core.RequestOptions): Core.PagePromise<MessageBatchesPage, MessageBatch>;
list(
query: BatchListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<MessageBatchesPage, MessageBatch> {
if (isRequestOptions(query)) {
return this.list({}, query);
}
return this._client.getAPIList('/v1/messages/batches', MessageBatchesPage, { query, ...options });
query: BatchListParams | null | undefined = {},
options?: RequestOptions,
): PagePromise<MessageBatchesPage, MessageBatch> {
return this._client.getAPIList('/v1/messages/batches', Page<MessageBatch>, { query, ...options });
}
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*/
delete(messageBatchID: string, options?: RequestOptions): APIPromise<DeletedMessageBatch> {
return this._client.delete(`/v1/messages/batches/${messageBatchID}`, options);
}
/**
* Batches may be canceled any time before processing ends. Once cancellation is

@@ -66,4 +67,4 @@ * initiated, the batch enters a `canceling` state, at which time the system may

*/
cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);
cancel(messageBatchID: string, options?: RequestOptions): APIPromise<MessageBatch> {
return this._client.post(`/v1/messages/batches/${messageBatchID}/cancel`, options);
}

@@ -79,6 +80,6 @@

async results(
messageBatchId: string,
options?: Core.RequestOptions,
messageBatchID: string,
options?: RequestOptions,
): Promise<JSONLDecoder<MessageBatchIndividualResponse>> {
const batch = await this.retrieve(messageBatchId);
const batch = await this.retrieve(messageBatchID);
if (!batch.results_url) {

@@ -96,4 +97,18 @@ throw new AnthropicError(

export class MessageBatchesPage extends Page<MessageBatch> {}
export type MessageBatchesPage = Page<MessageBatch>;
export interface DeletedMessageBatch {
/**
* ID of the Message Batch.
*/
id: string;
/**
* Deleted object type.
*
* For Message Batches, this is always `"message_batch_deleted"`.
*/
type: 'message_batch_deleted';
}
export interface MessageBatch {

@@ -288,6 +303,5 @@ /**

Batches.MessageBatchesPage = MessageBatchesPage;
export declare namespace Batches {
export {
type DeletedMessageBatch as DeletedMessageBatch,
type MessageBatch as MessageBatch,

@@ -301,3 +315,3 @@ type MessageBatchCanceledResult as MessageBatchCanceledResult,

type MessageBatchSucceededResult as MessageBatchSucceededResult,
MessageBatchesPage as MessageBatchesPage,
type MessageBatchesPage as MessageBatchesPage,
type BatchCreateParams as BatchCreateParams,

@@ -304,0 +318,0 @@ type BatchListParams as BatchListParams,

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export {
MessageBatchesPage,
Batches,
type DeletedMessageBatch,
type MessageBatch,

@@ -16,3 +16,4 @@ type MessageBatchCanceledResult,

type BatchListParams,
} from "./batches.js";
type MessageBatchesPage,
} from './batches';
export {

@@ -64,2 +65,2 @@ Messages,

type MessageCountTokensParams,
} from "./messages.js";
} from './messages';
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../resource.js";
import { APIPromise } from "../../core.js";
import * as Core from "../../core.js";
import * as MessagesAPI from "./messages.js";
import * as BatchesAPI from "./batches.js";
import { APIResource } from '../../resource';
import * as MessagesAPI from './messages';
import * as BatchesAPI from './batches';
import {

@@ -12,2 +10,3 @@ BatchCreateParams,

Batches,
DeletedMessageBatch,
MessageBatch,

@@ -22,7 +21,9 @@ MessageBatchCanceledResult,

MessageBatchesPage,
} from "./batches.js";
import { Stream } from "../../streaming.js";
import { MessageStream } from "../../lib/MessageStream.js";
} from './batches';
import { APIPromise } from '../../api-promise';
import { Stream } from '../../streaming';
import { RequestOptions } from '../../internal/request-options';
import { MessageStream } from '../../lib/MessageStream';
export { MessageStream } from "../../lib/MessageStream.js";
export { MessageStream } from '../../lib/MessageStream';

@@ -39,14 +40,14 @@ export class Messages extends APIResource {

*/
create(body: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Message>;
create(body: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Message>;
create(
body: MessageCreateParamsStreaming,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<Stream<RawMessageStreamEvent>>;
create(
body: MessageCreateParamsBase,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<Stream<RawMessageStreamEvent> | Message>;
create(
body: MessageCreateParams,
options?: Core.RequestOptions,
options?: RequestOptions,
): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {

@@ -71,3 +72,3 @@ if (body.model in DEPRECATED_MODELS) {

*/
stream(body: MessageStreamParams, options?: Core.RequestOptions): MessageStream {
stream(body: MessageStreamParams, options?: RequestOptions): MessageStream {
return MessageStream.createMessage(this, body, options);

@@ -82,6 +83,3 @@ }

*/
countTokens(
body: MessageCountTokensParams,
options?: Core.RequestOptions,
): Core.APIPromise<MessageTokensCount> {
countTokens(body: MessageCountTokensParams, options?: RequestOptions): APIPromise<MessageTokensCount> {
return this._client.post('/v1/messages/count_tokens', { body, ...options });

@@ -1069,3 +1067,2 @@ }

Messages.Batches = Batches;
Messages.MessageBatchesPage = MessageBatchesPage;

@@ -1123,2 +1120,3 @@ export declare namespace Messages {

Batches as Batches,
type DeletedMessageBatch as DeletedMessageBatch,
type MessageBatch as MessageBatch,

@@ -1132,3 +1130,3 @@ type MessageBatchCanceledResult as MessageBatchCanceledResult,

type MessageBatchSucceededResult as MessageBatchSucceededResult,
MessageBatchesPage as MessageBatchesPage,
type MessageBatchesPage as MessageBatchesPage,
type BatchCreateParams as BatchCreateParams,

@@ -1135,0 +1133,0 @@ type BatchListParams as BatchListParams,

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../resource.js";
import { isRequestOptions } from "../core.js";
import * as Core from "../core.js";
import { Page, type PageParams } from "../pagination.js";
import { APIResource } from '../resource';
import { APIPromise } from '../api-promise';
import { Page, type PageParams, PagePromise } from '../pagination';
import { RequestOptions } from '../internal/request-options';

@@ -15,4 +15,4 @@ export class Models extends APIResource {

*/
retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo> {
return this._client.get(`/v1/models/${modelId}`, options);
retrieve(modelID: string, options?: RequestOptions): APIPromise<ModelInfo> {
return this._client.get(`/v1/models/${modelID}`, options);
}

@@ -26,16 +26,11 @@

*/
list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(
query: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<ModelInfosPage, ModelInfo> {
if (isRequestOptions(query)) {
return this.list({}, query);
}
return this._client.getAPIList('/v1/models', ModelInfosPage, { query, ...options });
query: ModelListParams | null | undefined = {},
options?: RequestOptions,
): PagePromise<ModelInfosPage, ModelInfo> {
return this._client.getAPIList('/v1/models', Page<ModelInfo>, { query, ...options });
}
}
export class ModelInfosPage extends Page<ModelInfo> {}
export type ModelInfosPage = Page<ModelInfo>;

@@ -69,10 +64,8 @@ export interface ModelInfo {

Models.ModelInfosPage = ModelInfosPage;
export declare namespace Models {
export {
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
type ModelInfosPage as ModelInfosPage,
type ModelListParams as ModelListParams,
};
}

@@ -1,7 +0,7 @@

import { ReadableStream, type Response } from "./_shims/index.js";
import { AnthropicError } from "./error.js";
import { LineDecoder } from "./internal/decoders/line.js";
import { AnthropicError } from './error';
import { type ReadableStream } from './internal/shim-types';
import { makeReadableStream } from './internal/shims';
import { LineDecoder } from './internal/decoders/line';
import { createResponseHeaders } from "./core.js";
import { APIError } from "./error.js";
import { APIError } from './error';

@@ -69,8 +69,3 @@ type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;

if (sse.event === 'error') {
throw APIError.generate(
undefined,
`SSE Error: ${sse.data}`,
sse.data,
createResponseHeaders(response.headers),
);
throw APIError.generate(undefined, `SSE Error: ${sse.data}`, sse.data, response.headers);
}

@@ -181,3 +176,3 @@ }

return new ReadableStream({
return makeReadableStream({
async start() {

@@ -184,0 +179,0 @@ iter = self[Symbol.asyncIterator]();

@@ -8,5 +8,5 @@ {

"target": "es2015",
"lib": ["DOM"],
"lib": ["DOM", "DOM.Iterable"],
"moduleResolution": "node"
}
}

@@ -1,13 +0,5 @@

import { type RequestOptions } from "./core.js";
import {
FormData,
File,
type Blob,
type FilePropertyBag,
getMultipartRequestOptions,
type FsReadStream,
isFsReadStream,
} from "./_shims/index.js";
import { MultipartBody } from "./_shims/MultipartBody.js";
export { fileFromPath } from "./_shims/index.js";
import { type RequestOptions } from './internal/request-options';
import { type FilePropertyBag } from './internal/builtin-types';
import { isFsReadStreamLike, type FsReadStreamLike } from './internal/shims';
import './internal/polyfill/file.node.js';

@@ -26,6 +18,6 @@ type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;

*/
export type Uploadable = FileLike | ResponseLike | FsReadStream;
export type Uploadable = FileLike | ResponseLike | FsReadStreamLike;
/**
* Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.
* Intended to match web.Blob, node.Blob, undici.Blob, etc.
*/

@@ -41,8 +33,19 @@ export interface BlobLike {

slice(start?: number, end?: number): BlobLike;
// unfortunately @types/node-fetch@^2.6.4 doesn't type the arrayBuffer method
}
/**
* Intended to match web.File, node.File, node-fetch.File, etc.
* This check adds the arrayBuffer() method type because it is available and used at runtime
*/
export const isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise<ArrayBuffer> } =>
value != null &&
typeof value === 'object' &&
typeof value.size === 'number' &&
typeof value.type === 'string' &&
typeof value.text === 'function' &&
typeof value.slice === 'function' &&
typeof value.arrayBuffer === 'function';
/**
* Intended to match web.File, node.File, undici.File, etc.
*/
export interface FileLike extends BlobLike {

@@ -54,5 +57,16 @@ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */

}
declare var FileClass: {
prototype: FileLike;
new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): FileLike;
};
export const isFileLike = (value: any): value is FileLike =>
value != null &&
typeof value === 'object' &&
typeof value.name === 'string' &&
typeof value.lastModified === 'number' &&
isBlobLike(value);
/**
* Intended to match web.Response, node.Response, node-fetch.Response, etc.
* Intended to match web.Response, node.Response, undici.Response, etc.
*/

@@ -70,24 +84,4 @@ export interface ResponseLike {

export const isFileLike = (value: any): value is FileLike =>
value != null &&
typeof value === 'object' &&
typeof value.name === 'string' &&
typeof value.lastModified === 'number' &&
isBlobLike(value);
/**
* The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
* adds the arrayBuffer() method type because it is available and used at runtime
*/
export const isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise<ArrayBuffer> } =>
value != null &&
typeof value === 'object' &&
typeof value.size === 'number' &&
typeof value.type === 'string' &&
typeof value.text === 'function' &&
typeof value.slice === 'function' &&
typeof value.arrayBuffer === 'function';
export const isUploadable = (value: any): value is Uploadable => {
return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
return isFileLike(value) || isResponseLike(value) || isFsReadStreamLike(value);
};

@@ -98,2 +92,16 @@

/**
* Construct a `File` instance. This is used to ensure a helpful error is thrown
* for environments that don't define a global `File` yet and so that we don't
* accidentally rely on a global `File` type in our annotations.
*/
function makeFile(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): FileLike {
const File = (globalThis as any).File as typeof FileClass | undefined;
if (typeof File === 'undefined') {
throw new Error('`File` is not defined as a global which is required for file uploads');
}
return new File(fileBits, fileName, options);
}
/**
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats

@@ -129,3 +137,3 @@ * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s

return new File(data, name, options);
return makeFile(data, name, options);
}

@@ -144,3 +152,3 @@

return new File(bits, name, options);
return makeFile(bits, name, options);
}

@@ -197,5 +205,2 @@

export const isMultipartBody = (body: any): body is MultipartBody =>
body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';
/**

@@ -205,16 +210,14 @@ * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.

*/
export const maybeMultipartFormRequestOptions = async <T = Record<string, unknown>>(
opts: RequestOptions<T>,
): Promise<RequestOptions<T | MultipartBody>> => {
export const maybeMultipartFormRequestOptions = async (opts: RequestOptions): Promise<RequestOptions> => {
if (!hasUploadableValue(opts.body)) return opts;
const form = await createForm(opts.body);
return getMultipartRequestOptions(form, opts);
return { ...opts, body: await createForm(opts.body) };
};
export const multipartFormRequestOptions = async <T = Record<string, unknown>>(
opts: RequestOptions<T>,
): Promise<RequestOptions<T | MultipartBody>> => {
const form = await createForm(opts.body);
return getMultipartRequestOptions(form, opts);
type MultipartFormRequestOptions = Omit<RequestOptions, 'body'> & { body: unknown };
export const multipartFormRequestOptions = async (
opts: MultipartFormRequestOptions,
): Promise<RequestOptions> => {
return { ...opts, body: await createForm(opts.body) };
};

@@ -252,3 +255,3 @@

const file = await toFile(value);
form.append(key, file as File);
form.append(key, file as any);
} else if (Array.isArray(value)) {

@@ -255,0 +258,0 @@ await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));

@@ -1,1 +0,1 @@

export const VERSION = '0.33.1'; // x-release-please-version
export const VERSION = '0.34.0-alpha.0'; // x-release-please-version
import { ReadableStream, type Response } from "./_shims/index.js";
import { type ReadableStream } from "./internal/shim-types.js";
export type ServerSentEvent = {

@@ -4,0 +4,0 @@ event: string | null;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readableStreamAsyncIterable = exports._decodeChunks = exports._iterSSEMessages = exports.Stream = void 0;
const index_1 = require("./_shims/index.js");
const error_1 = require("./error.js");
const shims_1 = require("./internal/shims.js");
const line_1 = require("./internal/decoders/line.js");
const core_1 = require("./core.js");
const error_2 = require("./error.js");

@@ -53,3 +52,3 @@ class Stream {

if (sse.event === 'error') {
throw error_2.APIError.generate(undefined, `SSE Error: ${sse.data}`, sse.data, (0, core_1.createResponseHeaders)(response.headers));
throw error_2.APIError.generate(undefined, `SSE Error: ${sse.data}`, sse.data, response.headers);
}

@@ -157,3 +156,3 @@ }

const encoder = new TextEncoder();
return new index_1.ReadableStream({
return (0, shims_1.makeReadableStream)({
async start() {

@@ -160,0 +159,0 @@ iter = self[Symbol.asyncIterator]();

@@ -1,5 +0,7 @@

import { type RequestOptions } from "./core.js";
import { FormData, type Blob, type FilePropertyBag, type FsReadStream } from "./_shims/index.js";
import { MultipartBody } from "./_shims/MultipartBody.js";
export { fileFromPath } from "./_shims/index.js";
import { type RequestOptions } from "./internal/request-options.js";
import { type FilePropertyBag } from "./internal/builtin-types.js";
import { type FsReadStreamLike } from "./internal/shims.js";
import "./internal/polyfill/file.node.js";
type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;

@@ -16,5 +18,5 @@ export type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView;

*/
export type Uploadable = FileLike | ResponseLike | FsReadStream;
export type Uploadable = FileLike | ResponseLike | FsReadStreamLike;
/**
* Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.
* Intended to match web.Blob, node.Blob, undici.Blob, etc.
*/

@@ -32,4 +34,10 @@ export interface BlobLike {

/**
* Intended to match web.File, node.File, node-fetch.File, etc.
* This check adds the arrayBuffer() method type because it is available and used at runtime
*/
export declare const isBlobLike: (value: any) => value is BlobLike & {
arrayBuffer(): Promise<ArrayBuffer>;
};
/**
* Intended to match web.File, node.File, undici.File, etc.
*/
export interface FileLike extends BlobLike {

@@ -41,4 +49,5 @@ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */

}
export declare const isFileLike: (value: any) => value is FileLike;
/**
* Intended to match web.Response, node.Response, node-fetch.Response, etc.
* Intended to match web.Response, node.Response, undici.Response, etc.
*/

@@ -50,10 +59,2 @@ export interface ResponseLike {

export declare const isResponseLike: (value: any) => value is ResponseLike;
export declare const isFileLike: (value: any) => value is FileLike;
/**
* The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
* adds the arrayBuffer() method type because it is available and used at runtime
*/
export declare const isBlobLike: (value: any) => value is BlobLike & {
arrayBuffer(): Promise<ArrayBuffer>;
};
export declare const isUploadable: (value: any) => value is Uploadable;

@@ -71,3 +72,2 @@ export type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;

export declare function toFile(value: ToFileInput | PromiseLike<ToFileInput>, name?: string | null | undefined, options?: FilePropertyBag | undefined): Promise<FileLike>;
export declare const isMultipartBody: (body: any) => body is MultipartBody;
/**

@@ -77,5 +77,9 @@ * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.

*/
export declare const maybeMultipartFormRequestOptions: <T = Record<string, unknown>>(opts: RequestOptions<T>) => Promise<RequestOptions<MultipartBody | T>>;
export declare const multipartFormRequestOptions: <T = Record<string, unknown>>(opts: RequestOptions<T>) => Promise<RequestOptions<MultipartBody | T>>;
export declare const maybeMultipartFormRequestOptions: (opts: RequestOptions) => Promise<RequestOptions>;
type MultipartFormRequestOptions = Omit<RequestOptions, 'body'> & {
body: unknown;
};
export declare const multipartFormRequestOptions: (opts: MultipartFormRequestOptions) => Promise<RequestOptions>;
export declare const createForm: <T = Record<string, unknown>>(body: T | undefined) => Promise<FormData>;
export {};
//# sourceMappingURL=uploads.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = exports.isMultipartBody = exports.toFile = exports.isUploadable = exports.isBlobLike = exports.isFileLike = exports.isResponseLike = exports.fileFromPath = void 0;
const index_1 = require("./_shims/index.js");
var index_2 = require("./_shims/index.js");
Object.defineProperty(exports, "fileFromPath", { enumerable: true, get: function () { return index_2.fileFromPath; } });
const isResponseLike = (value) => value != null &&
typeof value === 'object' &&
typeof value.url === 'string' &&
typeof value.blob === 'function';
exports.isResponseLike = isResponseLike;
const isFileLike = (value) => value != null &&
typeof value === 'object' &&
typeof value.name === 'string' &&
typeof value.lastModified === 'number' &&
(0, exports.isBlobLike)(value);
exports.isFileLike = isFileLike;
exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = exports.toFile = exports.isUploadable = exports.isResponseLike = exports.isFileLike = exports.isBlobLike = void 0;
const shims_1 = require("./internal/shims.js");
require("./internal/polyfill/file.node.js");
/**
* The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
* adds the arrayBuffer() method type because it is available and used at runtime
* This check adds the arrayBuffer() method type because it is available and used at runtime
*/

@@ -30,7 +17,30 @@ const isBlobLike = (value) => value != null &&

exports.isBlobLike = isBlobLike;
const isFileLike = (value) => value != null &&
typeof value === 'object' &&
typeof value.name === 'string' &&
typeof value.lastModified === 'number' &&
(0, exports.isBlobLike)(value);
exports.isFileLike = isFileLike;
const isResponseLike = (value) => value != null &&
typeof value === 'object' &&
typeof value.url === 'string' &&
typeof value.blob === 'function';
exports.isResponseLike = isResponseLike;
const isUploadable = (value) => {
return (0, exports.isFileLike)(value) || (0, exports.isResponseLike)(value) || (0, index_1.isFsReadStream)(value);
return (0, exports.isFileLike)(value) || (0, exports.isResponseLike)(value) || (0, shims_1.isFsReadStreamLike)(value);
};
exports.isUploadable = isUploadable;
/**
* Construct a `File` instance. This is used to ensure a helpful error is thrown
* for environments that don't define a global `File` yet and so that we don't
* accidentally rely on a global `File` type in our annotations.
*/
function makeFile(fileBits, fileName, options) {
const File = globalThis.File;
if (typeof File === 'undefined') {
throw new Error('`File` is not defined as a global which is required for file uploads');
}
return new File(fileBits, fileName, options);
}
/**
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats

@@ -58,3 +68,3 @@ * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s

const data = (0, exports.isBlobLike)(blob) ? [(await blob.arrayBuffer())] : [blob];
return new index_1.File(data, name, options);
return makeFile(data, name, options);
}

@@ -69,3 +79,3 @@ const bits = await getBytes(value);

}
return new index_1.File(bits, name, options);
return makeFile(bits, name, options);
}

@@ -113,4 +123,2 @@ exports.toFile = toFile;

const isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';
exports.isMultipartBody = isMultipartBody;
/**

@@ -123,13 +131,11 @@ * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.

return opts;
const form = await (0, exports.createForm)(opts.body);
return (0, index_1.getMultipartRequestOptions)(form, opts);
return { ...opts, body: await (0, exports.createForm)(opts.body) };
};
exports.maybeMultipartFormRequestOptions = maybeMultipartFormRequestOptions;
const multipartFormRequestOptions = async (opts) => {
const form = await (0, exports.createForm)(opts.body);
return (0, index_1.getMultipartRequestOptions)(form, opts);
return { ...opts, body: await (0, exports.createForm)(opts.body) };
};
exports.multipartFormRequestOptions = multipartFormRequestOptions;
const createForm = async (body) => {
const form = new index_1.FormData();
const form = new FormData();
await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));

@@ -136,0 +142,0 @@ return form;

@@ -1,2 +0,2 @@

export declare const VERSION = "0.33.1";
export declare const VERSION = "0.34.0-alpha.0";
//# sourceMappingURL=version.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VERSION = void 0;
exports.VERSION = '0.33.1'; // x-release-please-version
exports.VERSION = '0.34.0-alpha.0'; // x-release-please-version
//# sourceMappingURL=version.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc