@imgly/plugin-ai-text-generation-web
Version:
AI text generation plugin for the CE.SDK editor
7 lines • 65.7 kB
JavaScript
var L="0.39.0";var xt=!1,D,et,nr,sr,ir,_t,or,Re,tt,At,rt,ve,St;function kt(r,e={auto:!1}){if(xt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(D)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${D}'\``);xt=e.auto,D=r.kind,et=r.fetch,nr=r.Request,sr=r.Response,ir=r.Headers,_t=r.FormData,or=r.Blob,Re=r.File,tt=r.ReadableStream,At=r.getMultipartRequestOptions,rt=r.getDefaultAgent,ve=r.fileFromPath,St=r.isFsReadStream}var Te=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function Pt({manuallyImported:r}={}){let e=r?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",t,n,s,i;try{t=fetch,n=Request,s=Response,i=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:s,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(o,a)=>({...a,body:new Te(o)}),getDefaultAgent:o=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:o=>!1}}D||kt(Pt(),{auto:!0});var c=class extends Error{},m=class r extends c{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["request-id"],this.error=t}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new F({message:n,cause:Ie(t)});let i=t;return e===400?new ie(e,i,n,s):e===401?new oe(e,i,n,s):e===403?new ae(e,i,n,s):e===404?new ce(e,i,n,s):e===409?new le(e,i,n,s):e===422?new ue(e,i,n,s):e===429?new he(e,i,n,s):e>=500?new de(e,i,n,s):new r(e,i,n,s)}},w=class extends m{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},F=class extends m{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},V=class extends F{constructor({message:e}={}){super({message:e??"Request timed out."})}},ie=class extends m{},oe=class extends m{},ae=class extends m{},ce=class extends m{},le=class extends m{},ue=class extends m{},he=class extends m{},de=class extends m{};var Oe=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},H=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},_,R=class{constructor(){_.set(this,void 0),this.buffer=new Uint8Array,Oe(this,_,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;let s=[],i;for(;(i=lr(this.buffer,H(this,_,"f")))!=null;){if(i.carriage&&H(this,_,"f")==null){Oe(this,_,i.index,"f");continue}if(H(this,_,"f")!=null&&(i.index!==H(this,_,"f")+1||i.carriage)){s.push(this.decodeText(this.buffer.slice(0,H(this,_,"f")-1))),this.buffer=this.buffer.slice(H(this,_,"f")),Oe(this,_,null,"f");continue}let o=H(this,_,"f")!==null?i.preceding-1:i.preceding,a=this.decodeText(this.buffer.slice(0,o));s.push(a),this.buffer=this.buffer.slice(i.index),Oe(this,_,null,"f")}return s}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new c(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new c(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new c("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
`):[]}};_=new WeakMap;R.NEWLINE_CHARS=new Set([`
`,"\r"]);R.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function lr(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Et(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}function fe(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var P=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*s(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let o of ur(e,t)){if(o.event==="completion")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event==="message_start"||o.event==="message_delta"||o.event==="message_stop"||o.event==="content_block_start"||o.event==="content_block_delta"||o.event==="content_block_stop")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event!=="ping"&&o.event==="error")throw m.generate(void 0,`SSE Error: ${o.data}`,o.data,st(e.headers))}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new r(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){let o=new R,a=fe(e);for await(let d of a)for(let h of o.decode(d))yield h;for(let d of o.flush())yield d}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let a of s())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new r(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=i=>({next:()=>{if(i.length===0){let o=n.next();e.push(o),t.push(o)}return i.shift()}});return[new r(()=>s(e),this.controller),new r(()=>s(t),this.controller)]}toReadableStream(){let e=this,t,n=new TextEncoder;return new tt({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:i,done:o}=await t.next();if(o)return s.close();let a=n.encode(JSON.stringify(i)+`
`);s.enqueue(a)}catch(i){s.error(i)}},async cancel(){await t.return?.()}})}};async function*ur(r,e){if(!r.body)throw e.abort(),new c("Attempted to iterate over a response with no body");let t=new nt,n=new R,s=fe(r.body);for await(let i of hr(s))for(let o of n.decode(i)){let a=t.decode(o);a&&(yield a)}for(let i of n.flush()){let o=t.decode(i);o&&(yield o)}}async function*hr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let i;for(;(i=Et(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var nt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=dr(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function dr(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var fr=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",pr=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&pe(r),pe=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function";async function Mt(r,e,t){if(r=await r,pr(r))return r;if(fr(r)){let s=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=pe(s)?[await s.arrayBuffer()]:[s];return new Re(i,e,t)}let n=await mr(r);if(e||(e=yr(r)??"unknown_file"),!t?.type){let s=n[0]?.type;typeof s=="string"&&(t={...t,type:s})}return new Re(n,e,t)}async function mr(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(pe(r))e.push(await r.arrayBuffer());else if(wr(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${gr(r)}`);return e}function gr(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function yr(r){return it(r.name)||it(r.filename)||it(r.path)?.split(/[\\/]/).pop()}var it=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},wr=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",ot=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var xr=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},_r=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Be;async function Ot(r){let{response:e}=r;if(r.options.stream)return Y("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):P.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let i=await e.json();return Y("response",e.status,e.url,e.headers,i),Bt(i,e)}let s=await e.text();return Y("response",e.status,e.url,e.headers,s),s}function Bt(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Fe=class r extends Promise{constructor(e,t=Ot){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>Bt(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},qe=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:i}){this.baseURL=e,this.maxRetries=at("maxRetries",t),this.timeout=at("timeout",n),this.httpAgent=s,this.fetch=i??et}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Pr(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Tr()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async s=>{let i=s&&pe(s?.body)?new DataView(await s.body.arrayBuffer()):s?.body instanceof DataView?s.body:s?.body instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s?.body)?new DataView(s.body.buffer):s?.body;return{method:e,path:t,...s,body:i}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};let{method:n,path:s,query:i,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:ot(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,d=this.calculateContentLength(a),h=this.buildURL(s,i);"timeout"in e&&at("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let p=e.httpAgent??this.httpAgent??rt(h),y=e.timeout+1e3;typeof p?.options?.timeout=="number"&&y>(p.options.timeout??0)&&(p.options.timeout=y),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let O=this.buildHeaders({options:e,headers:o,contentLength:d,retryCount:t});return{req:{method:n,...a&&{body:a},headers:O,...p&&{agent:p},signal:e.signal??null},url:h,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){let i={};n&&(i["content-length"]=n);let o=this.defaultHeaders(e);return It(i,o),It(i,t),ot(e.body)&&D!=="node"&&delete i["content-type"],Ce(o,"x-stainless-retry-count")===void 0&&Ce(t,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(s)),Ce(o,"x-stainless-timeout")===void 0&&Ce(t,"x-stainless-timeout")===void 0&&e.timeout&&(i["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(i,t),i}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new c("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,s){return m.generate(e,t,n,s)}request(e,t=null){return new Fe(this.makeRequest(e,t))}async makeRequest(e,t){let n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);let{req:i,url:o,timeout:a}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(i,{url:o,options:n}),Y("request",o,n,i.headers),n.signal?.aborted)throw new w;let d=new AbortController,h=await this.fetchWithTimeout(o,i,a,d).catch(Ie);if(h instanceof Error){if(n.signal?.aborted)throw new w;if(t)return this.retryRequest(n,t);throw h.name==="AbortError"?new V:new F({cause:h})}let p=st(h.headers);if(!h.ok){if(t&&this.shouldRetry(h)){let G=`retrying, ${t} attempts remaining`;return Y(`response (error; ${G})`,h.status,o,p),this.retryRequest(n,t,p)}let y=await h.text().catch(G=>Ie(G).message),O=Er(y),B=O?void 0:y;throw Y(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,h.status,o,p,B),this.makeStatusError(h.status,O,B,p)}return{response:h,options:n,controller:d}}requestAPIList(e,t){let n=this.makeRequest(t,null);return new ct(this,n,e)}buildURL(e,t){let n=Rr(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return me(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new c(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){let{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>s.abort());let a=setTimeout(()=>s.abort(),n),d={signal:s.signal,...o};d.method&&(d.method=d.method.toUpperCase());let h=60*1e3,p=setTimeout(()=>{if(d&&d?.agent?.sockets)for(let y of Object.values(d?.agent?.sockets).flat())y?.setKeepAlive&&y.setKeepAlive(!0,h)},h);return this.fetch.call(void 0,e,d).finally(()=>{clearTimeout(a),clearTimeout(p)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let s,i=n?.["retry-after-ms"];if(i){let a=parseFloat(i);Number.isNaN(a)||(s=a)}let o=n?.["retry-after"];if(o&&!s){let a=parseFloat(o);Number.isNaN(a)?s=Date.parse(o)-Date.now():s=a*1e3}if(!(s&&0<=s&&s<60*1e3)){let a=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,a)}return await vr(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${L}`}},$e=class{constructor(e,t,n,s){Be.set(this,void 0),xr(this,Be,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new c("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[s,i]of n)e.url.searchParams.set(s,i);t.query=void 0,t.path=e.url.toString()}return await _r(this,Be,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Be=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ct=class extends Fe{constructor(e,t,n){super(t,async s=>new n(e,s.response,await Ot(s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},st=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let n=t.toString();return e[n.toLowerCase()]||e[n]}}),Ar={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},A=r=>typeof r=="object"&&r!==null&&!me(r)&&Object.keys(r).every(e=>Ct(Ar,e)),Sr=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":vt(Deno.build.os),"X-Stainless-Arch":Rt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":vt(process.platform),"X-Stainless-Arch":Rt(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=kr();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function kr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${s}.${i}.${o}`}}}return null}var Rt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",vt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Tt,Pr=()=>Tt??(Tt=Sr()),Er=r=>{try{return JSON.parse(r)}catch{return}},Mr=/^[a-z][a-z0-9+.-]*:/i,Rr=r=>Mr.test(r),vr=r=>new Promise(e=>setTimeout(e,r)),at=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new c(`${r} must be an integer`);if(e<0)throw new c(`${r} must be a positive integer`);return e},Ie=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(String(r))};var je=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function me(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ct(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function It(r,e){for(let t in e){if(!Ct(e,t))continue;let n=t.toLowerCase();if(!n)continue;let s=e[t];s===null?delete r[n]:s!==void 0&&(r[n]=s)}}function Y(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var Tr=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Ft=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Ir=r=>typeof r?.get=="function";var Ce=(r,e)=>{let t=e.toLowerCase();if(Ir(r)){let n=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(s,i,o)=>i+o.toUpperCase());for(let s of[e,t,e.toUpperCase(),n]){let i=r.get(s);if(i)return i}}for(let[n,s]of Object.entries(r))if(n.toLowerCase()===t)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${e} header, using the first entry.`),s[0]):s};var E=class extends $e{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};var g=class{constructor(e){this._client=e}};var W=class extends g{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return A(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",z,{query:e,...t})}},z=class extends E{};W.BetaModelInfosPage=z;var Z=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new R;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new c("Attempted to iterate over a response with no body");return new r(fe(e.body),t)}};var Q=class extends g{create(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},n){if(A(t))return this.retrieve(e,{},t);let{betas:s}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}list(e={},t){if(A(e))return this.list({},e);let{betas:n,...s}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",ee,{query:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(A(t))return this.delete(e,{},t);let{betas:s}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}cancel(e,t={},n){if(A(t))return this.cancel(e,{},t);let{betas:s}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}async results(e,t={},n){if(A(t))return this.results(e,{},t);let s=await this.retrieve(e);if(!s.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:i}=t;return this._client.get(s.results_url,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...n?.headers},__binaryResponse:!0})._thenUnwrap((o,a)=>Z.fromResponse(a.response,a.controller))}},ee=class extends E{};Q.BetaMessageBatchesPage=ee;var Fr=r=>{let e=0,t=[];for(;e<r.length;){let n=r[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",d=!1;for(n=r[++e];n!=='"';){if(e===r.length){d=!0;break}if(n==="\\"){if(e++,e===r.length){d=!0;break}a+=n+r[e],n=r[++e]}else a+=n,n=r[++e]}n=r[++e],d||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let i=/[0-9]/;if(n&&i.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=r[++e]);n&&i.test(n)||n===".";)a+=n,n=r[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(n&&o.test(n)){let a="";for(;n&&o.test(n)&&e!==r.length;)a+=n,n=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},te=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),te(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),te(r);case"string":let n=r[r.length-2];if(n?.type==="delimiter")return r=r.slice(0,r.length-1),te(r);if(n?.type==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),te(r);break;case"delimiter":return r=r.slice(0,r.length-1),te(r);break}return r},qr=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},$r=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Ne=r=>JSON.parse($r(qr(te(Fr(r)))));var b=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},l=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},S,q,ge,Ue,ye,we,Le,be,v,xe,De,He,re,We,Qe,lt,qt,ut,ht,dt,ft,$t,jt="__json_buf",Xe=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),this.controller=new AbortController,ge.set(this,void 0),Ue.set(this,()=>{}),ye.set(this,()=>{}),we.set(this,void 0),Le.set(this,()=>{}),be.set(this,()=>{}),v.set(this,{}),xe.set(this,!1),De.set(this,!1),He.set(this,!1),re.set(this,!1),We.set(this,void 0),Qe.set(this,void 0),ut.set(this,e=>{if(b(this,De,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new w),e instanceof w)return b(this,He,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),b(this,ge,new Promise((e,t)=>{b(this,Ue,e,"f"),b(this,ye,t,"f")}),"f"),b(this,we,new Promise((e,t)=>{b(this,Le,e,"f"),b(this,be,t,"f")}),"f"),l(this,ge,"f").catch(()=>{}),l(this,we,"f").catch(()=>{})}get response(){return l(this,We,"f")}get request_id(){return l(this,Qe,"f")}async withResponse(){let e=await l(this,ge,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let s=new r;for(let i of t.messages)s._addMessageParam(i);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},l(this,ut,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,S,"m",ht).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)l(this,S,"m",dt).call(this,a);if(o.controller.signal?.aborted)throw new w;l(this,S,"m",ft).call(this)}_connected(e){this.ended||(b(this,We,e,"f"),b(this,Qe,e?.headers.get("request-id"),"f"),l(this,Ue,"f").call(this,e),this._emit("connect"))}get ended(){return l(this,xe,"f")}get errored(){return l(this,De,"f")}get aborted(){return l(this,He,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,v,"f")[e]||(l(this,v,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=l(this,v,"f")[e];if(!n)return this;let s=n.findIndex(i=>i.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(l(this,v,"f")[e]||(l(this,v,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{b(this,re,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){b(this,re,!0,"f"),await l(this,we,"f")}get currentMessage(){return l(this,q,"f")}async finalMessage(){return await this.done(),l(this,S,"m",lt).call(this)}async finalText(){return await this.done(),l(this,S,"m",qt).call(this)}_emit(e,...t){if(l(this,xe,"f"))return;e==="end"&&(b(this,xe,!0,"f"),l(this,Le,"f").call(this));let n=l(this,v,"f")[e];if(n&&(l(this,v,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!l(this,re,"f")&&!n?.length&&Promise.reject(s),l(this,ye,"f").call(this,s),l(this,be,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!l(this,re,"f")&&!n?.length&&Promise.reject(s),l(this,ye,"f").call(this,s),l(this,be,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",l(this,S,"m",lt).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,S,"m",ht).call(this),this._connected(null);let s=P.fromReadableStream(e,this.controller);for await(let i of s)l(this,S,"m",dt).call(this,i);if(s.controller.signal?.aborted)throw new w;l(this,S,"m",ft).call(this)}[(q=new WeakMap,ge=new WeakMap,Ue=new WeakMap,ye=new WeakMap,we=new WeakMap,Le=new WeakMap,be=new WeakMap,v=new WeakMap,xe=new WeakMap,De=new WeakMap,He=new WeakMap,re=new WeakMap,We=new WeakMap,Qe=new WeakMap,ut=new WeakMap,S=new WeakSet,lt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},qt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},ht=function(){this.ended||b(this,q,void 0,"f")},dt=function(t){if(this.ended)return;let n=l(this,S,"m",$t).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{b(this,q,n,"f");break}case"content_block_start":case"message_delta":break}},ft=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=l(this,q,"f");if(!t)throw new c("request ended without sending any chunks");return b(this,q,void 0,"f"),t},$t=function(t){let n=l(this,q,"f");if(t.type==="message_start"){if(n)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let i=s[jt]||"";i+=t.delta.partial_json,Object.defineProperty(s,jt,{value:i,enumerable:!1,writable:!0}),i&&(s.input=Ne(i))}break}case"thinking_delta":{s?.type==="thinking"&&(s.thinking+=t.delta.thinking);break}case"signature_delta":{s?.type==="thinking"&&(s.signature=t.delta.signature);break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new P(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Nt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},$=class extends g{constructor(){super(...arguments),this.batches=new Q(this._client)}create(e,t){let{betas:n,...s}=e;return s.model in Nt&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${Nt[s.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:s,timeout:this._client._options.timeout??(s.stream?6e5:this._client._calculateNonstreamingTimeout(s.max_tokens)),...t,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return Xe.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};$.Batches=Q;$.BetaMessageBatchesPage=ee;var M=class extends g{constructor(){super(...arguments),this.models=new W(this._client),this.messages=new $(this._client)}};M.Models=W;M.BetaModelInfosPage=z;M.Messages=$;var X=class extends g{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var K=class extends g{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return A(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",ne,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((s,i)=>Z.fromResponse(i.response,i.controller))}},ne=class extends E{};K.MessageBatchesPage=ne;var x=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},u=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},k,j,_e,Ke,Ae,Se,Je,ke,T,Pe,Ge,Ve,se,Ye,ze,pt,Ut,mt,gt,yt,wt,Lt,Dt="__json_buf",Ze=class r{constructor(){k.add(this),this.messages=[],this.receivedMessages=[],j.set(this,void 0),this.controller=new AbortController,_e.set(this,void 0),Ke.set(this,()=>{}),Ae.set(this,()=>{}),Se.set(this,void 0),Je.set(this,()=>{}),ke.set(this,()=>{}),T.set(this,{}),Pe.set(this,!1),Ge.set(this,!1),Ve.set(this,!1),se.set(this,!1),Ye.set(this,void 0),ze.set(this,void 0),mt.set(this,e=>{if(x(this,Ge,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new w),e instanceof w)return x(this,Ve,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),x(this,_e,new Promise((e,t)=>{x(this,Ke,e,"f"),x(this,Ae,t,"f")}),"f"),x(this,Se,new Promise((e,t)=>{x(this,Je,e,"f"),x(this,ke,t,"f")}),"f"),u(this,_e,"f").catch(()=>{}),u(this,Se,"f").catch(()=>{})}get response(){return u(this,Ye,"f")}get request_id(){return u(this,ze,"f")}async withResponse(){let e=await u(this,_e,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let s=new r;for(let i of t.messages)s._addMessageParam(i);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,mt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),u(this,k,"m",gt).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)u(this,k,"m",yt).call(this,a);if(o.controller.signal?.aborted)throw new w;u(this,k,"m",wt).call(this)}_connected(e){this.ended||(x(this,Ye,e,"f"),x(this,ze,e?.headers.get("request-id"),"f"),u(this,Ke,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Pe,"f")}get errored(){return u(this,Ge,"f")}get aborted(){return u(this,Ve,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=u(this,T,"f")[e];if(!n)return this;let s=n.findIndex(i=>i.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{x(this,se,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){x(this,se,!0,"f"),await u(this,Se,"f")}get currentMessage(){return u(this,j,"f")}async finalMessage(){return await this.done(),u(this,k,"m",pt).call(this)}async finalText(){return await this.done(),u(this,k,"m",Ut).call(this)}_emit(e,...t){if(u(this,Pe,"f"))return;e==="end"&&(x(this,Pe,!0,"f"),u(this,Je,"f").call(this));let n=u(this,T,"f")[e];if(n&&(u(this,T,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!u(this,se,"f")&&!n?.length&&Promise.reject(s),u(this,Ae,"f").call(this,s),u(this,ke,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!u(this,se,"f")&&!n?.length&&Promise.reject(s),u(this,Ae,"f").call(this,s),u(this,ke,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,k,"m",pt).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,k,"m",gt).call(this),this._connected(null);let s=P.fromReadableStream(e,this.controller);for await(let i of s)u(this,k,"m",yt).call(this,i);if(s.controller.signal?.aborted)throw new w;u(this,k,"m",wt).call(this)}[(j=new WeakMap,_e=new WeakMap,Ke=new WeakMap,Ae=new WeakMap,Se=new WeakMap,Je=new WeakMap,ke=new WeakMap,T=new WeakMap,Pe=new WeakMap,Ge=new WeakMap,Ve=new WeakMap,se=new WeakMap,Ye=new WeakMap,ze=new WeakMap,mt=new WeakMap,k=new WeakSet,pt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ut=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},gt=function(){this.ended||x(this,j,void 0,"f")},yt=function(t){if(this.ended)return;let n=u(this,k,"m",Lt).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{x(this,j,n,"f");break}case"content_block_start":case"message_delta":break}},wt=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=u(this,j,"f");if(!t)throw new c("request ended without sending any chunks");return x(this,j,void 0,"f"),t},Lt=function(t){let n=u(this,j,"f");if(t.type==="message_start"){if(n)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let i=s[Dt]||"";i+=t.delta.partial_json,Object.defineProperty(s,Dt,{value:i,enumerable:!1,writable:!0}),i&&(s.input=Ne(i))}break}case"thinking_delta":{s?.type==="thinking"&&(s.thinking+=t.delta.thinking);break}case"signature_delta":{s?.type==="thinking"&&(s.signature=t.delta.signature);break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new P(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var I=class extends g{constructor(){super(...arguments),this.batches=new K(this._client)}create(e,t){return e.model in Ht&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Ht[e.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return Ze.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Ht={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};I.Batches=K;I.MessageBatchesPage=ne;var N=class extends g{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return A(e)?this.list({},e):this._client.getAPIList("/v1/models",J,{query:e,...t})}},J=class extends E{};N.ModelInfosP