iobroker.javascript
Version:
Rules Engine for ioBroker
12 lines • 106 kB
JavaScript
import{c as tr,j as k}from"./createSvgIcon-BQT-7-GS.js";import{i as Z}from"./iobroker_javascript__loadShare__react__loadShare__-BiJPUKBK.js";import{i as j,c as an,C as nr}from"./index-DnqHzUyv.js";import{i as W,h as sr}from"./index-Cek-i92T.js";import{_ as rr}from"./preload-helper-Dp1pzeXC.js";import{C as ar,t as ir}from"./index-Dm1jc4t6.js";import or from"./ScriptEditorVanillaMonaco-DEgxOslR.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CBQgOKij.js";import"./inheritsLoose--KnFDOw1.js";const cr=tr(k.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 o(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 Tn=function(){const{crypto:s}=globalThis;if(s!=null&&s.randomUUID)return Tn=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 It(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}const Rt=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 v extends Error{}class J extends v{constructor(e,t,n,r){super(`${J.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 ut({message:n,cause:Rt(t)});const a=t==null?void 0:t.error;return e===400?new Mn(e,a,n,r):e===401?new Nn(e,a,n,r):e===403?new jn(e,a,n,r):e===404?new Fn(e,a,n,r):e===409?new Ln(e,a,n,r):e===422?new Dn(e,a,n,r):e===429?new Bn(e,a,n,r):e>=500?new Un(e,a,n,r):new J(e,a,n,r)}}class z extends J{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ut extends J{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Lt extends ut{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Mn extends J{}class Nn extends J{}class jn extends J{}class Fn extends J{}class Ln extends J{}class Dn extends J{}class Bn extends J{}class Un extends J{}class Wn extends v{constructor(){super("Could not parse response content as the length limit was reached")}}class qn extends v{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}const lr=/^[a-z][a-z0-9+.-]*:/i,ur=s=>lr.test(s);let V=s=>(V=Array.isArray,V(s)),on=V;function dr(s){return typeof s!="object"?{}:s??{}}function hr(s){if(!s)return!0;for(const e in s)return!1;return!0}function fr(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function _t(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}const mr=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new v(`${s} must be an integer`);if(e<0)throw new v(`${s} must be a positive integer`);return e},pr=s=>{try{return JSON.parse(s)}catch{return}},Fe=s=>new Promise(e=>setTimeout(e,s)),ye="5.5.1",gr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function _r(){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 yr=()=>{var t;const s=_r();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":ln(Deno.build.os),"X-Stainless-Arch":cn(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":ye,"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":ye,"X-Stainless-OS":ln(globalThis.process.platform??"unknown"),"X-Stainless-Arch":cn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=wr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"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":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function wr(){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 cn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",ln=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 un;const br=()=>un??(un=yr());function xr(){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 Jn(...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 Xn(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Jn({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 Hn(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 Sr(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 Ar=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Vn="RFC3986",Kn=s=>String(s),dn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Kn},Cr="RFC1738";let $t=(s,e)=>($t=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),$t(s,e));const ee=(()=>{const s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})(),yt=1024,vr=(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(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let i="";for(let c=0;c<a.length;c+=yt){const l=a.length>=yt?a.slice(c,c+yt):a,d=[];for(let y=0;y<l.length;++y){let u=l.charCodeAt(y);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||r===Cr&&(u===40||u===41)){d[d.length]=l.charAt(y);continue}if(u<128){d[d.length]=ee[u];continue}if(u<2048){d[d.length]=ee[192|u>>6]+ee[128|u&63];continue}if(u<55296||u>=57344){d[d.length]=ee[224|u>>12]+ee[128|u>>6&63]+ee[128|u&63];continue}y+=1,u=65536+((u&1023)<<10|l.charCodeAt(y)&1023),d[d.length]=ee[240|u>>18]+ee[128|u>>12&63]+ee[128|u>>6&63]+ee[128|u&63]}i+=d.join("")}return i};function Ir(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function hn(s,e){if(V(s)){const t=[];for(let n=0;n<s.length;n+=1)t.push(e(s[n]));return t}return e(s)}const Gn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Qn=function(s,e){Array.prototype.push.apply(s,V(e)?e:[e])};let fn;const B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:vr,encodeValuesOnly:!1,format:Vn,formatter:Kn,indices:!1,serializeDate(s){return(fn??(fn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Rr(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}const wt={};function zn(s,e,t,n,r,a,i,c,l,d,y,u,g,h,b,w,C,E){let m=s,_=E,p=0,A=!1;for(;(_=_.get(wt))!==void 0&&!A;){const P=_.get(s);if(p+=1,typeof P<"u"){if(P===p)throw new RangeError("Cyclic object value");A=!0}typeof _.get(wt)>"u"&&(p=0)}if(typeof d=="function"?m=d(e,m):m instanceof Date?m=g==null?void 0:g(m):t==="comma"&&V(m)&&(m=hn(m,function(P){return P instanceof Date?g==null?void 0:g(P):P})),m===null){if(a)return l&&!w?l(e,B.encoder,C,"key",h):e;m=""}if(Rr(m)||Ir(m)){if(l){const P=w?e:l(e,B.encoder,C,"key",h);return[(b==null?void 0:b(P))+"="+(b==null?void 0:b(l(m,B.encoder,C,"value",h)))]}return[(b==null?void 0:b(e))+"="+(b==null?void 0:b(String(m)))]}const O=[];if(typeof m>"u")return O;let I;if(t==="comma"&&V(m))w&&l&&(m=hn(m,l)),I=[{value:m.length>0?m.join(",")||null:void 0}];else if(V(d))I=d;else{const P=Object.keys(m);I=y?P.sort(y):P}const F=c?String(e).replace(/\./g,"%2E"):String(e),x=n&&V(m)&&m.length===1?F+"[]":F;if(r&&V(m)&&m.length===0)return x+"[]";for(let P=0;P<I.length;++P){const M=I[P],se=typeof M=="object"&&typeof M.value<"u"?M.value:m[M];if(i&&se===null)continue;const me=u&&c?M.replace(/\./g,"%2E"):M,N=V(m)?typeof t=="function"?t(x,me):x:x+(u?"."+me:"["+me+"]");E.set(s,p);const ie=new WeakMap;ie.set(wt,E),Qn(O,zn(se,N,t,n,r,a,i,c,t==="comma"&&w&&V(m)?null:l,d,y,u,g,h,b,w,C,ie))}return O}function $r(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=Vn;if(typeof s.format<"u"){if(!$t(dn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}const n=dn[t];let r=B.filter;(typeof s.filter=="function"||V(s.filter))&&(r=s.filter);let a;if(s.arrayFormat&&s.arrayFormat in Gn?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 Or(s,e={}){let t=s;const n=$r(e);let r,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):V(n.filter)&&(a=n.filter,r=a);const i=[];if(typeof t!="object"||t===null)return"";const c=Gn[n.arrayFormat],l=c==="comma"&&n.commaRoundTrip;r||(r=Object.keys(t)),n.sort&&r.sort(n.sort);const d=new WeakMap;for(let g=0;g<r.length;++g){const h=r[g];n.skipNulls&&t[h]===null||Qn(i,zn(t[h],h,c,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,d))}const y=i.join(n.delimiter);let u=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),y.length>0?u+y:""}function kr(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 mn;function Dt(s){let e;return(mn??(e=new globalThis.TextEncoder,mn=e.encode.bind(e)))(s)}let pn;function gn(s){let e;return(pn??(e=new globalThis.TextDecoder,pn=e.decode.bind(e)))(s)}var K,G;class dt{constructor(){K.set(this,void 0),G.set(this,void 0),R(this,K,new Uint8Array),R(this,G,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Dt(e):e;R(this,K,kr([o(this,K,"f"),t]));const n=[];let r;for(;(r=Er(o(this,K,"f"),o(this,G,"f")))!=null;){if(r.carriage&&o(this,G,"f")==null){R(this,G,r.index);continue}if(o(this,G,"f")!=null&&(r.index!==o(this,G,"f")+1||r.carriage)){n.push(gn(o(this,K,"f").subarray(0,o(this,G,"f")-1))),R(this,K,o(this,K,"f").subarray(o(this,G,"f"))),R(this,G,null);continue}const a=o(this,G,"f")!==null?r.preceding-1:r.preceding,i=gn(o(this,K,"f").subarray(0,a));n.push(i),R(this,K,o(this,K,"f").subarray(r.index)),R(this,G,null)}return n}flush(){return o(this,K,"f").length?this.decode(`
`):[]}}K=new WeakMap,G=new WeakMap;dt.NEWLINE_CHARS=new Set([`
`,"\r"]);dt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Er(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 Pr(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}class ne{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*r(){if(n)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(const i of Tr(e,t))if(!a){if(i.data.startsWith("[DONE]")){a=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let c;try{c=JSON.parse(i.data)}catch(l){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),l}if(c&&c.error)throw new J(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(i.data)}catch(l){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),l}if(i.event=="error")throw new J(void 0,c.error,c.message,void 0);yield{event:i.event,data:c}}}a=!0}catch(i){if(It(i))return;throw i}finally{a||t.abort()}}return new ne(r,t)}static fromReadableStream(e,t){let n=!1;async function*r(){const i=new dt,c=Hn(e);for await(const l of c)for(const d of i.decode(l))yield d;for(const l of i.flush())yield l}async function*a(){if(n)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(const c of r())i||c&&(yield JSON.parse(c));i=!0}catch(c){if(It(c))return;throw c}finally{i||t.abort()}}return new ne(a,t)}[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),new ne(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;return Jn({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=Dt(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*Tr(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new v("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 v("Attempted to iterate over a response with no body");const t=new Nr,n=new dt,r=Hn(s.body);for await(const a of Mr(r))for(const i of n.decode(a)){const c=t.decode(i);c&&(yield c)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*Mr(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"?Dt(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let a;for(;(a=Pr(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Nr{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]=jr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function jr(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}const st={off:0,error:200,warn:300,info:400,debug:500},_n=(s,e,t)=>{if(s){if(fr(st,s))return s;X(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(st))}`)}};function ve(){}function Ue(s,e,t){return!e||st[s]>st[t]?ve:e[s].bind(e)}const Fr={error:ve,warn:ve,info:ve,debug:ve};let yn=new WeakMap;function X(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Fr;const n=yn.get(e);if(n&&n[0]===t)return n[1];const r={error:Ue("error",e,t),warn:Ue("warn",e,t),info:Ue("info",e,t),debug:Ue("debug",e,t)};return yn.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);async function Yn(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{var u;if(e.options.stream)return X(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):ne.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const c=t.headers.get("content-type"),l=(u=c==null?void 0:c.split(";")[0])==null?void 0:u.trim();if((l==null?void 0:l.includes("application/json"))||(l==null?void 0:l.endsWith("+json"))){const g=await t.json();return Zn(g,t)}return await t.text()})();return X(s).debug(`[${n}] response parsed`,le({retryOfRequestLogID:r,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function Zn(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 Ie;class ht extends Promise{constructor(e,t,n=Yn){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,Ie.set(this,void 0),R(this,Ie,e)}_thenUnwrap(e){return new ht(o(this,Ie,"f"),this.responsePromise,async(t,n)=>Zn(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(o(this,Ie,"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)}}Ie=new WeakMap;var We;class es{constructor(e,t,n,r){We.set(this,void 0),R(this,We,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 v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,We,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(We=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Lr extends ht{constructor(e,t,n){super(e,t,async(r,a)=>new n(r,a.response,await Yn(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class ft extends es{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 es{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:{...dr(this.options.query),after:t}}:null}}const ts=()=>{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 Te(s,e,t){return ts(),new File(s,e??"unknown_file",t)}function Ge(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 ns=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",fe=async(s,e)=>({...s,body:await Br(s.body,e)}),wn=new WeakMap;function Dr(s){const e=typeof s=="function"?s:s.fetch,t=wn.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 wn.set(e,n),n}const Br=async(s,e)=>{if(!await Dr(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])=>Ot(t,n,r))),t},Ur=s=>s instanceof Blob&&"name"in s,Ot=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,Te([await t.blob()],Ge(t)));else if(ns(t))s.append(e,Te([await new Response(Xn(t)).blob()],Ge(t)));else if(Ur(t))s.append(e,t,Ge(t));else if(Array.isArray(t))await Promise.all(t.map(n=>Ot(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Ot(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`)}},ss=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",Wr=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&ss(s),qr=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Jr(s,e,t){if(ts(),s=await s,Wr(s))return s instanceof File?s:Te([await s.arrayBuffer()],s.name);if(qr(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Te(await kt(r),e,t)}const n=await kt(s);if(e||(e=Ge(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 Te(n,e,t)}async function kt(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(ss(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(ns(s))for await(const n of s)e.push(...await kt(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}`:""}${Xr(s)}`)}return e}function Xr(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}class ${constructor(e){this._client=e}}function rs(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Hr=(s=rs)=>function(t,...n){if(t.length===1)return t[0];let r=!1;const a=t.reduce((y,u,g)=>(/[?#]/.test(u)&&(r=!0),y+u+(g===n.length?"":(r?encodeURIComponent:s)(String(n[g])))),""),i=a.split(/[?#]/,1)[0],c=[],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let d;for(;(d=l.exec(i))!==null;)c.push({start:d.index,length:d[0].length});if(c.length>0){let y=0;const u=c.reduce((g,h)=>{const b=" ".repeat(h.start-y),w="^".repeat(h.length);return y=h.start+h.length,g+b+w},"");throw new v(`Path parameters result in path with invalid segments:
${a}
${u}`)}return a},f=Hr(rs);let as=class extends ${list(e,t={},n){return this._client.getAPIList(f`/chat/completions/${e}/messages`,L,{query:t,...n})}};function Vr(s){return typeof s.parse=="function"}const rt=s=>(s==null?void 0:s.role)==="assistant",is=s=>(s==null?void 0:s.role)==="tool";var Et,Qe,ze,Re,$e,Ye,Oe,ae,ke,at,it,we,os;class Bt{constructor(){Et.add(this),this.controller=new AbortController,Qe.set(this,void 0),ze.set(this,()=>{}),Re.set(this,()=>{}),$e.set(this,void 0),Ye.set(this,()=>{}),Oe.set(this,()=>{}),ae.set(this,{}),ke.set(this,!1),at.set(this,!1),it.set(this,!1),we.set(this,!1),R(this,Qe,new Promise((e,t)=>{R(this,ze,e,"f"),R(this,Re,t,"f")})),R(this,$e,new Promise((e,t)=>{R(this,Ye,e,"f"),R(this,Oe,t,"f")})),o(this,Qe,"f").catch(()=>{}),o(this,$e,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},o(this,Et,"m",os).bind(this))},0)}_connected(){this.ended||(o(this,ze,"f").call(this),this._emit("connect"))}get ended(){return o(this,ke,"f")}get errored(){return o(this,at,"f")}get aborted(){return o(this,it,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,ae,"f")[e]||(o(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=o(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(o(this,ae,"f")[e]||(o(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{R(this,we,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){R(this,we,!0),await o(this,$e,"f")}_emit(e,...t){if(o(this,ke,"f"))return;e==="end"&&(R(this,ke,!0),o(this,Ye,"f").call(this));const n=o(this,ae,"f")[e];if(n&&(o(this,ae,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!o(this,we,"f")&&!(n!=null&&n.length)&&Promise.reject(r),o(this,Re,"f").call(this,r),o(this,Oe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!o(this,we,"f")&&!(n!=null&&n.length)&&Promise.reject(r),o(this,Re,"f").call(this,r),o(this,Oe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Qe=new WeakMap,ze=new WeakMap,Re=new WeakMap,$e=new WeakMap,Ye=new WeakMap,Oe=new WeakMap,ae=new WeakMap,ke=new WeakMap,at=new WeakMap,it=new WeakMap,we=new WeakMap,Et=new WeakSet,os=function(e){if(R(this,at,!0),e instanceof Error&&e.name==="AbortError"&&(e=new z),e instanceof z)return R(this,it,!0),this._emit("abort",e);if(e instanceof v)return this._emit("error",e);if(e instanceof Error){const t=new v(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new v(String(e)))};function Ut(s){return(s==null?void 0:s.$brand)==="auto-parseable-response-format"}function Le(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function Kr(s,e){return!e||!cs(e)?{...s,choices:s.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Wt(s,e)}function Wt(s,e){const t=s.choices.map(n=>{var r;if(n.finish_reason==="length")throw new Wn;if(n.finish_reason==="content_filter")throw new qn;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((r=n.message.tool_calls)==null?void 0:r.map(a=>Qr(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Gr(e,n.message.content):null}}});return{...s,choices:t}}function Gr(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 Qr(s,e){var n;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Le(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function zr(s,e){var n;if(!s)return!1;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===e.function.name});return Le(t)||(t==null?void 0:t.function.strict)||!1}function cs(s){var e;return Ut(s.response_format)?!0:((e=s.tools)==null?void 0:e.some(t=>Le(t)||t.type==="function"&&t.function.strict===!0))??!1}function Yr(s){for(const e of s??[]){if(e.type!=="function")throw new v(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new v(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var H,Pt,ot,Tt,Mt,Nt,ls,us;const Zr=10;class ds extends Bt{constructor(){super(...arguments),H.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),is(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(rt(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 v("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),o(this,H,"m",Pt).call(this)}async finalMessage(){return await this.done(),o(this,H,"m",ot).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,H,"m",Tt).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,H,"m",Mt).call(this)}async totalUsage(){return await this.done(),o(this,H,"m",Nt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=o(this,H,"m",ot).call(this);t&&this._emit("finalMessage",t);const n=o(this,H,"m",Pt).call(this);n&&this._emit("finalContent",n);const r=o(this,H,"m",Tt).call(this);r&&this._emit("finalFunctionToolCall",r);const a=o(this,H,"m",Mt).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",o(this,H,"m",Nt).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())),o(this,H,"m",ls).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Wt(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 h,b,w;const r="tool",{tool_choice:a="auto",stream:i,...c}=t,l=typeof a!="string"&&((h=a==null?void 0:a.function)==null?void 0:h.name),{maxChatCompletions:d=Zr}=n||{},y=t.tools.map(C=>{if(Le(C)){if(!C.$callback)throw new v("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:C.$callback,name:C.function.name,description:C.function.description||"",parameters:C.function.parameters,parse:C.$parseRaw,strict:!0}}}return C}),u={};for(const C of y)C.type==="function"&&(u[C.function.name||C.function.function.name]=C.function);const g="tools"in t?y.map(C=>C.type==="function"?{type:"function",function:{name:C.function.name||C.function.function.name,parameters:C.function.parameters,description:C.function.description,strict:C.function.strict}}:C):void 0;for(const C of t.messages)this._addMessage(C,!1);for(let C=0;C<d;++C){const m=(b=(await this._createChatCompletion(e,{...c,tool_choice:a,tools:g,messages:[...this.messages]},n)).choices[0])==null?void 0:b.message;if(!m)throw new v("missing message in ChatCompletion response");if(!((w=m.tool_calls)!=null&&w.length))return;for(const _ of m.tool_calls){if(_.type!=="function")continue;const p=_.id,{name:A,arguments:O}=_.function,I=u[A];if(I){if(l&&l!==A){const M=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:p,content:M});continue}}else{const M=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(u).map(se=>JSON.stringify(se)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:p,content:M});continue}let F;try{F=Vr(I)?await I.parse(O):O}catch(M){const se=M instanceof Error?M.message:String(M);this._addMessage({role:r,tool_call_id:p,content:se});continue}const x=await I.function(F,this),P=o(this,H,"m",us).call(this,x);if(this._addMessage({role:r,tool_call_id:p,content:P}),l)return}}}}H=new WeakSet,Pt=function(){return o(this,H,"m",ot).call(this).content??null},ot=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(rt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new v("stream ended without producing a ChatCompletionMessage with role=assistant")},Tt=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const r=this.messages[n];if(rt(r)&&((e=r==null?void 0:r.tool_calls)!=null&&e.length))return(t=r.tool_calls.at(-1))==null?void 0:t.function}},Mt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(is(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}},Nt=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},ls=function(e){if(e.n!=null&&e.n>1)throw new v("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},us=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class qt extends ds{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),rt(e)&&e.content&&this._emit("content",e.content)}}const hs=1,fs=2,ms=4,ps=8,gs=16,_s=32,ys=64,ws=128,bs=256,xs=ws|bs,Ss=gs|_s|xs|ys,As=hs|fs|Ss,Cs=ms|ps,ea=As|Cs,U={STR:hs,NUM:fs,ARR:ms,OBJ:ps,NULL:gs,BOOL:_s,NAN:ys,INFINITY:ws,MINUS_INFINITY:bs,INF:xs,SPECIAL:Ss,ATOM:As,COLLECTION:Cs,ALL:ea};class ta extends Error{}class na extends Error{}function sa(s,e=U.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return ra(s.trim(),e)}const ra=(s,e)=>{const t=s.length;let n=0;const r=g=>{throw new ta(`${g} at position ${n}`)},a=g=>{throw new na(`${g} at position ${n}`)},i=()=>(u(),n>=t&&r("Unexpected end of input"),s[n]==='"'?c():s[n]==="{"?l():s[n]==="["?d():s.substring(n,n+4)==="null"||U.NULL&e&&t-n<4&&"null".startsWith(s.substring(n))?(n+=4,null):s.substring(n,n+4)==="true"||U.BOOL&e&&t-n<4&&"true".startsWith(s.substring(n))?(n+=4,!0):s.substring(n,n+5)==="false"||U.BOOL&e&&t-n<5&&"false".startsWith(s.substring(n))?(n+=5,!1):s.substring(n,n+8)==="Infinity"||U.INFINITY&e&&t-n<8&&"Infinity".startsWith(s.substring(n))?(n+=8,1/0):s.substring(n,n+9)==="-Infinity"||U.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(s.substring(n))?(n+=9,-1/0):s.substring(n,n+3)==="NaN"||U.NAN&e&&t-n<3&&"NaN".startsWith(s.substring(n))?(n+=3,NaN):y()),c=()=>{const g=n;let h=!1;for(n++;n<t&&(s[n]!=='"'||h&&s[n-1]==="\\");)h=s[n]==="\\"?!h:!1,n++;if(s.charAt(n)=='"')try{return JSON.parse(s.substring(g,++n-Number(h)))}catch(b){a(String(b))}else if(U.STR&e)try{return JSON.parse(s.substring(g,n-Number(h))+'"')}catch{return JSON.parse(s.substring(g,s.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,u();const g={};try{for(;s[n]!=="}";){if(u(),n>=t&&U.OBJ&e)return g;const h=c();u(),n++;try{const b=i();Object.defineProperty(g,h,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(U.OBJ&e)return g;throw b}u(),s[n]===","&&n++}}catch{if(U.OBJ&e)return g;r("Expected '}' at end of object")}return n++,g},d=()=>{n++;const g=[];try{for(;s[n]!=="]";)g.push(i()),u(),s[n]===","&&n++}catch{if(U.ARR&e)return g;r("Expected ']' at end of array")}return n++,g},y=()=>{if(n===0){s==="-"&&U.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s)}catch(h){if(U.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(h))}}const g=n;for(s[n]==="-"&&n++;s[n]&&!",]}".includes(s[n]);)n++;n==t&&!(U.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(s.substring(g,n))}catch{s.substring(g,n)==="-"&&U.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s.substring(g,s.lastIndexOf("e")))}catch(b){a(String(b))}}},u=()=>{for(;n<t&&`
\r `.includes(s[n]);)n++};return i()},bn=s=>sa(s,U.ALL^U.NUM);var D,re,pe,oe,bt,qe,xt,St,At,Je,Ct,xn;class je extends ds{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 o(this,oe,"f")}static fromReadableStream(e){const t=new je(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new je(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())),o(this,D,"m",bt).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const c of a)o(this,D,"m",xt).call(this,c);if((i=a.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(o(this,D,"m",Je).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())),o(this,D,"m",bt).call(this),this._connected();const r=ne.fromReadableStream(e,this.controller);let a;for await(const c of r)a&&a!==c.id&&this._addChatCompletion(o(this,D,"m",Je).call(this)),o(this,D,"m",xt).call(this,c),a=c.id;if((i=r.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(o(this,D,"m",Je).call(this))}[(re=new WeakMap,pe=new WeakMap,oe=new WeakMap,D=new WeakSet,bt=function(){this.ended||R(this,oe,void 0)},qe=function(t){let n=o(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},o(this,pe,"f")[t.index]=n,n)},xt=function(t){var r,a,i,c,l,d,y,u,g,h,b,w,C,E,m;if(this.ended)return;const n=o(this,D,"m",xn).call(this,t);this._emit("chunk",t,n);for(const _ of t.choices){const p=n.choices[_.index];_.delta.content!=null&&((r=p.message)==null?void 0:r.role)==="assistant"&&((a=p.message)!=null&&a.content)&&(this._emit("content",_.delta.content,p.message.content),this._emit("content.delta",{delta:_.delta.content,snapshot:p.message.content,parsed:p.message.parsed})),_.delta.refusal!=null&&((i=p.message)==null?void 0:i.role)==="assistant"&&((c=p.message)!=null&&c.refusal)&&this._emit("refusal.delta",{delta:_.delta.refusal,snapshot:p.message.refusal}),((l=_.logprobs)==null?void 0:l.content)!=null&&((d=p.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(y=_.logprobs)==null?void 0:y.content,snapshot:((u=p.logprobs)==null?void 0:u.content)??[]}),((g=_.logprobs)==null?void 0:g.refusal)!=null&&((h=p.message)==null?void 0:h.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(b=_.logprobs)==null?void 0:b.refusal,snapshot:((w=p.logprobs)==null?void 0:w.refusal)??[]});const A=o(this,D,"m",qe).call(this,p);p.finish_reason&&(o(this,D,"m",At).call(this,p),A.current_tool_call_index!=null&&o(this,D,"m",St).call(this,p,A.current_tool_call_index));for(const O of _.delta.tool_calls??[])A.current_tool_call_index!==O.index&&(o(this,D,"m",At).call(this,p),A.current_tool_call_index!=null&&o(this,D,"m",St).call(this,p,A.current_tool_call_index)),A.current_tool_call_index=O.index;for(const O of _.delta.tool_calls??[]){const I=(C=p.message.tool_calls)==null?void 0:C[O.index];I!=null&&I.type&&((I==null?void 0:I.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(E=I.function)==null?void 0:E.name,index:O.index,arguments:I.function.arguments,parsed_arguments:I.function.parsed_arguments,arguments_delta:((m=O.function)==null?void 0:m.arguments)??""}):(I==null||I.type,void 0))}}},St=function(t,n){var i,c,l;if(o(this,D,"m",qe).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 d=(l=(c=o(this,re,"f"))==null?void 0:c.tools)==null?void 0:l.find(y=>y.type==="function"&&y.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:Le(d)?d.$parseRaw(a.function.arguments):d!=null&&d.function.strict?JSON.parse(a.function.arguments):null})}else a.type},At=function(t){var r,a;const n=o(this,D,"m",qe).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=o(this,D,"m",Ct).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}))},Je=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");const t=o(this,oe,"f");if(!t)throw new v("request ended without sending any chunks");return R(this,oe,void 0),R(this,pe,[]),aa(t,o(this,re,"f"))},Ct=function(){var n;const t=(n=o(this,re,"f"))==null?void 0:n.response_format;return Ut(t)?t:null},xn=function(t){var n,r,a,i;let c=o(this,oe,"f");const{choices:l,...d}=t;c?Object.assign(c,d):c=R(this,oe,{...d,choices:[]});for(const{delta:y,finish_reason:u,index:g,logprobs:h=null,...b}of t.choices){let w=c.choices[g];if(w||(w=c.choices[g]={finish_reason:u,index:g,message:{},logprobs:h,...b}),h)if(!w.logprobs)w.logprobs=Object.assign({},h);else{const{content:O,refusal:I,...F}=h;Object.assign(w.logprobs,F),O&&((n=w.logprobs).content??(n.content=[]),w.logprobs.content.push(...O)),I&&((r=w.logprobs).refusal??(r.refusal=[]),w.logprobs.refusal.push(...I))}if(u&&(w.finish_reason=u,o(this,re,"f")&&cs(o(this,re,"f")))){if(u==="length")throw new Wn;if(u==="content_filter")throw new qn}if(Object.assign(w,b),!y)continue;const{content:C,refusal:E,function_call:m,role:_,tool_calls:p,...A}=y;if(Object.assign(w.message,A),E&&(w.message.refusal=(w.message.refusal||"")+E),_&&(w.message.role=_),m&&(w.message.function_call?(m.name&&(w.message.function_call.name=m.name),m.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=m.arguments)):w.message.function_call=m),C&&(w.message.content=(w.message.content||"")+C,!w.message.refusal&&o(this,D,"m",Ct).call(this)&&(w.message.parsed=bn(w.message.content))),p){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:O,id:I,type:F,function:x,...P}of p){const M=(i=w.message.tool_calls)[O]??(i[O]={});Object.assign(M,P),I&&(M.id=I),F&&(M.type=F),x&&(M.function??(M.function={name:x.name??"",arguments:""})),x!=null&&x.name&&(M.function.name=x.name),x!=null&&x.arguments&&(M.function.arguments+=x.arguments,zr(o(this,re,"f"),M)&&(M.function.parsed_arguments=bn(M.function.arguments)))}}}return c},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).toReadableStream()}}function aa(s,e){const{id:t,choices:n,created:r,model:a,system_fingerprint:i,...c}=s,l={...c,id:t,choices:n.map(({message:d,finish_reason:y,index:u,logprobs:g,...h})=>{if(!y)throw new v(`missing finish_reason for choice ${u}`);const{content:b=null,function_call:w,tool_calls:C,...E}=d,m=d.role;if(!m)throw new v(`missing role for choice ${u}`);if(w){const{arguments:_,name:p}=w;if(_==null)throw new v(`missing function_call.arguments for choice ${u}`);if(!p)throw new v(`missing function_call.name for choice ${u}`);return{...h,message:{content:b,function_call:{arguments:_,name:p},role:m,refusal:d.refusal??null},finish_reason:y,index:u,logprobs:g}}return C?{...h,index:u,finish_reason:y,logprobs:g,message:{...E,role:m,content:b,refusal:d.refusal??null,tool_calls:C.map((_,p)=>{const{function:A,type:O,id:I,...F}=_,{arguments:x,name:P,...M}=A||{};if(I==null)throw new v(`missing choices[${u}].tool_calls[${p}].id
${Xe(s)}`);if(O==null)throw new v(`missing choices[${u}].tool_calls[${p}].type
${Xe(s)}`);if(P==null)throw new v(`missing choices[${u}].tool_calls[${p}].function.name
${Xe(s)}`);if(x==null)throw new v(`missing choices[${u}].tool_calls[${p}].function.arguments
${Xe(s)}`);return{...F,id:I,type:O,function:{...M,name:P,arguments:x}}})}}:{...h,message:{...E,content:b,role:m,refusal:d.refusal??null},finish_reason:y,index:u,logprobs:g