braintrust 0.0.55 → 0.0.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +5 -4
- package/dist/cli.js +777 -375
- package/dist/framework.d.ts +2 -1
- package/dist/index.js +651 -236
- package/dist/isomorph.d.ts +12 -0
- package/dist/logger.d.ts +330 -90
- package/dist/stackutil.d.ts +8 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/util.d.ts +1 -0
- package/package.json +2 -2
package/dist/browser.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
function H(e,t){return function(){return e.apply(t,arguments)}}var{toString:Dt}=Object.prototype,{getPrototypeOf:_e}=Object,ee=(e=>t=>{let r=Dt.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),R=e=>(e=e.toLowerCase(),t=>ee(t)===e),te=e=>t=>typeof t===e,{isArray:U}=Array,q=te("undefined");function Ut(e){return e!==null&&!q(e)&&e.constructor!==null&&!q(e.constructor)&&_(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var $e=R("ArrayBuffer");function jt(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&$e(e.buffer),t}var kt=te("string"),_=te("function"),Ke=te("number"),re=e=>e!==null&&typeof e=="object",Lt=e=>e===!0||e===!1,Z=e=>{if(ee(e)!=="object")return!1;let t=_e(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Ft=R("Date"),It=R("File"),Bt=R("Blob"),vt=R("FileList"),zt=e=>re(e)&&_(e.pipe),Ht=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||_(e.append)&&((t=ee(e))==="formdata"||t==="object"&&_(e.toString)&&e.toString()==="[object FormData]"))},qt=R("URLSearchParams"),Mt=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function M(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,o;if(typeof e!="object"&&(e=[e]),U(e))for(n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else{let i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length,u;for(n=0;n<s;n++)u=i[n],t.call(null,e[u],u,e)}}function We(e,t){t=t.toLowerCase();let r=Object.keys(e),n=r.length,o;for(;n-- >0;)if(o=r[n],t===o.toLowerCase())return o;return null}var Ge=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),Xe=e=>!q(e)&&e!==Ge;function Ee(){let{caseless:e}=Xe(this)&&this||{},t={},r=(n,o)=>{let i=e&&We(t,o)||o;Z(t[i])&&Z(n)?t[i]=Ee(t[i],n):Z(n)?t[i]=Ee({},n):U(n)?t[i]=n.slice():t[i]=n};for(let n=0,o=arguments.length;n<o;n++)arguments[n]&&M(arguments[n],r);return t}var Jt=(e,t,r,{allOwnKeys:n}={})=>(M(t,(o,i)=>{r&&_(o)?e[i]=H(o,r):e[i]=o},{allOwnKeys:n}),e),Vt=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),$t=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},Kt=(e,t,r,n)=>{let o,i,s,u={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!n||n(s,e,t))&&!u[s]&&(t[s]=e[s],u[s]=!0);e=r!==!1&&_e(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Wt=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},Gt=e=>{if(!e)return null;if(U(e))return e;let t=e.length;if(!Ke(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},Xt=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&_e(Uint8Array)),Qt=(e,t)=>{let n=(e&&e[Symbol.iterator]).call(e),o;for(;(o=n.next())&&!o.done;){let i=o.value;t.call(e,i[0],i[1])}},Yt=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},Zt=R("HTMLFormElement"),er=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,o){return n.toUpperCase()+o}),Je=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),tr=R("RegExp"),Qe=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};M(r,(o,i)=>{t(o,i,e)!==!1&&(n[i]=o)}),Object.defineProperties(e,n)},rr=e=>{Qe(e,(t,r)=>{if(_(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(_(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},nr=(e,t)=>{let r={},n=o=>{o.forEach(i=>{r[i]=!0})};return U(e)?n(e):n(String(e).split(t)),r},or=()=>{},ir=(e,t)=>(e=+e,Number.isFinite(e)?e:t),xe="abcdefghijklmnopqrstuvwxyz",Ve="0123456789",Ye={DIGIT:Ve,ALPHA:xe,ALPHA_DIGIT:xe+xe.toUpperCase()+Ve},sr=(e=16,t=Ye.ALPHA_DIGIT)=>{let r="",{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function ar(e){return!!(e&&_(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var ur=e=>{let t=new Array(10),r=(n,o)=>{if(re(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[o]=n;let i=U(n)?[]:{};return M(n,(s,u)=>{let d=r(s,o+1);!q(d)&&(i[u]=d)}),t[o]=void 0,i}}return n};return r(e,0)},cr=R("AsyncFunction"),lr=e=>e&&(re(e)||_(e))&&_(e.then)&&_(e.catch),a={isArray:U,isArrayBuffer:$e,isBuffer:Ut,isFormData:Ht,isArrayBufferView:jt,isString:kt,isNumber:Ke,isBoolean:Lt,isObject:re,isPlainObject:Z,isUndefined:q,isDate:Ft,isFile:It,isBlob:Bt,isRegExp:tr,isFunction:_,isStream:zt,isURLSearchParams:qt,isTypedArray:Xt,isFileList:vt,forEach:M,merge:Ee,extend:Jt,trim:Mt,stripBOM:Vt,inherits:$t,toFlatObject:Kt,kindOf:ee,kindOfTest:R,endsWith:Wt,toArray:Gt,forEachEntry:Qt,matchAll:Yt,isHTMLForm:Zt,hasOwnProperty:Je,hasOwnProp:Je,reduceDescriptors:Qe,freezeMethods:rr,toObjectSet:nr,toCamelCase:er,noop:or,toFiniteNumber:ir,findKey:We,global:Ge,isContextDefined:Xe,ALPHABET:Ye,generateString:sr,isSpecCompliantForm:ar,toJSONObject:ur,isAsyncFn:cr,isThenable:lr};function j(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o)}a.inherits(j,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var Ze=j.prototype,et={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{et[e]={value:e}});Object.defineProperties(j,et);Object.defineProperty(Ze,"isAxiosError",{value:!0});j.from=(e,t,r,n,o,i)=>{let s=Object.create(Ze);return a.toFlatObject(e,s,function(d){return d!==Error.prototype},u=>u!=="isAxiosError"),j.call(s,e.message,t,r,n,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};var m=j;var ne=null;function Se(e){return a.isPlainObject(e)||a.isArray(e)}function rt(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function tt(e,t,r){return e?e.concat(t).map(function(o,i){return o=rt(o),!r&&i?"["+o+"]":o}).join(r?".":""):t}function dr(e){return a.isArray(e)&&!e.some(Se)}var fr=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function pr(e,t,r){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new(ne||FormData),r=a.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,A){return!a.isUndefined(A[h])});let n=r.metaTokens,o=r.visitor||l,i=r.dots,s=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(o))throw new TypeError("visitor must be a function");function c(p){if(p===null)return"";if(a.isDate(p))return p.toISOString();if(!d&&a.isBlob(p))throw new m("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(p)||a.isTypedArray(p)?d&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function l(p,h,A){let S=p;if(p&&!A&&typeof p=="object"){if(a.endsWith(h,"{}"))h=n?h:h.slice(0,-2),p=JSON.stringify(p);else if(a.isArray(p)&&dr(p)||(a.isFileList(p)||a.endsWith(h,"[]"))&&(S=a.toArray(p)))return h=rt(h),S.forEach(function(Y,Ct){!(a.isUndefined(Y)||Y===null)&&t.append(s===!0?tt([h],Ct,i):s===null?h:h+"[]",c(Y))}),!1}return Se(p)?!0:(t.append(tt(A,h,i),c(p)),!1)}let f=[],y=Object.assign(fr,{defaultVisitor:l,convertValue:c,isVisitable:Se});function g(p,h){if(!a.isUndefined(p)){if(f.indexOf(p)!==-1)throw Error("Circular reference detected in "+h.join("."));f.push(p),a.forEach(p,function(S,D){(!(a.isUndefined(S)||S===null)&&o.call(t,S,a.isString(D)?D.trim():D,h,y))===!0&&g(S,h?h.concat(D):[D])}),f.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return g(e),t}var N=pr;function nt(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function ot(e,t){this._pairs=[],e&&N(e,this,t)}var it=ot.prototype;it.append=function(t,r){this._pairs.push([t,r])};it.toString=function(t){let r=t?function(n){return t.call(this,n,nt)}:nt;return this._pairs.map(function(o){return r(o[0])+"="+r(o[1])},"").join("&")};var oe=ot;function mr(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function J(e,t,r){if(!t)return e;let n=r&&r.encode||mr,o=r&&r.serialize,i;if(o?i=o(t,r):i=a.isURLSearchParams(t)?t.toString():new oe(t,r).toString(n),i){let s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}var Re=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(n){n!==null&&t(n)})}},Ae=Re;var ie={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var st=typeof URLSearchParams<"u"?URLSearchParams:oe;var at=typeof FormData<"u"?FormData:null;var ut=typeof Blob<"u"?Blob:null;var hr=(()=>{let e;return typeof navigator<"u"&&((e=navigator.product)==="ReactNative"||e==="NativeScript"||e==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),gr=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),x={isBrowser:!0,classes:{URLSearchParams:st,FormData:at,Blob:ut},isStandardBrowserEnv:hr,isStandardBrowserWebWorkerEnv:gr,protocols:["http","https","file","blob","url","data"]};function Oe(e,t){return N(e,new x.classes.URLSearchParams,Object.assign({visitor:function(r,n,o,i){return x.isNode&&a.isBuffer(r)?(this.append(n,r.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function yr(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function wr(e){let t={},r=Object.keys(e),n,o=r.length,i;for(n=0;n<o;n++)i=r[n],t[i]=e[i];return t}function br(e){function t(r,n,o,i){let s=r[i++],u=Number.isFinite(+s),d=i>=r.length;return s=!s&&a.isArray(o)?o.length:s,d?(a.hasOwnProp(o,s)?o[s]=[o[s],n]:o[s]=n,!u):((!o[s]||!a.isObject(o[s]))&&(o[s]=[]),t(r,n,o[s],i)&&a.isArray(o[s])&&(o[s]=wr(o[s])),!u)}if(a.isFormData(e)&&a.isFunction(e.entries)){let r={};return a.forEachEntry(e,(n,o)=>{t(yr(n),o,r,0)}),r}return null}var se=br;var xr={"Content-Type":void 0};function Er(e,t,r){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var ae={transitional:ie,adapter:["xhr","http"],transformRequest:[function(t,r){let n=r.getContentType()||"",o=n.indexOf("application/json")>-1,i=a.isObject(t);if(i&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return o&&o?JSON.stringify(se(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let u;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Oe(t,this.formSerializer).toString();if((u=a.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return N(u?{"files[]":t}:t,d&&new d,this.formSerializer)}}return i||o?(r.setContentType("application/json",!1),Er(t)):t}],transformResponse:[function(t){let r=this.transitional||ae.transitional,n=r&&r.forcedJSONParsing,o=this.responseType==="json";if(t&&a.isString(t)&&(n&&!this.responseType||o)){let s=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(u){if(s)throw u.name==="SyntaxError"?m.from(u,m.ERR_BAD_RESPONSE,this,null,this.response):u}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:x.classes.FormData,Blob:x.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};a.forEach(["delete","get","head"],function(t){ae.headers[t]={}});a.forEach(["post","put","patch"],function(t){ae.headers[t]=a.merge(xr)});var k=ae;var _r=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ct=e=>{let t={},r,n,o;return e&&e.split(`
|
|
2
|
-
`).forEach(function(
|
|
3
|
-
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let n=new this(t);return r.forEach(o=>n.set(o)),n}static accessor(t){let n=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function i(s){let u=V(s);n[u]||(Or(o,s),n[u]=!0)}return a.isArray(t)?t.forEach(i):i(t),this}};L.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.freezeMethods(L.prototype);a.freezeMethods(L);var E=L;function $(e,t){let r=this||k,n=t||r,o=E.from(n.headers),i=n.data;return a.forEach(e,function(u){i=u.call(r,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function K(e){return!!(e&&e.__CANCEL__)}function dt(e,t,r){m.call(this,e??"canceled",m.ERR_CANCELED,t,r),this.name="CanceledError"}a.inherits(dt,m,{__CANCEL__:!0});var P=dt;function Pe(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new m("Request failed with status code "+r.status,[m.ERR_BAD_REQUEST,m.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var ft=x.isStandardBrowserEnv?function(){return{write:function(r,n,o,i,s,u){let d=[];d.push(r+"="+encodeURIComponent(n)),a.isNumber(o)&&d.push("expires="+new Date(o).toGMTString()),a.isString(i)&&d.push("path="+i),a.isString(s)&&d.push("domain="+s),u===!0&&d.push("secure"),document.cookie=d.join("; ")},read:function(r){let n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function Te(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ce(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function W(e,t){return e&&!Te(t)?Ce(e,t):t}var pt=x.isStandardBrowserEnv?function(){let t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function o(i){let s=i;return t&&(r.setAttribute("href",s),s=r.href),r.setAttribute("href",s),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=o(window.location.href),function(s){let u=a.isString(s)?o(s):s;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function De(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Nr(e,t){e=e||10;let r=new Array(e),n=new Array(e),o=0,i=0,s;return t=t!==void 0?t:1e3,function(d){let c=Date.now(),l=n[i];s||(s=c),r[o]=d,n[o]=c;let f=i,y=0;for(;f!==o;)y+=r[f++],f=f%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),c-s<t)return;let g=l&&c-l;return g?Math.round(y*1e3/g):void 0}}var mt=Nr;function ht(e,t){let r=0,n=mt(50,250);return o=>{let i=o.loaded,s=o.lengthComputable?o.total:void 0,u=i-r,d=n(u),c=i<=s;r=i;let l={loaded:i,total:s,progress:s?i/s:void 0,bytes:u,rate:d||void 0,estimated:d&&s&&c?(s-i)/d:void 0,event:o};l[t?"download":"upload"]=!0,e(l)}}var Pr=typeof XMLHttpRequest<"u",gt=Pr&&function(e){return new Promise(function(r,n){let o=e.data,i=E.from(e.headers).normalize(),s=e.responseType,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}a.isFormData(o)&&(x.isStandardBrowserEnv||x.isStandardBrowserWebWorkerEnv?i.setContentType(!1):i.setContentType("multipart/form-data;",!1));let c=new XMLHttpRequest;if(e.auth){let g=e.auth.username||"",p=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(g+":"+p))}let l=W(e.baseURL,e.url);c.open(e.method.toUpperCase(),J(l,e.params,e.paramsSerializer),!0),c.timeout=e.timeout;function f(){if(!c)return;let g=E.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),h={data:!s||s==="text"||s==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:g,config:e,request:c};Pe(function(S){r(S),d()},function(S){n(S),d()},h),c=null}if("onloadend"in c?c.onloadend=f:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(f)},c.onabort=function(){c&&(n(new m("Request aborted",m.ECONNABORTED,e,c)),c=null)},c.onerror=function(){n(new m("Network Error",m.ERR_NETWORK,e,c)),c=null},c.ontimeout=function(){let p=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",h=e.transitional||ie;e.timeoutErrorMessage&&(p=e.timeoutErrorMessage),n(new m(p,h.clarifyTimeoutError?m.ETIMEDOUT:m.ECONNABORTED,e,c)),c=null},x.isStandardBrowserEnv){let g=(e.withCredentials||pt(l))&&e.xsrfCookieName&&ft.read(e.xsrfCookieName);g&&i.set(e.xsrfHeaderName,g)}o===void 0&&i.setContentType(null),"setRequestHeader"in c&&a.forEach(i.toJSON(),function(p,h){c.setRequestHeader(h,p)}),a.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),s&&s!=="json"&&(c.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&c.addEventListener("progress",ht(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",ht(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=g=>{c&&(n(!g||g.type?new P(null,e,c):g),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));let y=De(l);if(y&&x.protocols.indexOf(y)===-1){n(new m("Unsupported protocol "+y+":",m.ERR_BAD_REQUEST,e));return}c.send(o||null)})};var ce={http:ne,xhr:gt};a.forEach(ce,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var yt={getAdapter:e=>{e=a.isArray(e)?e:[e];let{length:t}=e,r,n;for(let o=0;o<t&&(r=e[o],!(n=a.isString(r)?ce[r.toLowerCase()]:r));o++);if(!n)throw n===!1?new m(`Adapter ${r} is not supported by the environment`,"ERR_NOT_SUPPORT"):new Error(a.hasOwnProp(ce,r)?`Adapter '${r}' is not available in the build`:`Unknown adapter '${r}'`);if(!a.isFunction(n))throw new TypeError("adapter is not a function");return n},adapters:ce};function Ue(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new P(null,e)}function le(e){return Ue(e),e.headers=E.from(e.headers),e.data=$.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),yt.getAdapter(e.adapter||k.adapter)(e).then(function(n){return Ue(e),n.data=$.call(e,e.transformResponse,n),n.headers=E.from(n.headers),n},function(n){return K(n)||(Ue(e),n&&n.response&&(n.response.data=$.call(e,e.transformResponse,n.response),n.response.headers=E.from(n.response.headers))),Promise.reject(n)})}var wt=e=>e instanceof E?e.toJSON():e;function O(e,t){t=t||{};let r={};function n(c,l,f){return a.isPlainObject(c)&&a.isPlainObject(l)?a.merge.call({caseless:f},c,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function o(c,l,f){if(a.isUndefined(l)){if(!a.isUndefined(c))return n(void 0,c,f)}else return n(c,l,f)}function i(c,l){if(!a.isUndefined(l))return n(void 0,l)}function s(c,l){if(a.isUndefined(l)){if(!a.isUndefined(c))return n(void 0,c)}else return n(void 0,l)}function u(c,l,f){if(f in t)return n(c,l);if(f in e)return n(void 0,c)}let d={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:u,headers:(c,l)=>o(wt(c),wt(l),!0)};return a.forEach(Object.keys(Object.assign({},e,t)),function(l){let f=d[l]||o,y=f(e[l],t[l],l);a.isUndefined(y)&&f!==u||(r[l]=y)}),r}var de="1.4.0";var je={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{je[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});var bt={};je.transitional=function(t,r,n){function o(i,s){return"[Axios v"+de+"] Transitional option '"+i+"'"+s+(n?". "+n:"")}return(i,s,u)=>{if(t===!1)throw new m(o(s," has been removed"+(r?" in "+r:"")),m.ERR_DEPRECATED);return r&&!bt[s]&&(bt[s]=!0,console.warn(o(s," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(i,s,u):!0}};function Tr(e,t,r){if(typeof e!="object")throw new m("options must be an object",m.ERR_BAD_OPTION_VALUE);let n=Object.keys(e),o=n.length;for(;o-- >0;){let i=n[o],s=t[i];if(s){let u=e[i],d=u===void 0||s(u,i,e);if(d!==!0)throw new m("option "+i+" must be "+d,m.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new m("Unknown option "+i,m.ERR_BAD_OPTION)}}var fe={assertOptions:Tr,validators:je};var T=fe.validators,F=class{constructor(t){this.defaults=t,this.interceptors={request:new Ae,response:new Ae}}request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=O(this.defaults,r);let{transitional:n,paramsSerializer:o,headers:i}=r;n!==void 0&&fe.assertOptions(n,{silentJSONParsing:T.transitional(T.boolean),forcedJSONParsing:T.transitional(T.boolean),clarifyTimeoutError:T.transitional(T.boolean)},!1),o!=null&&(a.isFunction(o)?r.paramsSerializer={serialize:o}:fe.assertOptions(o,{encode:T.function,serialize:T.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s;s=i&&a.merge(i.common,i[r.method]),s&&a.forEach(["delete","get","head","post","put","patch","common"],p=>{delete i[p]}),r.headers=E.concat(s,i);let u=[],d=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(r)===!1||(d=d&&h.synchronous,u.unshift(h.fulfilled,h.rejected))});let c=[];this.interceptors.response.forEach(function(h){c.push(h.fulfilled,h.rejected)});let l,f=0,y;if(!d){let p=[le.bind(this),void 0];for(p.unshift.apply(p,u),p.push.apply(p,c),y=p.length,l=Promise.resolve(r);f<y;)l=l.then(p[f++],p[f++]);return l}y=u.length;let g=r;for(f=0;f<y;){let p=u[f++],h=u[f++];try{g=p(g)}catch(A){h.call(this,A);break}}try{l=le.call(this,g)}catch(p){return Promise.reject(p)}for(f=0,y=c.length;f<y;)l=l.then(c[f++],c[f++]);return l}getUri(t){t=O(this.defaults,t);let r=W(t.baseURL,t.url);return J(r,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){F.prototype[t]=function(r,n){return this.request(O(n||{},{method:t,url:r,data:(n||{}).data}))}});a.forEach(["post","put","patch"],function(t){function r(n){return function(i,s,u){return this.request(O(u||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:s}))}}F.prototype[t]=r(),F.prototype[t+"Form"]=r(!0)});var G=F;var ke=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(i){r=i});let n=this;this.promise.then(o=>{if(!n._listeners)return;let i=n._listeners.length;for(;i-- >0;)n._listeners[i](o);n._listeners=null}),this.promise.then=o=>{let i,s=new Promise(u=>{n.subscribe(u),i=u}).then(o);return s.cancel=function(){n.unsubscribe(i)},s},t(function(i,s,u){n.reason||(n.reason=new P(i,s,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}static source(){let t;return{token:new e(function(o){t=o}),cancel:t}}},xt=ke;function Le(e){return function(r){return e.apply(null,r)}}function Fe(e){return a.isObject(e)&&e.isAxiosError===!0}var Ie={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ie).forEach(([e,t])=>{Ie[t]=e});var Et=Ie;function _t(e){let t=new G(e),r=H(G.prototype.request,t);return a.extend(r,G.prototype,t,{allOwnKeys:!0}),a.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return _t(O(e,o))},r}var w=_t(k);w.Axios=G;w.CanceledError=P;w.CancelToken=xt;w.isCancel=K;w.VERSION=de;w.toFormData=N;w.AxiosError=m;w.Cancel=w.CanceledError;w.all=function(t){return Promise.all(t)};w.spread=Le;w.isAxiosError=Fe;w.mergeConfig=O;w.AxiosHeaders=E;w.formToJSON=e=>se(a.isHTMLForm(e)?new FormData(e):e);w.HttpStatusCode=Et;w.default=w;var I=w;var{Axios:yi,AxiosError:wi,CanceledError:bi,isCancel:xi,CancelToken:Ei,VERSION:_i,all:Si,Cancel:Ri,isAxiosError:Ai,spread:Oi,toFormData:Ni,AxiosHeaders:Pi,HttpStatusCode:Ti,formToJSON:Ci,mergeConfig:Di}=I;var pe,Cr=new Uint8Array(16);function Be(){if(!pe&&(pe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!pe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return pe(Cr)}var b=[];for(let e=0;e<256;++e)b.push((e+256).toString(16).slice(1));function St(e,t=0){return(b[e[t+0]]+b[e[t+1]]+b[e[t+2]]+b[e[t+3]]+"-"+b[e[t+4]]+b[e[t+5]]+"-"+b[e[t+6]]+b[e[t+7]]+"-"+b[e[t+8]]+b[e[t+9]]+"-"+b[e[t+10]]+b[e[t+11]]+b[e[t+12]]+b[e[t+13]]+b[e[t+14]]+b[e[t+15]]).toLowerCase()}var Dr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ve={randomUUID:Dr};function Ur(e,t,r){if(ve.randomUUID&&!t&&!e)return ve.randomUUID();e=e||{};let n=e.random||(e.rng||Be)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let o=0;o<16;++o)t[r+o]=n[o];return t}return St(n)}var me=Ur;var jr={makeAxios:e=>I.create({...e}),getRepoStatus:async()=>{},getPastNAncestors:async()=>[],getEnv:e=>{}},B=jr;var X={current_project:null,current_experiment:null},v=null,Rt=null,ye=null,be=null,Nt=null,At=!1,kr="_xact_id",Q=class e{constructor(t){this.base_url=t,this.token=null,this.session=null,this._reset()}async ping(){try{let t=await this.get("ping");return z===null&&(z=t.data),t.status===200}catch{return!1}}make_long_lived(){this._reset()}static sanitize_token(t){return t.trim()}set_token(t){t=e.sanitize_token(t),this.token=t,this._reset()}_reset(){let t={};this.token&&(t.Authorization=`Bearer ${this.token}`),this.session=B.makeAxios({headers:t})}async get(t,r=void 0){return await this.session.get(ze(this.base_url,t),{params:r})}async post(t,r=void 0,n=void 0){return await this.session.post(ze(this.base_url,t),r,n)}async get_json(t,r=void 0,n=0){let o=n+1;for(let i=0;i<o;i++)try{return(await this.get(`${t}`,r)).data}catch(s){if(i<o-1){console.log(`Retrying API request ${t} ${r} ${s.status} ${s.text}`);continue}throw s}}async post_json(t,r=void 0){return(await this.post(`${t}`,r,{headers:{"Content-Type":"application/json"}})).data}},he=null;function Me(){return he||(he=new Q(v)),he}var ge=null;function C(){return ge||(ge=new Q(Nt)),ge}var z=null;async function Pt(){return z===null&&(z=await C().get_json("ping")),z}function Lr(){he=null,ge=null,z=null}var Ot=class{constructor(t,r,n){this.name=t,this.id=r,this.org_id=n}};var Fr=10*1024*1024;function Ir(e){return`[${e.join(",")}]`}var we=class{constructor(){this.items=[];this.active_flush=Promise.resolve([]);this.active_flush_resolved=!0}log(t){this.items.push(...t),this.active_flush_resolved&&(this.active_flush_resolved=!1,this.active_flush=this.flush_once())}async flush_once(t=100){this.active_flush_resolved=!1;let r=(this.items||[]).reverse();this.items=[];let n=[];for(;;){let o=[],i=0;for(;o.length<t&&i<Fr/2;){let s=null;if(r.length>0)s=r.pop();else break;let u=JSON.stringify(s);o.push(u),i+=u.length}if(o.length>0)n=(await C().post_json("logs",Ir(o))).data;else break}return this.items.length>0?this.active_flush=this.flush_once():this.active_flush_resolved=!0,n}async flush(){for(;await this.active_flush,!this.active_flush_resolved;);}};async function Xi(e,t={}){let{experiment:r,description:n,dataset:o,baseExperiment:i,isPublic:s,update:u,apiUrl:d,apiKey:c,orgName:l,disableCache:f}=t||{};await Tt({orgName:l,disableCache:f,apiKey:c,apiUrl:d});let y=await vr(e,{experimentName:r,description:n,dataset:o,update:u,baseExperiment:i,isPublic:s});return X.current_experiment=y,y}async function Qi(e,t={}){let{dataset:r,description:n,version:o,apiUrl:i,apiKey:s,orgName:u,disableCache:d}=t||{};return await Tt({orgName:u,disableCache:d,apiKey:s,apiUrl:i}),await zr(e,{name:r,description:n,version:o})}async function Tt(e={}){let{apiUrl:t=B.getEnv("BRAINTRUST_API_URL")||"https://www.braintrustdata.com",apiKey:r=B.getEnv("BRAINTRUST_API_KEY"),orgName:n=void 0,disableCache:o=!1}=e||{},{forceLogin:i=!1}=e||{};if((t!=v||r!==void 0&&Q.sanitize_token(r)!=Rt||n!==void 0&&n!=be)&&(i=!0),At&&!i)return;Lr(),v=t;let s=null,u=!1,d=null;if(r!==void 0){let l=(await I.post(ze(v,"/api/apikey/login"),{token:r})).data;Br(l.org_info,n),d=C(),d.set_token(r),u=await d.ping()}else throw new Error("Please specify an api key. Token based login is not yet implemented in the JS client.");if(!d)throw new Error("Conn should be set at this point (a bug)");u||await d.get("ping"),d.make_long_lived(),Me().set_token(r),Rt=d.token,At=!0}function Yi(e){if(!X.current_experiment)throw new Error("Not initialized. Please call init() first");return X.current_experiment.log(e)}async function Zi(e={}){if(!X.current_experiment)throw new Error("Not initialized. Please call init() first");return await X.current_experiment.summarize(e)}function Br(e,t){if(e.length===0)throw new Error("This user is not part of any organizations.");for(let r of e)if(t===void 0||r.name===t){ye=r.id,be=r.name,Nt=r.api_url;break}if(ye===void 0)throw new Error(`Organization ${t} not found. Must be one of ${e.map(r=>r.name).join(", ")}`)}function ze(...e){return e.map(t=>t.replace(/^\//,"")).join("/")}async function vr(e,{experimentName:t,description:r,dataset:n,update:o,baseExperiment:i,isPublic:s}={experimentName:void 0,description:void 0,baseExperiment:void 0,isPublic:!1}){let u={project_name:e,org_id:ye};t&&(u.experiment_name=t),r&&(u.description=r),o&&(u.update=o);let d=await B.getRepoStatus();d&&(u.repo_info=d),i?u.base_experiment=i:u.ancestor_commits=await B.getPastNAncestors(),n!==void 0&&(u.dataset_id=n.id,u.dataset_version=await n.version()),s!==void 0&&(u.public=s);let c=await Me().post_json("api/experiment/register",u),l=c.project,f=c.experiment,y=(await Pt()).id;return new He(l,f.id,f.name,y,n)}var He=class{constructor(t,r,n,o,i){this.project=t,this.id=r,this.name=n,this.user_id=o,this.dataset=i,this.logger=new we}log({input:t,output:r,expected:n,scores:o,metadata:i,id:s,datasetRecordId:u,inputs:d}){if(t===void 0&&d===void 0)throw new Error("Either input or inputs (deprecated) must be specified. Prefer input.");if(t!==void 0&&d!==void 0)throw new Error("Only one of input or inputs (deprecated) can be specified. Prefer input.");for(let[l,f]of Object.entries(o)){if(typeof l!="string")throw new Error("score names must be strings");if(typeof f=="boolean"&&(f=f?1:0,o[l]=f),typeof f!="number")throw new Error("score values must be numbers");if(f<0||f>1)throw new Error("score values must be between 0 and 1")}if(i!==void 0){for(let l of Object.keys(i))if(typeof l!="string")throw new Error("metadata keys must be strings")}if(this.dataset&&u===void 0)throw new Error("datasetRecordId must be specified when using a dataset");if(!this.dataset&&u!==void 0)throw new Error("datasetRecordId cannot be specified when not using a dataset");let c={id:s||me(),inputs:t??d,output:r,expected:n,scores:o,project_id:this.project.id,experiment_id:this.id,user_id:this.user_id,created:new Date().toISOString(),dataset_record_id:u,metadata:i};return this.logger.log([c]),c.id}async summarize(t={}){let{summarizeScores:r=!0,comparisonExperimentId:n=void 0}=t||{};await this.logger.flush();let o=`${v}/app/${encodeURIComponent(be)}/p/${encodeURIComponent(this.project.name)}`,i=`${o}/${encodeURIComponent(this.name)}`,s,u;if(r){if(n===void 0){let l=(await C().get("/crud/base_experiments",{id:this.id})).data;l.length>0&&(n=l[0].base_exp_id,u=l[0].base_exp_name)}n!==void 0&&(s=await C().get_json("/experiment-comparison",{experiment_id:this.id,base_experiment_id:n},3))}return{projectName:this.project.name,experimentName:this.name,projectUrl:o,experimentUrl:i,comparisonExperimentName:u,scores:s}}};async function zr(e,{name:t,description:r,version:n}={}){let o={org_id:ye,project_name:e,dataset_name:t,description:r},i=await Me().post_json("api/dataset/register",o),s=i.project,u=i.dataset,d=(await Pt()).id;return new qe(s,u.id,u.name,d,n)}var qe=class{constructor(t,r,n,o,i){this._fetchedData=void 0;this.project=t,this.id=r,this.name=n,this.user_id=o,this.pinnedVersion=i,this.logger=new we}insert({input:t,output:r,metadata:n,id:o}){if(n!==void 0){for(let s of Object.keys(n))if(typeof s!="string")throw new Error("metadata keys must be strings")}let i={id:o||me(),inputs:t,output:r,project_id:this.project.id,dataset_id:this.id,user_id:this.user_id,created:new Date().toISOString(),metadata:n};return this.logger.log([i]),i.id}delete(t){let r=this.user_id,n={id:t,project_id:this.project.id,dataset_id:this.id,user_id:r,created:new Date().toISOString(),_object_delete:!0};return this.logger.log([n]),n.id}async summarize(t={}){let{summarizeData:r=!0}=t||{};await this.logger.flush();let n=`${v}/app/${encodeURIComponent(be)}/p/${encodeURIComponent(this.project.name)}`,o=`${n}/d/${encodeURIComponent(this.name)}`,i;return r&&(i=await C().get_json("dataset-summary",{dataset_id:this.id},3)),{projectName:this.project.name,datasetName:this.name,projectUrl:n,datasetUrl:o,dataSummary:i}}async*fetch(){let t=await this.fetchedData();for(let r of t)yield{id:r.id,input:r.input&&JSON.parse(r.input),output:r.input&&JSON.parse(r.output),metadata:r.metadata&&JSON.parse(r.metadata)};this.clearCache()}[Symbol.asyncIterator](){return this.fetch()}async fetchedData(){if(this._fetchedData===void 0){let r=await(await C().get("object/dataset",{id:this.id,fmt:"json",version:this.pinnedVersion})).data;this._fetchedData=r.split(`
|
|
4
|
-
`).filter(n=>n.trim()!=="").map(n=>JSON.parse(n))}return this._fetchedData||[]}clearCache(){this._fetchedData=void 0}async version(){if(this.pinnedVersion!==void 0)return this.pinnedVersion;{let t=await this.fetchedData(),r;for(let n of t){let o=n[kr];(r===void 0||(o??o>r))&&(r=o)}return r}}};export{qe as Dataset,He as Experiment,Ot as Project,Xi as init,Qi as initDataset,Yi as log,Tt as login,Zi as summarize};
|
|
1
|
+
function M(t,e){return function(){return t.apply(e,arguments)}}var{toString:Tt}=Object.prototype,{getPrototypeOf:we}=Object,ee=(t=>e=>{let r=Tt.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),O=t=>(t=t.toLowerCase(),e=>ee(e)===t),te=t=>e=>typeof e===t,{isArray:k}=Array,q=te("undefined");function Pt(t){return t!==null&&!q(t)&&t.constructor!==null&&!q(t.constructor)&&_(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var Ke=O("ArrayBuffer");function Ut(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Ke(t.buffer),e}var Lt=te("string"),_=te("function"),We=te("number"),re=t=>t!==null&&typeof t=="object",kt=t=>t===!0||t===!1,Z=t=>{if(ee(t)!=="object")return!1;let e=we(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},It=O("Date"),Ft=O("File"),Dt=O("Blob"),jt=O("FileList"),vt=t=>re(t)&&_(t.pipe),Bt=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||_(t.append)&&((e=ee(t))==="formdata"||e==="object"&&_(t.toString)&&t.toString()==="[object FormData]"))},zt=O("URLSearchParams"),Ht=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function J(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),k(t))for(n=0,i=t.length;n<i;n++)e.call(null,t[n],n,t);else{let s=r?Object.getOwnPropertyNames(t):Object.keys(t),o=s.length,u;for(n=0;n<o;n++)u=s[n],e.call(null,t[u],u,t)}}function Ge(t,e){e=e.toLowerCase();let r=Object.keys(t),n=r.length,i;for(;n-- >0;)if(i=r[n],e===i.toLowerCase())return i;return null}var Xe=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),Qe=t=>!q(t)&&t!==Xe;function be(){let{caseless:t}=Qe(this)&&this||{},e={},r=(n,i)=>{let s=t&&Ge(e,i)||i;Z(e[s])&&Z(n)?e[s]=be(e[s],n):Z(n)?e[s]=be({},n):k(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&J(arguments[n],r);return e}var Mt=(t,e,r,{allOwnKeys:n}={})=>(J(e,(i,s)=>{r&&_(i)?t[s]=M(i,r):t[s]=i},{allOwnKeys:n}),t),qt=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Jt=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},Vt=(t,e,r,n)=>{let i,s,o,u={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!u[o]&&(e[o]=t[o],u[o]=!0);t=r!==!1&&we(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},$t=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},Kt=t=>{if(!t)return null;if(k(t))return t;let e=t.length;if(!We(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Wt=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&we(Uint8Array)),Gt=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},Xt=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Qt=O("HTMLFormElement"),Yt=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),Ve=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Zt=O("RegExp"),Ye=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};J(r,(i,s)=>{e(i,s,t)!==!1&&(n[s]=i)}),Object.defineProperties(t,n)},er=t=>{Ye(t,(e,r)=>{if(_(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(_(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},tr=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return k(t)?n(t):n(String(t).split(e)),r},rr=()=>{},nr=(t,e)=>(t=+t,Number.isFinite(t)?t:e),xe="abcdefghijklmnopqrstuvwxyz",$e="0123456789",Ze={DIGIT:$e,ALPHA:xe,ALPHA_DIGIT:xe+xe.toUpperCase()+$e},ir=(t=16,e=Ze.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function sr(t){return!!(t&&_(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var or=t=>{let e=new Array(10),r=(n,i)=>{if(re(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=k(n)?[]:{};return J(n,(o,u)=>{let p=r(o,i+1);!q(p)&&(s[u]=p)}),e[i]=void 0,s}}return n};return r(t,0)},ar=O("AsyncFunction"),ur=t=>t&&(re(t)||_(t))&&_(t.then)&&_(t.catch),a={isArray:k,isArrayBuffer:Ke,isBuffer:Pt,isFormData:Bt,isArrayBufferView:Ut,isString:Lt,isNumber:We,isBoolean:kt,isObject:re,isPlainObject:Z,isUndefined:q,isDate:It,isFile:Ft,isBlob:Dt,isRegExp:Zt,isFunction:_,isStream:vt,isURLSearchParams:zt,isTypedArray:Wt,isFileList:jt,forEach:J,merge:be,extend:Mt,trim:Ht,stripBOM:qt,inherits:Jt,toFlatObject:Vt,kindOf:ee,kindOfTest:O,endsWith:$t,toArray:Kt,forEachEntry:Gt,matchAll:Xt,isHTMLForm:Qt,hasOwnProperty:Ve,hasOwnProp:Ve,reduceDescriptors:Ye,freezeMethods:er,toObjectSet:tr,toCamelCase:Yt,noop:rr,toFiniteNumber:nr,findKey:Ge,global:Xe,isContextDefined:Qe,ALPHABET:Ze,generateString:ir,isSpecCompliantForm:sr,toJSONObject:or,isAsyncFn:ar,isThenable:ur};function I(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}a.inherits(I,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var et=I.prototype,tt={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{tt[t]={value:t}});Object.defineProperties(I,tt);Object.defineProperty(et,"isAxiosError",{value:!0});I.from=(t,e,r,n,i,s)=>{let o=Object.create(et);return a.toFlatObject(t,o,function(p){return p!==Error.prototype},u=>u!=="isAxiosError"),I.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var h=I;var ne=null;function Ee(t){return a.isPlainObject(t)||a.isArray(t)}function nt(t){return a.endsWith(t,"[]")?t.slice(0,-2):t}function rt(t,e,r){return t?t.concat(e).map(function(i,s){return i=nt(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function cr(t){return a.isArray(t)&&!t.some(Ee)}var lr=a.toFlatObject(a,{},null,function(e){return/^is[A-Z]/.test(e)});function pr(t,e,r){if(!a.isObject(t))throw new TypeError("target must be an object");e=e||new(ne||FormData),r=a.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,C){return!a.isUndefined(C[g])});let n=r.metaTokens,i=r.visitor||l,s=r.dots,o=r.indexes,p=(r.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(e);if(!a.isFunction(i))throw new TypeError("visitor must be a function");function c(d){if(d===null)return"";if(a.isDate(d))return d.toISOString();if(!p&&a.isBlob(d))throw new h("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(d)||a.isTypedArray(d)?p&&typeof Blob=="function"?new Blob([d]):Buffer.from(d):d}function l(d,g,C){let A=d;if(d&&!C&&typeof d=="object"){if(a.endsWith(g,"{}"))g=n?g:g.slice(0,-2),d=JSON.stringify(d);else if(a.isArray(d)&&cr(d)||(a.isFileList(d)||a.endsWith(g,"[]"))&&(A=a.toArray(d)))return g=nt(g),A.forEach(function(Y,Nt){!(a.isUndefined(Y)||Y===null)&&e.append(o===!0?rt([g],Nt,s):o===null?g:g+"[]",c(Y))}),!1}return Ee(d)?!0:(e.append(rt(C,g,s),c(d)),!1)}let f=[],x=Object.assign(lr,{defaultVisitor:l,convertValue:c,isVisitable:Ee});function y(d,g){if(!a.isUndefined(d)){if(f.indexOf(d)!==-1)throw Error("Circular reference detected in "+g.join("."));f.push(d),a.forEach(d,function(A,L){(!(a.isUndefined(A)||A===null)&&i.call(e,A,a.isString(L)?L.trim():L,g,x))===!0&&y(A,g?g.concat(L):[L])}),f.pop()}}if(!a.isObject(t))throw new TypeError("data must be an object");return y(t),e}var T=pr;function it(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function st(t,e){this._pairs=[],t&&T(t,this,e)}var ot=st.prototype;ot.append=function(e,r){this._pairs.push([e,r])};ot.toString=function(e){let r=e?function(n){return e.call(this,n,it)}:it;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var ie=st;function dr(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function V(t,e,r){if(!e)return t;let n=r&&r.encode||dr,i=r&&r.serialize,s;if(i?s=i(e,r):s=a.isURLSearchParams(e)?e.toString():new ie(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var Se=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){a.forEach(this.handlers,function(n){n!==null&&e(n)})}},_e=Se;var se={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var at=typeof URLSearchParams<"u"?URLSearchParams:ie;var ut=typeof FormData<"u"?FormData:null;var ct=typeof Blob<"u"?Blob:null;var fr=(()=>{let t;return typeof navigator<"u"&&((t=navigator.product)==="ReactNative"||t==="NativeScript"||t==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),mr=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),E={isBrowser:!0,classes:{URLSearchParams:at,FormData:ut,Blob:ct},isStandardBrowserEnv:fr,isStandardBrowserWebWorkerEnv:mr,protocols:["http","https","file","blob","url","data"]};function Re(t,e){return T(t,new E.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return E.isNode&&a.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function hr(t){return a.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function gr(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n<i;n++)s=r[n],e[s]=t[s];return e}function yr(t){function e(r,n,i,s){let o=r[s++],u=Number.isFinite(+o),p=s>=r.length;return o=!o&&a.isArray(i)?i.length:o,p?(a.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!u):((!i[o]||!a.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&a.isArray(i[o])&&(i[o]=gr(i[o])),!u)}if(a.isFormData(t)&&a.isFunction(t.entries)){let r={};return a.forEachEntry(t,(n,i)=>{e(hr(n),i,r,0)}),r}return null}var oe=yr;var xr={"Content-Type":void 0};function br(t,e,r){if(a.isString(t))try{return(e||JSON.parse)(t),a.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var ae={transitional:se,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=a.isObject(e);if(s&&a.isHTMLForm(e)&&(e=new FormData(e)),a.isFormData(e))return i&&i?JSON.stringify(oe(e)):e;if(a.isArrayBuffer(e)||a.isBuffer(e)||a.isStream(e)||a.isFile(e)||a.isBlob(e))return e;if(a.isArrayBufferView(e))return e.buffer;if(a.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let u;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Re(e,this.formSerializer).toString();if((u=a.isFileList(e))||n.indexOf("multipart/form-data")>-1){let p=this.env&&this.env.FormData;return T(u?{"files[]":e}:e,p&&new p,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),br(e)):e}],transformResponse:[function(e){let r=this.transitional||ae.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&a.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(u){if(o)throw u.name==="SyntaxError"?h.from(u,h.ERR_BAD_RESPONSE,this,null,this.response):u}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:E.classes.FormData,Blob:E.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};a.forEach(["delete","get","head"],function(e){ae.headers[e]={}});a.forEach(["post","put","patch"],function(e){ae.headers[e]=a.merge(xr)});var F=ae;var wr=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),lt=t=>{let e={},r,n,i;return t&&t.split(`
|
|
2
|
+
`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&wr[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e};var pt=Symbol("internals");function $(t){return t&&String(t).trim().toLowerCase()}function ue(t){return t===!1||t==null?t:a.isArray(t)?t.map(ue):String(t)}function Er(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var Sr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Ae(t,e,r,n,i){if(a.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!a.isString(e)){if(a.isString(n))return e.indexOf(n)!==-1;if(a.isRegExp(n))return n.test(e)}}function _r(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function Rr(t,e){let r=a.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var D=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(u,p,c){let l=$(p);if(!l)throw new Error("header name must be a non-empty string");let f=a.findKey(i,l);(!f||i[f]===void 0||c===!0||c===void 0&&i[f]!==!1)&&(i[f||p]=ue(u))}let o=(u,p)=>a.forEach(u,(c,l)=>s(c,l,p));return a.isPlainObject(e)||e instanceof this.constructor?o(e,r):a.isString(e)&&(e=e.trim())&&!Sr(e)?o(lt(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=$(e),e){let n=a.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Er(i);if(a.isFunction(r))return r.call(this,i,n);if(a.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=$(e),e){let n=a.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||Ae(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=$(o),o){let u=a.findKey(n,o);u&&(!r||Ae(n,n[u],u,r))&&(delete n[u],i=!0)}}return a.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||Ae(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return a.forEach(this,(i,s)=>{let o=a.findKey(n,s);if(o){r[o]=ue(i),delete r[s];return}let u=e?_r(s):String(s).trim();u!==s&&delete r[s],r[u]=ue(i),n[u]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return a.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&a.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(`
|
|
3
|
+
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[pt]=this[pt]={accessors:{}}).accessors,i=this.prototype;function s(o){let u=$(o);n[u]||(Rr(i,o),n[u]=!0)}return a.isArray(e)?e.forEach(s):s(e),this}};D.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.freezeMethods(D.prototype);a.freezeMethods(D);var S=D;function K(t,e){let r=this||F,n=e||r,i=S.from(n.headers),s=n.data;return a.forEach(t,function(u){s=u.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function W(t){return!!(t&&t.__CANCEL__)}function dt(t,e,r){h.call(this,t??"canceled",h.ERR_CANCELED,e,r),this.name="CanceledError"}a.inherits(dt,h,{__CANCEL__:!0});var P=dt;function Oe(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new h("Request failed with status code "+r.status,[h.ERR_BAD_REQUEST,h.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var ft=E.isStandardBrowserEnv?function(){return{write:function(r,n,i,s,o,u){let p=[];p.push(r+"="+encodeURIComponent(n)),a.isNumber(i)&&p.push("expires="+new Date(i).toGMTString()),a.isString(s)&&p.push("path="+s),a.isString(o)&&p.push("domain="+o),u===!0&&p.push("secure"),document.cookie=p.join("; ")},read:function(r){let n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function Ce(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Ne(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}function G(t,e){return t&&!Ce(e)?Ne(t,e):e}var mt=E.isStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let u=a.isString(o)?i(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function Te(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Ar(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(p){let c=Date.now(),l=n[s];o||(o=c),r[i]=p,n[i]=c;let f=s,x=0;for(;f!==i;)x+=r[f++],f=f%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o<e)return;let y=l&&c-l;return y?Math.round(x*1e3/y):void 0}}var ht=Ar;function gt(t,e){let r=0,n=ht(50,250);return i=>{let s=i.loaded,o=i.lengthComputable?i.total:void 0,u=s-r,p=n(u),c=s<=o;r=s;let l={loaded:s,total:o,progress:o?s/o:void 0,bytes:u,rate:p||void 0,estimated:p&&o&&c?(o-s)/p:void 0,event:i};l[e?"download":"upload"]=!0,t(l)}}var Or=typeof XMLHttpRequest<"u",yt=Or&&function(t){return new Promise(function(r,n){let i=t.data,s=S.from(t.headers).normalize(),o=t.responseType,u;function p(){t.cancelToken&&t.cancelToken.unsubscribe(u),t.signal&&t.signal.removeEventListener("abort",u)}a.isFormData(i)&&(E.isStandardBrowserEnv||E.isStandardBrowserWebWorkerEnv?s.setContentType(!1):s.setContentType("multipart/form-data;",!1));let c=new XMLHttpRequest;if(t.auth){let y=t.auth.username||"",d=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(y+":"+d))}let l=G(t.baseURL,t.url);c.open(t.method.toUpperCase(),V(l,t.params,t.paramsSerializer),!0),c.timeout=t.timeout;function f(){if(!c)return;let y=S.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),g={data:!o||o==="text"||o==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:y,config:t,request:c};Oe(function(A){r(A),p()},function(A){n(A),p()},g),c=null}if("onloadend"in c?c.onloadend=f:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(f)},c.onabort=function(){c&&(n(new h("Request aborted",h.ECONNABORTED,t,c)),c=null)},c.onerror=function(){n(new h("Network Error",h.ERR_NETWORK,t,c)),c=null},c.ontimeout=function(){let d=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",g=t.transitional||se;t.timeoutErrorMessage&&(d=t.timeoutErrorMessage),n(new h(d,g.clarifyTimeoutError?h.ETIMEDOUT:h.ECONNABORTED,t,c)),c=null},E.isStandardBrowserEnv){let y=(t.withCredentials||mt(l))&&t.xsrfCookieName&&ft.read(t.xsrfCookieName);y&&s.set(t.xsrfHeaderName,y)}i===void 0&&s.setContentType(null),"setRequestHeader"in c&&a.forEach(s.toJSON(),function(d,g){c.setRequestHeader(g,d)}),a.isUndefined(t.withCredentials)||(c.withCredentials=!!t.withCredentials),o&&o!=="json"&&(c.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&c.addEventListener("progress",gt(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",gt(t.onUploadProgress)),(t.cancelToken||t.signal)&&(u=y=>{c&&(n(!y||y.type?new P(null,t,c):y),c.abort(),c=null)},t.cancelToken&&t.cancelToken.subscribe(u),t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u)));let x=Te(l);if(x&&E.protocols.indexOf(x)===-1){n(new h("Unsupported protocol "+x+":",h.ERR_BAD_REQUEST,t));return}c.send(i||null)})};var ce={http:ne,xhr:yt};a.forEach(ce,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var xt={getAdapter:t=>{t=a.isArray(t)?t:[t];let{length:e}=t,r,n;for(let i=0;i<e&&(r=t[i],!(n=a.isString(r)?ce[r.toLowerCase()]:r));i++);if(!n)throw n===!1?new h(`Adapter ${r} is not supported by the environment`,"ERR_NOT_SUPPORT"):new Error(a.hasOwnProp(ce,r)?`Adapter '${r}' is not available in the build`:`Unknown adapter '${r}'`);if(!a.isFunction(n))throw new TypeError("adapter is not a function");return n},adapters:ce};function Pe(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new P(null,t)}function le(t){return Pe(t),t.headers=S.from(t.headers),t.data=K.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),xt.getAdapter(t.adapter||F.adapter)(t).then(function(n){return Pe(t),n.data=K.call(t,t.transformResponse,n),n.headers=S.from(n.headers),n},function(n){return W(n)||(Pe(t),n&&n.response&&(n.response.data=K.call(t,t.transformResponse,n.response),n.response.headers=S.from(n.response.headers))),Promise.reject(n)})}var bt=t=>t instanceof S?t.toJSON():t;function N(t,e){e=e||{};let r={};function n(c,l,f){return a.isPlainObject(c)&&a.isPlainObject(l)?a.merge.call({caseless:f},c,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function i(c,l,f){if(a.isUndefined(l)){if(!a.isUndefined(c))return n(void 0,c,f)}else return n(c,l,f)}function s(c,l){if(!a.isUndefined(l))return n(void 0,l)}function o(c,l){if(a.isUndefined(l)){if(!a.isUndefined(c))return n(void 0,c)}else return n(void 0,l)}function u(c,l,f){if(f in e)return n(c,l);if(f in t)return n(void 0,c)}let p={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:u,headers:(c,l)=>i(bt(c),bt(l),!0)};return a.forEach(Object.keys(Object.assign({},t,e)),function(l){let f=p[l]||i,x=f(t[l],e[l],l);a.isUndefined(x)&&f!==u||(r[l]=x)}),r}var pe="1.4.0";var Ue={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Ue[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var wt={};Ue.transitional=function(e,r,n){function i(s,o){return"[Axios v"+pe+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,u)=>{if(e===!1)throw new h(i(o," has been removed"+(r?" in "+r:"")),h.ERR_DEPRECATED);return r&&!wt[o]&&(wt[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,u):!0}};function Cr(t,e,r){if(typeof t!="object")throw new h("options must be an object",h.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let u=t[s],p=u===void 0||o(u,s,t);if(p!==!0)throw new h("option "+s+" must be "+p,h.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new h("Unknown option "+s,h.ERR_BAD_OPTION)}}var de={assertOptions:Cr,validators:Ue};var U=de.validators,j=class{constructor(e){this.defaults=e,this.interceptors={request:new _e,response:new _e}}request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=N(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&de.assertOptions(n,{silentJSONParsing:U.transitional(U.boolean),forcedJSONParsing:U.transitional(U.boolean),clarifyTimeoutError:U.transitional(U.boolean)},!1),i!=null&&(a.isFunction(i)?r.paramsSerializer={serialize:i}:de.assertOptions(i,{encode:U.function,serialize:U.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o;o=s&&a.merge(s.common,s[r.method]),o&&a.forEach(["delete","get","head","post","put","patch","common"],d=>{delete s[d]}),r.headers=S.concat(o,s);let u=[],p=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(r)===!1||(p=p&&g.synchronous,u.unshift(g.fulfilled,g.rejected))});let c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let l,f=0,x;if(!p){let d=[le.bind(this),void 0];for(d.unshift.apply(d,u),d.push.apply(d,c),x=d.length,l=Promise.resolve(r);f<x;)l=l.then(d[f++],d[f++]);return l}x=u.length;let y=r;for(f=0;f<x;){let d=u[f++],g=u[f++];try{y=d(y)}catch(C){g.call(this,C);break}}try{l=le.call(this,y)}catch(d){return Promise.reject(d)}for(f=0,x=c.length;f<x;)l=l.then(c[f++],c[f++]);return l}getUri(e){e=N(this.defaults,e);let r=G(e.baseURL,e.url);return V(r,e.params,e.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(e){j.prototype[e]=function(r,n){return this.request(N(n||{},{method:e,url:r,data:(n||{}).data}))}});a.forEach(["post","put","patch"],function(e){function r(n){return function(s,o,u){return this.request(N(u||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}j.prototype[e]=r(),j.prototype[e+"Form"]=r(!0)});var X=j;var Le=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});let n=this;this.promise.then(i=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(u=>{n.subscribe(u),s=u}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,u){n.reason||(n.reason=new P(s,o,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},Et=Le;function ke(t){return function(r){return t.apply(null,r)}}function Ie(t){return a.isObject(t)&&t.isAxiosError===!0}var Fe={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Fe).forEach(([t,e])=>{Fe[e]=t});var St=Fe;function _t(t){let e=new X(t),r=M(X.prototype.request,e);return a.extend(r,X.prototype,e,{allOwnKeys:!0}),a.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return _t(N(t,i))},r}var b=_t(F);b.Axios=X;b.CanceledError=P;b.CancelToken=Et;b.isCancel=W;b.VERSION=pe;b.toFormData=T;b.AxiosError=h;b.Cancel=b.CanceledError;b.all=function(e){return Promise.all(e)};b.spread=ke;b.isAxiosError=Ie;b.mergeConfig=N;b.AxiosHeaders=S;b.formToJSON=t=>oe(a.isHTMLForm(t)?new FormData(t):t);b.HttpStatusCode=St;b.default=b;var v=b;var{Axios:ws,AxiosError:Es,CanceledError:Ss,isCancel:_s,CancelToken:Rs,VERSION:As,all:Os,Cancel:Cs,isAxiosError:Ns,spread:Ts,toFormData:Ps,AxiosHeaders:Us,HttpStatusCode:Ls,formToJSON:ks,mergeConfig:Is}=v;var fe,Nr=new Uint8Array(16);function De(){if(!fe&&(fe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!fe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return fe(Nr)}var w=[];for(let t=0;t<256;++t)w.push((t+256).toString(16).slice(1));function Rt(t,e=0){return(w[t[e+0]]+w[t[e+1]]+w[t[e+2]]+w[t[e+3]]+"-"+w[t[e+4]]+w[t[e+5]]+"-"+w[t[e+6]]+w[t[e+7]]+"-"+w[t[e+8]]+w[t[e+9]]+"-"+w[t[e+10]]+w[t[e+11]]+w[t[e+12]]+w[t[e+13]]+w[t[e+14]]+w[t[e+15]]).toLowerCase()}var Tr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),je={randomUUID:Tr};function Pr(t,e,r){if(je.randomUUID&&!e&&!t)return je.randomUUID();t=t||{};let n=t.random||(t.rng||De)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let i=0;i<16;++i)e[r+i]=n[i];return e}return Rt(n)}var B=Pr;var ve=class{constructor(){}enterWith(e){}run(e,r){return r()}getStore(){}},Ur={makeAxios:t=>v.create({...t}),getRepoStatus:async()=>{},getPastNAncestors:async()=>[],getEnv:t=>{},getCallerLocation:()=>{},newAsyncLocalStorage:()=>new ve},R=Ur;function z(t,e){let r=!0;try{let n=t();return n instanceof Promise?(r=!1,n.finally(e)):n}finally{r&&e()}}var Be=class{constructor(){this.kind="span";this.id="",this.span_id="",this.root_span_id=""}log(e){}startSpan(e,r){return this}traced(e,r,n){return r(this)}end(e){return e?.endTime??ge()}close(e){return this.end(e)}},At=new Be,me=class{constructor(){this.id=B(),this.currentExperiment=R.newAsyncLocalStorage(),this.currentSpan=R.newAsyncLocalStorage(),this.apiUrl=null,this.loginToken=null,this.orgId=null,this.orgName=null,this.logUrl=null,this.loggedIn=!1,this._apiConn=null,this._logConn=null,this._userInfo=null,globalThis.__inherited_braintrust_state=this}apiConn(){if(!this._apiConn){if(!this.apiUrl)throw new Error("Must initialize apiUrl before requesting apiConn");this._apiConn=new Q(this.apiUrl)}return this._apiConn}logConn(){if(!this._logConn){if(!this.logUrl)throw new Error("Must initialize logUrl before requesting logConn");this._logConn=new Q(this.logUrl)}return this._logConn}async userInfo(){return this._userInfo||(this._userInfo=await this.logConn().get_json("ping")),this._userInfo}setUserInfoIfNull(e){this._userInfo||(this._userInfo=e)}},m=globalThis.__inherited_braintrust_state||new me,no=()=>m,ze=class{constructor(){this.unterminatedObjects=new Map,process.on("exit",()=>{this.warnUnterminated()})}addUnterminated(e,r){this.unterminatedObjects.set(e,r)}removeUnterminated(e){this.unterminatedObjects.delete(e)}warnUnterminated(){if(this.unterminatedObjects.size===0)return;let e="WARNING: Did not close the following braintrust objects. We recommend running `.close` on the listed objects, or by running them inside a callback so they are closed automatically:";this.unterminatedObjects.forEach((r,n)=>{let i=`
|
|
4
|
+
Object of type ${n?.constructor?.name}`;r&&(i+=` created at ${JSON.stringify(r)}`),e+=i}),console.warn(e)}},H=new ze,Lr="_xact_id",Q=class t{constructor(e){this.base_url=e,this.token=null,this.session=null,this._reset()}async ping(){try{let e=await this.get("ping");return m.setUserInfoIfNull(e.data),e.status===200}catch{return!1}}make_long_lived(){this._reset()}static sanitize_token(e){return e.trim()}set_token(e){e=t.sanitize_token(e),this.token=e,this._reset()}_reset(){let e={};this.token&&(e.Authorization=`Bearer ${this.token}`),this.session=R.makeAxios({headers:e})}async get(e,r=void 0){return await this.session.get(He(this.base_url,e),{params:r})}async post(e,r=void 0,n=void 0){return await this.session.post(He(this.base_url,e),r,n)}async get_json(e,r=void 0,n=0){let i=n+1;for(let s=0;s<i;s++)try{return(await this.get(`${e}`,r)).data}catch(o){if(s<i-1){console.log(`Retrying API request ${e} ${r} ${o.status} ${o.text}`);continue}throw o}}async post_json(e,r=void 0){return(await this.post(`${e}`,r,{headers:{"Content-Type":"application/json"}})).data}},Ot=class{constructor(e,r,n){this.name=e,this.id=r,this.org_id=n}},kr=10*1024*1024;function Ir(t){return`[${t.join(",")}]`}var he=class{constructor(){this.items=[];this.active_flush=Promise.resolve([]);this.active_flush_resolved=!0}log(e){this.items.push(...e),this.active_flush_resolved&&(this.active_flush_resolved=!1,this.active_flush=this.flush_once())}async flush_once(e=100){this.active_flush_resolved=!1;let r=(this.items||[]).reverse();this.items=[];let n=[];for(;;){let i=[],s=0;for(;i.length<e&&s<kr/2;){let o=null;if(r.length>0)o=r.pop();else break;let u=JSON.stringify(o);i.push(u),s+=u.length}if(i.length>0)n=(await m.logConn().post_json("logs",Ir(i))).data;else break}return this.items.length>0?this.active_flush=this.flush_once():this.active_flush_resolved=!0,n}async flush(){for(;await this.active_flush,!this.active_flush_resolved;);}};async function Fr(t,e={}){let{experiment:r,description:n,dataset:i,baseExperiment:s,isPublic:o,update:u,apiUrl:p,apiKey:c,orgName:l,disableCache:f}=e||{};return await Ct({orgName:l,disableCache:f,apiKey:c,apiUrl:p}),await qr(t,{experimentName:r,description:n,dataset:i,update:u,baseExperiment:s,isPublic:o})}async function io(t,e,r={}){let n=await Fr(t,r);return z(()=>r.setCurrent??!0?ye(n,()=>e(n)):e(n),()=>n.close())}async function Dr(t,e={}){let{dataset:r,description:n,version:i,apiUrl:s,apiKey:o,orgName:u,disableCache:p}=e||{};return await Ct({orgName:u,disableCache:p,apiKey:o,apiUrl:s}),await Jr(t,{name:r,description:n,version:i})}async function so(t,e,r={}){let n=await Dr(t,r);return z(()=>e(n),()=>n.close())}async function Ct(t={}){let{apiUrl:e=R.getEnv("BRAINTRUST_API_URL")||"https://www.braintrustdata.com",apiKey:r=R.getEnv("BRAINTRUST_API_KEY"),orgName:n=void 0,disableCache:i=!1}=t||{},{forceLogin:s=!1}=t||{};if((e!=m.apiUrl||r!==void 0&&Q.sanitize_token(r)!=m.loginToken||n!==void 0&&n!=m.orgName)&&(s=!0),m.loggedIn&&!s)return;m=new me,m.apiUrl=e;let o=null,u=!1,p=null;if(r!==void 0){let l=(await v.post(He(m.apiUrl,"/api/apikey/login"),{token:r})).data;zr(l.org_info,n),p=m.logConn(),p.set_token(r),u=await p.ping()}else throw new Error("Please specify an api key. Token based login is not yet implemented in the JS client.");if(!p)throw new Error("Conn should be set at this point (a bug)");u||await p.get("ping"),p.make_long_lived(),m.apiConn().set_token(r),m.loginToken=p.token,m.loggedIn=!0}function oo(t){let e=m.currentExperiment.getStore();if(!e)throw new Error("Not initialized. Please call init() first");return e.log(t)}async function ao(t={}){let e=m.currentExperiment.getStore();if(!e)throw new Error("Not initialized. Please call init() first");return await e.summarize(t)}function jr(){return m.currentExperiment.getStore()}function vr(){return m.currentSpan.getStore()}function Br(t){let{name:e,...r}=t??{},n=(e??R.getCallerLocation()?.caller_functionname)||"root",i=vr();if(!Object.is(i,At))return i.startSpan(n,r);let s=jr();return s?s.startSpan({name:n,...r}):At}function uo(t,e){let r=Br(e);return z(()=>e?.setCurrent??!0?ye(r,()=>t(r)):t(r),()=>r.end())}function ye(t,e){if(t.kind==="experiment")return m.currentExperiment.run(t,e);if(t.kind==="span")return m.currentSpan.run(t,e);throw new Error(`Invalid object of type ${t.constructor.name}`)}function zr(t,e){if(t.length===0)throw new Error("This user is not part of any organizations.");for(let r of t)if(e===void 0||r.name===e){m.orgId=r.id,m.orgName=r.name,m.logUrl=r.api_url;break}if(m.orgId===void 0)throw new Error(`Organization ${e} not found. Must be one of ${t.map(r=>r.name).join(", ")}`)}function He(...t){return t.map(e=>e.replace(/^\//,"")).join("/")}function ge(){return new Date().getTime()/1e3}function Hr(t){if(t.scores)for(let[e,r]of Object.entries(t.scores)){if(typeof e!="string")throw new Error("score names must be strings");if(typeof r=="boolean"&&(r=r?1:0,t.scores[e]=r),typeof r!="number")throw new Error("score values must be numbers");if(r<0||r>1)throw new Error("score values must be between 0 and 1")}if(t.metadata){for(let e of Object.keys(t.metadata))if(typeof e!="string")throw new Error("metadata keys must be strings")}if(t.metrics){for(let e of Object.keys(t.metrics))if(typeof e!="string")throw new Error("metric keys must be strings");for(let e of["start","end","caller_functionname","caller_filename","caller_lineno"])if(e in t.metrics)throw new Error(`Key ${e} may not be specified in metrics`)}if("input"in t&&t.input&&"inputs"in t&&t.inputs)throw new Error("Only one of input or inputs (deprecated) can be specified. Prefer input.");if("inputs"in t){let{inputs:e,...r}=t;return{input:e,...r}}else return{...t}}function Mr(t,e){if("input"in t&&t.input&&"inputs"in t&&t.inputs||!("input"in t)&&!("inputs"in t))throw new Error("Exactly one of input or inputs (deprecated) must be specified. Prefer input.");if(!t.scores)throw new Error("scores must be specified");if(e&&t.datasetRecordId===void 0)throw new Error("datasetRecordId must be specified when using a dataset");if(!e&&t.datasetRecordId!==void 0)throw new Error("datasetRecordId cannot be specified when not using a dataset");return t}async function qr(t,{experimentName:e,description:r,dataset:n,update:i,baseExperiment:s,isPublic:o}={experimentName:void 0,description:void 0,baseExperiment:void 0,isPublic:!1}){let u={project_name:t,org_id:m.orgId};e&&(u.experiment_name=e),r&&(u.description=r),i&&(u.update=i);let p=await R.getRepoStatus();p&&(u.repo_info=p),s?u.base_experiment=s:u.ancestor_commits=await R.getPastNAncestors(),n!==void 0&&(u.dataset_id=n.id,u.dataset_version=await n.version()),o!==void 0&&(u.public=o);let c=await m.apiConn().post_json("api/experiment/register",u),l=c.project,f=c.experiment,x=(await m.userInfo()).id;return new Me(l,f.id,f.name,x,n)}var Me=class{constructor(e,r,n,i,s){this.kind="experiment";this.finished=!1,this.project=e,this.id=r,this.name=n,this.user_id=i,this.dataset=s,this.logger=new he,this.lastStartTime=ge(),H.addUnterminated(this,R.getCallerLocation())}log(e){this.checkNotFinished(),e=Mr(e,!!this.dataset);let r=this.startSpan({startTime:this.lastStartTime,event:e});return this.lastStartTime=r.end(),r.id}startSpan(e){this.checkNotFinished();let{name:r,...n}=e??{};return new qe({experimentLogger:this.logger,name:r??"root",...n,rootExperiment:this})}traced(e,r){let{setCurrent:n,...i}=r??{},s=this.startSpan(i);return z(()=>n??!0?ye(s,()=>e(s)):e(s),()=>s.end())}async summarize(e={}){let{summarizeScores:r=!0,comparisonExperimentId:n=void 0}=e||{};await this.logger.flush();let i=`${m.apiUrl}/app/${encodeURIComponent(m.orgName)}/p/${encodeURIComponent(this.project.name)}`,s=`${i}/${encodeURIComponent(this.name)}`,o,u;if(r){if(n===void 0){let l=(await m.logConn().get("/crud/base_experiments",{id:this.id})).data;l.length>0&&(n=l[0].base_exp_id,u=l[0].base_exp_name)}n!==void 0&&(o=await m.logConn().get_json("/experiment-comparison",{experiment_id:this.id,base_experiment_id:n},3))}return{projectName:this.project.name,experimentName:this.name,projectUrl:i,experimentUrl:s,comparisonExperimentName:u,scores:o}}async close(){return this.checkNotFinished(),await this.logger.flush(),this.finished=!0,H.removeUnterminated(this),this.id}checkNotFinished(){if(this.finished)throw new Error("Cannot invoke method on finished experiment")}},qe=class t{constructor(e){this.kind="span";this.finished=!1,this.experimentLogger=e.experimentLogger;let r=R.getCallerLocation();if(this.internalData={metrics:{start:e.startTime??ge(),...r},span_attributes:{...e.spanAttributes,name:e.name}},this.id=e.event?.id??B(),this.span_id=B(),"rootExperiment"in e)this.root_span_id=this.span_id,this._project_id=e.rootExperiment.project.id,this._experiment_id=e.rootExperiment.id,this.internalData=Object.assign(this.internalData,{user_id:e.rootExperiment.user_id,created:new Date().toISOString()});else if("parentSpan"in e)this.root_span_id=e.parentSpan.root_span_id,this._project_id=e.parentSpan._project_id,this._experiment_id=e.parentSpan._experiment_id,this.internalData.span_parents=[e.parentSpan.span_id];else throw new Error("Must provide either 'rootExperiment' or 'parentSpan'");this.isMerge=!1;let{id:n,...i}=e.event??{};this.log(i),this.isMerge=!0,H.addUnterminated(this,r)}log(e){this.checkNotFinished();let n={...Hr(e),...this.internalData,id:this.id,span_id:this.span_id,root_span_id:this.root_span_id,project_id:this._project_id,experiment_id:this._experiment_id,_is_merge:this.isMerge};this.internalData={},this.experimentLogger.log([n])}startSpan(e,r){return this.checkNotFinished(),new t({experimentLogger:this.experimentLogger,name:e,...r,parentSpan:this})}traced(e,r,n){let{setCurrent:i,...s}=n??{},o=this.startSpan(e,s);return z(()=>i??!0?ye(o,()=>r(o)):r(o),()=>o.end())}end(e){this.checkNotFinished();let r=e?.endTime??ge();return this.internalData={metrics:{end:r}},this.log({}),this.finished=!0,H.removeUnterminated(this),r}close(e){return this.end(e)}checkNotFinished(){if(this.finished)throw new Error("Cannot invoke method on finished span")}};async function Jr(t,{name:e,description:r,version:n}={}){let i={org_id:m.orgId,project_name:t,dataset_name:e,description:r},s=await m.apiConn().post_json("api/dataset/register",i),o=s.project,u=s.dataset,p=(await m.userInfo()).id;return new Je(o,u.id,u.name,p,n)}var Je=class{constructor(e,r,n,i,s){this._fetchedData=void 0;this.finished=!1,this.project=e,this.id=r,this.name=n,this.user_id=i,this.pinnedVersion=s,this.logger=new he,H.addUnterminated(this,R.getCallerLocation())}insert({input:e,output:r,metadata:n,id:i}){if(this.checkNotFinished(),n!==void 0){for(let o of Object.keys(n))if(typeof o!="string")throw new Error("metadata keys must be strings")}let s={id:i||B(),inputs:e,output:r,project_id:this.project.id,dataset_id:this.id,user_id:this.user_id,created:new Date().toISOString(),metadata:n};return this.logger.log([s]),s.id}delete(e){this.checkNotFinished();let r=this.user_id,n={id:e,project_id:this.project.id,dataset_id:this.id,user_id:r,created:new Date().toISOString(),_object_delete:!0};return this.logger.log([n]),n.id}async summarize(e={}){this.checkNotFinished();let{summarizeData:r=!0}=e||{};await this.logger.flush();let n=`${m.apiUrl}/app/${encodeURIComponent(m.orgName)}/p/${encodeURIComponent(this.project.name)}`,i=`${n}/d/${encodeURIComponent(this.name)}`,s;return r&&(s=await m.logConn().get_json("dataset-summary",{dataset_id:this.id},3)),{projectName:this.project.name,datasetName:this.name,projectUrl:n,datasetUrl:i,dataSummary:s}}async*fetch(){this.checkNotFinished();let e=await this.fetchedData();for(let r of e)yield{id:r.id,input:r.input&&JSON.parse(r.input),output:r.input&&JSON.parse(r.output),metadata:r.metadata&&JSON.parse(r.metadata)};this.clearCache()}[Symbol.asyncIterator](){return this.checkNotFinished(),this.fetch()}async fetchedData(){if(this.checkNotFinished(),this._fetchedData===void 0){let r=await(await m.logConn().get("object/dataset",{id:this.id,fmt:"json",version:this.pinnedVersion})).data;this._fetchedData=r.split(`
|
|
5
|
+
`).filter(n=>n.trim()!=="").map(n=>JSON.parse(n))}return this._fetchedData||[]}clearCache(){this.checkNotFinished(),this._fetchedData=void 0}async version(){if(this.checkNotFinished(),this.pinnedVersion!==void 0)return this.pinnedVersion;{let e=await this.fetchedData(),r;for(let n of e){let i=n[Lr];(r===void 0||(i??i>r))&&(r=i)}return r}}async close(){return this.checkNotFinished(),await this.logger.flush(),this.finished=!0,H.removeUnterminated(this),this.id}checkNotFinished(){if(this.finished)throw new Error("Cannot invoke method on finished dataset")}};export{Je as Dataset,Me as Experiment,Be as NoopSpan,Ot as Project,qe as SpanImpl,no as _internalGetGlobalState,jr as currentExperiment,vr as currentSpan,Fr as init,Dr as initDataset,oo as log,Ct as login,At as noopSpan,Br as startSpan,ao as summarize,uo as traced,ye as withCurrent,so as withDataset,io as withExperiment};
|