@imgly/plugin-ai-text-generation-web 0.2.4 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +31 -4
- package/dist/anthropic/index.mjs +9 -9
- package/dist/anthropic/index.mjs.map +4 -4
- package/dist/index.mjs +15 -15
- package/dist/index.mjs.map +4 -4
- package/dist/open-ai/index.mjs +9 -9
- package/dist/open-ai/index.mjs.map +4 -4
- package/dist/quickActions/ChangeTextTo.d.ts +1 -0
- package/dist/quickActions/ChangeTone.d.ts +1 -0
- package/dist/quickActions/Fix.d.ts +1 -0
- package/dist/quickActions/Improve.d.ts +1 -0
- package/dist/quickActions/Longer.d.ts +1 -0
- package/dist/quickActions/Shorter.d.ts +1 -0
- package/dist/quickActions/Translate.d.ts +1 -0
- package/dist/quickActions/__tests__/Translate.test.d.ts +1 -0
- package/package.json +17 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.2.6] - 2025-09-09
|
|
6
|
+
|
|
7
|
+
### New Features
|
|
8
|
+
|
|
9
|
+
- [all] **Feature API Integration**: Added comprehensive Feature API support across all AI plugins to control visibility and availability of features through feature flags. Core features include `providerSelect`, `quickAction`, `quickAction.providerSelect`, `fromText`, and `fromImage` flags.
|
|
10
|
+
- [all] **Quick Action Feature Flags**: Each quick action now automatically registers and respects its own feature flag (e.g., `ly.img.plugin-ai-image-generation-web.quickAction.editImage`), allowing fine-grained control over which quick actions are available to users.
|
|
11
|
+
- [image-generation] **Provider Style Group Control**: Added Feature API support for Recraft providers to control style group visibility. RecraftV3 supports `style.image` and `style.vector` flags, while Recraft20b adds `style.icon` flag for controlling icon style availability.
|
|
12
|
+
- [all] **Provider Selection Feature Flags**: Added support for controlling provider selection UI in both panels (`providerSelect`) and quick actions (`quickAction.providerSelect`), with proper handling when multiple providers are configured.
|
|
13
|
+
|
|
14
|
+
## [0.2.5] - 2025-09-03
|
|
15
|
+
|
|
16
|
+
### New Features
|
|
17
|
+
|
|
18
|
+
- [image-generation] **NanoBanana Provider**: Added NanoBanana text-to-image provider via fal.ai with fast generation times, 1024×1024 resolution, support for multiple output formats (JPEG, PNG), configurable number of images (1-4), and remixPageWithPrompt quick action
|
|
19
|
+
- [image-generation] **NanoBananaEdit Provider**: Added NanoBananaEdit image-to-image provider via fal.ai for editing existing images with text prompts, supporting all standard quick actions (editImage, swapBackground, styleTransfer, artistTransfer, createVariant, combineImages with up to 10 images, remixPage, remixPageWithPrompt)
|
|
20
|
+
- [all] **AI Style Asset Library Translations**: AI style presets in asset libraries now automatically use localized names and descriptions from provider translation files, eliminating the need for manual translation configuration
|
|
21
|
+
|
|
22
|
+
### Bug Fixes
|
|
23
|
+
|
|
24
|
+
- [all] **fal.ai Provider Configuration**: Fixed singleton configuration conflict when using multiple fal.ai providers with different proxy URLs. Each provider now maintains its own client instance instead of overwriting a global configuration
|
|
25
|
+
- [video-generation] **Missing Dependency**: Added missing `@fal-ai/client` dependency to plugin-ai-video-generation-web package.json to ensure the package works correctly when installed independently
|
|
26
|
+
|
|
5
27
|
## [0.2.4] - 2025-08-07
|
|
6
28
|
|
|
7
29
|
### New Features
|
package/README.md
CHANGED
|
@@ -215,6 +215,25 @@ cesdk.i18n.setTranslations({
|
|
|
215
215
|
});
|
|
216
216
|
```
|
|
217
217
|
|
|
218
|
+
### Feature Control
|
|
219
|
+
|
|
220
|
+
You can control various aspects of the text generation plugin using the Feature API:
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
// Disable provider selection dropdown
|
|
224
|
+
cesdk.feature.enable('ly.img.plugin-ai-text-generation-web.providerSelect', false);
|
|
225
|
+
|
|
226
|
+
// Disable all quick actions
|
|
227
|
+
cesdk.feature.enable('ly.img.plugin-ai-text-generation-web.quickAction', false);
|
|
228
|
+
|
|
229
|
+
// Disable specific quick actions
|
|
230
|
+
cesdk.feature.enable('ly.img.plugin-ai-text-generation-web.quickAction.improve', false);
|
|
231
|
+
cesdk.feature.enable('ly.img.plugin-ai-text-generation-web.quickAction.translate', false);
|
|
232
|
+
cesdk.feature.enable('ly.img.plugin-ai-text-generation-web.quickAction.changeTone', false);
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
For more information about Feature API and available feature flags, see the [@imgly/plugin-ai-generation-web documentation](https://github.com/imgly/plugins/tree/main/packages/plugin-ai-generation-web#available-feature-flags).
|
|
236
|
+
|
|
218
237
|
### Customizing Labels and Translations
|
|
219
238
|
|
|
220
239
|
You can customize all labels and text in the AI text generation interface using the translation system. This allows you to provide better labels for your users in any language.
|
|
@@ -252,12 +271,17 @@ cesdk.i18n.setTranslations({
|
|
|
252
271
|
|
|
253
272
|
#### QuickAction Translations
|
|
254
273
|
|
|
255
|
-
Text QuickActions (like "Improve Writing", "Fix Grammar", etc.) use their own translation keys:
|
|
274
|
+
Text QuickActions (like "Improve Writing", "Fix Grammar", etc.) use their own translation keys with provider-specific overrides:
|
|
256
275
|
|
|
257
276
|
```typescript
|
|
258
277
|
cesdk.i18n.setTranslations({
|
|
259
278
|
en: {
|
|
260
|
-
//
|
|
279
|
+
// Provider-specific translations (highest priority)
|
|
280
|
+
'ly.img.plugin-ai-text-generation-web.anthropic.quickAction.improve': 'Improve with Claude',
|
|
281
|
+
'ly.img.plugin-ai-text-generation-web.anthropic.quickAction.fix': 'Fix with Claude',
|
|
282
|
+
'ly.img.plugin-ai-text-generation-web.openai.quickAction.translate': 'Translate with GPT',
|
|
283
|
+
|
|
284
|
+
// Generic plugin translations
|
|
261
285
|
'ly.img.plugin-ai-text-generation-web.quickAction.improve': 'Improve Writing',
|
|
262
286
|
'ly.img.plugin-ai-text-generation-web.quickAction.fix': 'Fix Grammar',
|
|
263
287
|
'ly.img.plugin-ai-text-generation-web.quickAction.shorter': 'Make Shorter',
|
|
@@ -270,14 +294,17 @@ cesdk.i18n.setTranslations({
|
|
|
270
294
|
'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.prompt': 'Transform Text...',
|
|
271
295
|
'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.prompt.placeholder': 'e.g. "Convert to bullet points"',
|
|
272
296
|
'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.apply': 'Transform',
|
|
273
|
-
|
|
274
297
|
'ly.img.plugin-ai-text-generation-web.quickAction.translate.language': 'Target Language',
|
|
275
298
|
'ly.img.plugin-ai-text-generation-web.quickAction.translate.apply': 'Translate'
|
|
276
299
|
}
|
|
277
300
|
});
|
|
278
301
|
```
|
|
279
302
|
|
|
280
|
-
**QuickAction Translation
|
|
303
|
+
**QuickAction Translation Priority:**
|
|
304
|
+
1. Provider-specific: `ly.img.plugin-ai-text-generation-web.${provider}.quickAction.${action}.${field}`
|
|
305
|
+
2. Generic plugin: `ly.img.plugin-ai-text-generation-web.quickAction.${action}.${field}`
|
|
306
|
+
|
|
307
|
+
**Translation Structure:**
|
|
281
308
|
- Base key (e.g., `.quickAction.improve`): Button text when QuickAction is collapsed
|
|
282
309
|
- `.prompt`: Label for input field when expanded
|
|
283
310
|
- `.prompt.placeholder`: Placeholder text for input field
|
package/dist/anthropic/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ur=typeof global=="object"&&global&&global.Object===Object&&global,rr=Ur,Br=typeof self=="object"&&self&&self.Object===Object&&self,Fr=rr||Br||Function("return this")(),C=Fr,zr=C.Symbol,K=zr,ir=Object.prototype,qr=ir.hasOwnProperty,Vr=ir.toString,ce=K?K.toStringTag:void 0;function Hr(r){var e=qr.call(r,ce),t=r[ce];try{r[ce]=void 0;var i=!0}catch{}var n=Vr.call(r);return i&&(e?r[ce]=t:delete r[ce]),n}var Wr=Hr,Gr=Object.prototype,Qr=Gr.toString;function Yr(r){return Qr.call(r)}var Kr=Yr,Jr="[object Null]",Xr="[object Undefined]",zt=K?K.toStringTag:void 0;function Zr(r){return r==null?r===void 0?Xr:Jr:zt&&zt in Object(r)?Wr(r):Kr(r)}var ge=Zr;function ei(r){return r!=null&&typeof r=="object"}var vt=ei,Ms=Array.isArray;function ti(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var nr=ti,ri="[object AsyncFunction]",ii="[object Function]",ni="[object GeneratorFunction]",oi="[object Proxy]";function si(r){if(!nr(r))return!1;var e=ge(r);return e==ii||e==ni||e==ri||e==oi}var ai=si,li=C["__core-js_shared__"],gt=li,qt=function(){var r=/[^.]+$/.exec(gt&>.keys&>.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ui(r){return!!qt&&qt in r}var ci=ui,di=Function.prototype,pi=di.toString;function fi(r){if(r!=null){try{return pi.call(r)}catch{}try{return r+""}catch{}}return""}var U=fi,gi=/[\\^$.*+?()[\]{}|]/g,hi=/^\[object .+?Constructor\]$/,mi=Function.prototype,yi=Object.prototype,bi=mi.toString,wi=yi.hasOwnProperty,ki=RegExp("^"+bi.call(wi).replace(gi,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xi(r){if(!nr(r)||ci(r))return!1;var e=ai(r)?ki:hi;return e.test(U(r))}var vi=xi;function _i(r,e){return r?.[e]}var Ai=_i;function Si(r,e){var t=Ai(r,e);return vi(t)?t:void 0}var J=Si,Mi=J(C,"WeakMap"),yt=Mi;function Ii(r,e){return r===e||r!==r&&e!==e}var Ei=Ii,Ci=9007199254740991;function Pi(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ci}var Ti=Pi,Is=Object.prototype,ji="[object Arguments]";function $i(r){return vt(r)&&ge(r)==ji}var Vt=$i,or=Object.prototype,Ri=or.hasOwnProperty,Li=or.propertyIsEnumerable,Es=Vt(function(){return arguments}())?Vt:function(r){return vt(r)&&Ri.call(r,"callee")&&!Li.call(r,"callee")},sr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ht=sr&&typeof module=="object"&&module&&!module.nodeType&&module,Ni=Ht&&Ht.exports===sr,Wt=Ni?C.Buffer:void 0,Cs=Wt?Wt.isBuffer:void 0,Oi="[object Arguments]",Di="[object Array]",Ui="[object Boolean]",Bi="[object Date]",Fi="[object Error]",zi="[object Function]",qi="[object Map]",Vi="[object Number]",Hi="[object Object]",Wi="[object RegExp]",Gi="[object Set]",Qi="[object String]",Yi="[object WeakMap]",Ki="[object ArrayBuffer]",Ji="[object DataView]",Xi="[object Float32Array]",Zi="[object Float64Array]",en="[object Int8Array]",tn="[object Int16Array]",rn="[object Int32Array]",nn="[object Uint8Array]",on="[object Uint8ClampedArray]",sn="[object Uint16Array]",an="[object Uint32Array]",p={};p[Xi]=p[Zi]=p[en]=p[tn]=p[rn]=p[nn]=p[on]=p[sn]=p[an]=!0;p[Oi]=p[Di]=p[Ki]=p[Ui]=p[Ji]=p[Bi]=p[Fi]=p[zi]=p[qi]=p[Vi]=p[Hi]=p[Wi]=p[Gi]=p[Qi]=p[Yi]=!1;function ln(r){return vt(r)&&Ti(r.length)&&!!p[ge(r)]}var un=ln;function cn(r){return function(e){return r(e)}}var dn=cn,ar=typeof exports=="object"&&exports&&!exports.nodeType&&exports,de=ar&&typeof module=="object"&&module&&!module.nodeType&&module,pn=de&&de.exports===ar,ht=pn&&rr.process,fn=function(){try{var r=de&&de.require&&de.require("util").types;return r||ht&&ht.binding&&ht.binding("util")}catch{}}(),Gt=fn,Qt=Gt&&Gt.isTypedArray,Ps=Qt?dn(Qt):un,gn=Object.prototype,Ts=gn.hasOwnProperty;function hn(r,e){return function(t){return r(e(t))}}var mn=hn,js=mn(Object.keys,Object),yn=Object.prototype,$s=yn.hasOwnProperty,bn=J(Object,"create"),pe=bn;function wn(){this.__data__=pe?pe(null):{},this.size=0}var kn=wn;function xn(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var vn=xn,_n="__lodash_hash_undefined__",An=Object.prototype,Sn=An.hasOwnProperty;function Mn(r){var e=this.__data__;if(pe){var t=e[r];return t===_n?void 0:t}return Sn.call(e,r)?e[r]:void 0}var In=Mn,En=Object.prototype,Cn=En.hasOwnProperty;function Pn(r){var e=this.__data__;return pe?e[r]!==void 0:Cn.call(e,r)}var Tn=Pn,jn="__lodash_hash_undefined__";function $n(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=pe&&e===void 0?jn:e,this}var Rn=$n;function X(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}X.prototype.clear=kn;X.prototype.delete=vn;X.prototype.get=In;X.prototype.has=Tn;X.prototype.set=Rn;var Yt=X;function Ln(){this.__data__=[],this.size=0}var Nn=Ln;function On(r,e){for(var t=r.length;t--;)if(Ei(r[t][0],e))return t;return-1}var Oe=On,Dn=Array.prototype,Un=Dn.splice;function Bn(r){var e=this.__data__,t=Oe(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Un.call(e,t,1),--this.size,!0}var Fn=Bn;function zn(r){var e=this.__data__,t=Oe(e,r);return t<0?void 0:e[t][1]}var qn=zn;function Vn(r){return Oe(this.__data__,r)>-1}var Hn=Vn;function Wn(r,e){var t=this.__data__,i=Oe(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}var Gn=Wn;function Z(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}Z.prototype.clear=Nn;Z.prototype.delete=Fn;Z.prototype.get=qn;Z.prototype.has=Hn;Z.prototype.set=Gn;var De=Z,Qn=J(C,"Map"),fe=Qn;function Yn(){this.size=0,this.__data__={hash:new Yt,map:new(fe||De),string:new Yt}}var Kn=Yn;function Jn(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Xn=Jn;function Zn(r,e){var t=r.__data__;return Xn(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Ue=Zn;function eo(r){var e=Ue(this,r).delete(r);return this.size-=e?1:0,e}var to=eo;function ro(r){return Ue(this,r).get(r)}var io=ro;function no(r){return Ue(this,r).has(r)}var oo=no;function so(r,e){var t=Ue(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}var ao=so;function ee(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}ee.prototype.clear=Kn;ee.prototype.delete=to;ee.prototype.get=io;ee.prototype.has=oo;ee.prototype.set=ao;var lr=ee;function lo(){this.__data__=new De,this.size=0}var uo=lo;function co(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var po=co;function fo(r){return this.__data__.get(r)}var go=fo;function ho(r){return this.__data__.has(r)}var mo=ho,yo=200;function bo(r,e){var t=this.__data__;if(t instanceof De){var i=t.__data__;if(!fe||i.length<yo-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new lr(i)}return t.set(r,e),this.size=t.size,this}var wo=bo;function he(r){var e=this.__data__=new De(r);this.size=e.size}he.prototype.clear=uo;he.prototype.delete=po;he.prototype.get=go;he.prototype.has=mo;he.prototype.set=wo;var ko=Object.prototype,Rs=ko.propertyIsEnumerable,xo=J(C,"DataView"),bt=xo,vo=J(C,"Promise"),wt=vo,_o=J(C,"Set"),kt=_o,Kt="[object Map]",Ao="[object Object]",Jt="[object Promise]",Xt="[object Set]",Zt="[object WeakMap]",er="[object DataView]",So=U(bt),Mo=U(fe),Io=U(wt),Eo=U(kt),Co=U(yt),Y=ge;(bt&&Y(new bt(new ArrayBuffer(1)))!=er||fe&&Y(new fe)!=Kt||wt&&Y(wt.resolve())!=Jt||kt&&Y(new kt)!=Xt||yt&&Y(new yt)!=Zt)&&(Y=function(r){var e=ge(r),t=e==Ao?r.constructor:void 0,i=t?U(t):"";if(i)switch(i){case So:return er;case Mo:return Kt;case Io:return Jt;case Eo:return Xt;case Co:return Zt}return e});var Ls=C.Uint8Array,Po="__lodash_hash_undefined__";function To(r){return this.__data__.set(r,Po),this}var jo=To;function $o(r){return this.__data__.has(r)}var Ro=$o;function xt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new lr;++e<t;)this.add(r[e])}xt.prototype.add=xt.prototype.push=jo;xt.prototype.has=Ro;var tr=K?K.prototype:void 0,Ns=tr?tr.valueOf:void 0,Lo=Object.prototype,Os=Lo.hasOwnProperty,No=Object.prototype,Ds=No.hasOwnProperty,Us=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Bs=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Fs=new RegExp(/[A-Fa-f0-9]{2}/,"g");function ur(r,e){let t={...r};if(!e)return t;for(let[i,n]of Object.entries(e))n===!1||n===null||n===void 0?delete t[i]:n===!0?i in r||(t[i]=!0):t[i]=n;return t}var mt="@imgly/plugin-ai-generation",zs=`
|
|
2
2
|
<svg>
|
|
3
3
|
<symbol
|
|
4
4
|
fill="none"
|
|
@@ -59,24 +59,24 @@ var Br=typeof global=="object"&&global&&global.Object===Object&&global,rr=Br,Ur=
|
|
|
59
59
|
|
|
60
60
|
</symbol>
|
|
61
61
|
</svg>
|
|
62
|
-
`;var
|
|
63
|
-
`):[]}};
|
|
64
|
-
`,"\r"]);P.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qo(r,e){for(let n=e??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function mr(r){for(let i=0;i<r.length-1;i++){if(r[i]===10&&r[i+1]===10||r[i]===13&&r[i+1]===13)return i+2;if(r[i]===13&&r[i+1]===10&&i+3<r.length&&r[i+2]===13&&r[i+3]===10)return i+4}return-1}function Ae(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 M=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let i=!1;async function*n(){if(i)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(let s of Vo(e,t)){if(s.event==="completion")try{yield JSON.parse(s.data)}catch(a){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),a}if(s.event==="message_start"||s.event==="message_delta"||s.event==="message_stop"||s.event==="content_block_start"||s.event==="content_block_delta"||s.event==="content_block_stop")try{yield JSON.parse(s.data)}catch(a){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),a}if(s.event!=="ping"&&s.event==="error")throw
|
|
62
|
+
`;var B="0.39.0";var cr=!1,F,_t,Oo,Do,Uo,dr,Bo,Be,At,pr,St,Fe,fr;function gr(r,e={auto:!1}){if(cr)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(F)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${F}'\``);cr=e.auto,F=r.kind,_t=r.fetch,Oo=r.Request,Do=r.Response,Uo=r.Headers,dr=r.FormData,Bo=r.Blob,Be=r.File,At=r.ReadableStream,pr=r.getMultipartRequestOptions,St=r.getDefaultAgent,Fe=r.fileFromPath,fr=r.isFsReadStream}var ze=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function hr({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,i,n,o;try{t=fetch,i=Request,n=Response,o=Headers}catch(s){throw new Error(`this environment is missing the following Web Fetch API type: ${s.message}. ${e}`)}return{kind:"web",fetch:t,Request:i,Response:n,Headers:o,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(s,a)=>({...a,body:new ze(s)}),getDefaultAgent:s=>{},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:s=>!1}}F||gr(hr(),{auto:!0});var l=class extends Error{},h=class r extends l{constructor(e,t,i,n){super(`${r.makeMessage(e,t,i)}`),this.status=e,this.headers=n,this.request_id=n?.["request-id"],this.error=t}static makeMessage(e,t,i){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):i;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,i,n){if(!e||!n)return new R({message:i,cause:qe(t)});let o=t;return e===400?new me(e,o,i,n):e===401?new ye(e,o,i,n):e===403?new be(e,o,i,n):e===404?new we(e,o,i,n):e===409?new ke(e,o,i,n):e===422?new xe(e,o,i,n):e===429?new ve(e,o,i,n):e>=500?new _e(e,o,i,n):new r(e,o,i,n)}},y=class extends h{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},R=class extends h{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},te=class extends R{constructor({message:e}={}){super({message:e??"Request timed out."})}},me=class extends h{},ye=class extends h{},be=class extends h{},we=class extends h{},ke=class extends h{},xe=class extends h{},ve=class extends h{},_e=class extends h{};var Ve=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},z=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},x,P=class{constructor(){x.set(this,void 0),this.buffer=new Uint8Array,Ve(this,x,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,i=new Uint8Array(this.buffer.length+t.length);i.set(this.buffer),i.set(t,this.buffer.length),this.buffer=i;let n=[],o;for(;(o=qo(this.buffer,z(this,x,"f")))!=null;){if(o.carriage&&z(this,x,"f")==null){Ve(this,x,o.index,"f");continue}if(z(this,x,"f")!=null&&(o.index!==z(this,x,"f")+1||o.carriage)){n.push(this.decodeText(this.buffer.slice(0,z(this,x,"f")-1))),this.buffer=this.buffer.slice(z(this,x,"f")),Ve(this,x,null,"f");continue}let s=z(this,x,"f")!==null?o.preceding-1:o.preceding,a=this.decodeText(this.buffer.slice(0,s));n.push(a),this.buffer=this.buffer.slice(o.index),Ve(this,x,null,"f")}return n}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 l(`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 l(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new l("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
|
|
63
|
+
`):[]}};x=new WeakMap;P.NEWLINE_CHARS=new Set([`
|
|
64
|
+
`,"\r"]);P.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qo(r,e){for(let n=e??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function mr(r){for(let i=0;i<r.length-1;i++){if(r[i]===10&&r[i+1]===10||r[i]===13&&r[i+1]===13)return i+2;if(r[i]===13&&r[i+1]===10&&i+3<r.length&&r[i+2]===13&&r[i+3]===10)return i+4}return-1}function Ae(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 M=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let i=!1;async function*n(){if(i)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(let s of Vo(e,t)){if(s.event==="completion")try{yield JSON.parse(s.data)}catch(a){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),a}if(s.event==="message_start"||s.event==="message_delta"||s.event==="message_stop"||s.event==="content_block_start"||s.event==="content_block_delta"||s.event==="content_block_stop")try{yield JSON.parse(s.data)}catch(a){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),a}if(s.event!=="ping"&&s.event==="error")throw h.generate(void 0,`SSE Error: ${s.data}`,s.data,It(e.headers))}o=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{o||t.abort()}}return new r(n,t)}static fromReadableStream(e,t){let i=!1;async function*n(){let s=new P,a=Ae(e);for await(let f of a)for(let g of s.decode(f))yield g;for(let f of s.flush())yield f}async function*o(){if(i)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let s=!1;try{for await(let a of n())s||a&&(yield JSON.parse(a));s=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{s||t.abort()}}return new r(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],i=this.iterator(),n=o=>({next:()=>{if(o.length===0){let s=i.next();e.push(s),t.push(s)}return o.shift()}});return[new r(()=>n(e),this.controller),new r(()=>n(t),this.controller)]}toReadableStream(){let e=this,t,i=new TextEncoder;return new At({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=i.encode(JSON.stringify(o)+`
|
|
65
65
|
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Vo(r,e){if(!r.body)throw e.abort(),new l("Attempted to iterate over a response with no body");let t=new Mt,i=new P,n=Ae(r.body);for await(let o of Ho(n))for(let s of i.decode(o)){let a=t.decode(s);a&&(yield a)}for(let o of i.flush()){let s=t.decode(o);s&&(yield s)}}async function*Ho(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let i=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,n=new Uint8Array(e.length+i.length);n.set(e),n.set(i,e.length),e=n;let o;for(;(o=mr(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Mt=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 o={event:this.event,data:this.data.join(`
|
|
66
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,i,n]=Wo(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Wo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var Go=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Qo=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Se(r),Se=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 yr(r,e,t){if(r=await r,Qo(r))return r;if(Go(r)){let n=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Se(n)?[await n.arrayBuffer()]:[n];return new Ue(o,e,t)}let i=await Yo(r);if(e||(e=Jo(r)??"unknown_file"),!t?.type){let n=i[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new Ue(i,e,t)}async function Yo(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Se(r))e.push(await r.arrayBuffer());else if(Xo(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${Ko(r)}`);return e}function Ko(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Jo(r){return Et(r.name)||Et(r.filename)||Et(r.path)?.split(/[\\/]/).pop()}var Et=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Xo=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ct=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var es=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},ts=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},He;async function vr(r){let{response:e}=r;if(r.options.stream)return re("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):M.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 o=await e.json();return re("response",e.status,e.url,e.headers,o),_r(o,e)}let n=await e.text();return re("response",e.status,e.url,e.headers,n),n}function _r(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 Ge=class r extends Promise{constructor(e,t=vr){super(i=>{i(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>_r(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:i=6e5,httpAgent:n,fetch:o}){this.baseURL=e,this.maxRetries=Pt("maxRetries",t),this.timeout=Pt("timeout",i),this.httpAgent=n,this.fetch=o??_t}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...os(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${cs()}`}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,i){return this.request(Promise.resolve(i).then(async n=>{let o=n&&Se(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:o}}))}getAPIList(e,t,i){return this.requestAPIList(t,{method:"get",path:e,...i})}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:i,path:n,query:o,headers:s={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Ct(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,f=this.calculateContentLength(a),h=this.buildURL(n,o);"timeout"in e&&Pt("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let x=e.httpAgent??this.httpAgent??St(h),v=e.timeout+1e3;typeof x?.options?.timeout=="number"&&v>(x.options.timeout??0)&&(x.options.timeout=v),this.idempotencyHeader&&i!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let Q=this.buildHeaders({options:e,headers:s,contentLength:f,retryCount:t});return{req:{method:i,...a&&{body:a},headers:Q,...x&&{agent:x},signal:e.signal??null},url:h,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:i,retryCount:n}){let o={};i&&(o["content-length"]=i);let s=this.defaultHeaders(e);return kr(o,s),kr(o,t),Ct(e.body)&&F!=="node"&&delete o["content-type"],We(s,"x-stainless-retry-count")===void 0&&We(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(n)),We(s,"x-stainless-timeout")===void 0&&We(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(o,t),o}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new l("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:i}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,i,n){return g.generate(e,t,i,n)}request(e,t=null){return new Ge(this.makeRequest(e,t))}async makeRequest(e,t){let i=await e,n=i.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(i);let{req:o,url:s,timeout:a}=this.buildRequest(i,{retryCount:n-t});if(await this.prepareRequest(o,{url:s,options:i}),re("request",s,i,o.headers),i.signal?.aborted)throw new y;let f=new AbortController,h=await this.fetchWithTimeout(s,o,a,f).catch(qe);if(h instanceof Error){if(i.signal?.aborted)throw new y;if(t)return this.retryRequest(i,t);throw h.name==="AbortError"?new te:new R({cause:h})}let x=It(h.headers);if(!h.ok){if(t&&this.shouldRetry(h)){let ft=`retrying, ${t} attempts remaining`;return re(`response (error; ${ft})`,h.status,s,x),this.retryRequest(i,t,x)}let v=await h.text().catch(ft=>qe(ft).message),Q=ss(v),pt=Q?void 0:v;throw re(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,h.status,s,x,pt),this.makeStatusError(h.status,Q,pt,x)}return{response:h,options:i,controller:f}}requestAPIList(e,t){let i=this.makeRequest(t,null);return new Tt(this,i,e)}buildURL(e,t){let i=ls(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Me(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,i])=>typeof i<"u").map(([t,i])=>{if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(i)}`;if(i===null)return`${encodeURIComponent(t)}=`;throw new l(`Cannot stringify type ${typeof i}; 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,i,n){let{signal:o,...s}=t||{};o&&o.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),i),f={signal:n.signal,...s};f.method&&(f.method=f.method.toUpperCase());let h=60*1e3,x=setTimeout(()=>{if(f&&f?.agent?.sockets)for(let v of Object.values(f?.agent?.sockets).flat())v?.setKeepAlive&&v.setKeepAlive(!0,h)},h);return this.fetch.call(void 0,e,f).finally(()=>{clearTimeout(a),clearTimeout(x)})}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,i){let n,o=i?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(n=a)}let s=i?.["retry-after"];if(s&&!n){let a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}if(!(n&&0<=n&&n<60*1e3)){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await us(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${U}`}},Ye=class{constructor(e,t,i,n){He.set(this,void 0),es(this,He,e,"f"),this.options=n,this.response=t,this.body=i}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new l("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 i=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,o]of i)e.url.searchParams.set(n,o);t.query=void 0,t.path=e.url.toString()}return await ts(this,He,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Tt=class extends Ge{constructor(e,t,i){super(t,async n=>new i(e,n.response,await vr(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},It=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let i=t.toString();return e[i.toLowerCase()]||e[i]}}),rs={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},_=r=>typeof r=="object"&&r!==null&&!Me(r)&&Object.keys(r).every(e=>Ar(rs,e)),is=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":wr(Deno.build.os),"X-Stainless-Arch":br(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":U,"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":U,"X-Stainless-OS":wr(process.platform),"X-Stainless-Arch":br(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=ns();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"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":U,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ns(){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 i=t.exec(navigator.userAgent);if(i){let n=i[1]||0,o=i[2]||0,s=i[3]||0;return{browser:e,version:`${n}.${o}.${s}`}}}return null}var br=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",wr=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"),xr,os=()=>xr??(xr=is()),ss=r=>{try{return JSON.parse(r)}catch{return}},as=/^[a-z][a-z0-9+.-]*:/i,ls=r=>as.test(r),us=r=>new Promise(e=>setTimeout(e,r)),Pt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new l(`${r} must be an integer`);if(e<0)throw new l(`${r} must be a positive integer`);return e},qe=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 Ke=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 Ar(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function kr(r,e){for(let t in e){if(!Ar(e,t))continue;let i=t.toLowerCase();if(!i)continue;let n=e[t];n===null?delete r[i]:n!==void 0&&(r[i]=n)}}function re(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var cs=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Sr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",ds=r=>typeof r?.get=="function";var We=(r,e)=>{let t=e.toLowerCase();if(ds(r)){let i=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,o,s)=>o+s.toUpperCase());for(let n of[e,t,e.toUpperCase(),i]){let o=r.get(n);if(o)return o}}for(let[i,n]of Object.entries(r))if(i.toLowerCase()===t)return Array.isArray(n)?(n.length<=1||console.warn(`Received ${n.length} entries for the ${e} header, using the first entry.`),n[0]):n};var I=class extends Ye{constructor(e,t,i,n){super(e,t,i,n),this.data=i.data||[],this.has_more=i.has_more||!1,this.first_id=i.first_id||null,this.last_id=i.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 m=class{constructor(e){this._client=e}};var q=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ie,{query:e,...t})}},ie=class extends I{};q.BetaModelInfosPage=ie;var ne=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new P;for await(let t of this.iterator)for(let i of e.decode(t))yield JSON.parse(i);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 l("Attempted to iterate over a response with no body");return new r(Ae(e.body),t)}};var V=class extends m{create(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},i){if(_(t))return this.retrieve(e,{},t);let{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}list(e={},t){if(_(e))return this.list({},e);let{betas:i,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",oe,{query:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},i){if(_(t))return this.delete(e,{},t);let{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}cancel(e,t={},i){if(_(t))return this.cancel(e,{},t);let{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}async results(e,t={},i){if(_(t))return this.results(e,{},t);let n=await this.retrieve(e);if(!n.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=t;return this._client.get(n.results_url,{...i,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...i?.headers},__binaryResponse:!0})._thenUnwrap((s,a)=>ne.fromResponse(a.response,a.controller))}},oe=class extends I{};V.BetaMessageBatchesPage=oe;var gs=r=>{let e=0,t=[];for(;e<r.length;){let i=r[e];if(i==="\\"){e++;continue}if(i==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(i==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(i==="["){t.push({type:"paren",value:"["}),e++;continue}if(i==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(i===":"){t.push({type:"separator",value:":"}),e++;continue}if(i===","){t.push({type:"delimiter",value:","}),e++;continue}if(i==='"'){let a="",f=!1;for(i=r[++e];i!=='"';){if(e===r.length){f=!0;break}if(i==="\\"){if(e++,e===r.length){f=!0;break}a+=i+r[e],i=r[++e]}else a+=i,i=r[++e]}i=r[++e],f||t.push({type:"string",value:a});continue}if(i&&/\s/.test(i)){e++;continue}let o=/[0-9]/;if(i&&o.test(i)||i==="-"||i==="."){let a="";for(i==="-"&&(a+=i,i=r[++e]);i&&o.test(i)||i===".";)a+=i,i=r[++e];t.push({type:"number",value:a});continue}let s=/[a-z]/i;if(i&&s.test(i)){let a="";for(;i&&s.test(i)&&e!==r.length;)a+=i,i=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},se=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),se(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),se(r);case"string":let i=r[r.length-2];if(i?.type==="delimiter")return r=r.slice(0,r.length-1),se(r);if(i?.type==="brace"&&i.value==="{")return r=r.slice(0,r.length-1),se(r);break;case"delimiter":return r=r.slice(0,r.length-1),se(r);break}return r},ms=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},ys=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Je=r=>JSON.parse(ys(ms(se(gs(r)))));var b=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},u=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},A,L,Ie,Xe,Ee,Ce,Ze,Pe,T,Te,et,tt,ae,rt,it,$t,Mr,jt,Rt,Lt,Nt,Ir,Er="__json_buf",nt=class r{constructor(){A.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),this.controller=new AbortController,Ie.set(this,void 0),Xe.set(this,()=>{}),Ee.set(this,()=>{}),Ce.set(this,void 0),Ze.set(this,()=>{}),Pe.set(this,()=>{}),T.set(this,{}),Te.set(this,!1),et.set(this,!1),tt.set(this,!1),ae.set(this,!1),rt.set(this,void 0),it.set(this,void 0),jt.set(this,e=>{if(b(this,et,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return b(this,tt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),b(this,Ie,new Promise((e,t)=>{b(this,Xe,e,"f"),b(this,Ee,t,"f")}),"f"),b(this,Ce,new Promise((e,t)=>{b(this,Ze,e,"f"),b(this,Pe,t,"f")}),"f"),u(this,Ie,"f").catch(()=>{}),u(this,Ce,"f").catch(()=>{})}get response(){return u(this,rt,"f")}get request_id(){return u(this,it,"f")}async withResponse(){let e=await u(this,Ie,"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,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,jt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)u(this,A,"m",Lt).call(this,a);if(s.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}_connected(e){this.ended||(b(this,rt,e,"f"),b(this,it,e?.headers.get("request-id"),"f"),u(this,Xe,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Te,"f")}get errored(){return u(this,et,"f")}get aborted(){return u(this,tt,"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 i=u(this,T,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,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,i)=>{b(this,ae,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){b(this,ae,!0,"f"),await u(this,Ce,"f")}get currentMessage(){return u(this,L,"f")}async finalMessage(){return await this.done(),u(this,A,"m",$t).call(this)}async finalText(){return await this.done(),u(this,A,"m",Mr).call(this)}_emit(e,...t){if(u(this,Te,"f"))return;e==="end"&&(b(this,Te,!0,"f"),u(this,Ze,"f").call(this));let i=u(this,T,"f")[e];if(i&&(u(this,T,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,A,"m",$t).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let o of n)u(this,A,"m",Lt).call(this,o);if(n.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}[(L=new WeakMap,Ie=new WeakMap,Xe=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Ze=new WeakMap,Pe=new WeakMap,T=new WeakMap,Te=new WeakMap,et=new WeakMap,tt=new WeakMap,ae=new WeakMap,rt=new WeakMap,it=new WeakMap,jt=new WeakMap,A=new WeakSet,$t=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Mr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Rt=function(){this.ended||b(this,L,void 0,"f")},Lt=function(t){if(this.ended)return;let i=u(this,A,"m",Ir).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{b(this,L,i,"f");break}case"content_block_start":case"message_delta":break}},Nt=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=u(this,L,"f");if(!t)throw new l("request ended without sending any chunks");return b(this,L,void 0,"f"),t},Ir=function(t){let i=u(this,L,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[Er]||"";o+=t.delta.partial_json,Object.defineProperty(n,Er,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Cr={"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"},N=class extends m{constructor(){super(...arguments),this.batches=new V(this._client)}create(e,t){let{betas:i,...n}=e;return n.model in Cr&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Cr[n.model]}
|
|
67
|
-
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:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return nt.createMessage(this,e,t)}countTokens(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};N.Batches=V;N.BetaMessageBatchesPage=oe;var E=class extends m{constructor(){super(...arguments),this.models=new q(this._client),this.messages=new N(this._client)}};E.Models=q;E.BetaModelInfosPage=ie;E.Messages=N;var H=class extends m{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var W=class extends m{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 _(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",le,{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 i=await this.retrieve(e);if(!i.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);return this._client.get(i.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((n,o)=>ne.fromResponse(o.response,o.controller))}},le=class extends I{};W.MessageBatchesPage=le;var w=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},c=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},S,O,$e,ot,je,Re,st,Le,$,Ne,at,lt,ue,ut,ct,Ot,Pr,Dt,Bt,Ut,Ft,Tr,$r="__json_buf",dt=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],O.set(this,void 0),this.controller=new AbortController,$e.set(this,void 0),ot.set(this,()=>{}),je.set(this,()=>{}),Re.set(this,void 0),st.set(this,()=>{}),Le.set(this,()=>{}),$.set(this,{}),Ne.set(this,!1),at.set(this,!1),lt.set(this,!1),ue.set(this,!1),ut.set(this,void 0),ct.set(this,void 0),Dt.set(this,e=>{if(w(this,at,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return w(this,lt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),w(this,$e,new Promise((e,t)=>{w(this,ot,e,"f"),w(this,je,t,"f")}),"f"),w(this,Re,new Promise((e,t)=>{w(this,st,e,"f"),w(this,Le,t,"f")}),"f"),c(this,$e,"f").catch(()=>{}),c(this,Re,"f").catch(()=>{})}get response(){return c(this,ut,"f")}get request_id(){return c(this,ct,"f")}async withResponse(){let e=await c(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,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Dt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Bt).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)c(this,S,"m",Ut).call(this,a);if(s.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}_connected(e){this.ended||(w(this,ut,e,"f"),w(this,ct,e?.headers.get("request-id"),"f"),c(this,ot,"f").call(this,e),this._emit("connect"))}get ended(){return c(this,Ne,"f")}get errored(){return c(this,at,"f")}get aborted(){return c(this,lt,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,$,"f")[e]||(c(this,$,"f")[e]=[])).push({listener:t}),this}off(e,t){let i=c(this,$,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,1),this}once(e,t){return(c(this,$,"f")[e]||(c(this,$,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,i)=>{w(this,ue,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){w(this,ue,!0,"f"),await c(this,Re,"f")}get currentMessage(){return c(this,O,"f")}async finalMessage(){return await this.done(),c(this,S,"m",Ot).call(this)}async finalText(){return await this.done(),c(this,S,"m",Pr).call(this)}_emit(e,...t){if(c(this,Ne,"f"))return;e==="end"&&(w(this,Ne,!0,"f"),c(this,st,"f").call(this));let i=c(this,$,"f")[e];if(i&&(c(this,$,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,je,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,je,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",c(this,S,"m",Ot).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Bt).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let o of n)c(this,S,"m",Ut).call(this,o);if(n.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}[(O=new WeakMap,$e=new WeakMap,ot=new WeakMap,je=new WeakMap,Re=new WeakMap,st=new WeakMap,Le=new WeakMap,$=new WeakMap,Ne=new WeakMap,at=new WeakMap,lt=new WeakMap,ue=new WeakMap,ut=new WeakMap,ct=new WeakMap,Dt=new WeakMap,S=new WeakSet,Ot=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Pr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Bt=function(){this.ended||w(this,O,void 0,"f")},Ut=function(t){if(this.ended)return;let i=c(this,S,"m",Tr).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{w(this,O,i,"f");break}case"content_block_start":case"message_delta":break}},Ft=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=c(this,O,"f");if(!t)throw new l("request ended without sending any chunks");return w(this,O,void 0,"f"),t},Tr=function(t){let i=c(this,O,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[$r]||"";o+=t.delta.partial_json,Object.defineProperty(n,$r,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var j=class extends m{constructor(){super(...arguments),this.batches=new W(this._client)}create(e,t){return e.model in jr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${jr[e.model]}
|
|
68
|
-
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 dt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}
|
|
66
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,i,n]=Wo(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Wo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var Go=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Qo=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Se(r),Se=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 yr(r,e,t){if(r=await r,Qo(r))return r;if(Go(r)){let n=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Se(n)?[await n.arrayBuffer()]:[n];return new Be(o,e,t)}let i=await Yo(r);if(e||(e=Jo(r)??"unknown_file"),!t?.type){let n=i[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new Be(i,e,t)}async function Yo(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Se(r))e.push(await r.arrayBuffer());else if(Xo(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${Ko(r)}`);return e}function Ko(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Jo(r){return Et(r.name)||Et(r.filename)||Et(r.path)?.split(/[\\/]/).pop()}var Et=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Xo=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ct=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var es=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},ts=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},He;async function vr(r){let{response:e}=r;if(r.options.stream)return re("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):M.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 o=await e.json();return re("response",e.status,e.url,e.headers,o),_r(o,e)}let n=await e.text();return re("response",e.status,e.url,e.headers,n),n}function _r(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 Ge=class r extends Promise{constructor(e,t=vr){super(i=>{i(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>_r(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:i=6e5,httpAgent:n,fetch:o}){this.baseURL=e,this.maxRetries=Pt("maxRetries",t),this.timeout=Pt("timeout",i),this.httpAgent=n,this.fetch=o??_t}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...os(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${cs()}`}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,i){return this.request(Promise.resolve(i).then(async n=>{let o=n&&Se(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:o}}))}getAPIList(e,t,i){return this.requestAPIList(t,{method:"get",path:e,...i})}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:i,path:n,query:o,headers:s={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Ct(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,f=this.calculateContentLength(a),g=this.buildURL(n,o);"timeout"in e&&Pt("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let k=e.httpAgent??this.httpAgent??St(g),v=e.timeout+1e3;typeof k?.options?.timeout=="number"&&v>(k.options.timeout??0)&&(k.options.timeout=v),this.idempotencyHeader&&i!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let Q=this.buildHeaders({options:e,headers:s,contentLength:f,retryCount:t});return{req:{method:i,...a&&{body:a},headers:Q,...k&&{agent:k},signal:e.signal??null},url:g,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:i,retryCount:n}){let o={};i&&(o["content-length"]=i);let s=this.defaultHeaders(e);return xr(o,s),xr(o,t),Ct(e.body)&&F!=="node"&&delete o["content-type"],We(s,"x-stainless-retry-count")===void 0&&We(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(n)),We(s,"x-stainless-timeout")===void 0&&We(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(o,t),o}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new l("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:i}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,i,n){return h.generate(e,t,i,n)}request(e,t=null){return new Ge(this.makeRequest(e,t))}async makeRequest(e,t){let i=await e,n=i.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(i);let{req:o,url:s,timeout:a}=this.buildRequest(i,{retryCount:n-t});if(await this.prepareRequest(o,{url:s,options:i}),re("request",s,i,o.headers),i.signal?.aborted)throw new y;let f=new AbortController,g=await this.fetchWithTimeout(s,o,a,f).catch(qe);if(g instanceof Error){if(i.signal?.aborted)throw new y;if(t)return this.retryRequest(i,t);throw g.name==="AbortError"?new te:new R({cause:g})}let k=It(g.headers);if(!g.ok){if(t&&this.shouldRetry(g)){let ft=`retrying, ${t} attempts remaining`;return re(`response (error; ${ft})`,g.status,s,k),this.retryRequest(i,t,k)}let v=await g.text().catch(ft=>qe(ft).message),Q=ss(v),pt=Q?void 0:v;throw re(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,g.status,s,k,pt),this.makeStatusError(g.status,Q,pt,k)}return{response:g,options:i,controller:f}}requestAPIList(e,t){let i=this.makeRequest(t,null);return new Tt(this,i,e)}buildURL(e,t){let i=ls(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Me(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,i])=>typeof i<"u").map(([t,i])=>{if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(i)}`;if(i===null)return`${encodeURIComponent(t)}=`;throw new l(`Cannot stringify type ${typeof i}; 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,i,n){let{signal:o,...s}=t||{};o&&o.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),i),f={signal:n.signal,...s};f.method&&(f.method=f.method.toUpperCase());let g=60*1e3,k=setTimeout(()=>{if(f&&f?.agent?.sockets)for(let v of Object.values(f?.agent?.sockets).flat())v?.setKeepAlive&&v.setKeepAlive(!0,g)},g);return this.fetch.call(void 0,e,f).finally(()=>{clearTimeout(a),clearTimeout(k)})}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,i){let n,o=i?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(n=a)}let s=i?.["retry-after"];if(s&&!n){let a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}if(!(n&&0<=n&&n<60*1e3)){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await us(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${B}`}},Ye=class{constructor(e,t,i,n){He.set(this,void 0),es(this,He,e,"f"),this.options=n,this.response=t,this.body=i}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new l("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 i=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,o]of i)e.url.searchParams.set(n,o);t.query=void 0,t.path=e.url.toString()}return await ts(this,He,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Tt=class extends Ge{constructor(e,t,i){super(t,async n=>new i(e,n.response,await vr(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},It=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let i=t.toString();return e[i.toLowerCase()]||e[i]}}),rs={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},_=r=>typeof r=="object"&&r!==null&&!Me(r)&&Object.keys(r).every(e=>Ar(rs,e)),is=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":wr(Deno.build.os),"X-Stainless-Arch":br(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":B,"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":B,"X-Stainless-OS":wr(process.platform),"X-Stainless-Arch":br(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=ns();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"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":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ns(){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 i=t.exec(navigator.userAgent);if(i){let n=i[1]||0,o=i[2]||0,s=i[3]||0;return{browser:e,version:`${n}.${o}.${s}`}}}return null}var br=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",wr=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"),kr,os=()=>kr??(kr=is()),ss=r=>{try{return JSON.parse(r)}catch{return}},as=/^[a-z][a-z0-9+.-]*:/i,ls=r=>as.test(r),us=r=>new Promise(e=>setTimeout(e,r)),Pt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new l(`${r} must be an integer`);if(e<0)throw new l(`${r} must be a positive integer`);return e},qe=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 Ke=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 Ar(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function xr(r,e){for(let t in e){if(!Ar(e,t))continue;let i=t.toLowerCase();if(!i)continue;let n=e[t];n===null?delete r[i]:n!==void 0&&(r[i]=n)}}function re(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var cs=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Sr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",ds=r=>typeof r?.get=="function";var We=(r,e)=>{let t=e.toLowerCase();if(ds(r)){let i=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,o,s)=>o+s.toUpperCase());for(let n of[e,t,e.toUpperCase(),i]){let o=r.get(n);if(o)return o}}for(let[i,n]of Object.entries(r))if(i.toLowerCase()===t)return Array.isArray(n)?(n.length<=1||console.warn(`Received ${n.length} entries for the ${e} header, using the first entry.`),n[0]):n};var I=class extends Ye{constructor(e,t,i,n){super(e,t,i,n),this.data=i.data||[],this.has_more=i.has_more||!1,this.first_id=i.first_id||null,this.last_id=i.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 m=class{constructor(e){this._client=e}};var q=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ie,{query:e,...t})}},ie=class extends I{};q.BetaModelInfosPage=ie;var ne=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new P;for await(let t of this.iterator)for(let i of e.decode(t))yield JSON.parse(i);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 l("Attempted to iterate over a response with no body");return new r(Ae(e.body),t)}};var V=class extends m{create(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},i){if(_(t))return this.retrieve(e,{},t);let{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}list(e={},t){if(_(e))return this.list({},e);let{betas:i,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",oe,{query:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},i){if(_(t))return this.delete(e,{},t);let{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}cancel(e,t={},i){if(_(t))return this.cancel(e,{},t);let{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}async results(e,t={},i){if(_(t))return this.results(e,{},t);let n=await this.retrieve(e);if(!n.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=t;return this._client.get(n.results_url,{...i,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...i?.headers},__binaryResponse:!0})._thenUnwrap((s,a)=>ne.fromResponse(a.response,a.controller))}},oe=class extends I{};V.BetaMessageBatchesPage=oe;var hs=r=>{let e=0,t=[];for(;e<r.length;){let i=r[e];if(i==="\\"){e++;continue}if(i==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(i==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(i==="["){t.push({type:"paren",value:"["}),e++;continue}if(i==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(i===":"){t.push({type:"separator",value:":"}),e++;continue}if(i===","){t.push({type:"delimiter",value:","}),e++;continue}if(i==='"'){let a="",f=!1;for(i=r[++e];i!=='"';){if(e===r.length){f=!0;break}if(i==="\\"){if(e++,e===r.length){f=!0;break}a+=i+r[e],i=r[++e]}else a+=i,i=r[++e]}i=r[++e],f||t.push({type:"string",value:a});continue}if(i&&/\s/.test(i)){e++;continue}let o=/[0-9]/;if(i&&o.test(i)||i==="-"||i==="."){let a="";for(i==="-"&&(a+=i,i=r[++e]);i&&o.test(i)||i===".";)a+=i,i=r[++e];t.push({type:"number",value:a});continue}let s=/[a-z]/i;if(i&&s.test(i)){let a="";for(;i&&s.test(i)&&e!==r.length;)a+=i,i=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},se=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),se(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),se(r);case"string":let i=r[r.length-2];if(i?.type==="delimiter")return r=r.slice(0,r.length-1),se(r);if(i?.type==="brace"&&i.value==="{")return r=r.slice(0,r.length-1),se(r);break;case"delimiter":return r=r.slice(0,r.length-1),se(r);break}return r},ms=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},ys=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Je=r=>JSON.parse(ys(ms(se(hs(r)))));var b=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},u=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},A,L,Ie,Xe,Ee,Ce,Ze,Pe,T,Te,et,tt,ae,rt,it,jt,Mr,$t,Rt,Lt,Nt,Ir,Er="__json_buf",nt=class r{constructor(){A.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),this.controller=new AbortController,Ie.set(this,void 0),Xe.set(this,()=>{}),Ee.set(this,()=>{}),Ce.set(this,void 0),Ze.set(this,()=>{}),Pe.set(this,()=>{}),T.set(this,{}),Te.set(this,!1),et.set(this,!1),tt.set(this,!1),ae.set(this,!1),rt.set(this,void 0),it.set(this,void 0),$t.set(this,e=>{if(b(this,et,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return b(this,tt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),b(this,Ie,new Promise((e,t)=>{b(this,Xe,e,"f"),b(this,Ee,t,"f")}),"f"),b(this,Ce,new Promise((e,t)=>{b(this,Ze,e,"f"),b(this,Pe,t,"f")}),"f"),u(this,Ie,"f").catch(()=>{}),u(this,Ce,"f").catch(()=>{})}get response(){return u(this,rt,"f")}get request_id(){return u(this,it,"f")}async withResponse(){let e=await u(this,Ie,"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,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,$t,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)u(this,A,"m",Lt).call(this,a);if(s.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}_connected(e){this.ended||(b(this,rt,e,"f"),b(this,it,e?.headers.get("request-id"),"f"),u(this,Xe,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Te,"f")}get errored(){return u(this,et,"f")}get aborted(){return u(this,tt,"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 i=u(this,T,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,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,i)=>{b(this,ae,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){b(this,ae,!0,"f"),await u(this,Ce,"f")}get currentMessage(){return u(this,L,"f")}async finalMessage(){return await this.done(),u(this,A,"m",jt).call(this)}async finalText(){return await this.done(),u(this,A,"m",Mr).call(this)}_emit(e,...t){if(u(this,Te,"f"))return;e==="end"&&(b(this,Te,!0,"f"),u(this,Ze,"f").call(this));let i=u(this,T,"f")[e];if(i&&(u(this,T,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,A,"m",jt).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let o of n)u(this,A,"m",Lt).call(this,o);if(n.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}[(L=new WeakMap,Ie=new WeakMap,Xe=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Ze=new WeakMap,Pe=new WeakMap,T=new WeakMap,Te=new WeakMap,et=new WeakMap,tt=new WeakMap,ae=new WeakMap,rt=new WeakMap,it=new WeakMap,$t=new WeakMap,A=new WeakSet,jt=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Mr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Rt=function(){this.ended||b(this,L,void 0,"f")},Lt=function(t){if(this.ended)return;let i=u(this,A,"m",Ir).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{b(this,L,i,"f");break}case"content_block_start":case"message_delta":break}},Nt=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=u(this,L,"f");if(!t)throw new l("request ended without sending any chunks");return b(this,L,void 0,"f"),t},Ir=function(t){let i=u(this,L,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[Er]||"";o+=t.delta.partial_json,Object.defineProperty(n,Er,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Cr={"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"},N=class extends m{constructor(){super(...arguments),this.batches=new V(this._client)}create(e,t){let{betas:i,...n}=e;return n.model in Cr&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Cr[n.model]}
|
|
67
|
+
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:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return nt.createMessage(this,e,t)}countTokens(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};N.Batches=V;N.BetaMessageBatchesPage=oe;var E=class extends m{constructor(){super(...arguments),this.models=new q(this._client),this.messages=new N(this._client)}};E.Models=q;E.BetaModelInfosPage=ie;E.Messages=N;var H=class extends m{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var W=class extends m{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 _(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",le,{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 i=await this.retrieve(e);if(!i.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);return this._client.get(i.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((n,o)=>ne.fromResponse(o.response,o.controller))}},le=class extends I{};W.MessageBatchesPage=le;var w=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},c=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},S,O,je,ot,$e,Re,st,Le,j,Ne,at,lt,ue,ut,ct,Ot,Pr,Dt,Ut,Bt,Ft,Tr,jr="__json_buf",dt=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],O.set(this,void 0),this.controller=new AbortController,je.set(this,void 0),ot.set(this,()=>{}),$e.set(this,()=>{}),Re.set(this,void 0),st.set(this,()=>{}),Le.set(this,()=>{}),j.set(this,{}),Ne.set(this,!1),at.set(this,!1),lt.set(this,!1),ue.set(this,!1),ut.set(this,void 0),ct.set(this,void 0),Dt.set(this,e=>{if(w(this,at,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return w(this,lt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),w(this,je,new Promise((e,t)=>{w(this,ot,e,"f"),w(this,$e,t,"f")}),"f"),w(this,Re,new Promise((e,t)=>{w(this,st,e,"f"),w(this,Le,t,"f")}),"f"),c(this,je,"f").catch(()=>{}),c(this,Re,"f").catch(()=>{})}get response(){return c(this,ut,"f")}get request_id(){return c(this,ct,"f")}async withResponse(){let e=await c(this,je,"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,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Dt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Ut).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)c(this,S,"m",Bt).call(this,a);if(s.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}_connected(e){this.ended||(w(this,ut,e,"f"),w(this,ct,e?.headers.get("request-id"),"f"),c(this,ot,"f").call(this,e),this._emit("connect"))}get ended(){return c(this,Ne,"f")}get errored(){return c(this,at,"f")}get aborted(){return c(this,lt,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,j,"f")[e]||(c(this,j,"f")[e]=[])).push({listener:t}),this}off(e,t){let i=c(this,j,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,1),this}once(e,t){return(c(this,j,"f")[e]||(c(this,j,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,i)=>{w(this,ue,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){w(this,ue,!0,"f"),await c(this,Re,"f")}get currentMessage(){return c(this,O,"f")}async finalMessage(){return await this.done(),c(this,S,"m",Ot).call(this)}async finalText(){return await this.done(),c(this,S,"m",Pr).call(this)}_emit(e,...t){if(c(this,Ne,"f"))return;e==="end"&&(w(this,Ne,!0,"f"),c(this,st,"f").call(this));let i=c(this,j,"f")[e];if(i&&(c(this,j,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,$e,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,$e,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",c(this,S,"m",Ot).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Ut).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let o of n)c(this,S,"m",Bt).call(this,o);if(n.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}[(O=new WeakMap,je=new WeakMap,ot=new WeakMap,$e=new WeakMap,Re=new WeakMap,st=new WeakMap,Le=new WeakMap,j=new WeakMap,Ne=new WeakMap,at=new WeakMap,lt=new WeakMap,ue=new WeakMap,ut=new WeakMap,ct=new WeakMap,Dt=new WeakMap,S=new WeakSet,Ot=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Pr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Ut=function(){this.ended||w(this,O,void 0,"f")},Bt=function(t){if(this.ended)return;let i=c(this,S,"m",Tr).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{w(this,O,i,"f");break}case"content_block_start":case"message_delta":break}},Ft=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=c(this,O,"f");if(!t)throw new l("request ended without sending any chunks");return w(this,O,void 0,"f"),t},Tr=function(t){let i=c(this,O,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[jr]||"";o+=t.delta.partial_json,Object.defineProperty(n,jr,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var $=class extends m{constructor(){super(...arguments),this.batches=new W(this._client)}create(e,t){return e.model in $r&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${$r[e.model]}
|
|
68
|
+
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 dt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},$r={"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"};$.Batches=W;$.MessageBatchesPage=le;var D=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models",G,{query:e,...t})}},G=class extends I{};D.ModelInfosPage=G;var Rr,d=class extends Qe{constructor({baseURL:e=Ke("ANTHROPIC_BASE_URL"),apiKey:t=Ke("ANTHROPIC_API_KEY")??null,authToken:i=Ke("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){let o={apiKey:t,authToken:i,...n,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&Sr())throw new l(`It looks like you're running in a browser-like environment.
|
|
69
69
|
|
|
70
70
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
71
71
|
If you understand the risks and have appropriate mitigations in place,
|
|
72
72
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
73
73
|
|
|
74
74
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
75
|
-
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new H(this),this.messages=new
|
|
75
|
+
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new H(this),this.messages=new $(this),this.models=new D(this),this.beta=new E(this),this._options=o,this.apiKey=t,this.authToken=i}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"])&&t["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&t.authorization!==null)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(e){let t=this.apiKeyAuth(e),i=this.bearerAuth(e);return t!=null&&!Me(t)?t:i!=null&&!Me(i)?i:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};Rr=d;d.Anthropic=Rr;d.HUMAN_PROMPT=`
|
|
76
76
|
|
|
77
77
|
Human:`;d.AI_PROMPT=`
|
|
78
78
|
|
|
79
|
-
Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=l;d.APIError=
|
|
79
|
+
Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=l;d.APIError=h;d.APIConnectionError=R;d.APIConnectionTimeoutError=te;d.APIUserAbortError=y;d.NotFoundError=we;d.ConflictError=ke;d.RateLimitError=ve;d.BadRequestError=me;d.AuthenticationError=ye;d.InternalServerError=_e;d.PermissionDeniedError=be;d.UnprocessableEntityError=xe;d.toFile=yr;d.fileFromPath=Fe;d.Completions=H;d.Messages=$;d.Models=D;d.ModelInfosPage=G;d.Beta=E;var{HUMAN_PROMPT:kl,AI_PROMPT:xl}=d,Lr=d;var xs={model:"claude-3-7-sonnet-20250219",max_tokens:8192,temperature:.1},Nr={headers:{"x-api-key":null,authorization:null}};async function vs(r,e,t,i){let n={};e.model&&(n.model=e.model),e.maxTokens&&(n.max_tokens=e.maxTokens),e.temperature&&(n.temperature=e.temperature);let o=await r.messages.create({...xs,...n,stream:!0,messages:[{role:"user",content:[{type:"text",text:t}]}]},{signal:i,...Nr,headers:{...Nr.headers??{},...e.headers}});async function*s(){try{for await(let a of o)a.type==="content_block_delta"&&a.delta.type==="text_delta"&&(yield a.delta.text)}catch(a){throw console.error("Stream error:",a),a}}return s()}var Or=vs;function Dr(r){return()=>{let e=null,i=ur({"ly.img.improve":!0,"ly.img.fix":{},"ly.img.shorter":!0,"ly.img.longer":{},"ly.img.changeTone":!0,"ly.img.translate":!0,"ly.img.changeTextTo":{}},r.supportedQuickActions),n={kind:"text",id:"anthropic",name:"Anthropic",initialize:async()=>{e=new Lr({dangerouslyAllowBrowser:!0,baseURL:r.proxyUrl,apiKey:null,authToken:null})},input:{quickActions:{supported:i}},output:{middleware:r.middlewares??r.middleware??[],generate:async({prompt:o,blockId:s},{engine:a,abortSignal:f})=>{if(e==null)throw new Error("Anthropic SDK is not initialized");if(s!=null&&a.block.getType(s)!=="//ly.img.ubq/text")throw new Error("If a block is provided to this generation, it most be a text block");r.debug&&console.log("Sending prompt to Anthropic:",JSON.stringify(o,void 0,2));let g=await Or(e,{proxyUrl:r.proxyUrl,headers:r.headers,model:r.model??"claude-3-7-sonnet-20250219"},o,f);async function*k(){let v="";for await(let Q of g){if(f?.aborted)break;v+=Q,yield{kind:"text",text:v}}return{kind:"text",text:v}}return k()}}};return Promise.resolve(n)}}var _s={AnthropicProvider:Dr},Cl=_s;export{Cl as default};
|
|
80
80
|
/*! Bundled license information:
|
|
81
81
|
|
|
82
82
|
@imgly/plugin-ai-generation-web/dist/index.mjs:
|