braintrust 0.0.56 → 0.0.58

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 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(s){o=s.indexOf(":"),r=s.substring(0,o).trim().toLowerCase(),n=s.substring(o+1).trim(),!(!r||t[r]&&_r[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var lt=Symbol("internals");function V(e){return e&&String(e).trim().toLowerCase()}function ue(e){return e===!1||e==null?e:a.isArray(e)?e.map(ue):String(e)}function Sr(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}var Rr=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ne(e,t,r,n,o){if(a.isFunction(n))return n.call(this,t,r);if(o&&(t=r),!!a.isString(t)){if(a.isString(n))return t.indexOf(n)!==-1;if(a.isRegExp(n))return n.test(t)}}function Ar(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function Or(e,t){let r=a.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(o,i,s){return this[n].call(this,t,o,i,s)},configurable:!0})})}var L=class{constructor(t){t&&this.set(t)}set(t,r,n){let o=this;function i(u,d,c){let l=V(d);if(!l)throw new Error("header name must be a non-empty string");let f=a.findKey(o,l);(!f||o[f]===void 0||c===!0||c===void 0&&o[f]!==!1)&&(o[f||d]=ue(u))}let s=(u,d)=>a.forEach(u,(c,l)=>i(c,l,d));return a.isPlainObject(t)||t instanceof this.constructor?s(t,r):a.isString(t)&&(t=t.trim())&&!Rr(t)?s(ct(t),r):t!=null&&i(r,t,n),this}get(t,r){if(t=V(t),t){let n=a.findKey(this,t);if(n){let o=this[n];if(!r)return o;if(r===!0)return Sr(o);if(a.isFunction(r))return r.call(this,o,n);if(a.isRegExp(r))return r.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=V(t),t){let n=a.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||Ne(this,this[n],n,r)))}return!1}delete(t,r){let n=this,o=!1;function i(s){if(s=V(s),s){let u=a.findKey(n,s);u&&(!r||Ne(n,n[u],u,r))&&(delete n[u],o=!0)}}return a.isArray(t)?t.forEach(i):i(t),o}clear(t){let r=Object.keys(this),n=r.length,o=!1;for(;n--;){let i=r[n];(!t||Ne(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){let r=this,n={};return a.forEach(this,(o,i)=>{let s=a.findKey(n,i);if(s){r[s]=ue(o),delete r[i];return}let u=t?Ar(i):String(i).trim();u!==i&&delete r[i],r[u]=ue(o),n[u]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return a.forEach(this,(n,o)=>{n!=null&&n!==!1&&(r[o]=t&&a.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
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 q(t,e){return function(){return t.apply(e,arguments)}}var{toString:kt}=Object.prototype,{getPrototypeOf:Ee}=Object,te=(t=>e=>{let r=kt.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),O=t=>(t=t.toLowerCase(),e=>te(e)===t),re=t=>e=>typeof e===t,{isArray:L}=Array,$=re("undefined");function Ft(t){return t!==null&&!$(t)&&t.constructor!==null&&!$(t.constructor)&&_(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var Xe=O("ArrayBuffer");function jt(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Xe(t.buffer),e}var vt=re("string"),_=re("function"),Qe=re("number"),ne=t=>t!==null&&typeof t=="object",Bt=t=>t===!0||t===!1,ee=t=>{if(te(t)!=="object")return!1;let e=Ee(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},zt=O("Date"),Mt=O("File"),Ht=O("Blob"),qt=O("FileList"),$t=t=>ne(t)&&_(t.pipe),Jt=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||_(t.append)&&((e=te(t))==="formdata"||e==="object"&&_(t.toString)&&t.toString()==="[object FormData]"))},Vt=O("URLSearchParams"),Kt=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]),L(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,c;for(n=0;n<o;n++)c=s[n],e.call(null,t[c],c,t)}}function Ye(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 Ze=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),et=t=>!$(t)&&t!==Ze;function we(){let{caseless:t}=et(this)&&this||{},e={},r=(n,i)=>{let s=t&&Ye(e,i)||i;ee(e[s])&&ee(n)?e[s]=we(e[s],n):ee(n)?e[s]=we({},n):L(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 Wt=(t,e,r,{allOwnKeys:n}={})=>(J(e,(i,s)=>{r&&_(i)?t[s]=q(i,r):t[s]=i},{allOwnKeys:n}),t),Gt=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Xt=(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)},Qt=(t,e,r,n)=>{let i,s,o,c={};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))&&!c[o]&&(e[o]=t[o],c[o]=!0);t=r!==!1&&Ee(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},Yt=(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},Zt=t=>{if(!t)return null;if(L(t))return t;let e=t.length;if(!Qe(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},er=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Ee(Uint8Array)),tr=(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])}},rr=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},nr=O("HTMLFormElement"),ir=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),We=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),sr=O("RegExp"),tt=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};J(r,(i,s)=>{e(i,s,t)!==!1&&(n[s]=i)}),Object.defineProperties(t,n)},or=t=>{tt(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+"'")})}})},ar=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return L(t)?n(t):n(String(t).split(e)),r},cr=()=>{},ur=(t,e)=>(t=+t,Number.isFinite(t)?t:e),be="abcdefghijklmnopqrstuvwxyz",Ge="0123456789",rt={DIGIT:Ge,ALPHA:be,ALPHA_DIGIT:be+be.toUpperCase()+Ge},lr=(t=16,e=rt.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function dr(t){return!!(t&&_(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var pr=t=>{let e=new Array(10),r=(n,i)=>{if(ne(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=L(n)?[]:{};return J(n,(o,c)=>{let d=r(o,i+1);!$(d)&&(s[c]=d)}),e[i]=void 0,s}}return n};return r(t,0)},fr=O("AsyncFunction"),mr=t=>t&&(ne(t)||_(t))&&_(t.then)&&_(t.catch),a={isArray:L,isArrayBuffer:Xe,isBuffer:Ft,isFormData:Jt,isArrayBufferView:jt,isString:vt,isNumber:Qe,isBoolean:Bt,isObject:ne,isPlainObject:ee,isUndefined:$,isDate:zt,isFile:Mt,isBlob:Ht,isRegExp:sr,isFunction:_,isStream:$t,isURLSearchParams:Vt,isTypedArray:er,isFileList:qt,forEach:J,merge:we,extend:Wt,trim:Kt,stripBOM:Gt,inherits:Xt,toFlatObject:Qt,kindOf:te,kindOfTest:O,endsWith:Yt,toArray:Zt,forEachEntry:tr,matchAll:rr,isHTMLForm:nr,hasOwnProperty:We,hasOwnProp:We,reduceDescriptors:tt,freezeMethods:or,toObjectSet:ar,toCamelCase:ir,noop:cr,toFiniteNumber:ur,findKey:Ye,global:Ze,isContextDefined:et,ALPHABET:rt,generateString:lr,isSpecCompliantForm:dr,toJSONObject:pr,isAsyncFn:fr,isThenable:mr};function D(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(D,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 nt=D.prototype,it={};["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=>{it[t]={value:t}});Object.defineProperties(D,it);Object.defineProperty(nt,"isAxiosError",{value:!0});D.from=(t,e,r,n,i,s)=>{let o=Object.create(nt);return a.toFlatObject(t,o,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),D.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var h=D;var ie=null;function Se(t){return a.isPlainObject(t)||a.isArray(t)}function ot(t){return a.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,r){return t?t.concat(e).map(function(i,s){return i=ot(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function hr(t){return a.isArray(t)&&!t.some(Se)}var gr=a.toFlatObject(a,{},null,function(e){return/^is[A-Z]/.test(e)});function yr(t,e,r){if(!a.isObject(t))throw new TypeError("target must be an object");e=e||new(ie||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,d=(r.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(e);if(!a.isFunction(i))throw new TypeError("visitor must be a function");function u(p){if(p===null)return"";if(a.isDate(p))return p.toISOString();if(!d&&a.isBlob(p))throw new h("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,g,C){let A=p;if(p&&!C&&typeof p=="object"){if(a.endsWith(g,"{}"))g=n?g:g.slice(0,-2),p=JSON.stringify(p);else if(a.isArray(p)&&hr(p)||(a.isFileList(p)||a.endsWith(g,"[]"))&&(A=a.toArray(p)))return g=ot(g),A.forEach(function(Z,Dt){!(a.isUndefined(Z)||Z===null)&&e.append(o===!0?st([g],Dt,s):o===null?g:g+"[]",u(Z))}),!1}return Se(p)?!0:(e.append(st(C,g,s),u(p)),!1)}let f=[],x=Object.assign(gr,{defaultVisitor:l,convertValue:u,isVisitable:Se});function y(p,g){if(!a.isUndefined(p)){if(f.indexOf(p)!==-1)throw Error("Circular reference detected in "+g.join("."));f.push(p),a.forEach(p,function(A,U){(!(a.isUndefined(A)||A===null)&&i.call(e,A,a.isString(U)?U.trim():U,g,x))===!0&&y(A,g?g.concat(U):[U])}),f.pop()}}if(!a.isObject(t))throw new TypeError("data must be an object");return y(t),e}var T=yr;function at(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function ct(t,e){this._pairs=[],t&&T(t,this,e)}var ut=ct.prototype;ut.append=function(e,r){this._pairs.push([e,r])};ut.toString=function(e){let r=e?function(n){return e.call(this,n,at)}:at;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var se=ct;function xr(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||xr,i=r&&r.serialize,s;if(i?s=i(e,r):s=a.isURLSearchParams(e)?e.toString():new se(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var _e=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)})}},Re=_e;var oe={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var lt=typeof URLSearchParams<"u"?URLSearchParams:se;var dt=typeof FormData<"u"?FormData:null;var pt=typeof Blob<"u"?Blob:null;var br=(()=>{let t;return typeof navigator<"u"&&((t=navigator.product)==="ReactNative"||t==="NativeScript"||t==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),wr=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),E={isBrowser:!0,classes:{URLSearchParams:lt,FormData:dt,Blob:pt},isStandardBrowserEnv:br,isStandardBrowserWebWorkerEnv:wr,protocols:["http","https","file","blob","url","data"]};function Ae(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 Er(t){return a.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Sr(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 _r(t){function e(r,n,i,s){let o=r[s++],c=Number.isFinite(+o),d=s>=r.length;return o=!o&&a.isArray(i)?i.length:o,d?(a.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!a.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&a.isArray(i[o])&&(i[o]=Sr(i[o])),!c)}if(a.isFormData(t)&&a.isFunction(t.entries)){let r={};return a.forEachEntry(t,(n,i)=>{e(Er(n),i,r,0)}),r}return null}var ae=_r;var Rr={"Content-Type":void 0};function Ar(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 ce={transitional:oe,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(ae(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 c;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Ae(e,this.formSerializer).toString();if((c=a.isFileList(e))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return T(c?{"files[]":e}:e,d&&new d,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Ar(e)):e}],transformResponse:[function(e){let r=this.transitional||ce.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(c){if(o)throw c.name==="SyntaxError"?h.from(c,h.ERR_BAD_RESPONSE,this,null,this.response):c}}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){ce.headers[e]={}});a.forEach(["post","put","patch"],function(e){ce.headers[e]=a.merge(Rr)});var k=ce;var Or=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"]),ft=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]&&Or[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e};var mt=Symbol("internals");function K(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 Cr(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 Nr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Oe(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 Tr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function Pr(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 F=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(c,d,u){let l=K(d);if(!l)throw new Error("header name must be a non-empty string");let f=a.findKey(i,l);(!f||i[f]===void 0||u===!0||u===void 0&&i[f]!==!1)&&(i[f||d]=ue(c))}let o=(c,d)=>a.forEach(c,(u,l)=>s(u,l,d));return a.isPlainObject(e)||e instanceof this.constructor?o(e,r):a.isString(e)&&(e=e.trim())&&!Nr(e)?o(ft(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=K(e),e){let n=a.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Cr(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=K(e),e){let n=a.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||Oe(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=K(o),o){let c=a.findKey(n,o);c&&(!r||Oe(n,n[c],c,r))&&(delete n[c],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||Oe(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 c=e?Tr(s):String(s).trim();c!==s&&delete r[s],r[c]=ue(i),n[c]=!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[mt]=this[mt]={accessors:{}}).accessors,i=this.prototype;function s(o){let c=K(o);n[c]||(Pr(i,o),n[c]=!0)}return a.isArray(e)?e.forEach(s):s(e),this}};F.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.freezeMethods(F.prototype);a.freezeMethods(F);var S=F;function W(t,e){let r=this||k,n=e||r,i=S.from(n.headers),s=n.data;return a.forEach(t,function(c){s=c.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function G(t){return!!(t&&t.__CANCEL__)}function ht(t,e,r){h.call(this,t??"canceled",h.ERR_CANCELED,e,r),this.name="CanceledError"}a.inherits(ht,h,{__CANCEL__:!0});var P=ht;function Ce(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 gt=E.isStandardBrowserEnv?function(){return{write:function(r,n,i,s,o,c){let d=[];d.push(r+"="+encodeURIComponent(n)),a.isNumber(i)&&d.push("expires="+new Date(i).toGMTString()),a.isString(s)&&d.push("path="+s),a.isString(o)&&d.push("domain="+o),c===!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 Ne(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Te(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}function X(t,e){return t&&!Ne(e)?Te(t,e):e}var yt=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 c=a.isString(o)?i(o):o;return c.protocol===n.protocol&&c.host===n.host}}():function(){return function(){return!0}}();function Pe(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Ir(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(d){let u=Date.now(),l=n[s];o||(o=u),r[i]=d,n[i]=u;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),u-o<e)return;let y=l&&u-l;return y?Math.round(x*1e3/y):void 0}}var xt=Ir;function bt(t,e){let r=0,n=xt(50,250);return i=>{let s=i.loaded,o=i.lengthComputable?i.total:void 0,c=s-r,d=n(c),u=s<=o;r=s;let l={loaded:s,total:o,progress:o?s/o:void 0,bytes:c,rate:d||void 0,estimated:d&&o&&u?(o-s)/d:void 0,event:i};l[e?"download":"upload"]=!0,t(l)}}var Ur=typeof XMLHttpRequest<"u",wt=Ur&&function(t){return new Promise(function(r,n){let i=t.data,s=S.from(t.headers).normalize(),o=t.responseType,c;function d(){t.cancelToken&&t.cancelToken.unsubscribe(c),t.signal&&t.signal.removeEventListener("abort",c)}a.isFormData(i)&&(E.isStandardBrowserEnv||E.isStandardBrowserWebWorkerEnv?s.setContentType(!1):s.setContentType("multipart/form-data;",!1));let u=new XMLHttpRequest;if(t.auth){let y=t.auth.username||"",p=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(y+":"+p))}let l=X(t.baseURL,t.url);u.open(t.method.toUpperCase(),V(l,t.params,t.paramsSerializer),!0),u.timeout=t.timeout;function f(){if(!u)return;let y=S.from("getAllResponseHeaders"in u&&u.getAllResponseHeaders()),g={data:!o||o==="text"||o==="json"?u.responseText:u.response,status:u.status,statusText:u.statusText,headers:y,config:t,request:u};Ce(function(A){r(A),d()},function(A){n(A),d()},g),u=null}if("onloadend"in u?u.onloadend=f:u.onreadystatechange=function(){!u||u.readyState!==4||u.status===0&&!(u.responseURL&&u.responseURL.indexOf("file:")===0)||setTimeout(f)},u.onabort=function(){u&&(n(new h("Request aborted",h.ECONNABORTED,t,u)),u=null)},u.onerror=function(){n(new h("Network Error",h.ERR_NETWORK,t,u)),u=null},u.ontimeout=function(){let p=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",g=t.transitional||oe;t.timeoutErrorMessage&&(p=t.timeoutErrorMessage),n(new h(p,g.clarifyTimeoutError?h.ETIMEDOUT:h.ECONNABORTED,t,u)),u=null},E.isStandardBrowserEnv){let y=(t.withCredentials||yt(l))&&t.xsrfCookieName&&gt.read(t.xsrfCookieName);y&&s.set(t.xsrfHeaderName,y)}i===void 0&&s.setContentType(null),"setRequestHeader"in u&&a.forEach(s.toJSON(),function(p,g){u.setRequestHeader(g,p)}),a.isUndefined(t.withCredentials)||(u.withCredentials=!!t.withCredentials),o&&o!=="json"&&(u.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&u.addEventListener("progress",bt(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&u.upload&&u.upload.addEventListener("progress",bt(t.onUploadProgress)),(t.cancelToken||t.signal)&&(c=y=>{u&&(n(!y||y.type?new P(null,t,u):y),u.abort(),u=null)},t.cancelToken&&t.cancelToken.subscribe(c),t.signal&&(t.signal.aborted?c():t.signal.addEventListener("abort",c)));let x=Pe(l);if(x&&E.protocols.indexOf(x)===-1){n(new h("Unsupported protocol "+x+":",h.ERR_BAD_REQUEST,t));return}u.send(i||null)})};var le={http:ie,xhr:wt};a.forEach(le,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var Et={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)?le[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(le,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:le};function Ie(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new P(null,t)}function de(t){return Ie(t),t.headers=S.from(t.headers),t.data=W.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Et.getAdapter(t.adapter||k.adapter)(t).then(function(n){return Ie(t),n.data=W.call(t,t.transformResponse,n),n.headers=S.from(n.headers),n},function(n){return G(n)||(Ie(t),n&&n.response&&(n.response.data=W.call(t,t.transformResponse,n.response),n.response.headers=S.from(n.response.headers))),Promise.reject(n)})}var St=t=>t instanceof S?t.toJSON():t;function N(t,e){e=e||{};let r={};function n(u,l,f){return a.isPlainObject(u)&&a.isPlainObject(l)?a.merge.call({caseless:f},u,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function i(u,l,f){if(a.isUndefined(l)){if(!a.isUndefined(u))return n(void 0,u,f)}else return n(u,l,f)}function s(u,l){if(!a.isUndefined(l))return n(void 0,l)}function o(u,l){if(a.isUndefined(l)){if(!a.isUndefined(u))return n(void 0,u)}else return n(void 0,l)}function c(u,l,f){if(f in e)return n(u,l);if(f in t)return n(void 0,u)}let d={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:c,headers:(u,l)=>i(St(u),St(l),!0)};return a.forEach(Object.keys(Object.assign({},t,e)),function(l){let f=d[l]||i,x=f(t[l],e[l],l);a.isUndefined(x)&&f!==c||(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 _t={};Ue.transitional=function(e,r,n){function i(s,o){return"[Axios v"+pe+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,c)=>{if(e===!1)throw new h(i(o," has been removed"+(r?" in "+r:"")),h.ERR_DEPRECATED);return r&&!_t[o]&&(_t[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,c):!0}};function Lr(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 c=t[s],d=c===void 0||o(c,s,t);if(d!==!0)throw new h("option "+s+" must be "+d,h.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new h("Unknown option "+s,h.ERR_BAD_OPTION)}}var fe={assertOptions:Lr,validators:Ue};var I=fe.validators,j=class{constructor(e){this.defaults=e,this.interceptors={request:new Re,response:new Re}}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&&fe.assertOptions(n,{silentJSONParsing:I.transitional(I.boolean),forcedJSONParsing:I.transitional(I.boolean),clarifyTimeoutError:I.transitional(I.boolean)},!1),i!=null&&(a.isFunction(i)?r.paramsSerializer={serialize:i}:fe.assertOptions(i,{encode:I.function,serialize:I.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"],p=>{delete s[p]}),r.headers=S.concat(o,s);let c=[],d=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(r)===!1||(d=d&&g.synchronous,c.unshift(g.fulfilled,g.rejected))});let u=[];this.interceptors.response.forEach(function(g){u.push(g.fulfilled,g.rejected)});let l,f=0,x;if(!d){let p=[de.bind(this),void 0];for(p.unshift.apply(p,c),p.push.apply(p,u),x=p.length,l=Promise.resolve(r);f<x;)l=l.then(p[f++],p[f++]);return l}x=c.length;let y=r;for(f=0;f<x;){let p=c[f++],g=c[f++];try{y=p(y)}catch(C){g.call(this,C);break}}try{l=de.call(this,y)}catch(p){return Promise.reject(p)}for(f=0,x=u.length;f<x;)l=l.then(u[f++],u[f++]);return l}getUri(e){e=N(this.defaults,e);let r=X(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,c){return this.request(N(c||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}j.prototype[e]=r(),j.prototype[e+"Form"]=r(!0)});var Q=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(c=>{n.subscribe(c),s=c}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,c){n.reason||(n.reason=new P(s,o,c),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}}},Rt=Le;function De(t){return function(r){return t.apply(null,r)}}function ke(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 At=Fe;function Ot(t){let e=new Q(t),r=q(Q.prototype.request,e);return a.extend(r,Q.prototype,e,{allOwnKeys:!0}),a.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return Ot(N(t,i))},r}var b=Ot(k);b.Axios=Q;b.CanceledError=P;b.CancelToken=Rt;b.isCancel=G;b.VERSION=pe;b.toFormData=T;b.AxiosError=h;b.Cancel=b.CanceledError;b.all=function(e){return Promise.all(e)};b.spread=De;b.isAxiosError=ke;b.mergeConfig=N;b.AxiosHeaders=S;b.formToJSON=t=>ae(a.isHTMLForm(t)?new FormData(t):t);b.HttpStatusCode=At;b.default=b;var v=b;var{Axios:Cs,AxiosError:Ct,CanceledError:Ns,isCancel:Ts,CancelToken:Ps,VERSION:Is,all:Us,Cancel:Ls,isAxiosError:Ds,spread:ks,toFormData:Fs,AxiosHeaders:js,HttpStatusCode:vs,formToJSON:Bs,mergeConfig:zs}=v;var me,Dr=new Uint8Array(16);function je(){if(!me&&(me=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!me))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return me(Dr)}var w=[];for(let t=0;t<256;++t)w.push((t+256).toString(16).slice(1));function Nt(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 kr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ve={randomUUID:kr};function Fr(t,e,r){if(ve.randomUUID&&!e&&!t)return ve.randomUUID();t=t||{};let n=t.random||(t.rng||je)();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 Nt(n)}var B=Fr;var Be=class{constructor(){}enterWith(e){}run(e,r){return r()}getStore(){}},jr={makeAxios:t=>v.create({...t}),getRepoStatus:async()=>{},getPastNAncestors:async()=>[],getEnv:t=>{},getCallerLocation:()=>{},newAsyncLocalStorage:()=>new Be},R=jr;var Tt="_xact_id",z="_is_merge";function M(t,e){let r=!0;try{let n=t();return n instanceof Promise?(r=!1,n.finally(e)):n}finally{r&&e()}}function ze(t,e){for(let[r,n]of Object.entries(e)){let i=t[r];i instanceof Object&&!Array.isArray(i)&&e instanceof Object&&!Array.isArray(n)?ze(i,n):t[r]=n}}function vr(t){let e=r=>t[r]??"";return e("experiment_id")+":"+e("dataset_id")+":"+e("prompt_session_id")+":"+e("id")}function Pt(t){let e=[],r=[];for(let i of t)i.id===void 0?e.push(i):r.push(i);let n={};for(let i of r){let s=vr(i),o=n[s];if(o!==void 0&&i[z]){let c=!o[z];ze(o,i),c&&delete o[z]}else n[s]=i}return e.push(...Object.values(n)),e}var He=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??ye()}close(e){return this.end(e)}},It=new He,he=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 Y(this.apiUrl)}return this._apiConn}logConn(){if(!this._logConn){if(!this.logUrl)throw new Error("Must initialize logUrl before requesting logConn");this._logConn=new Y(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 he,fo=()=>m,qe=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 qe,Y=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($e(this.base_url,e),{params:r})}async post(e,r=void 0,n=void 0){return await this.session.post($e(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}},Ut=class{constructor(e,r,n){this.name=e,this.id=r,this.org_id=n}},Br=10*1024*1024;function zr(t){return`[${t.join(",")}]`}var Mr=100,Me=3,ge=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=Mr){this.active_flush_resolved=!1;let r=Pt(this.items||[]).reverse();this.items=[];let n=[];for(;;){let s=[],o=0;for(;s.length<e&&o<Br/2;){let c=null;if(r.length>0)c=r.pop();else break;let d=JSON.stringify(c);s.push(d),o+=d.length}if(s.length===0)break;n.push((async()=>{let c=zr(s);for(let d=0;d<Me;d++){let u=performance.now();try{return(await m.logConn().post_json("logs",c)).map(l=>l.id)}catch(l){let f=d+1===Me?"":" Retrying",x=(()=>l instanceof Ct&&l.response?`${l.response.status}: ${JSON.stringify(l.response.data)}`:`${l}`)();console.warn(`log request failed. Elapsed time: ${(performance.now()-u)/1e3} seconds. Payload size: ${c.length}. Error: ${x}.${f}`)}}return console.warn(`log request failed after ${Me} retries. Dropping batch`),[]})())}let i=await Promise.all(n);return this.items.length>0?this.active_flush=this.flush_once():this.active_flush_resolved=!0,i}async flush(){for(;await this.active_flush,!this.active_flush_resolved;);}};async function Hr(t,e={}){let{experiment:r,description:n,dataset:i,baseExperiment:s,isPublic:o,update:c,apiUrl:d,apiKey:u,orgName:l,disableCache:f}=e||{};return await Lt({orgName:l,disableCache:f,apiKey:u,apiUrl:d}),await Xr(t,{experimentName:r,description:n,dataset:i,update:c,baseExperiment:s,isPublic:o})}async function mo(t,e,r={}){let n=await Hr(t,r);return M(()=>r.setCurrent??!0?xe(n,()=>e(n)):e(n),()=>n.close())}async function qr(t,e={}){let{dataset:r,description:n,version:i,apiUrl:s,apiKey:o,orgName:c,disableCache:d}=e||{};return await Lt({orgName:c,disableCache:d,apiKey:o,apiUrl:s}),await Qr(t,{name:r,description:n,version:i})}async function ho(t,e,r={}){let n=await qr(t,r);return M(()=>e(n),()=>n.close())}async function Lt(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&&Y.sanitize_token(r)!=m.loginToken||n!==void 0&&n!=m.orgName)&&(s=!0),m.loggedIn&&!s)return;m=new he,m.apiUrl=e;let o=null,c=!1,d=null;if(r!==void 0){let l=(await v.post($e(m.apiUrl,"/api/apikey/login"),{token:r})).data;Kr(l.org_info,n),d=m.logConn(),d.set_token(r),c=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)");c||await d.get("ping"),d.make_long_lived(),m.apiConn().set_token(r),m.loginToken=d.token,m.loggedIn=!0}function go(t){let e=m.currentExperiment.getStore();if(!e)throw new Error("Not initialized. Please call init() first");return e.log(t)}async function yo(t={}){let e=m.currentExperiment.getStore();if(!e)throw new Error("Not initialized. Please call init() first");return await e.summarize(t)}function $r(){return m.currentExperiment.getStore()}function Jr(){return m.currentSpan.getStore()}function Vr(t){let{name:e,...r}=t??{},n=(e??R.getCallerLocation()?.caller_functionname)||"root",i=Jr();if(!Object.is(i,It))return i.startSpan(n,r);let s=$r();return s?s.startSpan({name:n,...r}):It}function xo(t,e){let r=Vr(e);return M(()=>e?.setCurrent??!0?xe(r,()=>t(r)):t(r),()=>r.end())}function xe(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 Kr(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 $e(...t){return t.map(e=>e.replace(/^\//,"")).join("/")}function ye(){return new Date().getTime()/1e3}function Wr(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 Gr(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 Xr(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 c={project_name:t,org_id:m.orgId};e&&(c.experiment_name=e),r&&(c.description=r),i&&(c.update=i);let d=await R.getRepoStatus();d&&(c.repo_info=d),s?c.base_experiment=s:c.ancestor_commits=await R.getPastNAncestors(),n!==void 0&&(c.dataset_id=n.id,c.dataset_version=await n.version()),o!==void 0&&(c.public=o);let u=await m.apiConn().post_json("api/experiment/register",c),l=u.project,f=u.experiment,x=(await m.userInfo()).id;return new Je(l,f.id,f.name,x,n)}var Je=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 ge,this.lastStartTime=ye(),H.addUnterminated(this,R.getCallerLocation())}log(e){this.checkNotFinished(),e=Gr(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 Ve({experimentLogger:this.logger,name:r??"root",...n,rootExperiment:this})}traced(e,r){let{setCurrent:n,...i}=r??{},s=this.startSpan(i);return M(()=>n??!0?xe(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,c;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,c=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:c,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")}},Ve=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??ye(),...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={...Wr(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,[z]: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 M(()=>i??!0?xe(o,()=>r(o)):r(o),()=>o.end())}end(e){this.checkNotFinished();let r=e?.endTime??ye();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 Qr(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,c=s.dataset,d=(await m.userInfo()).id;return new Ke(o,c.id,c.name,d,n)}var Ke=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 ge,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[Tt];(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{Ke as Dataset,Je as Experiment,He as NoopSpan,Ut as Project,Ve as SpanImpl,fo as _internalGetGlobalState,$r as currentExperiment,Jr as currentSpan,Hr as init,qr as initDataset,go as log,Lt as login,It as noopSpan,Vr as startSpan,yo as summarize,xo as traced,xe as withCurrent,ho as withDataset,mo as withExperiment};