iobroker.javascript
Version:
Rules Engine for ioBroker
10 lines • 112 kB
JavaScript
import{c as pr,j as P}from"./createSvgIcon-DlIk-fDn.js";import{i as Z}from"./iobroker_javascript__loadShare__react__loadShare__-i8pXne9X.js";import{i as j,c as pn,C as gr}from"./index-Cjl4b70e.js";import{i as U,h as _r}from"./index-DBgNhNiJ.js";import{_ as yr}from"./preload-helper-BDBacUwf.js";import{C as wr,t as br}from"./index-DZ3lKVw8.js";import xr from"./ScriptEditorVanillaMonaco-CJS71hoK.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-DZdFIfoQ.js";import"./inheritsLoose-DNrhibGS.js";const Sr=pr(P.jsx("path",{d:"M11.07 12.85c.77-1.39 2.25-2.21 3.11-3.44.91-1.29.4-3.7-2.18-3.7-1.69 0-2.52 1.28-2.87 2.34L6.54 6.96C7.25 4.83 9.18 3 11.99 3c2.35 0 3.96 1.07 4.78 2.41.7 1.15 1.11 3.3.03 4.9-1.2 1.77-2.35 2.31-2.97 3.45-.25.46-.35.76-.35 2.24h-2.89c-.01-.78-.13-2.05.48-3.15M14 20c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2"}),"QuestionMark");function R(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}function c(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}let qn=function(){const{crypto:s}=globalThis;if(s!=null&&s.randomUUID)return qn=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function Et(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}const Pt=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};class x extends Error{}class H extends x{constructor(e,t,n,r){super(`${H.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r==null?void 0:r.get("x-request-id"),this.error=t;const a=t;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(e,t,n){const r=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new pt({message:n,cause:Pt(t)});const a=t==null?void 0:t.error;return e===400?new Jn(e,a,n,r):e===401?new Hn(e,a,n,r):e===403?new Xn(e,a,n,r):e===404?new Kn(e,a,n,r):e===409?new Vn(e,a,n,r):e===422?new Gn(e,a,n,r):e===429?new Qn(e,a,n,r):e>=500?new zn(e,a,n,r):new H(e,a,n,r)}}class z extends H{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class pt extends H{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Jt extends pt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Jn extends H{}class Hn extends H{}class Xn extends H{}class Kn extends H{}class Vn extends H{}class Gn extends H{}class Qn extends H{}class zn extends H{}class Yn extends x{constructor(){super("Could not parse response content as the length limit was reached")}}class Zn extends x{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Re extends Error{constructor(e){super(e)}}const Ar=/^[a-z][a-z0-9+.-]*:/i,vr=s=>Ar.test(s);let K=s=>(K=Array.isArray,K(s)),gn=K;function es(s){return typeof s!="object"?{}:s??{}}function Cr(s){if(!s)return!0;for(const e in s)return!1;return!0}function Ir(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function St(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}const Rr=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${s} must be an integer`);if(e<0)throw new x(`${s} must be a positive integer`);return e},$r=s=>{try{return JSON.parse(s)}catch{return}},Be=s=>new Promise(e=>setTimeout(e,s)),we="5.23.2",kr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Or(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Er=()=>{var t;const s=Or();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":yn(Deno.build.os),"X-Stainless-Arch":_n(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((t=Deno.version)==null?void 0:t.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":yn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":_n(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Pr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Pr(){if(typeof navigator>"u"||!navigator)return null;const s=[{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(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const _n=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",yn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown");let wn;const Tr=()=>wn??(wn=Er());function Mr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ts(...s){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function ns(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return ts({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function ss(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Nr(s){var n,r;if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await((r=(n=s[Symbol.asyncIterator]()).return)==null?void 0:r.call(n));return}const e=s.getReader(),t=e.cancel();e.releaseLock(),await t}const jr=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),rs="RFC3986",as=s=>String(s),bn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:as},Fr="RFC1738";let Tt=(s,e)=>(Tt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Tt(s,e));const ee=(()=>{const s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})(),At=1024,Lr=(s,e,t,n,r)=>{if(s.length===0)return s;let a=s;if(typeof s=="symbol"?a=Symbol.prototype.toString.call(s):typeof s!="string"&&(a=String(s)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=At){const l=a.length>=At?a.slice(o,o+At):a,u=[];for(let m=0;m<l.length;++m){let h=l.charCodeAt(m);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||r===Fr&&(h===40||h===41)){u[u.length]=l.charAt(m);continue}if(h<128){u[u.length]=ee[h];continue}if(h<2048){u[u.length]=ee[192|h>>6]+ee[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=ee[224|h>>12]+ee[128|h>>6&63]+ee[128|h&63];continue}m+=1,h=65536+((h&1023)<<10|l.charCodeAt(m)&1023),u[u.length]=ee[240|h>>18]+ee[128|h>>12&63]+ee[128|h>>6&63]+ee[128|h&63]}i+=u.join("")}return i};function Dr(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function xn(s,e){if(K(s)){const t=[];for(let n=0;n<s.length;n+=1)t.push(e(s[n]));return t}return e(s)}const is={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},os=function(s,e){Array.prototype.push.apply(s,K(e)?e:[e])};let Sn;const B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Lr,encodeValuesOnly:!1,format:rs,formatter:as,indices:!1,serializeDate(s){return(Sn??(Sn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Br(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}const vt={};function cs(s,e,t,n,r,a,i,o,l,u,m,h,g,d,b,w,v,E){let p=s,y=E,_=0,C=!1;for(;(y=y.get(vt))!==void 0&&!C;){const T=y.get(s);if(_+=1,typeof T<"u"){if(T===_)throw new RangeError("Cyclic object value");C=!0}typeof y.get(vt)>"u"&&(_=0)}if(typeof u=="function"?p=u(e,p):p instanceof Date?p=g==null?void 0:g(p):t==="comma"&&K(p)&&(p=xn(p,function(T){return T instanceof Date?g==null?void 0:g(T):T})),p===null){if(a)return l&&!w?l(e,B.encoder,v,"key",d):e;p=""}if(Br(p)||Dr(p)){if(l){const T=w?e:l(e,B.encoder,v,"key",d);return[(b==null?void 0:b(T))+"="+(b==null?void 0:b(l(p,B.encoder,v,"value",d)))]}return[(b==null?void 0:b(e))+"="+(b==null?void 0:b(String(p)))]}const k=[];if(typeof p>"u")return k;let $;if(t==="comma"&&K(p))w&&l&&(p=xn(p,l)),$=[{value:p.length>0?p.join(",")||null:void 0}];else if(K(u))$=u;else{const T=Object.keys(p);$=m?T.sort(m):T}const F=o?String(e).replace(/\./g,"%2E"):String(e),A=n&&K(p)&&p.length===1?F+"[]":F;if(r&&K(p)&&p.length===0)return A+"[]";for(let T=0;T<$.length;++T){const M=$[T],se=typeof M=="object"&&typeof M.value<"u"?M.value:p[M];if(i&&se===null)continue;const me=h&&o?M.replace(/\./g,"%2E"):M,N=K(p)?typeof t=="function"?t(A,me):A:A+(h?"."+me:"["+me+"]");E.set(s,_);const ie=new WeakMap;ie.set(vt,E),os(k,cs(se,N,t,n,r,a,i,o,t==="comma"&&w&&K(p)?null:l,u,m,h,g,d,b,w,v,ie))}return k}function Wr(s=B){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=s.charset||B.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=rs;if(typeof s.format<"u"){if(!Tt(bn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}const n=bn[t];let r=B.filter;(typeof s.filter=="function"||K(s.filter))&&(r=s.filter);let a;if(s.arrayFormat&&s.arrayFormat in is?a=s.arrayFormat:"indices"in s?a=s.indices?"indices":"repeat":a=B.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:B.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:B.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:B.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:B.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?B.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:B.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:B.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:B.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:B.encodeValuesOnly,filter:r,format:t,formatter:n,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:B.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:B.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:B.strictNullHandling}}function Ur(s,e={}){let t=s;const n=Wr(e);let r,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):K(n.filter)&&(a=n.filter,r=a);const i=[];if(typeof t!="object"||t===null)return"";const o=is[n.arrayFormat],l=o==="comma"&&n.commaRoundTrip;r||(r=Object.keys(t)),n.sort&&r.sort(n.sort);const u=new WeakMap;for(let g=0;g<r.length;++g){const d=r[g];n.skipNulls&&t[d]===null||os(i,cs(t[d],d,o,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}const m=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),m.length>0?h+m:""}function qr(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}let An;function Ht(s){let e;return(An??(e=new globalThis.TextEncoder,An=e.encode.bind(e)))(s)}let vn;function Cn(s){let e;return(vn??(e=new globalThis.TextDecoder,vn=e.decode.bind(e)))(s)}var V,G;class gt{constructor(){V.set(this,void 0),G.set(this,void 0),R(this,V,new Uint8Array),R(this,G,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ht(e):e;R(this,V,qr([c(this,V,"f"),t]));const n=[];let r;for(;(r=Jr(c(this,V,"f"),c(this,G,"f")))!=null;){if(r.carriage&&c(this,G,"f")==null){R(this,G,r.index);continue}if(c(this,G,"f")!=null&&(r.index!==c(this,G,"f")+1||r.carriage)){n.push(Cn(c(this,V,"f").subarray(0,c(this,G,"f")-1))),R(this,V,c(this,V,"f").subarray(c(this,G,"f"))),R(this,G,null);continue}const a=c(this,G,"f")!==null?r.preceding-1:r.preceding,i=Cn(c(this,V,"f").subarray(0,a));n.push(i),R(this,V,c(this,V,"f").subarray(r.index)),R(this,G,null)}return n}flush(){return c(this,V,"f").length?this.decode(`
`):[]}}V=new WeakMap,G=new WeakMap;gt.NEWLINE_CHARS=new Set([`
`,"\r"]);gt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Jr(s,e){for(let r=e??0;r<s.length;r++){if(s[r]===10)return{preceding:r,index:r+1,carriage:!1};if(s[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Hr(s){for(let n=0;n<s.length-1;n++){if(s[n]===10&&s[n+1]===10||s[n]===13&&s[n+1]===13)return n+2;if(s[n]===13&&s[n+1]===10&&n+3<s.length&&s[n+2]===13&&s[n+3]===10)return n+4}return-1}const ot={off:0,error:200,warn:300,info:400,debug:500},In=(s,e,t)=>{if(s){if(Ir(ot,s))return s;q(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(ot))}`)}};function $e(){}function Je(s,e,t){return!e||ot[s]>ot[t]?$e:e[s].bind(e)}const Xr={error:$e,warn:$e,info:$e,debug:$e};let Rn=new WeakMap;function q(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Xr;const n=Rn.get(e);if(n&&n[0]===t)return n[1];const r={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return Rn.set(e,[t,r]),r}const le=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Ie;class ne{constructor(e,t,n){this.iterator=e,Ie.set(this,void 0),this.controller=t,R(this,Ie,n)}static fromSSEResponse(e,t,n){let r=!1;const a=n?q(n):console;async function*i(){if(r)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of Kr(e,t))if(!o){if(l.data.startsWith("[DONE]")){o=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let u;try{u=JSON.parse(l.data)}catch(m){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),m}if(u&&u.error)throw new H(void 0,u.error,void 0,e.headers);yield u}else{let u;try{u=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new H(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}o=!0}catch(l){if(Et(l))return;throw l}finally{o||t.abort()}}return new ne(i,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*a(){const o=new gt,l=ss(e);for await(const u of l)for(const m of o.decode(u))yield m;for(const u of o.flush())yield u}async function*i(){if(r)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of a())o||l&&(yield JSON.parse(l));o=!0}catch(l){if(Et(l))return;throw l}finally{o||t.abort()}}return new ne(i,t,n)}[(Ie=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new ne(()=>r(e),this.controller,c(this,Ie,"f")),new ne(()=>r(t),this.controller,c(this,Ie,"f"))]}toReadableStream(){const e=this;let t;return ts({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:a}=await t.next();if(a)return n.close();const i=Ht(JSON.stringify(r)+`
`);n.enqueue(i)}catch(r){n.error(r)}},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}}async function*Kr(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");const t=new Gr,n=new gt,r=ss(s.body);for await(const a of Vr(r))for(const i of n.decode(a)){const o=t.decode(i);o&&(yield o)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*Vr(s){let e=new Uint8Array;for await(const t of s){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ht(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let a;for(;(a=Hr(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Gr{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;const a={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=Qr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Qr(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function ls(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{var h;if(e.options.stream)return q(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s):ne.fromSSEResponse(t,e.controller,s);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.headers.get("content-type"),l=(h=o==null?void 0:o.split(";")[0])==null?void 0:h.trim();if((l==null?void 0:l.includes("application/json"))||(l==null?void 0:l.endsWith("+json"))){const g=await t.json();return us(g,t)}return await t.text()})();return q(s).debug(`[${n}] response parsed`,le({retryOfRequestLogID:r,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function us(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var ke;class _t extends Promise{constructor(e,t,n=ls){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,ke.set(this,void 0),R(this,ke,e)}_thenUnwrap(e){return new _t(c(this,ke,"f"),this.responsePromise,async(t,n)=>us(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,ke,"f"),e))),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)}}ke=new WeakMap;var He;class Xt{constructor(e,t,n,r){He.set(this,void 0),R(this,He,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,He,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class zr extends _t{constructor(e,t,n){super(e,t,async(r,a)=>new n(r,a.response,await ls(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class yt extends Xt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class L extends Xt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;const e=this.getPaginatedItems(),t=(n=e[e.length-1])==null?void 0:n.id;return t?{...this.options,query:{...es(this.options.query),after:t}}:null}}class Yr extends Xt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...es(this.options.query),after:e}}:null}}const hs=()=>{var s;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((s=e==null?void 0:e.versions)==null?void 0:s.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function je(s,e,t){return hs(),new File(s,e??"unknown_file",t)}function Ye(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}const ds=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",fe=async(s,e)=>({...s,body:await ea(s.body,e)}),$n=new WeakMap;function Zr(s){const e=typeof s=="function"?s:s.fetch,t=$n.get(e);if(t)return t;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return $n.set(e,n),n}const ea=async(s,e)=>{if(!await Zr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,r])=>Mt(t,n,r))),t},ta=s=>s instanceof Blob&&"name"in s,Mt=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,je([await t.blob()],Ye(t)));else if(ds(t))s.append(e,je([await new Response(ns(t)).blob()],Ye(t)));else if(ta(t))s.append(e,t,Ye(t));else if(Array.isArray(t))await Promise.all(t.map(n=>Mt(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Mt(s,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},fs=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",na=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&fs(s),sa=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function ra(s,e,t){if(hs(),s=await s,na(s))return s instanceof File?s:je([await s.arrayBuffer()],s.name);if(sa(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),je(await Nt(r),e,t)}const n=await Nt(s);if(e||(e=Ye(s)),!(t!=null&&t.type)){const r=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(t={...t,type:r})}return je(n,e,t)}async function Nt(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(fs(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(ds(s))for await(const n of s)e.push(...await Nt(n));else{const n=(t=s==null?void 0:s.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof s}${n?`; constructor: ${n}`:""}${aa(s)}`)}return e}function aa(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}class I{constructor(e){this._client=e}}function ms(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const kn=Object.freeze(Object.create(null)),ia=(s=ms)=>function(t,...n){if(t.length===1)return t[0];let r=!1;const a=[],i=t.reduce((m,h,g)=>{var w;/[?#]/.test(h)&&(r=!0);const d=n[g];let b=(r?encodeURIComponent:s)(""+d);return g!==n.length&&(d==null||typeof d=="object"&&d.toString===((w=Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??kn)??kn))==null?void 0:w.toString))&&(b=d+"",a.push({start:m.length+h.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),m+h+(g===n.length?"":b)},""),o=i.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;(u=l.exec(o))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((m,h)=>m.start-h.start),a.length>0){let m=0;const h=a.reduce((g,d)=>{const b=" ".repeat(d.start-m),w="^".repeat(d.length);return m=d.start+d.length,g+b+w},"");throw new x(`Path parameters result in path with invalid segments:
${a.map(g=>g.error).join(`
`)}
${i}
${h}`)}return i},f=ia(ms);let ps=class extends I{list(e,t={},n){return this._client.getAPIList(f`/chat/completions/${e}/messages`,L,{query:t,...n})}};function ct(s){return s!==void 0&&"function"in s&&s.function!==void 0}function Kt(s){return(s==null?void 0:s.$brand)==="auto-parseable-response-format"}function We(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function oa(s,e){return!e||!gs(e)?{...s,choices:s.choices.map(t=>(_s(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Vt(s,e)}function Vt(s,e){const t=s.choices.map(n=>{var r;if(n.finish_reason==="length")throw new Yn;if(n.finish_reason==="content_filter")throw new Zn;return _s(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((r=n.message.tool_calls)==null?void 0:r.map(a=>la(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ca(e,n.message.content):null}}});return{...s,choices:t}}function ca(s,e){var t,n;return((t=s.response_format)==null?void 0:t.type)!=="json_schema"?null:((n=s.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function la(s,e){var n;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return ct(r)&&((a=r.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:We(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function ua(s,e){var n;if(!s||!("tools"in s)||!s.tools)return!1;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return ct(r)&&((a=r.function)==null?void 0:a.name)===e.function.name});return ct(t)&&(We(t)||(t==null?void 0:t.function.strict)||!1)}function gs(s){var e;return Kt(s.response_format)?!0:((e=s.tools)==null?void 0:e.some(t=>We(t)||t.type==="function"&&t.function.strict===!0))??!1}function _s(s){for(const e of s||[])if(e.type!=="function")throw new x(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function ha(s){for(const e of s??[]){if(e.type!=="function")throw new x(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new x(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const lt=s=>(s==null?void 0:s.role)==="assistant",ys=s=>(s==null?void 0:s.role)==="tool";var jt,Ze,et,Oe,Ee,tt,Pe,ae,Te,ut,ht,be,ws;class Gt{constructor(){jt.add(this),this.controller=new AbortController,Ze.set(this,void 0),et.set(this,()=>{}),Oe.set(this,()=>{}),Ee.set(this,void 0),tt.set(this,()=>{}),Pe.set(this,()=>{}),ae.set(this,{}),Te.set(this,!1),ut.set(this,!1),ht.set(this,!1),be.set(this,!1),R(this,Ze,new Promise((e,t)=>{R(this,et,e,"f"),R(this,Oe,t,"f")})),R(this,Ee,new Promise((e,t)=>{R(this,tt,e,"f"),R(this,Pe,t,"f")})),c(this,Ze,"f").catch(()=>{}),c(this,Ee,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,jt,"m",ws).bind(this))},0)}_connected(){this.ended||(c(this,et,"f").call(this),this._emit("connect"))}get ended(){return c(this,Te,"f")}get errored(){return c(this,ut,"f")}get aborted(){return c(this,ht,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,ae,"f")[e]||(c(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=c(this,ae,"f")[e];if(!n)return this;const r=n.findIndex(a=>a.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(c(this,ae,"f")[e]||(c(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{R(this,be,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){R(this,be,!0),await c(this,Ee,"f")}_emit(e,...t){if(c(this,Te,"f"))return;e==="end"&&(R(this,Te,!0),c(this,tt,"f").call(this));const n=c(this,ae,"f")[e];if(n&&(c(this,ae,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!c(this,be,"f")&&!(n!=null&&n.length)&&Promise.reject(r),c(this,Oe,"f").call(this,r),c(this,Pe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!c(this,be,"f")&&!(n!=null&&n.length)&&Promise.reject(r),c(this,Oe,"f").call(this,r),c(this,Pe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Ze=new WeakMap,et=new WeakMap,Oe=new WeakMap,Ee=new WeakMap,tt=new WeakMap,Pe=new WeakMap,ae=new WeakMap,Te=new WeakMap,ut=new WeakMap,ht=new WeakMap,be=new WeakMap,jt=new WeakSet,ws=function(e){if(R(this,ut,!0),e instanceof Error&&e.name==="AbortError"&&(e=new z),e instanceof z)return R(this,ht,!0),this._emit("abort",e);if(e instanceof x)return this._emit("error",e);if(e instanceof Error){const t=new x(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new x(String(e)))};function da(s){return typeof s.parse=="function"}var X,Ft,dt,Lt,Dt,Bt,bs,xs;const fa=10;class Ss extends Gt{constructor(){super(...arguments),X.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),ys(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(lt(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new x("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,X,"m",Ft).call(this)}async finalMessage(){return await this.done(),c(this,X,"m",dt).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,X,"m",Lt).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,X,"m",Dt).call(this)}async totalUsage(){return await this.done(),c(this,X,"m",Bt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=c(this,X,"m",dt).call(this);t&&this._emit("finalMessage",t);const n=c(this,X,"m",Ft).call(this);n&&this._emit("finalContent",n);const r=c(this,X,"m",Lt).call(this);r&&this._emit("finalFunctionToolCall",r);const a=c(this,X,"m",Dt).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,X,"m",Bt).call(this))}async _createChatCompletion(e,t,n){const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,X,"m",bs).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Vt(a,t))}async _runChatCompletion(e,t,n){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){var d,b,w;const r="tool",{tool_choice:a="auto",stream:i,...o}=t,l=typeof a!="string"&&a.type==="function"&&((d=a==null?void 0:a.function)==null?void 0:d.name),{maxChatCompletions:u=fa}=n||{},m=t.tools.map(v=>{if(We(v)){if(!v.$callback)throw new x("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:v.$callback,name:v.function.name,description:v.function.description||"",parameters:v.function.parameters,parse:v.$parseRaw,strict:!0}}}return v}),h={};for(const v of m)v.type==="function"&&(h[v.function.name||v.function.function.name]=v.function);const g="tools"in t?m.map(v=>v.type==="function"?{type:"function",function:{name:v.function.name||v.function.function.name,parameters:v.function.parameters,description:v.function.description,strict:v.function.strict}}:v):void 0;for(const v of t.messages)this._addMessage(v,!1);for(let v=0;v<u;++v){const p=(b=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:g,messages:[...this.messages]},n)).choices[0])==null?void 0:b.message;if(!p)throw new x("missing message in ChatCompletion response");if(!((w=p.tool_calls)!=null&&w.length))return;for(const y of p.tool_calls){if(y.type!=="function")continue;const _=y.id,{name:C,arguments:k}=y.function,$=h[C];if($){if(l&&l!==C){const M=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:_,content:M});continue}}else{const M=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(h).map(se=>JSON.stringify(se)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:_,content:M});continue}let F;try{F=da($)?await $.parse(k):k}catch(M){const se=M instanceof Error?M.message:String(M);this._addMessage({role:r,tool_call_id:_,content:se});continue}const A=await $.function(F,this),T=c(this,X,"m",xs).call(this,A);if(this._addMessage({role:r,tool_call_id:_,content:T}),l)return}}}}X=new WeakSet,Ft=function(){return c(this,X,"m",dt).call(this).content??null},dt=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(lt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new x("stream ended without producing a ChatCompletionMessage with role=assistant")},Lt=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const r=this.messages[n];if(lt(r)&&((e=r==null?void 0:r.tool_calls)!=null&&e.length))return(t=r.tool_calls.filter(a=>a.type==="function").at(-1))==null?void 0:t.function}},Dt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ys(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>{var r;return n.role==="assistant"&&((r=n.tool_calls)==null?void 0:r.some(a=>a.type==="function"&&a.id===t.tool_call_id))}))return t.content}},Bt=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},bs=function(e){if(e.n!=null&&e.n>1)throw new x("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Qt extends Ss{static runTools(e,t,n){const r=new Qt,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,a)),r}_addMessage(e,t=!0){super._addMessage(e,t),lt(e)&&e.content&&this._emit("content",e.content)}}const As=1,vs=2,Cs=4,Is=8,Rs=16,$s=32,ks=64,Os=128,Es=256,Ps=Os|Es,Ts=Rs|$s|Ps|ks,Ms=As|vs|Ts,Ns=Cs|Is,ma=Ms|Ns,W={STR:As,NUM:vs,ARR:Cs,OBJ:Is,NULL:Rs,BOOL:$s,NAN:ks,INFINITY:Os,MINUS_INFINITY:Es,INF:Ps,SPECIAL:Ts,ATOM:Ms,COLLECTION:Ns,ALL:ma};class pa extends Error{}class ga extends Error{}function _a(s,e=W.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return ya(s.trim(),e)}const ya=(s,e)=>{const t=s.length;let n=0;const r=g=>{throw new pa(`${g} at position ${n}`)},a=g=>{throw new ga(`${g} at position ${n}`)},i=()=>(h(),n>=t&&r("Unexpected end of input"),s[n]==='"'?o():s[n]==="{"?l():s[n]==="["?u():s.substring(n,n+4)==="null"||W.NULL&e&&t-n<4&&"null".startsWith(s.substring(n))?(n+=4,null):s.substring(n,n+4)==="true"||W.BOOL&e&&t-n<4&&"true".startsWith(s.substring(n))?(n+=4,!0):s.substring(n,n+5)==="false"||W.BOOL&e&&t-n<5&&"false".startsWith(s.substring(n))?(n+=5,!1):s.substring(n,n+8)==="Infinity"||W.INFINITY&e&&t-n<8&&"Infinity".startsWith(s.substring(n))?(n+=8,1/0):s.substring(n,n+9)==="-Infinity"||W.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(s.substring(n))?(n+=9,-1/0):s.substring(n,n+3)==="NaN"||W.NAN&e&&t-n<3&&"NaN".startsWith(s.substring(n))?(n+=3,NaN):m()),o=()=>{const g=n;let d=!1;for(n++;n<t&&(s[n]!=='"'||d&&s[n-1]==="\\");)d=s[n]==="\\"?!d:!1,n++;if(s.charAt(n)=='"')try{return JSON.parse(s.substring(g,++n-Number(d)))}catch(b){a(String(b))}else if(W.STR&e)try{return JSON.parse(s.substring(g,n-Number(d))+'"')}catch{return JSON.parse(s.substring(g,s.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,h();const g={};try{for(;s[n]!=="}";){if(h(),n>=t&&W.OBJ&e)return g;const d=o();h(),n++;try{const b=i();Object.defineProperty(g,d,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(W.OBJ&e)return g;throw b}h(),s[n]===","&&n++}}catch{if(W.OBJ&e)return g;r("Expected '}' at end of object")}return n++,g},u=()=>{n++;const g=[];try{for(;s[n]!=="]";)g.push(i()),h(),s[n]===","&&n++}catch{if(W.ARR&e)return g;r("Expected ']' at end of array")}return n++,g},m=()=>{if(n===0){s==="-"&&W.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s)}catch(d){if(W.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}a(String(d))}}const g=n;for(s[n]==="-"&&n++;s[n]&&!",]}".includes(s[n]);)n++;n==t&&!(W.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(s.substring(g,n))}catch{s.substring(g,n)==="-"&&W.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s.substring(g,s.lastIndexOf("e")))}catch(b){a(String(b))}}},h=()=>{for(;n<t&&`
\r `.includes(s[n]);)n++};return i()},On=s=>_a(s,W.ALL^W.NUM);var D,re,pe,oe,Ct,Xe,It,Rt,$t,Ke,kt,En;class De extends Ss{constructor(e){super(),D.add(this),re.set(this,void 0),pe.set(this,void 0),oe.set(this,void 0),R(this,re,e),R(this,pe,[])}get currentChatCompletionSnapshot(){return c(this,oe,"f")}static fromReadableStream(e){const t=new De(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new De(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,n){var i;super._createChatCompletion;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,D,"m",Ct).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const o of a)c(this,D,"m",It).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(c(this,D,"m",Ke).call(this))}async _fromReadableStream(e,t){var i;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,D,"m",Ct).call(this),this._connected();const r=ne.fromReadableStream(e,this.controller);let a;for await(const o of r)a&&a!==o.id&&this._addChatCompletion(c(this,D,"m",Ke).call(this)),c(this,D,"m",It).call(this,o),a=o.id;if((i=r.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(c(this,D,"m",Ke).call(this))}[(re=new WeakMap,pe=new WeakMap,oe=new WeakMap,D=new WeakSet,Ct=function(){this.ended||R(this,oe,void 0)},Xe=function(t){let n=c(this,pe,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,pe,"f")[t.index]=n,n)},It=function(t){var r,a,i,o,l,u,m,h,g,d,b,w,v,E,p;if(this.ended)return;const n=c(this,D,"m",En).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const _=n.choices[y.index];y.delta.content!=null&&((r=_.message)==null?void 0:r.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",y.delta.content,_.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),y.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((o=_.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:_.message.refusal}),((l=y.logprobs)==null?void 0:l.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(m=y.logprobs)==null?void 0:m.content,snapshot:((h=_.logprobs)==null?void 0:h.content)??[]}),((g=y.logprobs)==null?void 0:g.refusal)!=null&&((d=_.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(b=y.logprobs)==null?void 0:b.refusal,snapshot:((w=_.logprobs)==null?void 0:w.refusal)??[]});const C=c(this,D,"m",Xe).call(this,_);_.finish_reason&&(c(this,D,"m",$t).call(this,_),C.current_tool_call_index!=null&&c(this,D,"m",Rt).call(this,_,C.current_tool_call_index));for(const k of y.delta.tool_calls??[])C.current_tool_call_index!==k.index&&(c(this,D,"m",$t).call(this,_),C.current_tool_call_index!=null&&c(this,D,"m",Rt).call(this,_,C.current_tool_call_index)),C.current_tool_call_index=k.index;for(const k of y.delta.tool_calls??[]){const $=(v=_.message.tool_calls)==null?void 0:v[k.index];$!=null&&$.type&&(($==null?void 0:$.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(E=$.function)==null?void 0:E.name,index:k.index,arguments:$.function.arguments,parsed_arguments:$.function.parsed_arguments,arguments_delta:((p=k.function)==null?void 0:p.arguments)??""}):($==null||$.type,void 0))}}},Rt=function(t,n){var i,o,l;if(c(this,D,"m",Xe).call(this,t).done_tool_calls.has(n))return;const a=(i=t.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const u=(l=(o=c(this,re,"f"))==null?void 0:o.tools)==null?void 0:l.find(m=>ct(m)&&m.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:We(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},$t=function(t){var r,a;const n=c(this,D,"m",Xe).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=c(this,D,"m",kt).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(r=t.logprobs)!=null&&r.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(a=t.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Ke=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const t=c(this,oe,"f");if(!t)throw new x("request ended without sending any chunks");return R(this,oe,void 0),R(this,pe,[]),wa(t,c(this,re,"f"))},kt=function(){var n;const t=(n=c(this,re,"f"))==null?void 0:n.response_format;return Kt(t)?t:null},En=function(t){var n,r,a,i;let o=c(this,oe,"f");const{choices:l,...u}=t;o?Object.assign(o,u):o=R(this,oe,{...u,choices:[]});for(const{delta:m,finish_reason:h,index:g,logprobs:d=null,...b}of t.choices){let w=o.choices[g];if(w||(w=o.choices[g]={finish_reason:h,index:g,message:{},logprobs:d,...b}),d)if(!w.logprobs)w.logprobs=Object.assign({},d);else{const{content:k,refusal:$,...F}=d;Object.assign(w.logprobs,F),k&&((n=w.logprobs).content??(n.content=[]),w.logprobs.content.push(...k)),$&&((r=w.logprobs).refusal??(r.refusal=[]),w.logprobs.refusal.push(...$))}if(h&&(w.finish_reason=h,c(this,re,"f")&&gs(c(this,re,"f")))){if(h==="length")throw new Yn;if(h==="content_filter")throw new Zn}if(Object.assign(w,b),!m)continue;const{content:v,refusal:E,function_call:p,role:y,tool_calls:_,...C}=m;if(Object.assign(w.message,C),E&&(w.message.refusal=(w.message.refusal||"")+E),y&&(w.message.role=y),p&&(w.message.function_call?(p.name&&(w.message.function_call.name=p.name),p.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=p.arguments)):w.message.function_call=p),v&&(w.message.content=(w.message.content||"")+v,!w.message.refusal&&c(this,D,"m",kt).call(this)&&(w.message.parsed=On(w.message.content))),_){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:k,id:$,type:F,function:A,...T}of _){const M=(i=w.message.tool_calls)[k]??(i[k]={});Object.assign(M,T),$&&(M.id=$),F&&(M.type=F),A&&(M.function??(M.function={name:A.name??"",arguments:""})),A!=null&&A.name&&(M.function.name=A.name),A!=null&&A.arguments&&(M.function.arguments+=A.arguments,ua(c(this,re,"f"),M)&&(M.function.parsed_arguments=On(M.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadabl