@checksum-ai/runtime 4.14.0-beta.2 → 4.15.0
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/.env +1 -1
- package/checksum-progress-reporter.js +17 -17
- package/cli.js +103 -103
- package/index.js +1 -1
- package/package.json +1 -1
- package/test-run-monitor.js +27 -27
package/test-run-monitor.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";var xm=Object.create;var dr=Object.defineProperty;var Am=Object.getOwnPropertyDescriptor;var Rm=Object.getOwnPropertyNames;var Cm=Object.getPrototypeOf,Om=Object.prototype.hasOwnProperty;var o=(t,e)=>dr(t,"name",{value:e,configurable:!0});var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Nm=(t,e)=>{for(var r in e)dr(t,r,{get:e[r],enumerable:!0})},eo=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Rm(e))!Om.call(t,s)&&s!==r&&dr(t,s,{get:()=>e[s],enumerable:!(n=Am(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?xm(Cm(t)):{},eo(e||!t||!t.__esModule?dr(r,"default",{value:t,enumerable:!0}):r,t)),Mm=t=>eo(dr({},"__esModule",{value:!0}),t);var Xo=P((Ox,Ds)=>{"use strict";var yh=Object.prototype.hasOwnProperty,Ae="~";function pr(){}o(pr,"Events");Object.create&&(pr.prototype=Object.create(null),new pr().__proto__||(Ae=!1));function _h(t,e,r){this.fn=t,this.context=e,this.once=r||!1}o(_h,"EE");function Yo(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new _h(r,n||t,s),a=Ae?Ae+e:e;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],i]:t._events[a].push(i):(t._events[a]=i,t._eventsCount++),t}o(Yo,"addListener");function nn(t,e){--t._eventsCount===0?t._events=new pr:delete t._events[e]}o(nn,"clearEvent");function ve(){this._events=new pr,this._eventsCount=0}o(ve,"EventEmitter");ve.prototype.eventNames=o(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)yh.call(r,n)&&e.push(Ae?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");ve.prototype.listeners=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,a=new Array(i);s<i;s++)a[s]=n[s].fn;return a},"listeners");ve.prototype.listenerCount=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");ve.prototype.emit=o(function(e,r,n,s,i,a){var c=Ae?Ae+e:e;if(!this._events[c])return!1;var l=this._events[c],u=arguments.length,d,p;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,r),!0;case 3:return l.fn.call(l.context,r,n),!0;case 4:return l.fn.call(l.context,r,n,s),!0;case 5:return l.fn.call(l.context,r,n,s,i),!0;case 6:return l.fn.call(l.context,r,n,s,i,a),!0}for(p=1,d=new Array(u-1);p<u;p++)d[p-1]=arguments[p];l.fn.apply(l.context,d)}else{var _=l.length,g;for(p=0;p<_;p++)switch(l[p].once&&this.removeListener(e,l[p].fn,void 0,!0),u){case 1:l[p].fn.call(l[p].context);break;case 2:l[p].fn.call(l[p].context,r);break;case 3:l[p].fn.call(l[p].context,r,n);break;case 4:l[p].fn.call(l[p].context,r,n,s);break;default:if(!d)for(g=1,d=new Array(u-1);g<u;g++)d[g-1]=arguments[g];l[p].fn.apply(l[p].context,d)}}return!0},"emit");ve.prototype.on=o(function(e,r,n){return Yo(this,e,r,n,!1)},"on");ve.prototype.once=o(function(e,r,n){return Yo(this,e,r,n,!0)},"once");ve.prototype.removeListener=o(function(e,r,n,s){var i=Ae?Ae+e:e;if(!this._events[i])return this;if(!r)return nn(this,i),this;var a=this._events[i];if(a.fn)a.fn===r&&(!s||a.once)&&(!n||a.context===n)&&nn(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==r||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=l.length===1?l[0]:l:nn(this,i)}return this},"removeListener");ve.prototype.removeAllListeners=o(function(e){var r;return e?(r=Ae?Ae+e:e,this._events[r]&&nn(this,r)):(this._events=new pr,this._eventsCount=0),this},"removeAllListeners");ve.prototype.off=ve.prototype.removeListener;ve.prototype.addListener=ve.prototype.on;ve.prefixed=Ae;ve.EventEmitter=ve;typeof Ds<"u"&&(Ds.exports=ve)});var ec=P((Mx,Qo)=>{"use strict";Qo.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var rc=P((kx,an)=>{"use strict";var bh=ec(),sn=class extends Error{static{o(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},tc=o((t,e,r)=>new Promise((n,s)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(l){s(l)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,c=r instanceof Error?r:new sn(a);typeof t.cancel=="function"&&t.cancel(),s(c)},e);bh(t.then(n,s),()=>{clearTimeout(i)})}),"pTimeout");an.exports=tc;an.exports.default=tc;an.exports.TimeoutError=sn});var nc=P($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});function Eh(t,e,r){let n=0,s=t.length;for(;s>0;){let i=s/2|0,a=n+i;r(t[a],e)<=0?(n=++a,s-=i+1):s=i}return n}o(Eh,"lowerBound");$s.default=Eh});var sc=P(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var wh=nc(),Us=class{static{o(this,"PriorityQueue")}constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let s=wh.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(s,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};Fs.default=Us});var cn=P(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Th=Xo(),ic=rc(),vh=sc(),on=o(()=>{},"empty"),Sh=new ic.TimeoutError,Bs=class extends Th{static{o(this,"PQueue")}constructor(e){var r,n,s,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=on,this._resolveIdle=on,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:vh.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=on,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=on,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,s)=>{let i=o(async()=>{this._pendingCount++,this._intervalCount++;try{let a=this._timeout===void 0&&r.timeout===void 0?e():ic.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&s(Sh)});n(await a)}catch(a){s(a)}this._next()},"run");this._queue.enqueue(i,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};js.default=Bs});var vr=P((QC,Nl)=>{"use strict";var Hg="2.0.0",Gg=Number.MAX_SAFE_INTEGER||9007199254740991,zg=16,Vg=250,qg=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Nl.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:zg,MAX_SAFE_BUILD_LENGTH:Vg,MAX_SAFE_INTEGER:Gg,RELEASE_TYPES:qg,SEMVER_SPEC_VERSION:Hg,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Sr=P((eO,Ml)=>{"use strict";var Wg=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};Ml.exports=Wg});var Xt=P((ot,kl)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:wi,MAX_SAFE_BUILD_LENGTH:Kg,MAX_LENGTH:Zg}=vr(),Jg=Sr();ot=kl.exports={};var Yg=ot.re=[],Xg=ot.safeRe=[],L=ot.src=[],Qg=ot.safeSrc=[],D=ot.t={},ey=0,Ti="[a-zA-Z0-9-]",ty=[["\\s",1],["\\d",Zg],[Ti,Kg]],ry=o(t=>{for(let[e,r]of ty)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},"makeSafeRegex"),V=o((t,e,r)=>{let n=ry(e),s=ey++;Jg(t,s,e),D[t]=s,L[s]=e,Qg[s]=n,Yg[s]=new RegExp(e,r?"g":void 0),Xg[s]=new RegExp(n,r?"g":void 0)},"createToken");V("NUMERICIDENTIFIER","0|[1-9]\\d*");V("NUMERICIDENTIFIERLOOSE","\\d+");V("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Ti}*`);V("MAINVERSION",`(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})`);V("MAINVERSIONLOOSE",`(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASEIDENTIFIER",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIER]})`);V("PRERELEASEIDENTIFIERLOOSE",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASE",`(?:-(${L[D.PRERELEASEIDENTIFIER]}(?:\\.${L[D.PRERELEASEIDENTIFIER]})*))`);V("PRERELEASELOOSE",`(?:-?(${L[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${L[D.PRERELEASEIDENTIFIERLOOSE]})*))`);V("BUILDIDENTIFIER",`${Ti}+`);V("BUILD",`(?:\\+(${L[D.BUILDIDENTIFIER]}(?:\\.${L[D.BUILDIDENTIFIER]})*))`);V("FULLPLAIN",`v?${L[D.MAINVERSION]}${L[D.PRERELEASE]}?${L[D.BUILD]}?`);V("FULL",`^${L[D.FULLPLAIN]}$`);V("LOOSEPLAIN",`[v=\\s]*${L[D.MAINVERSIONLOOSE]}${L[D.PRERELEASELOOSE]}?${L[D.BUILD]}?`);V("LOOSE",`^${L[D.LOOSEPLAIN]}$`);V("GTLT","((?:<|>)?=?)");V("XRANGEIDENTIFIERLOOSE",`${L[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);V("XRANGEIDENTIFIER",`${L[D.NUMERICIDENTIFIER]}|x|X|\\*`);V("XRANGEPLAIN",`[v=\\s]*(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:${L[D.PRERELEASE]})?${L[D.BUILD]}?)?)?`);V("XRANGEPLAINLOOSE",`[v=\\s]*(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:${L[D.PRERELEASELOOSE]})?${L[D.BUILD]}?)?)?`);V("XRANGE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAIN]}$`);V("XRANGELOOSE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAINLOOSE]}$`);V("COERCEPLAIN",`(^|[^\\d])(\\d{1,${wi}})(?:\\.(\\d{1,${wi}}))?(?:\\.(\\d{1,${wi}}))?`);V("COERCE",`${L[D.COERCEPLAIN]}(?:$|[^\\d])`);V("COERCEFULL",L[D.COERCEPLAIN]+`(?:${L[D.PRERELEASE]})?(?:${L[D.BUILD]})?(?:$|[^\\d])`);V("COERCERTL",L[D.COERCE],!0);V("COERCERTLFULL",L[D.COERCEFULL],!0);V("LONETILDE","(?:~>?)");V("TILDETRIM",`(\\s*)${L[D.LONETILDE]}\\s+`,!0);ot.tildeTrimReplace="$1~";V("TILDE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAIN]}$`);V("TILDELOOSE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAINLOOSE]}$`);V("LONECARET","(?:\\^)");V("CARETTRIM",`(\\s*)${L[D.LONECARET]}\\s+`,!0);ot.caretTrimReplace="$1^";V("CARET",`^${L[D.LONECARET]}${L[D.XRANGEPLAIN]}$`);V("CARETLOOSE",`^${L[D.LONECARET]}${L[D.XRANGEPLAINLOOSE]}$`);V("COMPARATORLOOSE",`^${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]})$|^$`);V("COMPARATOR",`^${L[D.GTLT]}\\s*(${L[D.FULLPLAIN]})$|^$`);V("COMPARATORTRIM",`(\\s*)${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]}|${L[D.XRANGEPLAIN]})`,!0);ot.comparatorTrimReplace="$1$2$3";V("HYPHENRANGE",`^\\s*(${L[D.XRANGEPLAIN]})\\s+-\\s+(${L[D.XRANGEPLAIN]})\\s*$`);V("HYPHENRANGELOOSE",`^\\s*(${L[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${L[D.XRANGEPLAINLOOSE]})\\s*$`);V("STAR","(<|>)?=?\\s*\\*");V("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");V("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var An=P((rO,Pl)=>{"use strict";var ny=Object.freeze({loose:!0}),sy=Object.freeze({}),iy=o(t=>t?typeof t!="object"?ny:t:sy,"parseOptions");Pl.exports=iy});var vi=P((sO,$l)=>{"use strict";var Ll=/^[0-9]+$/,Dl=o((t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=Ll.test(t),n=Ll.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:t<e?-1:1},"compareIdentifiers"),ay=o((t,e)=>Dl(e,t),"rcompareIdentifiers");$l.exports={compareIdentifiers:Dl,rcompareIdentifiers:ay}});var Se=P((aO,Fl)=>{"use strict";var Rn=Sr(),{MAX_LENGTH:Ul,MAX_SAFE_INTEGER:Cn}=vr(),{safeRe:On,t:Nn}=Xt(),oy=An(),{compareIdentifiers:Si}=vi(),Ii=class t{static{o(this,"SemVer")}constructor(e,r){if(r=oy(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Ul)throw new TypeError(`version is longer than ${Ul} characters`);Rn("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=e.trim().match(r.loose?On[Nn.LOOSE]:On[Nn.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Cn||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Cn||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Cn||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&i<Cn)return i}return s}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Rn("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=e.prerelease[r];if(Rn("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Si(n,s)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let n=this.build[r],s=e.build[r];if(Rn("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Si(n,s)}while(++r)}inc(e,r,n){if(e.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?On[Nn.PRERELEASELOOSE]:On[Nn.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let i=[r,s];n===!1&&(i=[r]),Si(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Fl.exports=Ii});var Dt=P((cO,jl)=>{"use strict";var Bl=Se(),cy=o((t,e,r=!1)=>{if(t instanceof Bl)return t;try{return new Bl(t,e)}catch(n){if(!r)return null;throw n}},"parse");jl.exports=cy});var Gl=P((uO,Hl)=>{"use strict";var ly=Dt(),uy=o((t,e)=>{let r=ly(t,e);return r?r.version:null},"valid");Hl.exports=uy});var Vl=P((fO,zl)=>{"use strict";var dy=Dt(),fy=o((t,e)=>{let r=dy(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null},"clean");zl.exports=fy});var Kl=P((mO,Wl)=>{"use strict";var ql=Se(),py=o((t,e,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new ql(t instanceof ql?t.version:t,r).inc(e,n,s).version}catch{return null}},"inc");Wl.exports=py});var Yl=P((gO,Jl)=>{"use strict";var Zl=Dt(),my=o((t,e)=>{let r=Zl(t,null,!0),n=Zl(e,null,!0),s=r.compare(n);if(s===0)return null;let i=s>0,a=i?r:n,c=i?n:r,l=!!a.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(a)===0)return c.minor&&!c.patch?"minor":"patch"}let d=l?"pre":"";return r.major!==n.major?d+"major":r.minor!==n.minor?d+"minor":r.patch!==n.patch?d+"patch":"prerelease"},"diff");Jl.exports=my});var Ql=P((_O,Xl)=>{"use strict";var hy=Se(),gy=o((t,e)=>new hy(t,e).major,"major");Xl.exports=gy});var tu=P((EO,eu)=>{"use strict";var yy=Se(),_y=o((t,e)=>new yy(t,e).minor,"minor");eu.exports=_y});var nu=P((TO,ru)=>{"use strict";var by=Se(),Ey=o((t,e)=>new by(t,e).patch,"patch");ru.exports=Ey});var iu=P((SO,su)=>{"use strict";var wy=Dt(),Ty=o((t,e)=>{let r=wy(t,e);return r&&r.prerelease.length?r.prerelease:null},"prerelease");su.exports=Ty});var Ge=P((xO,ou)=>{"use strict";var au=Se(),vy=o((t,e,r)=>new au(t,r).compare(new au(e,r)),"compare");ou.exports=vy});var lu=P((RO,cu)=>{"use strict";var Sy=Ge(),Iy=o((t,e,r)=>Sy(e,t,r),"rcompare");cu.exports=Iy});var du=P((OO,uu)=>{"use strict";var xy=Ge(),Ay=o((t,e)=>xy(t,e,!0),"compareLoose");uu.exports=Ay});var Mn=P((MO,pu)=>{"use strict";var fu=Se(),Ry=o((t,e,r)=>{let n=new fu(t,r),s=new fu(e,r);return n.compare(s)||n.compareBuild(s)},"compareBuild");pu.exports=Ry});var hu=P((PO,mu)=>{"use strict";var Cy=Mn(),Oy=o((t,e)=>t.sort((r,n)=>Cy(r,n,e)),"sort");mu.exports=Oy});var yu=P((DO,gu)=>{"use strict";var Ny=Mn(),My=o((t,e)=>t.sort((r,n)=>Ny(n,r,e)),"rsort");gu.exports=My});var Ir=P((UO,_u)=>{"use strict";var ky=Ge(),Py=o((t,e,r)=>ky(t,e,r)>0,"gt");_u.exports=Py});var kn=P((BO,bu)=>{"use strict";var Ly=Ge(),Dy=o((t,e,r)=>Ly(t,e,r)<0,"lt");bu.exports=Dy});var xi=P((HO,Eu)=>{"use strict";var $y=Ge(),Uy=o((t,e,r)=>$y(t,e,r)===0,"eq");Eu.exports=Uy});var Ai=P((zO,wu)=>{"use strict";var Fy=Ge(),By=o((t,e,r)=>Fy(t,e,r)!==0,"neq");wu.exports=By});var Pn=P((qO,Tu)=>{"use strict";var jy=Ge(),Hy=o((t,e,r)=>jy(t,e,r)>=0,"gte");Tu.exports=Hy});var Ln=P((KO,vu)=>{"use strict";var Gy=Ge(),zy=o((t,e,r)=>Gy(t,e,r)<=0,"lte");vu.exports=zy});var Ri=P((JO,Su)=>{"use strict";var Vy=xi(),qy=Ai(),Wy=Ir(),Ky=Pn(),Zy=kn(),Jy=Ln(),Yy=o((t,e,r,n)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Vy(t,r,n);case"!=":return qy(t,r,n);case">":return Wy(t,r,n);case">=":return Ky(t,r,n);case"<":return Zy(t,r,n);case"<=":return Jy(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}},"cmp");Su.exports=Yy});var xu=P((XO,Iu)=>{"use strict";var Xy=Se(),Qy=Dt(),{safeRe:Dn,t:$n}=Xt(),e_=o((t,e)=>{if(t instanceof Xy)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?Dn[$n.COERCEFULL]:Dn[$n.COERCE]);else{let l=e.includePrerelease?Dn[$n.COERCERTLFULL]:Dn[$n.COERCERTL],u;for(;(u=l.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",i=r[4]||"0",a=e.includePrerelease&&r[5]?`-${r[5]}`:"",c=e.includePrerelease&&r[6]?`+${r[6]}`:"";return Qy(`${n}.${s}.${i}${a}${c}`,e)},"coerce");Iu.exports=e_});var Ru=P((eN,Au)=>{"use strict";var Ci=class{static{o(this,"LRUCache")}constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(e,r)}return this}};Au.exports=Ci});var ze=P((rN,Mu)=>{"use strict";var t_=/\s+/g,Oi=class t{static{o(this,"Range")}constructor(e,r){if(r=n_(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof Ni)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(t_," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Ou(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&u_(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&c_)|(this.options.loose&&l_))+":"+e,s=Cu.get(n);if(s)return s;let i=this.options.loose,a=i?Re[Ie.HYPHENRANGELOOSE]:Re[Ie.HYPHENRANGE];e=e.replace(a,E_(this.options.includePrerelease)),ee("hyphen replace",e),e=e.replace(Re[Ie.COMPARATORTRIM],i_),ee("comparator trim",e),e=e.replace(Re[Ie.TILDETRIM],a_),ee("tilde trim",e),e=e.replace(Re[Ie.CARETTRIM],o_),ee("caret trim",e);let c=e.split(" ").map(p=>d_(p,this.options)).join(" ").split(/\s+/).map(p=>b_(p,this.options));i&&(c=c.filter(p=>(ee("loose invalid filter",p,this.options),!!p.match(Re[Ie.COMPARATORLOOSE])))),ee("range list",c);let l=new Map,u=c.map(p=>new Ni(p,this.options));for(let p of u){if(Ou(p))return[p];l.set(p.value,p)}l.size>1&&l.has("")&&l.delete("");let d=[...l.values()];return Cu.set(n,d),d}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(n=>Nu(n,r)&&e.set.some(s=>Nu(s,r)&&n.every(i=>s.every(a=>i.intersects(a,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new s_(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(w_(this.set[r],e,this.options))return!0;return!1}};Mu.exports=Oi;var r_=Ru(),Cu=new r_,n_=An(),Ni=xr(),ee=Sr(),s_=Se(),{safeRe:Re,t:Ie,comparatorTrimReplace:i_,tildeTrimReplace:a_,caretTrimReplace:o_}=Xt(),{FLAG_INCLUDE_PRERELEASE:c_,FLAG_LOOSE:l_}=vr(),Ou=o(t=>t.value==="<0.0.0-0","isNullSet"),u_=o(t=>t.value==="","isAny"),Nu=o((t,e)=>{let r=!0,n=t.slice(),s=n.pop();for(;r&&n.length;)r=n.every(i=>s.intersects(i,e)),s=n.pop();return r},"isSatisfiable"),d_=o((t,e)=>(t=t.replace(Re[Ie.BUILD],""),ee("comp",t,e),t=m_(t,e),ee("caret",t),t=f_(t,e),ee("tildes",t),t=g_(t,e),ee("xrange",t),t=__(t,e),ee("stars",t),t),"parseComparator"),Ce=o(t=>!t||t.toLowerCase()==="x"||t==="*","isX"),f_=o((t,e)=>t.trim().split(/\s+/).map(r=>p_(r,e)).join(" "),"replaceTildes"),p_=o((t,e)=>{let r=e.loose?Re[Ie.TILDELOOSE]:Re[Ie.TILDE];return t.replace(r,(n,s,i,a,c)=>{ee("tilde",t,n,s,i,a,c);let l;return Ce(s)?l="":Ce(i)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:Ce(a)?l=`>=${s}.${i}.0 <${s}.${+i+1}.0-0`:c?(ee("replaceTilde pr",c),l=`>=${s}.${i}.${a}-${c} <${s}.${+i+1}.0-0`):l=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,ee("tilde return",l),l})},"replaceTilde"),m_=o((t,e)=>t.trim().split(/\s+/).map(r=>h_(r,e)).join(" "),"replaceCarets"),h_=o((t,e)=>{ee("caret",t,e);let r=e.loose?Re[Ie.CARETLOOSE]:Re[Ie.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,(s,i,a,c,l)=>{ee("caret",t,s,i,a,c,l);let u;return Ce(i)?u="":Ce(a)?u=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Ce(c)?i==="0"?u=`>=${i}.${a}.0${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.0${n} <${+i+1}.0.0-0`:l?(ee("replaceCaret pr",l),i==="0"?a==="0"?u=`>=${i}.${a}.${c}-${l} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}-${l} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c}-${l} <${+i+1}.0.0-0`):(ee("no pr"),i==="0"?a==="0"?u=`>=${i}.${a}.${c}${n} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c} <${+i+1}.0.0-0`),ee("caret return",u),u})},"replaceCaret"),g_=o((t,e)=>(ee("replaceXRanges",t,e),t.split(/\s+/).map(r=>y_(r,e)).join(" ")),"replaceXRanges"),y_=o((t,e)=>{t=t.trim();let r=e.loose?Re[Ie.XRANGELOOSE]:Re[Ie.XRANGE];return t.replace(r,(n,s,i,a,c,l)=>{ee("xRange",t,n,s,i,a,c,l);let u=Ce(i),d=u||Ce(a),p=d||Ce(c),_=p;return s==="="&&_&&(s=""),l=e.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&_?(d&&(a=0),c=0,s===">"?(s=">=",d?(i=+i+1,a=0,c=0):(a=+a+1,c=0)):s==="<="&&(s="<",d?i=+i+1:a=+a+1),s==="<"&&(l="-0"),n=`${s+i}.${a}.${c}${l}`):d?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:p&&(n=`>=${i}.${a}.0${l} <${i}.${+a+1}.0-0`),ee("xRange return",n),n})},"replaceXRange"),__=o((t,e)=>(ee("replaceStars",t,e),t.trim().replace(Re[Ie.STAR],"")),"replaceStars"),b_=o((t,e)=>(ee("replaceGTE0",t,e),t.trim().replace(Re[e.includePrerelease?Ie.GTE0PRE:Ie.GTE0],"")),"replaceGTE0"),E_=o(t=>(e,r,n,s,i,a,c,l,u,d,p,_)=>(Ce(n)?r="":Ce(s)?r=`>=${n}.0.0${t?"-0":""}`:Ce(i)?r=`>=${n}.${s}.0${t?"-0":""}`:a?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,Ce(u)?l="":Ce(d)?l=`<${+u+1}.0.0-0`:Ce(p)?l=`<${u}.${+d+1}.0-0`:_?l=`<=${u}.${d}.${p}-${_}`:t?l=`<${u}.${d}.${+p+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),"hyphenReplace"),w_=o((t,e,r)=>{for(let n=0;n<t.length;n++)if(!t[n].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let n=0;n<t.length;n++)if(ee(t[n].semver),t[n].semver!==Ni.ANY&&t[n].semver.prerelease.length>0){let s=t[n].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0},"testSet")});var xr=P((sN,Uu)=>{"use strict";var Ar=Symbol("SemVer ANY"),Pi=class t{static{o(this,"Comparator")}static get ANY(){return Ar}constructor(e,r){if(r=ku(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),ki("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===Ar?this.value="":this.value=this.operator+this.semver.version,ki("comp",this)}parse(e){let r=this.options.loose?Pu[Lu.COMPARATORLOOSE]:Pu[Lu.COMPARATOR],n=e.match(r);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Du(n[2],this.options.loose):this.semver=Ar}toString(){return this.value}test(e){if(ki("Comparator.test",e,this.options.loose),this.semver===Ar||e===Ar)return!0;if(typeof e=="string")try{e=new Du(e,this.options)}catch{return!1}return Mi(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new $u(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new $u(this.value,r).test(e.semver):(r=ku(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Mi(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Mi(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Uu.exports=Pi;var ku=An(),{safeRe:Pu,t:Lu}=Xt(),Mi=Ri(),ki=Sr(),Du=Se(),$u=ze()});var Rr=P((aN,Fu)=>{"use strict";var T_=ze(),v_=o((t,e,r)=>{try{e=new T_(e,r)}catch{return!1}return e.test(t)},"satisfies");Fu.exports=v_});var ju=P((cN,Bu)=>{"use strict";var S_=ze(),I_=o((t,e)=>new S_(t,e).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" ")),"toComparators");Bu.exports=I_});var Gu=P((uN,Hu)=>{"use strict";var x_=Se(),A_=ze(),R_=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new A_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===-1)&&(n=a,s=new x_(n,r))}),n},"maxSatisfying");Hu.exports=R_});var Vu=P((fN,zu)=>{"use strict";var C_=Se(),O_=ze(),N_=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new O_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===1)&&(n=a,s=new C_(n,r))}),n},"minSatisfying");zu.exports=N_});var Ku=P((mN,Wu)=>{"use strict";var Li=Se(),M_=ze(),qu=Ir(),k_=o((t,e)=>{t=new M_(t,e);let r=new Li("0.0.0");if(t.test(r)||(r=new Li("0.0.0-0"),t.test(r)))return r;r=null;for(let n=0;n<t.set.length;++n){let s=t.set[n],i=null;s.forEach(a=>{let c=new Li(a.semver.version);switch(a.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!i||qu(c,i))&&(i=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${a.operator}`)}}),i&&(!r||qu(r,i))&&(r=i)}return r&&t.test(r)?r:null},"minVersion");Wu.exports=k_});var Ju=P((gN,Zu)=>{"use strict";var P_=ze(),L_=o((t,e)=>{try{return new P_(t,e).range||"*"}catch{return null}},"validRange");Zu.exports=L_});var Un=P((_N,ed)=>{"use strict";var D_=Se(),Qu=xr(),{ANY:$_}=Qu,U_=ze(),F_=Rr(),Yu=Ir(),Xu=kn(),B_=Ln(),j_=Pn(),H_=o((t,e,r,n)=>{t=new D_(t,n),e=new U_(e,n);let s,i,a,c,l;switch(r){case">":s=Yu,i=B_,a=Xu,c=">",l=">=";break;case"<":s=Xu,i=j_,a=Yu,c="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(F_(t,e,n))return!1;for(let u=0;u<e.set.length;++u){let d=e.set[u],p=null,_=null;if(d.forEach(g=>{g.semver===$_&&(g=new Qu(">=0.0.0")),p=p||g,_=_||g,s(g.semver,p.semver,n)?p=g:a(g.semver,_.semver,n)&&(_=g)}),p.operator===c||p.operator===l||(!_.operator||_.operator===c)&&i(t,_.semver))return!1;if(_.operator===l&&a(t,_.semver))return!1}return!0},"outside");ed.exports=H_});var rd=P((EN,td)=>{"use strict";var G_=Un(),z_=o((t,e,r)=>G_(t,e,">",r),"gtr");td.exports=z_});var sd=P((TN,nd)=>{"use strict";var V_=Un(),q_=o((t,e,r)=>V_(t,e,"<",r),"ltr");nd.exports=q_});var od=P((SN,ad)=>{"use strict";var id=ze(),W_=o((t,e,r)=>(t=new id(t,r),e=new id(e,r),t.intersects(e,r)),"intersects");ad.exports=W_});var ld=P((xN,cd)=>{"use strict";var K_=Rr(),Z_=Ge();cd.exports=(t,e,r)=>{let n=[],s=null,i=null,a=t.sort((d,p)=>Z_(d,p,r));for(let d of a)K_(d,e,r)?(i=d,s||(s=d)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let c=[];for(let[d,p]of n)d===p?c.push(d):!p&&d===a[0]?c.push("*"):p?d===a[0]?c.push(`<=${p}`):c.push(`${d} - ${p}`):c.push(`>=${d}`);let l=c.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var hd=P((AN,md)=>{"use strict";var ud=ze(),$i=xr(),{ANY:Di}=$i,Cr=Rr(),Ui=Ge(),J_=o((t,e,r={})=>{if(t===e)return!0;t=new ud(t,r),e=new ud(e,r);let n=!1;e:for(let s of t.set){for(let i of e.set){let a=X_(s,i,r);if(n=n||a!==null,a)continue e}if(n)return!1}return!0},"subset"),Y_=[new $i(">=0.0.0-0")],dd=[new $i(">=0.0.0")],X_=o((t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Di){if(e.length===1&&e[0].semver===Di)return!0;r.includePrerelease?t=Y_:t=dd}if(e.length===1&&e[0].semver===Di){if(r.includePrerelease)return!0;e=dd}let n=new Set,s,i;for(let g of t)g.operator===">"||g.operator===">="?s=fd(s,g,r):g.operator==="<"||g.operator==="<="?i=pd(i,g,r):n.add(g.semver);if(n.size>1)return null;let a;if(s&&i){if(a=Ui(s.semver,i.semver,r),a>0)return null;if(a===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let g of n){if(s&&!Cr(g,String(s),r)||i&&!Cr(g,String(i),r))return null;for(let y of e)if(!Cr(g,String(y),r))return!1;return!0}let c,l,u,d,p=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,_=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;p&&p.prerelease.length===1&&i.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let g of e){if(d=d||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",s){if(_&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===_.major&&g.semver.minor===_.minor&&g.semver.patch===_.patch&&(_=!1),g.operator===">"||g.operator===">="){if(c=fd(s,g,r),c===g&&c!==s)return!1}else if(s.operator===">="&&!Cr(s.semver,String(g),r))return!1}if(i){if(p&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===p.major&&g.semver.minor===p.minor&&g.semver.patch===p.patch&&(p=!1),g.operator==="<"||g.operator==="<="){if(l=pd(i,g,r),l===g&&l!==i)return!1}else if(i.operator==="<="&&!Cr(i.semver,String(g),r))return!1}if(!g.operator&&(i||s)&&a!==0)return!1}return!(s&&u&&!i&&a!==0||i&&d&&!s&&a!==0||_||p)},"simpleSubset"),fd=o((t,e,r)=>{if(!t)return e;let n=Ui(t.semver,e.semver,r);return n>0?t:n<0||e.operator===">"&&t.operator===">="?e:t},"higherGT"),pd=o((t,e,r)=>{if(!t)return e;let n=Ui(t.semver,e.semver,r);return n<0?t:n>0||e.operator==="<"&&t.operator==="<="?e:t},"lowerLT");md.exports=J_});var bd=P((CN,_d)=>{"use strict";var Fi=Xt(),gd=vr(),Q_=Se(),yd=vi(),eb=Dt(),tb=Gl(),rb=Vl(),nb=Kl(),sb=Yl(),ib=Ql(),ab=tu(),ob=nu(),cb=iu(),lb=Ge(),ub=lu(),db=du(),fb=Mn(),pb=hu(),mb=yu(),hb=Ir(),gb=kn(),yb=xi(),_b=Ai(),bb=Pn(),Eb=Ln(),wb=Ri(),Tb=xu(),vb=xr(),Sb=ze(),Ib=Rr(),xb=ju(),Ab=Gu(),Rb=Vu(),Cb=Ku(),Ob=Ju(),Nb=Un(),Mb=rd(),kb=sd(),Pb=od(),Lb=ld(),Db=hd();_d.exports={parse:eb,valid:tb,clean:rb,inc:nb,diff:sb,major:ib,minor:ab,patch:ob,prerelease:cb,compare:lb,rcompare:ub,compareLoose:db,compareBuild:fb,sort:pb,rsort:mb,gt:hb,lt:gb,eq:yb,neq:_b,gte:bb,lte:Eb,cmp:wb,coerce:Tb,Comparator:vb,Range:Sb,satisfies:Ib,toComparators:xb,maxSatisfying:Ab,minSatisfying:Rb,minVersion:Cb,validRange:Ob,outside:Nb,gtr:Mb,ltr:kb,intersects:Pb,simplifyRange:Lb,subset:Db,SemVer:Q_,re:Fi.re,src:Fi.src,tokens:Fi.t,SEMVER_SPEC_VERSION:gd.SEMVER_SPEC_VERSION,RELEASE_TYPES:gd.RELEASE_TYPES,compareIdentifiers:yd.compareIdentifiers,rcompareIdentifiers:yd.rcompareIdentifiers}});var hf=P(Qn=>{"use strict";Qn.byteLength=ow;Qn.toByteArray=lw;Qn.fromByteArray=fw;var dt=[],qe=[],aw=typeof Uint8Array<"u"?Uint8Array:Array,la="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Bt=0,pf=la.length;Bt<pf;++Bt)dt[Bt]=la[Bt],qe[la.charCodeAt(Bt)]=Bt;var Bt,pf;qe[45]=62;qe[95]=63;function mf(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}o(mf,"getLens");function ow(t){var e=mf(t),r=e[0],n=e[1];return(r+n)*3/4-n}o(ow,"byteLength");function cw(t,e,r){return(e+r)*3/4-r}o(cw,"_byteLength");function lw(t){var e,r=mf(t),n=r[0],s=r[1],i=new aw(cw(t,n,s)),a=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=qe[t.charCodeAt(l)]<<18|qe[t.charCodeAt(l+1)]<<12|qe[t.charCodeAt(l+2)]<<6|qe[t.charCodeAt(l+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=qe[t.charCodeAt(l)]<<2|qe[t.charCodeAt(l+1)]>>4,i[a++]=e&255),s===1&&(e=qe[t.charCodeAt(l)]<<10|qe[t.charCodeAt(l+1)]<<4|qe[t.charCodeAt(l+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}o(lw,"toByteArray");function uw(t){return dt[t>>18&63]+dt[t>>12&63]+dt[t>>6&63]+dt[t&63]}o(uw,"tripletToBase64");function dw(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(uw(n));return s.join("")}o(dw,"encodeChunk");function fw(t){for(var e,r=t.length,n=r%3,s=[],i=16383,a=0,c=r-n;a<c;a+=i)s.push(dw(t,a,a+i>c?c:a+i));return n===1?(e=t[r-1],s.push(dt[e>>2]+dt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(dt[e>>10]+dt[e>>4&63]+dt[e<<2&63]+"=")),s.join("")}o(fw,"fromByteArray")});var kf=P((z3,gt)=>{var ga=require("fs"),ts=require("path"),Dw=require("os"),$w=require("crypto"),Rf=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function Uw(){return Rf[Math.floor(Math.random()*Rf.length)]}o(Uw,"_getRandomTip");function rr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(rr,"parseBoolean");function Fw(){return process.stdout.isTTY}o(Fw,"supportsAnsi");function Bw(t){return Fw()?`\x1B[2m${t}\x1B[0m`:t}o(Bw,"dim");var jw=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Hw(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
2
|
-
`);let n;for(;(n=
|
|
3
|
-
`),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(Hw,"parse");function Gw(t){t=t||{};let e=Mf(t);t.path=e;let r=pe.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=Nf(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=Vw(r,c);i=pe.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return pe.parse(i)}o(Gw,"_parseVault");function zw(t){console.error(`\u26A0 ${t}`)}o(zw,"_warn");function Fr(t){console.log(`\u2506 ${t}`)}o(Fr,"_debug");function Of(t){console.log(`\u25C7 ${t}`)}o(Of,"_log");function Nf(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(Nf,"_dotenvKey");function Vw(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(Vw,"_instructions");function Mf(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)ga.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=ts.resolve(process.cwd(),".env.vault");return ga.existsSync(e)?e:null}o(Mf,"_vaultPath");function Cf(t){return t[0]==="~"?ts.join(Dw.homedir(),t.slice(1)):t}o(Cf,"_resolveHome");function qw(t){let e=rr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=rr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Of("loading env from encrypted .env.vault");let n=pe._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),pe.populate(s,n,t),{parsed:n}}o(qw,"_configVault");function Ww(t){let e=ts.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=rr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=rr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&Fr("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[Cf(t.path)];else{a=[];for(let d of t.path)a.push(Cf(d))}let c,l={};for(let d of a)try{let p=pe.parse(ga.readFileSync(d,{encoding:r}));pe.populate(l,p,t)}catch(p){s&&Fr(`failed to load ${d} ${p.message}`),c=p}let u=pe.populate(n,l,t);if(s=rr(n.DOTENV_CONFIG_DEBUG||s),i=rr(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,p=[];for(let _ of a)try{let g=ts.relative(process.cwd(),_);p.push(g)}catch(g){s&&Fr(`failed to load ${_} ${g.message}`),c=g}Of(`injected env (${d}) from ${p.join(",")} ${Bw(`// tip: ${Uw()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o(Ww,"configDotenv");function Kw(t){if(Nf(t).length===0)return pe.configDotenv(t);let e=Mf(t);return e?pe._configVault(t):(zw(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),pe.configDotenv(t))}o(Kw,"config");function Zw(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=$w.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o(Zw,"decrypt");function Jw(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&Fr(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(Jw,"populate");var pe={configDotenv:Ww,_configVault:qw,_parseVault:Gw,config:Kw,decrypt:Zw,parse:Hw,populate:Jw};gt.exports.configDotenv=pe.configDotenv;gt.exports._configVault=pe._configVault;gt.exports._parseVault=pe._parseVault;gt.exports.config=pe.config;gt.exports.decrypt=pe.decrypt;gt.exports.parse=pe.parse;gt.exports.populate=pe.populate;gt.exports=pe});var ya=P((b5,Ff)=>{Ff.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var rs=P(jf=>{var Bf={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function t0(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}o(t0,"E");for(let t of Object.keys(Bf))jf[t]=t0(Bf[t])});var qf=P((T5,Vf)=>{var r0=require("fs"),de=require("path"),Hf=ya(),n0=rs(),s0=typeof process=="object"&&process.platform==="win32",Gf=o(t=>typeof t=="object"&&t!==null,"is_Obj"),zf=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ne(t){this.sep=de.sep,this.fs=r0,Gf(t)&&Gf(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}o(ne,"Utils");Vf.exports=ne;ne.prototype.makeDir=function(t){let e=this;function r(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(i){if(!(!i||i.substr(-1,1)===":")){s+=e.sep+i;var a;try{a=e.fs.statSync(s)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw c}if(a&&a.isFile())throw n0.FILE_IN_THE_WAY(`"${s}"`)}})}o(r,"mkdirSync"),r(t)};ne.prototype.writeFileTo=function(t,e,r,n){let s=this;if(s.fs.existsSync(t)){if(!r)return!1;var i=s.fs.statSync(t);if(i.isDirectory())return!1}var a=de.dirname(t);s.fs.existsSync(a)||s.makeDir(a);var c;try{c=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),c=s.fs.openSync(t,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(t,n||438),!0};ne.prototype.writeFileToAsync=function(t,e,r,n,s){typeof n=="function"&&(s=n,n=void 0);let i=this;i.fs.exists(t,function(a){if(a&&!r)return s(!1);i.fs.stat(t,function(c,l){if(a&&l&&l.isDirectory())return s(!1);var u=de.dirname(t);i.fs.exists(u,function(d){if(!d)try{i.makeDir(u)}catch{return s(!1)}let p=o(function(_){i.fs.write(_,e,0,e.length,0,function(g){i.fs.close(_,function(){if(g)return s(!1);i.fs.chmod(t,n||438,function(){s(!0)})})})},"writeToFd");i.fs.open(t,"w",438,function(_,g){_?i.fs.chmod(t,438,function(){i.fs.open(t,"w",438,function(y,E){if(y||!E)return s(!1);p(E)})}):g?p(g):s(!1)})})})})};ne.prototype.findFiles=function(t){let e=this;function r(n,s,i,a){typeof s=="boolean"&&(i=s,s=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(l){let u=de.join(n,l),d=e.fs.statSync(u);if((!s||s.test(u))&&c.push(de.normalize(u)+(d.isDirectory()?e.sep:"")),d.isDirectory()&&i){let p=e.fs.realpathSync(u);a.has(p)||(a.add(p),c=c.concat(r(u,s,i,a)))}}),c}return o(r,"findSync"),r(t,void 0,!0,new Set([e.fs.realpathSync(t)]))};ne.prototype.findFilesAsync=function(t,e){let r=this,n=[],s=!1,i=o(function(c){s||(s=!0,e(c,c?void 0:n))},"finish"),a=o(function(c,l,u){r.fs.readdir(c,function(d,p){if(d)return u(d);let _=p.length;if(!_)return u();p.forEach(function(g){let y=de.join(c,g);r.fs.stat(y,function(E,w){if(E)return u(E);if(!w){--_||u();return}if(n.push(de.normalize(y)+(w.isDirectory()?r.sep:"")),!w.isDirectory()){--_||u();return}r.fs.realpath(y,function(S,I){if(S)return u(S);if(l.has(I)){--_||u();return}l.add(I),a(y,l,function(m){if(m)return u(m);--_||u()})})})})})},"walk");r.fs.realpath(t,function(c,l){if(c)return i(c);a(t,new Set([l]),i)})};ne.prototype.getAttributes=function(){};ne.prototype.setAttributes=function(){};ne.crc32update=function(t,e){return zf[(t^e)&255]^t>>>8};ne.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=ne.crc32update(r,t[n++]);return~r>>>0};ne.methodToString=function(t){switch(t){case Hf.STORED:return"STORED ("+t+")";case Hf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ne.canonical=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.join(".",e)};ne.zipnamefix=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.posix.join(".",e)};ne.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};ne.sanitize=function(t,e){t=de.resolve(de.normalize(t));for(var r=e.split("/"),n=0,s=r.length;n<s;n++){var i=de.normalize(de.join(t,r.slice(n,s).join(de.sep)));if(i===t||i.startsWith(t+de.sep))return i}return de.normalize(de.join(t,de.basename(e)))};ne.toBuffer=o(function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)},"toBuffer");ne.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ne.writeBigUInt64LE=function(t,e,r){let n=e>>>0,s=Math.floor(e/4294967296)>>>0;t.writeUInt32LE(n,r),t.writeUInt32LE(s,r+4)};ne.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ne.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};ne.isWin=s0;ne.crcTable=zf});var Kf=P((S5,Wf)=>{var i0=require("path");Wf.exports=function(t,{fs:e}){var r=t||"",n=i(),s=null;function i(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return o(i,"newAttr"),r&&e.existsSync(r)?(s=e.statSync(r),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=i0.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:o(function(){},"decodeAttributes"),encodeAttributes:o(function(){},"encodeAttributes"),toJSON:o(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Jf=P((x5,Zf)=>{Zf.exports={efs:!0,encode:o(t=>Buffer.from(t,"utf8"),"encode"),decode:o(t=>t.toString("utf8"),"decode")}});var sr=P((R5,nr)=>{nr.exports=qf();nr.exports.Constants=ya();nr.exports.Errors=rs();nr.exports.FileAttr=Kf();nr.exports.decoder=Jf()});var Xf=P((C5,Yf)=>{var It=sr(),M=It.Constants;Yf.exports=function(){var t=20,e=10,r=0,n=0,s=0,i=0,a=0,c=0,l=0,u=0,d=0,p=0,_=0,g=0,y=0;t|=It.isWin?2560:768,r|=M.FLG_EFS;let E={extraLen:0},w=o(m=>Math.max(0,m)>>>0,"uint32"),S=o(m=>Math.max(0,m)&65535,"uint16"),I=o(m=>Math.max(0,m)&255,"uint8");return s=It.fromDate2DOS(new Date),{get made(){return t},set made(m){t=m},get version(){return e},set version(m){e=m},get flags(){return r},set flags(m){r=m},get flags_efs(){return(r&M.FLG_EFS)>0},set flags_efs(m){m?r|=M.FLG_EFS:r&=~M.FLG_EFS},get flags_desc(){return(r&M.FLG_DESC)>0},set flags_desc(m){m?r|=M.FLG_DESC:r&=~M.FLG_DESC},get method(){return n},set method(m){switch(m){case M.STORED:this.version=10;break;case M.DEFLATED:default:this.version=20}n=m},get time(){return It.fromDOS2Date(this.timeval)},set time(m){m=new Date(m),this.timeval=It.fromDate2DOS(m)},get timeval(){return s},set timeval(m){s=w(m)},get timeHighByte(){return I(s>>>8)},get crc(){return i},set crc(m){i=w(m)},get compressedSize(){return a},set compressedSize(m){a=w(m)},get size(){return c},set size(m){c=w(m)},get fileNameLength(){return l},set fileNameLength(m){l=m},get extraLength(){return u},set extraLength(m){u=m},get extraLocalLength(){return E.extraLen},set extraLocalLength(m){E.extraLen=m},get commentLength(){return d},set commentLength(m){d=m},get diskNumStart(){return p},set diskNumStart(m){p=w(m)},get inAttr(){return _},set inAttr(m){_=w(m)},get attr(){return g},set attr(m){g=w(m)},get fileAttr(){return(g||0)>>16&4095},get offset(){return y},set offset(m){y=w(m)},get encrypted(){return(r&M.FLG_ENC)===M.FLG_ENC},get centralHeaderSize(){return M.CENHDR+l+u+d},get realDataOffset(){return y+M.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:o(function(m){var T=m.slice(y,y+M.LOCHDR);if(T.readUInt32LE(0)!==M.LOCSIG)throw It.Errors.INVALID_LOC();E.version=T.readUInt16LE(M.LOCVER),E.flags=T.readUInt16LE(M.LOCFLG),E.flags_desc=(E.flags&M.FLG_DESC)>0,E.method=T.readUInt16LE(M.LOCHOW),E.time=T.readUInt32LE(M.LOCTIM),E.crc=T.readUInt32LE(M.LOCCRC),E.compressedSize=T.readUInt32LE(M.LOCSIZ),E.size=T.readUInt32LE(M.LOCLEN),E.fnameLen=T.readUInt16LE(M.LOCNAM),E.extraLen=T.readUInt16LE(M.LOCEXT);let A=y+M.LOCHDR+E.fnameLen,N=A+E.extraLen;return m.slice(A,N)},"loadLocalHeaderFromBinary"),loadFromBinary:o(function(m){if(m.length!==M.CENHDR||m.readUInt32LE(0)!==M.CENSIG)throw It.Errors.INVALID_CEN();t=m.readUInt16LE(M.CENVEM),e=m.readUInt16LE(M.CENVER),r=m.readUInt16LE(M.CENFLG),n=m.readUInt16LE(M.CENHOW),s=m.readUInt32LE(M.CENTIM),i=m.readUInt32LE(M.CENCRC),a=m.readUInt32LE(M.CENSIZ),c=m.readUInt32LE(M.CENLEN),l=m.readUInt16LE(M.CENNAM),u=m.readUInt16LE(M.CENEXT),d=m.readUInt16LE(M.CENCOM),p=m.readUInt16LE(M.CENDSK),_=m.readUInt16LE(M.CENATT),g=m.readUInt32LE(M.CENATX),y=m.readUInt32LE(M.CENOFF)},"loadFromBinary"),localHeaderToBinary:o(function(){var m=Buffer.alloc(M.LOCHDR);return m.writeUInt32LE(M.LOCSIG,0),m.writeUInt16LE(e,M.LOCVER),m.writeUInt16LE(r&~M.FLG_DESC,M.LOCFLG),m.writeUInt16LE(n,M.LOCHOW),m.writeUInt32LE(s,M.LOCTIM),m.writeUInt32LE(i,M.LOCCRC),m.writeUInt32LE(a,M.LOCSIZ),m.writeUInt32LE(c,M.LOCLEN),m.writeUInt16LE(l,M.LOCNAM),m.writeUInt16LE(E.extraLen,M.LOCEXT),m},"localHeaderToBinary"),centralHeaderToBinary:o(function(){var m=Buffer.alloc(M.CENHDR+l+u+d);return m.writeUInt32LE(M.CENSIG,0),m.writeUInt16LE(t,M.CENVEM),m.writeUInt16LE(e,M.CENVER),m.writeUInt16LE(r&~M.FLG_DESC,M.CENFLG),m.writeUInt16LE(n,M.CENHOW),m.writeUInt32LE(s,M.CENTIM),m.writeUInt32LE(i,M.CENCRC),m.writeUInt32LE(a,M.CENSIZ),m.writeUInt32LE(c,M.CENLEN),m.writeUInt16LE(l,M.CENNAM),m.writeUInt16LE(u,M.CENEXT),m.writeUInt16LE(d,M.CENCOM),m.writeUInt16LE(p,M.CENDSK),m.writeUInt16LE(_,M.CENATT),m.writeUInt32LE(g,M.CENATX),m.writeUInt32LE(y,M.CENOFF),m},"centralHeaderToBinary"),toJSON:o(function(){let m=o(function(T){return T+" bytes"},"bytes");return{made:t,version:e,flags:r,method:It.methodToString(n),time:this.time,crc:"0x"+i.toString(16).toUpperCase(),compressedSize:m(a),size:m(c),fileNameLength:m(l),extraLength:m(u),commentLength:m(d),diskNumStart:p,inAttr:_,attr:g,offset:y,centralHeaderSize:m(M.CENHDR+l+u+d)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ep=P((N5,Qf)=>{var We=sr(),H=We.Constants;Qf.exports=function(){var t=0,e=0,r=0,n=0,s=0;let i=o(()=>t>H.EF_ZIP64_OR_16||e>H.EF_ZIP64_OR_16||r>H.EF_ZIP64_OR_32||n>H.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return r},set size(a){r=a},get offset(){return n},set offset(a){n=a},get commentLength(){return s},set commentLength(a){s=a},get mainHeaderSize(){return(i()?H.ZIP64HDR+H.END64HDR:0)+H.ENDHDR+s},loadFromBinary:o(function(a){if((a.length!==H.ENDHDR||a.readUInt32LE(0)!==H.ENDSIG)&&(a.length<H.ZIP64HDR||a.readUInt32LE(0)!==H.ZIP64SIG))throw We.Errors.INVALID_END();a.readUInt32LE(0)===H.ENDSIG?(t=a.readUInt16LE(H.ENDSUB),e=a.readUInt16LE(H.ENDTOT),r=a.readUInt32LE(H.ENDSIZ),n=a.readUInt32LE(H.ENDOFF),s=a.readUInt16LE(H.ENDCOM)):(t=We.readBigUInt64LE(a,H.ZIP64SUB),e=We.readBigUInt64LE(a,H.ZIP64TOT),r=We.readBigUInt64LE(a,H.ZIP64SIZB),n=We.readBigUInt64LE(a,H.ZIP64OFF),s=0)},"loadFromBinary"),toBinary:o(function(){if(!i()){var a=Buffer.alloc(H.ENDHDR+s);return a.writeUInt32LE(H.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,H.ENDSUB),a.writeUInt16LE(e,H.ENDTOT),a.writeUInt32LE(r,H.ENDSIZ),a.writeUInt32LE(n,H.ENDOFF),a.writeUInt16LE(s,H.ENDCOM),a.fill(" ",H.ENDHDR),a}var a=Buffer.alloc(this.mainHeaderSize);let c=0;a.writeUInt32LE(H.ZIP64SIG,c),We.writeBigUInt64LE(a,H.ZIP64HDR-H.ZIP64LEAD,c+H.ZIP64SIZE),a.writeUInt16LE(45,c+H.ZIP64VEM),a.writeUInt16LE(45,c+H.ZIP64VER),a.writeUInt32LE(0,c+H.ZIP64DSK),a.writeUInt32LE(0,c+H.ZIP64DSKDIR),We.writeBigUInt64LE(a,t,c+H.ZIP64SUB),We.writeBigUInt64LE(a,e,c+H.ZIP64TOT),We.writeBigUInt64LE(a,r,c+H.ZIP64SIZB),We.writeBigUInt64LE(a,n,c+H.ZIP64OFF);let l=n+r;return c+=H.ZIP64HDR,a.writeUInt32LE(H.END64SIG,c),a.writeUInt32LE(0,c+H.END64START),We.writeBigUInt64LE(a,l,c+H.END64OFF),a.writeUInt32LE(1,c+H.END64NUMDISKS),c+=H.END64HDR,a.writeUInt32LE(H.ENDSIG,c),a.writeUInt32LE(0,c+4),a.writeUInt16LE(Math.min(t,H.EF_ZIP64_OR_16),c+H.ENDSUB),a.writeUInt16LE(Math.min(e,H.EF_ZIP64_OR_16),c+H.ENDTOT),a.writeUInt32LE(Math.min(r,H.EF_ZIP64_OR_32),c+H.ENDSIZ),a.writeUInt32LE(Math.min(n,H.EF_ZIP64_OR_32),c+H.ENDOFF),a.writeUInt16LE(s,c+H.ENDCOM),a.fill(" ",c+H.ENDHDR),a},"toBinary"),toJSON:o(function(){let a=o(function(c,l){let u=c.toString(16).toUpperCase();for(;u.length<l;)u="0"+u;return"0x"+u},"offset");return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:a(n,4),commentLength:s}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ba=P(_a=>{_a.EntryHeader=Xf();_a.MainHeader=ep()});var rp=P((P5,tp)=>{tp.exports=function(t){var e=require("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:o(function(){return e.deflateRawSync(t,r)},"deflate"),deflateAsync:o(function(n){var s=e.createDeflateRaw(r),i=[],a=0;s.on("data",function(c){i.push(c),a+=c.length}),s.on("end",function(){var c=Buffer.alloc(a),l=0;c.fill(0);for(var u=0;u<i.length;u++){var d=i[u];d.copy(c,l),l+=d.length}n&&n(c)}),s.end(t)},"deflateAsync")}}});var sp=P((D5,np)=>{var a0=+(process?.versions?.node??"").split(".")[0]||0;np.exports=function(t,e){var r=require("zlib");let n=a0>=15&&e>0?{maxOutputLength:e}:{};return{inflate:o(function(){return r.inflateRawSync(t,n)},"inflate"),inflateAsync:o(function(s){var i=r.createInflateRaw(n),a=[],c=0;i.on("data",function(l){a.push(l),c+=l.length}),i.on("end",function(){var l=Buffer.alloc(c),u=0;l.fill(0);for(var d=0;d<a.length;d++){var p=a[d];p.copy(l,u),u+=p.length}s&&s(l)}),i.end(t)},"inflateAsync")}}});var lp=P((U5,cp)=>{"use strict";var{randomFillSync:ip}=require("crypto"),o0=rs(),c0=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),op=o((t,e)=>Math.imul(t,e)>>>0,"uMul"),ap=o((t,e)=>c0[(t^e)&255]^t>>>8,"crc32update"),Br=o(()=>typeof ip=="function"?ip(Buffer.alloc(12)):Br.node(),"genSalt");Br.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ns={genSalt:Br};function ss(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}o(ss,"Initkeys");ss.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ap(e[0],t),e[1]+=e[0]&255,e[1]=op(e[1],134775813)+1,e[2]=ap(e[2],e[1]>>>24),t};ss.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return op(t,t^1)>>8&255};function l0(t){let e=new ss(t);return function(r){let n=Buffer.alloc(r.length),s=0;for(let i of r)n[s++]=e.updateKeys(i^e.next());return n}}o(l0,"make_decrypter");function u0(t){let e=new ss(t);return function(r,n,s=0){n||(n=Buffer.alloc(r.length));for(let i of r){let a=e.next();n[s++]=i^a,e.updateKeys(i)}return n}}o(u0,"make_encrypter");function d0(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=l0(r),s=n(t.slice(0,12)),i=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==i)throw o0.WRONG_PASSWORD();return n(t.slice(12))}o(d0,"decrypt");function f0(t){Buffer.isBuffer(t)&&t.length>=12?ns.genSalt=function(){return t.slice(0,12)}:t==="node"?ns.genSalt=Br.node:ns.genSalt=Br}o(f0,"_salter");function p0(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=u0(r),i=ns.genSalt();i[11]=e.crc>>>24&255,n&&(i[10]=e.crc>>>16&255);let a=Buffer.alloc(t.length+12);return s(i,a),s(t,a,12)}o(p0,"encrypt");cp.exports={decrypt:d0,encrypt:p0,_salter:f0}});var up=P(is=>{is.Deflater=rp();is.Inflater=sp();is.ZipCrypto=lp()});var wa=P((j5,dp)=>{var X=sr(),m0=ba(),je=X.Constants,Ea=up();dp.exports=function(t,e){var r=new m0.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),i=!1,a=null,c=Buffer.alloc(0),l=Buffer.alloc(0),u=!0;let d=t,p=typeof d.decoder=="object"?d.decoder:X.decoder;u=p.hasOwnProperty("efs")?p.efs:!1;function _(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}o(_,"getCompressedDataFromZip");function g(m){let T=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return X.crc32(m)===T}o(g,"crc32OK");function y(m,T,A){if(typeof T>"u"&&typeof m=="string"&&(A=m,m=void 0),i)return m&&T&&T(Buffer.alloc(0),X.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var N=_();if(N.length===0)return m&&T&&T(N),N;if(r.encrypted){if(typeof A!="string"&&!Buffer.isBuffer(A))throw X.Errors.INVALID_PASS_PARAM();N=Ea.ZipCrypto.decrypt(N,r,A)}var O;switch(r.method){case X.Constants.STORED:if(O=Buffer.alloc(N.length),N.copy(O),g(O))return m&&T&&T(O),O;throw m&&T&&T(O,X.Errors.BAD_CRC()),X.Errors.BAD_CRC();case X.Constants.DEFLATED:var b=new Ea.Inflater(N,r.size);if(m)b.inflateAsync(function(j){T&&(g(j)?T(j):T(j,X.Errors.BAD_CRC()))});else{if(O=b.inflate(),!g(O))throw X.Errors.BAD_CRC(`"${p.decode(n)}"`);return O}break;default:throw m&&T&&T(Buffer.alloc(0),X.Errors.UNKNOWN_METHOD()),X.Errors.UNKNOWN_METHOD()}}o(y,"decompress");function E(m,T){if((!a||!a.length)&&Buffer.isBuffer(e))return m&&T&&T(_()),_();if(a.length&&!i){var A;switch(r.method){case X.Constants.STORED:return r.compressedSize=r.size,A=Buffer.alloc(a.length),a.copy(A),m&&T&&T(A),A;default:case X.Constants.DEFLATED:var N=new Ea.Deflater(a);if(m)N.deflateAsync(function(b){A=Buffer.alloc(b.length),r.compressedSize=b.length,b.copy(A),T&&T(A)});else{var O=N.deflate();return r.compressedSize=O.length,O}N=null;break}}else if(m&&T)T(Buffer.alloc(0));else return Buffer.alloc(0)}o(E,"compress");function w(m,T){return X.readBigUInt64LE(m,T)}o(w,"readUInt64LE");function S(m){try{for(var T=0,A,N,O;T+4<m.length;)A=m.readUInt16LE(T),T+=2,N=m.readUInt16LE(T),T+=2,O=m.slice(T,T+N),T+=N,je.ID_ZIP64===A&&I(O)}catch{throw X.Errors.EXTRA_FIELD_PARSE_ERROR()}}o(S,"parseExtra");function I(m){var T,A,N,O;m.length>=je.EF_ZIP64_SCOMP&&(T=w(m,je.EF_ZIP64_SUNCOMP),r.size===je.EF_ZIP64_OR_32&&(r.size=T)),m.length>=je.EF_ZIP64_RHO&&(A=w(m,je.EF_ZIP64_SCOMP),r.compressedSize===je.EF_ZIP64_OR_32&&(r.compressedSize=A)),m.length>=je.EF_ZIP64_DSN&&(N=w(m,je.EF_ZIP64_RHO),r.offset===je.EF_ZIP64_OR_32&&(r.offset=N)),m.length>=je.EF_ZIP64_DSN+4&&(O=m.readUInt32LE(je.EF_ZIP64_DSN),r.diskNumStart===je.EF_ZIP64_OR_16&&(r.diskNumStart=O))}return o(I,"parseZip64ExtendedInformation"),{get entryName(){return p.decode(n)},get rawEntryName(){return n},set entryName(m){n=X.toBuffer(m,p.encode);var T=n[n.length-1];i=T===47||T===92,r.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return c},set extra(m){c=m,r.extraLength=m.length,S(m)},get comment(){return p.decode(s)},set comment(m){if(s=X.toBuffer(m,p.encode),r.commentLength=s.length,s.length>65535)throw X.Errors.COMMENT_TOO_LONG()},get name(){let m=p.decode(n);return i?m.replace(/[/\\]$/,"").split("/").pop():m.split("/").pop()},get isDirectory(){return i},getCompressedData:o(function(){return E(!1,null)},"getCompressedData"),getCompressedDataAsync:o(function(m){E(!0,m)},"getCompressedDataAsync"),setData:o(function(m){a=X.toBuffer(m,X.decoder.encode),!i&&a.length?(r.size=a.length,r.method=X.Constants.DEFLATED,r.crc=X.crc32(m),r.changed=!0):r.method=X.Constants.STORED},"setData"),getData:o(function(m){return r.changed?a:y(!1,null,m)},"getData"),getDataAsync:o(function(m,T){r.changed?m(a):y(!0,m,T)},"getDataAsync"),set attr(m){r.attr=m},get attr(){return r.attr},set header(m){r.loadFromBinary(m)},get header(){return r},packCentralHeader:o(function(){r.flags_efs=this.efs,r.extraLength=c.length;var m=r.centralHeaderToBinary(),T=X.Constants.CENHDR;return n.copy(m,T),T+=n.length,c.copy(m,T),T+=r.extraLength,s.copy(m,T),m},"packCentralHeader"),packLocalHeader:o(function(){let m=0;r.flags_efs=this.efs,r.extraLocalLength=l.length;let T=r.localHeaderToBinary(),A=Buffer.alloc(T.length+n.length+r.extraLocalLength);return T.copy(A,m),m+=T.length,n.copy(A,m),m+=n.length,l.copy(A,m),m+=l.length,A},"packLocalHeader"),toJSON:o(function(){let m=o(function(T){return"<"+(T&&T.length+" bytes buffer"||"null")+">"},"bytes");return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:m(e),data:m(a)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var mp=P((G5,pp)=>{var fp=wa(),h0=ba(),Ne=sr();pp.exports=function(t,e){var r=[],n=Object.create(null),s=Buffer.alloc(0),i=new h0.MainHeader,a=!1,c=null;let l=new Set,u=e,{noSort:d,decoder:p}=u;t?y(u.readEntries):a=!0;function _(){let w=new Set;for(let S of Object.keys(n)){let I=S.split("/");if(I.pop(),!!I.length)for(let m=0;m<I.length;m++){let T=I.slice(0,m+1).join("/")+"/";w.add(T)}}for(let S of w)if(!(S in n)){let I=new fp(u);I.entryName=S,I.attr=16,I.temporary=!0,r.push(I),n[I.entryName]=I,l.add(I)}}o(_,"makeTemporaryFolders");function g(){if(a=!0,n=Object.create(null),i.diskEntries>(t.length-i.offset)/Ne.Constants.CENHDR)throw Ne.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(i.diskEntries);for(var w=i.offset,S=0;S<r.length;S++){var I=w,m=new fp(u,t);m.header=t.slice(I,I+=Ne.Constants.CENHDR),m.entryName=t.slice(I,I+=m.header.fileNameLength),m.header.extraLength&&(m.extra=t.slice(I,I+=m.header.extraLength)),m.header.commentLength&&(m.comment=t.slice(I,I+m.header.commentLength)),w+=m.header.centralHeaderSize,r[S]=m,n[m.entryName]=m}l.clear(),_()}o(g,"readEntries");function y(w){var S=t.length-Ne.Constants.ENDHDR,I=Math.max(0,S-65535),m=I,T=t.length,A=-1,N=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(I=0),S;S>=m;S--)if(t[S]===80){if(t.readUInt32LE(S)===Ne.Constants.ENDSIG){A=S,N=S,T=S+Ne.Constants.ENDHDR,m=S-Ne.Constants.END64HDR;continue}if(t.readUInt32LE(S)===Ne.Constants.END64SIG){m=I;continue}if(t.readUInt32LE(S)===Ne.Constants.ZIP64SIG){A=S,T=S+Ne.readBigUInt64LE(t,S+Ne.Constants.ZIP64SIZE)+Ne.Constants.ZIP64LEAD;break}}if(A==-1)throw Ne.Errors.INVALID_FORMAT();i.loadFromBinary(t.slice(A,T)),i.commentLength&&(s=t.slice(N+Ne.Constants.ENDHDR)),w&&g()}o(y,"readMainHeader");function E(){r.length>1&&!d&&(r=r.map(w=>({entry:w,key:w.entryName.toLowerCase()})).sort((w,S)=>w.key.localeCompare(S.key)).map(w=>w.entry))}return o(E,"sortEntries"),{get entries(){return a||g(),r.filter(w=>!l.has(w))},get comment(){return p.decode(s)},set comment(w){s=Ne.toBuffer(w,p.encode),i.commentLength=s.length},getEntryCount:o(function(){return a?r.length:i.diskEntries},"getEntryCount"),forEach:o(function(w){this.entries.forEach(w)},"forEach"),getEntry:o(function(w){return a||g(),n[w]||null},"getEntry"),setEntry:o(function(w){a||g(),r.push(w),n[w.entryName]=w,i.totalEntries=r.length},"setEntry"),deleteFile:o(function(w,S=!0){a||g();let I=n[w];this.getEntryChildren(I,S).map(T=>T.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:o(function(w){a||g();let S=n[w],I=r.indexOf(S);I>=0&&(r.splice(I,1),delete n[w],i.totalEntries=r.length)},"deleteEntry"),getEntryChildren:o(function(w,S=!0){if(a||g(),typeof w=="object")if(w.isDirectory&&S){let I=[],m=w.entryName;for(let T of r)T.entryName.startsWith(m)&&I.push(T);return I}else return[w];return[]},"getEntryChildren"),getChildCount:o(function(w){if(w&&w.isDirectory){let S=this.getEntryChildren(w);return S.includes(w)?S.length-1:S.length}return 0},"getChildCount"),compressToBuffer:o(function(){a||g(),E();let w=[],S=[],I=0,m=0;i.size=0,i.offset=0;let T=0;for(let O of this.entries){let b=O.getCompressedData();O.header.offset=m;let j=O.packLocalHeader(),G=j.length+b.length;m+=G,w.push(j),w.push(b);let B=O.packCentralHeader();S.push(B),i.size+=B.length,I+=G+B.length,T++}I+=i.mainHeaderSize,i.offset=m,i.totalEntries=T,m=0;let A=Buffer.alloc(I);for(let O of w)O.copy(A,m),m+=O.length;for(let O of S)O.copy(A,m),m+=O.length;let N=i.toBinary();return s&&s.copy(N,N.length-s.length),N.copy(A,m),t=A,a=!1,A},"compressToBuffer"),toAsyncBuffer:o(function(w,S,I,m){try{a||g(),E();let T=[],A=[],N=0,O=0,b=0;i.size=0,i.offset=0;let j=o(function(G){if(G.length>0){let B=G.shift(),Z=B.entryName+B.extra.toString();I&&I(Z),B.getCompressedDataAsync(function(ce){m&&m(Z),B.header.offset=O;let ke=B.packLocalHeader(),xt=ke.length+ce.length;O+=xt,T.push(ke),T.push(ce);let K=B.packCentralHeader();A.push(K),i.size+=K.length,N+=xt+K.length,b++,j(G)})}else{N+=i.mainHeaderSize,i.offset=O,i.totalEntries=b,O=0;let B=Buffer.alloc(N);T.forEach(function(ce){ce.copy(B,O),O+=ce.length}),A.forEach(function(ce){ce.copy(B,O),O+=ce.length});let Z=i.toBinary();s&&s.copy(Z,Z.length-s.length),Z.copy(B,O),t=B,a=!1,w(B)}},"compress2Buffer");j(Array.from(this.entries))}catch(T){S(T)}},"toAsyncBuffer")}}});var yp=P((V5,gp)=>{var ae=sr(),ie=require("path"),g0=wa(),y0=mp(),jt=o((...t)=>ae.findLast(t,e=>typeof e=="boolean"),"get_Bool"),hp=o((...t)=>ae.findLast(t,e=>typeof e=="string"),"get_Str"),_0=o((...t)=>ae.findLast(t,e=>typeof e=="function"),"get_Fun"),b0={noSort:!1,readEntries:!1,method:ae.Constants.NONE,fs:null};gp.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),b0);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=ae.Constants.BUFFER,t=void 0)),Object.assign(n,e);let s=new ae(n),i=o(y=>{y.filter(E=>E.attr).sort((E,w)=>w.path.length-E.path.length).forEach(E=>s.fs.chmodSync(E.path,E.attr))},"applyDirAttributes");if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=ae.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))n.method=ae.Constants.FILE,n.filename=t,r=s.fs.readFileSync(t);else throw ae.Errors.INVALID_FILENAME();let a=new y0(r,n),{canonical:c,sanitize:l,zipnamefix:u}=ae;function d(y){if(y&&a){var E;if(typeof y=="string"&&(E=a.getEntry(ie.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(E=a.getEntry(y.entryName)),E)return E}return null}o(d,"getEntry");function p(y){let{join:E,normalize:w,sep:S}=ie.posix;return E(ie.isAbsolute(y)?"/":".",w(S+y.split("\\").join(S)+S))}o(p,"fixPath");function _(y){return y instanceof RegExp?(function(E){return function(w){return E.test(w)}})(y):typeof y!="function"?()=>!0:y}o(_,"filenameFilter");let g=o((y,E)=>{let w=E.slice(-1);return w=w===s.sep?s.sep:"",ie.relative(y,E)+w},"relativePath");return{readFile:o(function(y,E){var w=d(y);return w&&w.getData(E)||null},"readFile"),childCount:o(function(y){let E=d(y);if(E)return a.getChildCount(E)},"childCount"),readFileAsync:o(function(y,E){var w=d(y);w?w.getDataAsync(E):E(null,"getEntry failed for:"+y)},"readFileAsync"),readAsText:o(function(y,E){var w=d(y);if(w){var S=w.getData();if(S&&S.length)return S.toString(E||"utf8")}return""},"readAsText"),readAsTextAsync:o(function(y,E,w){var S=d(y);S?S.getDataAsync(function(I,m){if(m){E(I,m);return}I&&I.length?E(I.toString(w||"utf8")):E("")}):E("")},"readAsTextAsync"),deleteFile:o(function(y,E=!0){var w=d(y);w&&a.deleteFile(w.entryName,E)},"deleteFile"),deleteEntry:o(function(y){var E=d(y);E&&a.deleteEntry(E.entryName)},"deleteEntry"),addZipComment:o(function(y){a.comment=y},"addZipComment"),getZipComment:o(function(){return a.comment||""},"getZipComment"),addZipEntryComment:o(function(y,E){var w=d(y);w&&(w.comment=E)},"addZipEntryComment"),getZipEntryComment:o(function(y){var E=d(y);return E&&E.comment||""},"getZipEntryComment"),updateFile:o(function(y,E){var w=d(y);w&&w.setData(E)},"updateFile"),addLocalFile:o(function(y,E,w,S){if(s.fs.existsSync(y)){E=E?p(E):"";let I=ie.win32.basename(ie.win32.normalize(y));E+=w||I;let m=s.fs.statSync(y),T=m.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);m.isDirectory()&&(E+=s.sep),this.addFile(E,T,S,m)}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFile"),addLocalFileAsync:o(function(y,E){y=typeof y=="object"?y:{localPath:y};let w=ie.resolve(y.localPath),{comment:S}=y,{zipPath:I,zipName:m}=y,T=this;s.fs.stat(w,function(A,N){if(A)return E(A,!1);I=I?p(I):"";let O=ie.win32.basename(ie.win32.normalize(w));if(I+=m||O,N.isFile())s.fs.readFile(w,function(b,j){return b?E(b,!1):(T.addFile(I,j,S,N),setImmediate(E,void 0,!0))});else if(N.isDirectory())return I+=s.sep,T.addFile(I,Buffer.alloc(0),S,N),setImmediate(E,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:o(function(y,E,w){if(w=_(w),E=E?p(E):"",y=ie.normalize(y),s.fs.existsSync(y)){let S=s.findFiles(y),I=this;if(S.length)for(let m of S){let T=ie.join(E,g(y,m));w(T)&&I.addLocalFile(m,ie.dirname(T))}}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFolder"),addLocalFolderAsync:o(function(y,E,w,S){S=_(S),w=w?p(w):"",y=ie.normalize(y);var I=this;s.fs.open(y,"r",function(m){if(m&&m.code==="ENOENT")E(void 0,ae.Errors.FILE_NOT_FOUND(y));else if(m)E(void 0,m);else{var T=s.findFiles(y),A=-1,N=o(function(){if(A+=1,A<T.length){var O=T[A],b=g(y,O).split("\\").join("/");b=b.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),S(b)?s.fs.stat(O,function(j,G){j&&E(void 0,j),G.isFile()?s.fs.readFile(O,function(B,Z){B?E(void 0,B):(I.addFile(w+b,Z,"",G),N())}):(I.addFile(w+b+"/",Buffer.alloc(0),"",G),N())}):process.nextTick(()=>{N()})}else E(!0,void 0)},"next");N()}})},"addLocalFolderAsync"),addLocalFolderAsync2:o(function(y,E){let w=this;y=typeof y=="object"?y:{localPath:y};let S=ie.resolve(p(y.localPath)),{zipPath:I,filter:m,namefix:T}=y;m instanceof RegExp?m=(function(O){return function(b){return O.test(b)}})(m):typeof m!="function"&&(m=o(function(){return!0},"filter")),I=I?p(I):"",T==="latin1"&&(T=o(O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof T!="function"&&(T=o(O=>O,"namefix"));let A=o(O=>ie.join(I,T(g(S,O))),"relPathFix"),N=o(O=>ie.win32.basename(ie.win32.normalize(T(O))),"fileNameFix");s.fs.open(S,"r",function(O){O&&O.code==="ENOENT"?E(void 0,ae.Errors.FILE_NOT_FOUND(S)):O?E(void 0,O):s.findFilesAsync(S,function(b,j){if(b)return E(b);j=j.filter(G=>m(A(G))),j.length||E(void 0,!1),setImmediate(j.reverse().reduce(function(G,B){return function(Z,ce){if(Z||ce===!1)return setImmediate(G,Z,!1);w.addLocalFileAsync({localPath:B,zipPath:ie.dirname(A(B)),zipName:N(B)},G)}},E))})})},"addLocalFolderAsync2"),addLocalFolderPromise:o(function(y,E){return new Promise((w,S)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},E),(I,m)=>{I&&S(I),m&&w(this)})})},"addLocalFolderPromise"),addFile:o(function(y,E,w,S){y=u(y);let I=d(y),m=I!=null;m||(I=new g0(n),I.entryName=y),I.comment=w||"";let T=typeof S=="object"&&S instanceof s.fs.Stats;T&&(I.header.time=S.mtime);var A=I.isDirectory?16:0;let N=I.isDirectory?16384:32768;return T?N|=4095&S.mode:typeof S=="number"?N|=4095&S:N|=I.isDirectory?493:420,A=(A|N<<16)>>>0,I.attr=A,I.setData(E),m||a.setEntry(I),I},"addFile"),getEntries:o(function(y){return a.password=y,a?a.entries:[]},"getEntries"),getEntry:o(function(y){return d(y)},"getEntry"),getEntryCount:o(function(){return a.getEntryCount()},"getEntryCount"),forEach:o(function(y){return a.forEach(y)},"forEach"),extractEntryTo:o(function(y,E,w,S,I,m){S=jt(!1,S),I=jt(!1,I),w=jt(!0,w),m=hp(I,m);var T=d(y);if(!T)throw ae.Errors.NO_ENTRY();var A=c(T.entryName),N=l(E,m&&!T.isDirectory?c(m):w?A:ie.basename(A));if(T.isDirectory){var O=a.getEntryChildren(T);return O.forEach(function(G){if(G.isDirectory)return;var B=G.getData();if(!B)throw ae.Errors.CANT_EXTRACT_FILE();var Z=c(w?G.entryName:G.entryName.substring(T.entryName.length)),ce=l(E,Z);let ke=I?G.header.fileAttr:void 0;s.writeFileTo(ce,B,S,ke)}),!0}var b=T.getData(a.password);if(!b)throw ae.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(N)&&!S)throw ae.Errors.CANT_OVERRIDE();let j=I?y.header.fileAttr:void 0;return s.writeFileTo(N,b,S,j),!0},"extractEntryTo"),test:o(function(y){if(!a)return!1;for(var E of a.entries)try{if(E.isDirectory)continue;var w=E.getData(y);if(!w)return!1}catch{return!1}return!0},"test"),extractAllTo:o(function(y,E,w,S){if(w=jt(!1,w),S=hp(w,S),E=jt(!1,E),!a)throw ae.Errors.NO_ZIP();let I=[];a.entries.forEach(function(m){var T=l(y,c(m.entryName));if(m.isDirectory){s.makeDir(T),w&&I.push({path:T,attr:m.header.fileAttr});return}var A=m.getData(S);if(!A)throw ae.Errors.CANT_EXTRACT_FILE();let N=w?m.header.fileAttr:void 0;s.writeFileTo(T,A,E,N);try{s.fs.utimesSync(T,m.header.time,m.header.time)}catch{}}),i(I)},"extractAllTo"),extractAllToAsync:o(function(y,E,w,S){if(S=_0(E,w,S),w=jt(!1,w),E=jt(!1,E),!S)return new Promise((b,j)=>{this.extractAllToAsync(y,E,w,function(G){G?j(G):b(this)})});if(!a){S(ae.Errors.NO_ZIP());return}y=ie.resolve(y);let I=o(b=>l(y,ie.normalize(c(b.entryName))),"getPath"),m=o((b,j)=>new Error(b+': "'+j+'"'),"getError"),T=[],A=[];a.entries.forEach(b=>{b.isDirectory?T.push(b):A.push(b)});let N=[];for(let b of T){let j=I(b),G=w?b.header.fileAttr:void 0;try{s.makeDir(j)}catch{S(m("Unable to create folder",j));continue}G&&N.push({path:j,attr:G});try{s.fs.utimesSync(j,b.header.time,b.header.time)}catch{}}let O=o(b=>{if(!b)try{i(N)}catch(j){return S(m("Unable to set folder permissions",j.path||""))}S(b)},"done");A.reverse().reduce(function(b,j){return function(G){if(G)b(G);else{let B=ie.normalize(c(j.entryName)),Z=l(y,B);j.getDataAsync(function(ce,ke){if(ke)b(ke);else if(!ce)b(ae.Errors.CANT_EXTRACT_FILE());else{let xt=w?j.header.fileAttr:void 0;s.writeFileToAsync(Z,ce,E,xt,function(K){if(!K)return b(m("Unable to write file",Z));s.fs.utimes(Z,j.header.time,j.header.time,function(){b()})})}})}}},O)()},"extractAllToAsync"),writeZip:o(function(y,E){if(arguments.length===1&&typeof y=="function"&&(E=y,y=""),!y&&n.filename&&(y=n.filename),!!y){var w=a.compressToBuffer();if(w){var S=s.writeFileTo(y,w,!0);typeof E=="function"&&E(S?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:o(function(y,E){let{overwrite:w,perm:S}=Object.assign({overwrite:!0},E);return new Promise((I,m)=>{!y&&n.filename&&(y=n.filename),y||m("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(T=>{let A=o(N=>N?I(N):m("ADM-ZIP: Wasn't able to write zip file"),"ret");s.writeFileToAsync(y,T,w,S,A)},m)})},"writeZipPromise"),toBufferPromise:o(function(){return new Promise((y,E)=>{a.toAsyncBuffer(y,E)})},"toBufferPromise"),toBuffer:o(function(y,E,w,S){return typeof y=="function"?(a.toAsyncBuffer(y,E,w,S),null):a.compressToBuffer()},"toBuffer")}}});var Sp=P((Z5,yt)=>{var va=require("fs"),os=require("path"),w0=require("os"),T0=require("crypto"),bp=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function v0(){return bp[Math.floor(Math.random()*bp.length)]}o(v0,"_getRandomTip");function ir(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(ir,"parseBoolean");function S0(){return process.stdout.isTTY}o(S0,"supportsAnsi");function I0(t){return S0()?`\x1B[2m${t}\x1B[0m`:t}o(I0,"dim");var x0=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function A0(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
4
|
-
`);let n;for(;(n=
|
|
5
|
-
`),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(A0,"parse");function R0(t){t=t||{};let e=vp(t);t.path=e;let r=me.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=Tp(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=O0(r,c);i=me.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return me.parse(i)}o(R0,"_parseVault");function C0(t){console.error(`\u26A0 ${t}`)}o(C0,"_warn");function jr(t){console.log(`\u2506 ${t}`)}o(jr,"_debug");function wp(t){console.log(`\u25C7 ${t}`)}o(wp,"_log");function Tp(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(Tp,"_dotenvKey");function O0(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(O0,"_instructions");function vp(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)va.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=os.resolve(process.cwd(),".env.vault");return va.existsSync(e)?e:null}o(vp,"_vaultPath");function Ep(t){return t[0]==="~"?os.join(w0.homedir(),t.slice(1)):t}o(Ep,"_resolveHome");function N0(t){let e=ir(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=ir(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&wp("loading env from encrypted .env.vault");let n=me._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),me.populate(s,n,t),{parsed:n}}o(N0,"_configVault");function M0(t){let e=os.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=ir(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=ir(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&jr("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[Ep(t.path)];else{a=[];for(let d of t.path)a.push(Ep(d))}let c,l={};for(let d of a)try{let p=me.parse(va.readFileSync(d,{encoding:r}));me.populate(l,p,t)}catch(p){s&&jr(`failed to load ${d} ${p.message}`),c=p}let u=me.populate(n,l,t);if(s=ir(n.DOTENV_CONFIG_DEBUG||s),i=ir(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,p=[];for(let _ of a)try{let g=os.relative(process.cwd(),_);p.push(g)}catch(g){s&&jr(`failed to load ${_} ${g.message}`),c=g}wp(`injected env (${d}) from ${p.join(",")} ${I0(`// tip: ${v0()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o(M0,"configDotenv");function k0(t){if(Tp(t).length===0)return me.configDotenv(t);let e=vp(t);return e?me._configVault(t):(C0(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),me.configDotenv(t))}o(k0,"config");function P0(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=T0.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o(P0,"decrypt");function L0(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&jr(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(L0,"populate");var me={configDotenv:M0,_configVault:N0,_parseVault:R0,config:k0,decrypt:P0,parse:A0,populate:L0};yt.exports.configDotenv=me.configDotenv;yt.exports._configVault=me._configVault;yt.exports._parseVault=me._parseVault;yt.exports.config=me.config;yt.exports.decrypt=me.decrypt;yt.exports.parse=me.parse;yt.exports.populate=me.populate;yt.exports=me});var ZT={};Nm(ZT,{TestRunMonitor:()=>Ts});module.exports=Mm(ZT);var As=o(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");var i5=require("@playwright/test");var A3=require("@playwright/test");var Mv=require("@playwright/test");var Rv=require("@playwright/test");var to=Object.defineProperty,W=o((t,e)=>{let r={};for(var n in t)to(r,n,{get:t[n],enumerable:!0});return e||to(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function ro(t){let e=Symbol.for(t);return{brand(r,n){let s=n?Symbol.for(`${t}.${n}`):e;class i extends r{static{o(this,"_Branded")}[s]=!0;constructor(...c){super(...c)}static isInstance(c){return typeof c=="object"&&c!==null&&s in c&&c[s]===!0}}return Object.defineProperty(i,"name",{value:r.name}),i},sub(r){return ro(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}o(ro,"createNamespace");var no=ro("langchain");var Rs=no.sub("error"),so=class extends Rs.brand(Error){static{o(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Pm=class extends Rs.brand(so,"model-abort"){static{o(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},Hv=class io extends Rs.brand(so,"context-overflow"){static{o(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new io(e.message);return r.cause=e,r}};var Lm=/([A-Z]+)([A-Z][a-z0-9]+)/g,Dm=/([a-z0-9])([A-Z])/g,$m=/[-_\s]+/g;function Um(t){return t.replace(Lm,"$1_$2").replace(Dm,"$1_$2").replace($m,"_").toLowerCase()}o(Um,"snakeCase");function ao(t,e){return e?.[t]||Um(t)}o(ao,"keyToJson");function oo(t,e,r){let n={};for(let s in t)Object.hasOwn(t,s)&&(n[e(s,r)]=t[s]);return n}o(oo,"mapKeys");var Fm="__lc_escaped__";function Bm(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}o(Bm,"needsEscaping");function jm(t){return{[Fm]:t}}o(jm,"escapeObject");function Hm(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}o(Hm,"isSerializableLike");function Gm(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}o(Gm,"createNotImplemented");function qr(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Gm(t);if(Hm(t))return t;e.add(t);let r=t;if(Bm(r))return e.delete(t),jm(r);let n={};for(let[s,i]of Object.entries(r))n[s]=qr(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>qr(r,e)):t}o(qr,"escapeIfNeeded");function co(t){return Array.isArray(t)?[...t]:{...t}}o(co,"shallowCopy");function zm(t,e){let r=co(t);for(let[n,s]of Object.entries(e)){let[i,...a]=n.split(".").reverse(),c=r;for(let l of a.reverse()){if(c[l]===void 0)break;c[l]=co(c[l]),c=c[l]}c[i]!==void 0&&(c[i]={lc:1,type:"secret",id:[s]})}return r}o(zm,"replaceSecrets");function Cs(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}o(Cs,"get_lc_unique_name");var Ot=class lo{static{o(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Cs(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof lo||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((c,l)=>(c[l]=l in this?this[l]:this.lc_kwargs[l],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let l=this,u=n,[d,...p]=c.split(".").reverse();for(let _ of p.reverse()){if(!(_ in l)||l[_]===void 0)return;(!(_ in u)||u[_]===void 0)&&(typeof l[_]=="object"&&l[_]!=null?u[_]={}:Array.isArray(l[_])&&(u[_]=[])),l=l[_],u=u[_]}d in l&&l[d]!==void 0&&(u[d]=u[d]||l[d])});let s={},i=new WeakSet;i.add(this);for(let[c,l]of Object.entries(n))s[c]=qr(l,i);let a=oo(Object.keys(r).length?zm(s,r):s,ao,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function fr(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}o(fr,"isDataContentBlock");function Wr(t){return fr(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}o(Wr,"isURLContentBlock");function Kr(t){return fr(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}o(Kr,"isBase64ContentBlock");function Os(t){return fr(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}o(Os,"isIDContentBlock");function Zr({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let s=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:s}}}o(Zr,"parseBase64DataUrl");function k(t,e){return F(t)&&t.type===e}o(k,"_isContentBlock");function F(t){return typeof t=="object"&&t!==null}o(F,"_isObject");function fe(t){return Array.isArray(t)}o(fe,"_isArray");function x(t){return typeof t=="string"}o(x,"_isString");function Ue(t){return typeof t=="number"}o(Ue,"_isNumber");function Jr(t){return t instanceof Uint8Array}o(Jr,"_isBytesArray");function Ns(t){try{return JSON.parse(t)}catch{return}}o(Ns,"safeParseJson");var Fe=o(t=>t(),"iife");function Vm(t){if(t.type==="char_location"&&x(t.document_title)&&Ue(t.start_char_index)&&Ue(t.end_char_index)&&x(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="page_location"&&x(t.document_title)&&Ue(t.start_page_number)&&Ue(t.end_page_number)&&x(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="content_block_location"&&x(t.document_title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="web_search_result_location"&&x(t.url)&&x(t.title)&&x(t.encrypted_index)&&x(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:s}}if(t.type==="search_result_location"&&x(t.source)&&x(t.title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:s,cited_text:i,...a}=t;return{...a,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:s,citedText:i}}}o(Vm,"convertAnthropicAnnotation");function fo(t){if(k(t,"document")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&x(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(k(t,"image")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}o(fo,"convertToV1FromAnthropicContentBlock");function po(t){function*e(){for(let r of t){let n=fo(r);n?yield n:yield r}}return o(e,"iterateContent"),Array.from(e())}o(po,"convertToV1FromAnthropicInput");function uo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){let{text:s,citations:i,...a}=n;if(fe(i)&&i.length){let c=i.reduce((l,u)=>{let d=Vm(u);return d?[...l,d]:l},[]);yield{...a,type:"text",text:s,annotations:c};continue}else{yield{...a,type:"text",text:s};continue}}else if(k(n,"thinking")&&x(n.thinking)){let{thinking:s,signature:i,...a}=n;yield{...a,type:"reasoning",reasoning:s,signature:i};continue}else if(k(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_use")&&x(n.name)&&x(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(k(n,"input_json_delta")){if(qm(t)&&t.tool_call_chunks?.length){let s=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(k(n,"server_tool_use")&&x(n.name)&&x(n.id)){let{name:s,id:i}=n;if(s==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.query))return n.input.query;if(x(n.partial_json)){let a=Ns(n.partial_json);if(a?.query)return a.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.code))return n.input.code;if(x(n.partial_json)){let a=Ns(n.partial_json);if(a?.code)return a.code}return""})}};continue}}else if(k(n,"web_search_tool_result")&&x(n.tool_use_id)&&fe(n.content)){let{content:s,tool_use_id:i}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:s.reduce((a,c)=>k(c,"web_search_result")?[...a,c.url]:a,[])}};continue}else if(k(n,"code_execution_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(k(n,"mcp_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(k(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(k(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let s=fo(n);if(s){yield s;continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(uo,"convertToV1FromAnthropicMessage");var mo={translateContent:uo,translateContentChunk:uo};function qm(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}o(qm,"_isAIMessageChunk");function Wm(t){return Wr(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Kr(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:Os(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}o(Wm,"convertToV1FromDataContentBlock");function ho(t){return t.map(Wm)}o(ho,"convertToV1FromDataContent");function go(t){return!!(k(t,"image_url")&&F(t.image_url)||k(t,"input_audio")&&F(t.input_audio)||k(t,"file")&&F(t.file))}o(go,"isOpenAIDataBlock");function yo(t){if(k(t,"image_url")&&F(t.image_url)&&x(t.image_url.url)){let e=Zr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(k(t,"input_audio")&&F(t.input_audio)&&x(t.input_audio.data)&&x(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(k(t,"file")&&F(t.file)&&x(t.file.data)){let e=Zr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(x(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}o(yo,"convertToV1FromOpenAIDataBlock");function Km(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Km,"convertToV1FromChatCompletions");function Zm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Zm,"convertToV1FromChatCompletionsChunk");function Yr(t){let e=[];for(let r of t)go(r)?e.push(yo(r)):e.push(r);return e}o(Yr,"convertToV1FromChatCompletionsInput");function Jm(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:s}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:s}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}o(Jm,"convertResponsesAnnotation");function _o(t){function*e(){F(t.additional_kwargs?.reasoning)&&fe(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,s)=>F(s)&&x(s.text)?`${n}${s.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(k(n,"text")){let{text:s,annotations:i,phase:a,extras:c,...l}=n,u=F(c)?{...c}:{};x(a)&&(u.phase=a);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(i)?yield{...l,...d,type:"text",text:String(s),annotations:i.map(Jm)}:yield{...l,...d,type:"text",text:String(s)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(F(t.additional_kwargs)&&fe(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(k(n,"web_search_call")){let s={};if(F(n.action)&&x(n.action.query)&&(s.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:s},n.status==="completed"||n.status==="failed"){let i={};F(n.action)&&(i.action=n.action),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:i}}continue}else if(k(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:fe(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:fe(n.results)?{results:n.results}:{}});continue}else if(k(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(k(n,"code_interpreter_call")){if(x(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),fe(n.outputs)){let s=Fe(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let i of n.outputs)if(k(i,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(i.logs),stdout:[0,void 0].includes(s)?String(i.logs):void 0}};continue}}continue}else if(k(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(k(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(k(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_search_call")){let s={};F(n.arguments)&&Object.assign(s,n.arguments);let i={};x(n.execution)&&(i.execution=n.execution),x(n.status)&&(i.status=n.status),x(n.call_id)&&(i.call_id=n.call_id),yield{id:x(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:s,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(k(n,"tool_search_output")){let s={name:"tool_search"};x(n.execution)&&(s.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:fe(n.tools)?n.tools:[]},extras:s};continue}else if(k(n,"image_generation_call")){x(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:x(n.id)?n.id:void 0,metadata:{status:x(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}F(n)&&(yield{type:"non_standard",value:n})}}return o(e,"iterateContent"),Array.from(e())}o(_o,"convertToV1FromResponses");function Ym(t){function*e(){yield*_o(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return o(e,"iterateContent"),Array.from(e())}o(Ym,"convertToV1FromResponsesChunk");var bo={translateContent:o(t=>typeof t.content=="string"?Km(t):_o(t),"translateContent"),translateContentChunk:o(t=>typeof t.content=="string"?Zm(t):Ym(t),"translateContentChunk")};function Ms(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}o(Ms,"isMessage");function Eo(t,e="pretty"){return e==="pretty"?Xm(t):JSON.stringify(t)}o(Eo,"convertToFormattedString");function Xm(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),s="=".repeat(n),i=r.length%2===0?s:`${s}=`;if(e.push(`${s}${r}${i}`),t.type==="ai"){let a=t;if(a.tool_calls&&a.tool_calls.length>0){e.push("Tool Calls:");for(let c of a.tool_calls){e.push(` ${c.name} (${c.id})`),e.push(` Call ID: ${c.id}`),e.push(" Args:");for(let[l,u]of Object.entries(c.args))e.push(` ${l}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){let a=t;a.name&&e.push(`Name: ${a.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
6
|
-
`)}o(Xm,"convertToPrettyString");var ks=Symbol.for("langchain.message");function Qm(t,e){function r(n,s){if(typeof n!="object"||n===null||n===void 0)return n;if(s>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,s+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],s+1);return i}return o(r,"helper"),JSON.stringify(r(t,0),null,2)}o(Qm,"stringifyWithDepthLimit");var ft=class extends Ot{static{o(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[ks]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[ho,Yr,po].reduce((e,r)=>r(e),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&ks in t&&t[ks]===!0&&Ms(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=Qm(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Eo(this,t)}};function Ps(t){let e=[],r=[];for(let n of t)if(n.function){let s=n.function.name;try{let i=JSON.parse(n.function.arguments);e.push({name:s||"",args:i||{},id:n.id})}catch{r.push({name:s,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}o(Ps,"defaultToolCallParser");function Ls(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}o(Ls,"convertFileFormatToMimeType");function rh(t){if(F(t.document)&&F(t.document.source)){let e=Ls(F(t.document)&&x(t.document.format)?t.document.format:"");if(F(t.document.source)){if(F(t.document.source.s3Location)&&x(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Jr(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(x(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(fe(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>F(n)&&x(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}o(rh,"convertConverseDocumentBlock");function nh(t){if(k(t,"image")&&F(t.image)){let e=Ls(F(t.image)&&x(t.image.format)?t.image.format:"");if(F(t.image.source)){if(F(t.image.source.s3Location)&&x(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Jr(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}o(nh,"convertConverseImageBlock");function sh(t){if(k(t,"video")&&F(t.video)){let e=Ls(F(t.video)&&x(t.video.format)?t.video.format:"");if(F(t.video.source)){if(F(t.video.source.s3Location)&&x(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Jr(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}o(sh,"convertConverseVideoBlock");function wo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(k(n,"citations_content")&&F(n.citationsContent)){yield{type:"text",text:fe(n.citationsContent.content)?n.citationsContent.content.reduce((s,i)=>F(i)&&x(i.text)?s+i.text:s,""):"",annotations:fe(n.citationsContent.citations)?n.citationsContent.citations.reduce((s,i)=>{if(F(i)){let a=fe(i.sourceContent)?i.sourceContent.reduce((l,u)=>F(u)&&x(u.text)?l+u.text:l,""):"",c=Fe(()=>{if(F(i.location)){let l=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(F(l))return{source:Ue(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Ue(l.start)?l.start:void 0,endIndex:Ue(l.end)?l.end:void 0}}return{}});s.push({type:"citation",citedText:a,...c})}return s},[]):[]};continue}else if(k(n,"document")&&F(n.document)){yield rh(n);continue}else if(k(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(k(n,"image")&&F(n.image)){yield nh(n);continue}else if(k(n,"reasoning_content")&&x(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(k(n,"tool_call"))continue;if(k(n,"video")&&F(n.video)){yield sh(n);continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(wo,"convertToV1FromChatBedrockConverseMessage");var To={translateContent:wo,translateContentChunk:wo};function vo(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(vo,"convertToV1FromDeepSeekMessage");var So={translateContent:vo,translateContentChunk:vo};function Io(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(k(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(k(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(k(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Io,"convertToV1FromChatGoogleMessage");var xo={translateContent:Io,translateContentChunk:Io};function Ao(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"reasoning")&&x(n.reasoning)){let s=Fe(()=>{let i=r.indexOf(n);if(fe(t.additional_kwargs?.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});x(s)?yield{type:"reasoning",reasoning:n.reasoning,signature:s}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"image_url")){if(x(n.image_url))if(n.image_url.startsWith("data:")){let s=n.image_url.match(/^data:([^;]+);base64,(.+)$/);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(k(n,"media")&&x(n.mimeType)&&x(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Ao,"convertToV1FromChatVertexMessage");var Ro={translateContent:Ao,translateContentChunk:Ao};function Co(t){let e=[],r=t.additional_kwargs?.reasoning;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,s=n.match(/<think>([\s\S]*?)<\/think>/);if(s){let i=s[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)){let s=n.text,i=s.match(/<think>([\s\S]*?)<\/think>/);if(i){let a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),s=s.replace(/<think>[\s\S]*?<\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Co,"convertToV1FromGroqMessage");var Oo={translateContent:Co,translateContentChunk:Co};function No(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(No,"convertToV1FromOllamaMessage");var Mo={translateContent:No,translateContentChunk:No};function ko(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let s of r){if(s==null||typeof s!="object")continue;let i=s.type;if(i==="reasoning.summary"){let a=s.summary;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}else if(i==="reasoning.text"){let a=s.text;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}}if(!n){let s=t.additional_kwargs?.reasoning_content;x(s)&&s.length>0&&e.push({type:"reasoning",reasoning:s})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&x(s.text)&&e.push({type:"text",text:s.text});for(let s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}o(ko,"convertToV1FromOpenRouterMessage");var Po={translateContent:ko,translateContentChunk:ko};function Lo(t){let e=[];if(F(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(fe(n.summary)){let s=n.summary.reduce((i,a)=>F(a)&&x(a.text)?`${i}${a.text}`:i,"");s.length>0&&e.push({type:"reasoning",reasoning:s})}}let r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Lo,"convertToV1FromXAIMessage");var Do={translateContent:Lo,translateContentChunk:Lo};function $o(t){function*e(){let r=Fe(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let n=t.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!t.content.some(s=>"thoughtSignature"in s)){let s=[...t.content];for(let i=s.length-1;i>=0;i--){let a=s[i];if(a.type==="text"&&!a.thought)return a.thoughtSignature=n.thoughtSignature,s}}return t.content}});for(let n of r){let s=Fe(()=>k(n,"text")&&x(n.text)?{type:"text",text:n.text}:k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:k(n,"functionResponse")?{type:"non_standard",value:n}:k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:k(n,"executableCode")?{type:"non_standard",value:n}:k(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),i=Fe(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:s.type==="text"?s.text:"",reasoningContentBlock:s}:s),a={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...i};for(let c in a)a[c]===void 0&&delete a[c];yield a}}return o(e,"iterateContent"),Array.from(e())}o($o,"convertToV1FromChatGoogleMessage");var Uo={translateContent:$o,translateContentChunk:$o};globalThis.lc_block_translators_registry??=new Map([["anthropic",mo],["bedrock-converse",To],["deepseek",So],["google",Uo],["google-genai",xo],["google-vertexai",Ro],["groq",Oo],["ollama",Mo],["openai",bo],["openrouter",Po],["xai",Do]]);function Fo(t){return globalThis.lc_block_translators_registry.get(t)}o(Fo,"getTranslator");function Bo(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}o(Bo,"mergeModalitiesTokenDetails");function ih(t,e){let r={...Bo(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}o(ih,"mergeInputTokenDetails");function ah(t,e){let r={...Bo(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}o(ah,"mergeOutputTokenDetails");function Xr(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:ih(t?.input_token_details,e?.input_token_details),output_token_details:ah(t?.output_token_details,e?.output_token_details)}}o(Xr,"mergeUsageMetadata");var bt=class extends ft{static{o(this,"AIMessage")}type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
1
|
+
"use strict";var Rm=Object.create;var dr=Object.defineProperty;var Om=Object.getOwnPropertyDescriptor;var Nm=Object.getOwnPropertyNames;var Mm=Object.getPrototypeOf,km=Object.prototype.hasOwnProperty;var o=(t,e)=>dr(t,"name",{value:e,configurable:!0});var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Pm=(t,e)=>{for(var r in e)dr(t,r,{get:e[r],enumerable:!0})},eo=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Nm(e))!km.call(t,s)&&s!==r&&dr(t,s,{get:()=>e[s],enumerable:!(n=Om(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?Rm(Mm(t)):{},eo(e||!t||!t.__esModule?dr(r,"default",{value:t,enumerable:!0}):r,t)),Lm=t=>eo(dr({},"__esModule",{value:!0}),t);var Xo=P((Dx,Ds)=>{"use strict";var Eh=Object.prototype.hasOwnProperty,Ae="~";function pr(){}o(pr,"Events");Object.create&&(pr.prototype=Object.create(null),new pr().__proto__||(Ae=!1));function wh(t,e,r){this.fn=t,this.context=e,this.once=r||!1}o(wh,"EE");function Yo(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new wh(r,n||t,s),a=Ae?Ae+e:e;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],i]:t._events[a].push(i):(t._events[a]=i,t._eventsCount++),t}o(Yo,"addListener");function nn(t,e){--t._eventsCount===0?t._events=new pr:delete t._events[e]}o(nn,"clearEvent");function ve(){this._events=new pr,this._eventsCount=0}o(ve,"EventEmitter");ve.prototype.eventNames=o(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Eh.call(r,n)&&e.push(Ae?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");ve.prototype.listeners=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,a=new Array(i);s<i;s++)a[s]=n[s].fn;return a},"listeners");ve.prototype.listenerCount=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");ve.prototype.emit=o(function(e,r,n,s,i,a){var c=Ae?Ae+e:e;if(!this._events[c])return!1;var l=this._events[c],u=arguments.length,d,p;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,r),!0;case 3:return l.fn.call(l.context,r,n),!0;case 4:return l.fn.call(l.context,r,n,s),!0;case 5:return l.fn.call(l.context,r,n,s,i),!0;case 6:return l.fn.call(l.context,r,n,s,i,a),!0}for(p=1,d=new Array(u-1);p<u;p++)d[p-1]=arguments[p];l.fn.apply(l.context,d)}else{var _=l.length,g;for(p=0;p<_;p++)switch(l[p].once&&this.removeListener(e,l[p].fn,void 0,!0),u){case 1:l[p].fn.call(l[p].context);break;case 2:l[p].fn.call(l[p].context,r);break;case 3:l[p].fn.call(l[p].context,r,n);break;case 4:l[p].fn.call(l[p].context,r,n,s);break;default:if(!d)for(g=1,d=new Array(u-1);g<u;g++)d[g-1]=arguments[g];l[p].fn.apply(l[p].context,d)}}return!0},"emit");ve.prototype.on=o(function(e,r,n){return Yo(this,e,r,n,!1)},"on");ve.prototype.once=o(function(e,r,n){return Yo(this,e,r,n,!0)},"once");ve.prototype.removeListener=o(function(e,r,n,s){var i=Ae?Ae+e:e;if(!this._events[i])return this;if(!r)return nn(this,i),this;var a=this._events[i];if(a.fn)a.fn===r&&(!s||a.once)&&(!n||a.context===n)&&nn(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==r||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=l.length===1?l[0]:l:nn(this,i)}return this},"removeListener");ve.prototype.removeAllListeners=o(function(e){var r;return e?(r=Ae?Ae+e:e,this._events[r]&&nn(this,r)):(this._events=new pr,this._eventsCount=0),this},"removeAllListeners");ve.prototype.off=ve.prototype.removeListener;ve.prototype.addListener=ve.prototype.on;ve.prefixed=Ae;ve.EventEmitter=ve;typeof Ds<"u"&&(Ds.exports=ve)});var ec=P((Ux,Qo)=>{"use strict";Qo.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var rc=P((Fx,an)=>{"use strict";var Th=ec(),sn=class extends Error{static{o(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},tc=o((t,e,r)=>new Promise((n,s)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(l){s(l)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,c=r instanceof Error?r:new sn(a);typeof t.cancel=="function"&&t.cancel(),s(c)},e);Th(t.then(n,s),()=>{clearTimeout(i)})}),"pTimeout");an.exports=tc;an.exports.default=tc;an.exports.TimeoutError=sn});var nc=P($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});function vh(t,e,r){let n=0,s=t.length;for(;s>0;){let i=s/2|0,a=n+i;r(t[a],e)<=0?(n=++a,s-=i+1):s=i}return n}o(vh,"lowerBound");$s.default=vh});var sc=P(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Sh=nc(),Us=class{static{o(this,"PriorityQueue")}constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let s=Sh.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(s,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};Fs.default=Us});var cn=P(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Ih=Xo(),ic=rc(),xh=sc(),on=o(()=>{},"empty"),Ah=new ic.TimeoutError,Bs=class extends Ih{static{o(this,"PQueue")}constructor(e){var r,n,s,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=on,this._resolveIdle=on,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:xh.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=on,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=on,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,s)=>{let i=o(async()=>{this._pendingCount++,this._intervalCount++;try{let a=this._timeout===void 0&&r.timeout===void 0?e():ic.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&s(Ah)});n(await a)}catch(a){s(a)}this._next()},"run");this._queue.enqueue(i,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};js.default=Bs});var vr=P((iO,Nl)=>{"use strict";var Vg="2.0.0",Wg=Number.MAX_SAFE_INTEGER||9007199254740991,qg=16,Kg=250,Zg=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Nl.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:qg,MAX_SAFE_BUILD_LENGTH:Kg,MAX_SAFE_INTEGER:Wg,RELEASE_TYPES:Zg,SEMVER_SPEC_VERSION:Vg,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Sr=P((aO,Ml)=>{"use strict";var Jg=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};Ml.exports=Jg});var Xt=P((ot,kl)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:wi,MAX_SAFE_BUILD_LENGTH:Yg,MAX_LENGTH:Xg}=vr(),Qg=Sr();ot=kl.exports={};var ey=ot.re=[],ty=ot.safeRe=[],L=ot.src=[],ry=ot.safeSrc=[],D=ot.t={},ny=0,Ti="[a-zA-Z0-9-]",sy=[["\\s",1],["\\d",Xg],[Ti,Yg]],iy=o(t=>{for(let[e,r]of sy)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},"makeSafeRegex"),V=o((t,e,r)=>{let n=iy(e),s=ny++;Qg(t,s,e),D[t]=s,L[s]=e,ry[s]=n,ey[s]=new RegExp(e,r?"g":void 0),ty[s]=new RegExp(n,r?"g":void 0)},"createToken");V("NUMERICIDENTIFIER","0|[1-9]\\d*");V("NUMERICIDENTIFIERLOOSE","\\d+");V("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Ti}*`);V("MAINVERSION",`(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})`);V("MAINVERSIONLOOSE",`(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASEIDENTIFIER",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIER]})`);V("PRERELEASEIDENTIFIERLOOSE",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASE",`(?:-(${L[D.PRERELEASEIDENTIFIER]}(?:\\.${L[D.PRERELEASEIDENTIFIER]})*))`);V("PRERELEASELOOSE",`(?:-?(${L[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${L[D.PRERELEASEIDENTIFIERLOOSE]})*))`);V("BUILDIDENTIFIER",`${Ti}+`);V("BUILD",`(?:\\+(${L[D.BUILDIDENTIFIER]}(?:\\.${L[D.BUILDIDENTIFIER]})*))`);V("FULLPLAIN",`v?${L[D.MAINVERSION]}${L[D.PRERELEASE]}?${L[D.BUILD]}?`);V("FULL",`^${L[D.FULLPLAIN]}$`);V("LOOSEPLAIN",`[v=\\s]*${L[D.MAINVERSIONLOOSE]}${L[D.PRERELEASELOOSE]}?${L[D.BUILD]}?`);V("LOOSE",`^${L[D.LOOSEPLAIN]}$`);V("GTLT","((?:<|>)?=?)");V("XRANGEIDENTIFIERLOOSE",`${L[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);V("XRANGEIDENTIFIER",`${L[D.NUMERICIDENTIFIER]}|x|X|\\*`);V("XRANGEPLAIN",`[v=\\s]*(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:${L[D.PRERELEASE]})?${L[D.BUILD]}?)?)?`);V("XRANGEPLAINLOOSE",`[v=\\s]*(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:${L[D.PRERELEASELOOSE]})?${L[D.BUILD]}?)?)?`);V("XRANGE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAIN]}$`);V("XRANGELOOSE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAINLOOSE]}$`);V("COERCEPLAIN",`(^|[^\\d])(\\d{1,${wi}})(?:\\.(\\d{1,${wi}}))?(?:\\.(\\d{1,${wi}}))?`);V("COERCE",`${L[D.COERCEPLAIN]}(?:$|[^\\d])`);V("COERCEFULL",L[D.COERCEPLAIN]+`(?:${L[D.PRERELEASE]})?(?:${L[D.BUILD]})?(?:$|[^\\d])`);V("COERCERTL",L[D.COERCE],!0);V("COERCERTLFULL",L[D.COERCEFULL],!0);V("LONETILDE","(?:~>?)");V("TILDETRIM",`(\\s*)${L[D.LONETILDE]}\\s+`,!0);ot.tildeTrimReplace="$1~";V("TILDE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAIN]}$`);V("TILDELOOSE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAINLOOSE]}$`);V("LONECARET","(?:\\^)");V("CARETTRIM",`(\\s*)${L[D.LONECARET]}\\s+`,!0);ot.caretTrimReplace="$1^";V("CARET",`^${L[D.LONECARET]}${L[D.XRANGEPLAIN]}$`);V("CARETLOOSE",`^${L[D.LONECARET]}${L[D.XRANGEPLAINLOOSE]}$`);V("COMPARATORLOOSE",`^${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]})$|^$`);V("COMPARATOR",`^${L[D.GTLT]}\\s*(${L[D.FULLPLAIN]})$|^$`);V("COMPARATORTRIM",`(\\s*)${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]}|${L[D.XRANGEPLAIN]})`,!0);ot.comparatorTrimReplace="$1$2$3";V("HYPHENRANGE",`^\\s*(${L[D.XRANGEPLAIN]})\\s+-\\s+(${L[D.XRANGEPLAIN]})\\s*$`);V("HYPHENRANGELOOSE",`^\\s*(${L[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${L[D.XRANGEPLAINLOOSE]})\\s*$`);V("STAR","(<|>)?=?\\s*\\*");V("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");V("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var An=P((cO,Pl)=>{"use strict";var ay=Object.freeze({loose:!0}),oy=Object.freeze({}),cy=o(t=>t?typeof t!="object"?ay:t:oy,"parseOptions");Pl.exports=cy});var vi=P((uO,$l)=>{"use strict";var Ll=/^[0-9]+$/,Dl=o((t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=Ll.test(t),n=Ll.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:t<e?-1:1},"compareIdentifiers"),ly=o((t,e)=>Dl(e,t),"rcompareIdentifiers");$l.exports={compareIdentifiers:Dl,rcompareIdentifiers:ly}});var Se=P((fO,Fl)=>{"use strict";var Cn=Sr(),{MAX_LENGTH:Ul,MAX_SAFE_INTEGER:Rn}=vr(),{safeRe:On,t:Nn}=Xt(),uy=An(),{compareIdentifiers:Si}=vi(),Ii=class t{static{o(this,"SemVer")}constructor(e,r){if(r=uy(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Ul)throw new TypeError(`version is longer than ${Ul} characters`);Cn("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=e.trim().match(r.loose?On[Nn.LOOSE]:On[Nn.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Rn||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Rn||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Rn||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&i<Rn)return i}return s}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Cn("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=e.prerelease[r];if(Cn("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Si(n,s)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let n=this.build[r],s=e.build[r];if(Cn("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Si(n,s)}while(++r)}inc(e,r,n){if(e.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?On[Nn.PRERELEASELOOSE]:On[Nn.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let i=[r,s];n===!1&&(i=[r]),Si(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Fl.exports=Ii});var Dt=P((mO,jl)=>{"use strict";var Bl=Se(),dy=o((t,e,r=!1)=>{if(t instanceof Bl)return t;try{return new Bl(t,e)}catch(n){if(!r)return null;throw n}},"parse");jl.exports=dy});var Gl=P((gO,Hl)=>{"use strict";var fy=Dt(),py=o((t,e)=>{let r=fy(t,e);return r?r.version:null},"valid");Hl.exports=py});var Vl=P((_O,zl)=>{"use strict";var my=Dt(),hy=o((t,e)=>{let r=my(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null},"clean");zl.exports=hy});var Kl=P((EO,ql)=>{"use strict";var Wl=Se(),gy=o((t,e,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Wl(t instanceof Wl?t.version:t,r).inc(e,n,s).version}catch{return null}},"inc");ql.exports=gy});var Yl=P((TO,Jl)=>{"use strict";var Zl=Dt(),yy=o((t,e)=>{let r=Zl(t,null,!0),n=Zl(e,null,!0),s=r.compare(n);if(s===0)return null;let i=s>0,a=i?r:n,c=i?n:r,l=!!a.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(a)===0)return c.minor&&!c.patch?"minor":"patch"}let d=l?"pre":"";return r.major!==n.major?d+"major":r.minor!==n.minor?d+"minor":r.patch!==n.patch?d+"patch":"prerelease"},"diff");Jl.exports=yy});var Ql=P((SO,Xl)=>{"use strict";var _y=Se(),by=o((t,e)=>new _y(t,e).major,"major");Xl.exports=by});var tu=P((xO,eu)=>{"use strict";var Ey=Se(),wy=o((t,e)=>new Ey(t,e).minor,"minor");eu.exports=wy});var nu=P((CO,ru)=>{"use strict";var Ty=Se(),vy=o((t,e)=>new Ty(t,e).patch,"patch");ru.exports=vy});var iu=P((OO,su)=>{"use strict";var Sy=Dt(),Iy=o((t,e)=>{let r=Sy(t,e);return r&&r.prerelease.length?r.prerelease:null},"prerelease");su.exports=Iy});var Ge=P((MO,ou)=>{"use strict";var au=Se(),xy=o((t,e,r)=>new au(t,r).compare(new au(e,r)),"compare");ou.exports=xy});var lu=P((PO,cu)=>{"use strict";var Ay=Ge(),Cy=o((t,e,r)=>Ay(e,t,r),"rcompare");cu.exports=Cy});var du=P((DO,uu)=>{"use strict";var Ry=Ge(),Oy=o((t,e)=>Ry(t,e,!0),"compareLoose");uu.exports=Oy});var Mn=P((UO,pu)=>{"use strict";var fu=Se(),Ny=o((t,e,r)=>{let n=new fu(t,r),s=new fu(e,r);return n.compare(s)||n.compareBuild(s)},"compareBuild");pu.exports=Ny});var hu=P((BO,mu)=>{"use strict";var My=Mn(),ky=o((t,e)=>t.sort((r,n)=>My(r,n,e)),"sort");mu.exports=ky});var yu=P((HO,gu)=>{"use strict";var Py=Mn(),Ly=o((t,e)=>t.sort((r,n)=>Py(n,r,e)),"rsort");gu.exports=Ly});var Ir=P((zO,_u)=>{"use strict";var Dy=Ge(),$y=o((t,e,r)=>Dy(t,e,r)>0,"gt");_u.exports=$y});var kn=P((WO,bu)=>{"use strict";var Uy=Ge(),Fy=o((t,e,r)=>Uy(t,e,r)<0,"lt");bu.exports=Fy});var xi=P((KO,Eu)=>{"use strict";var By=Ge(),jy=o((t,e,r)=>By(t,e,r)===0,"eq");Eu.exports=jy});var Ai=P((JO,wu)=>{"use strict";var Hy=Ge(),Gy=o((t,e,r)=>Hy(t,e,r)!==0,"neq");wu.exports=Gy});var Pn=P((XO,Tu)=>{"use strict";var zy=Ge(),Vy=o((t,e,r)=>zy(t,e,r)>=0,"gte");Tu.exports=Vy});var Ln=P((eN,vu)=>{"use strict";var Wy=Ge(),qy=o((t,e,r)=>Wy(t,e,r)<=0,"lte");vu.exports=qy});var Ci=P((rN,Su)=>{"use strict";var Ky=xi(),Zy=Ai(),Jy=Ir(),Yy=Pn(),Xy=kn(),Qy=Ln(),e_=o((t,e,r,n)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Ky(t,r,n);case"!=":return Zy(t,r,n);case">":return Jy(t,r,n);case">=":return Yy(t,r,n);case"<":return Xy(t,r,n);case"<=":return Qy(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}},"cmp");Su.exports=e_});var xu=P((sN,Iu)=>{"use strict";var t_=Se(),r_=Dt(),{safeRe:Dn,t:$n}=Xt(),n_=o((t,e)=>{if(t instanceof t_)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?Dn[$n.COERCEFULL]:Dn[$n.COERCE]);else{let l=e.includePrerelease?Dn[$n.COERCERTLFULL]:Dn[$n.COERCERTL],u;for(;(u=l.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",i=r[4]||"0",a=e.includePrerelease&&r[5]?`-${r[5]}`:"",c=e.includePrerelease&&r[6]?`+${r[6]}`:"";return r_(`${n}.${s}.${i}${a}${c}`,e)},"coerce");Iu.exports=n_});var Cu=P((aN,Au)=>{"use strict";var Ri=class{static{o(this,"LRUCache")}constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(e,r)}return this}};Au.exports=Ri});var ze=P((cN,Mu)=>{"use strict";var s_=/\s+/g,Oi=class t{static{o(this,"Range")}constructor(e,r){if(r=a_(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof Ni)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(s_," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Ou(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&p_(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&d_)|(this.options.loose&&f_))+":"+e,s=Ru.get(n);if(s)return s;let i=this.options.loose,a=i?Ce[Ie.HYPHENRANGELOOSE]:Ce[Ie.HYPHENRANGE];e=e.replace(a,v_(this.options.includePrerelease)),ee("hyphen replace",e),e=e.replace(Ce[Ie.COMPARATORTRIM],c_),ee("comparator trim",e),e=e.replace(Ce[Ie.TILDETRIM],l_),ee("tilde trim",e),e=e.replace(Ce[Ie.CARETTRIM],u_),ee("caret trim",e);let c=e.split(" ").map(p=>m_(p,this.options)).join(" ").split(/\s+/).map(p=>T_(p,this.options));i&&(c=c.filter(p=>(ee("loose invalid filter",p,this.options),!!p.match(Ce[Ie.COMPARATORLOOSE])))),ee("range list",c);let l=new Map,u=c.map(p=>new Ni(p,this.options));for(let p of u){if(Ou(p))return[p];l.set(p.value,p)}l.size>1&&l.has("")&&l.delete("");let d=[...l.values()];return Ru.set(n,d),d}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(n=>Nu(n,r)&&e.set.some(s=>Nu(s,r)&&n.every(i=>s.every(a=>i.intersects(a,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new o_(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(S_(this.set[r],e,this.options))return!0;return!1}};Mu.exports=Oi;var i_=Cu(),Ru=new i_,a_=An(),Ni=xr(),ee=Sr(),o_=Se(),{safeRe:Ce,t:Ie,comparatorTrimReplace:c_,tildeTrimReplace:l_,caretTrimReplace:u_}=Xt(),{FLAG_INCLUDE_PRERELEASE:d_,FLAG_LOOSE:f_}=vr(),Ou=o(t=>t.value==="<0.0.0-0","isNullSet"),p_=o(t=>t.value==="","isAny"),Nu=o((t,e)=>{let r=!0,n=t.slice(),s=n.pop();for(;r&&n.length;)r=n.every(i=>s.intersects(i,e)),s=n.pop();return r},"isSatisfiable"),m_=o((t,e)=>(t=t.replace(Ce[Ie.BUILD],""),ee("comp",t,e),t=y_(t,e),ee("caret",t),t=h_(t,e),ee("tildes",t),t=b_(t,e),ee("xrange",t),t=w_(t,e),ee("stars",t),t),"parseComparator"),Re=o(t=>!t||t.toLowerCase()==="x"||t==="*","isX"),h_=o((t,e)=>t.trim().split(/\s+/).map(r=>g_(r,e)).join(" "),"replaceTildes"),g_=o((t,e)=>{let r=e.loose?Ce[Ie.TILDELOOSE]:Ce[Ie.TILDE];return t.replace(r,(n,s,i,a,c)=>{ee("tilde",t,n,s,i,a,c);let l;return Re(s)?l="":Re(i)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:Re(a)?l=`>=${s}.${i}.0 <${s}.${+i+1}.0-0`:c?(ee("replaceTilde pr",c),l=`>=${s}.${i}.${a}-${c} <${s}.${+i+1}.0-0`):l=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,ee("tilde return",l),l})},"replaceTilde"),y_=o((t,e)=>t.trim().split(/\s+/).map(r=>__(r,e)).join(" "),"replaceCarets"),__=o((t,e)=>{ee("caret",t,e);let r=e.loose?Ce[Ie.CARETLOOSE]:Ce[Ie.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,(s,i,a,c,l)=>{ee("caret",t,s,i,a,c,l);let u;return Re(i)?u="":Re(a)?u=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Re(c)?i==="0"?u=`>=${i}.${a}.0${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.0${n} <${+i+1}.0.0-0`:l?(ee("replaceCaret pr",l),i==="0"?a==="0"?u=`>=${i}.${a}.${c}-${l} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}-${l} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c}-${l} <${+i+1}.0.0-0`):(ee("no pr"),i==="0"?a==="0"?u=`>=${i}.${a}.${c}${n} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c} <${+i+1}.0.0-0`),ee("caret return",u),u})},"replaceCaret"),b_=o((t,e)=>(ee("replaceXRanges",t,e),t.split(/\s+/).map(r=>E_(r,e)).join(" ")),"replaceXRanges"),E_=o((t,e)=>{t=t.trim();let r=e.loose?Ce[Ie.XRANGELOOSE]:Ce[Ie.XRANGE];return t.replace(r,(n,s,i,a,c,l)=>{ee("xRange",t,n,s,i,a,c,l);let u=Re(i),d=u||Re(a),p=d||Re(c),_=p;return s==="="&&_&&(s=""),l=e.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&_?(d&&(a=0),c=0,s===">"?(s=">=",d?(i=+i+1,a=0,c=0):(a=+a+1,c=0)):s==="<="&&(s="<",d?i=+i+1:a=+a+1),s==="<"&&(l="-0"),n=`${s+i}.${a}.${c}${l}`):d?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:p&&(n=`>=${i}.${a}.0${l} <${i}.${+a+1}.0-0`),ee("xRange return",n),n})},"replaceXRange"),w_=o((t,e)=>(ee("replaceStars",t,e),t.trim().replace(Ce[Ie.STAR],"")),"replaceStars"),T_=o((t,e)=>(ee("replaceGTE0",t,e),t.trim().replace(Ce[e.includePrerelease?Ie.GTE0PRE:Ie.GTE0],"")),"replaceGTE0"),v_=o(t=>(e,r,n,s,i,a,c,l,u,d,p,_)=>(Re(n)?r="":Re(s)?r=`>=${n}.0.0${t?"-0":""}`:Re(i)?r=`>=${n}.${s}.0${t?"-0":""}`:a?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,Re(u)?l="":Re(d)?l=`<${+u+1}.0.0-0`:Re(p)?l=`<${u}.${+d+1}.0-0`:_?l=`<=${u}.${d}.${p}-${_}`:t?l=`<${u}.${d}.${+p+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),"hyphenReplace"),S_=o((t,e,r)=>{for(let n=0;n<t.length;n++)if(!t[n].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let n=0;n<t.length;n++)if(ee(t[n].semver),t[n].semver!==Ni.ANY&&t[n].semver.prerelease.length>0){let s=t[n].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0},"testSet")});var xr=P((uN,Uu)=>{"use strict";var Ar=Symbol("SemVer ANY"),Pi=class t{static{o(this,"Comparator")}static get ANY(){return Ar}constructor(e,r){if(r=ku(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),ki("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===Ar?this.value="":this.value=this.operator+this.semver.version,ki("comp",this)}parse(e){let r=this.options.loose?Pu[Lu.COMPARATORLOOSE]:Pu[Lu.COMPARATOR],n=e.match(r);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Du(n[2],this.options.loose):this.semver=Ar}toString(){return this.value}test(e){if(ki("Comparator.test",e,this.options.loose),this.semver===Ar||e===Ar)return!0;if(typeof e=="string")try{e=new Du(e,this.options)}catch{return!1}return Mi(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new $u(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new $u(this.value,r).test(e.semver):(r=ku(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Mi(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Mi(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Uu.exports=Pi;var ku=An(),{safeRe:Pu,t:Lu}=Xt(),Mi=Ci(),ki=Sr(),Du=Se(),$u=ze()});var Cr=P((fN,Fu)=>{"use strict";var I_=ze(),x_=o((t,e,r)=>{try{e=new I_(e,r)}catch{return!1}return e.test(t)},"satisfies");Fu.exports=x_});var ju=P((mN,Bu)=>{"use strict";var A_=ze(),C_=o((t,e)=>new A_(t,e).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" ")),"toComparators");Bu.exports=C_});var Gu=P((gN,Hu)=>{"use strict";var R_=Se(),O_=ze(),N_=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new O_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===-1)&&(n=a,s=new R_(n,r))}),n},"maxSatisfying");Hu.exports=N_});var Vu=P((_N,zu)=>{"use strict";var M_=Se(),k_=ze(),P_=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new k_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===1)&&(n=a,s=new M_(n,r))}),n},"minSatisfying");zu.exports=P_});var Ku=P((EN,qu)=>{"use strict";var Li=Se(),L_=ze(),Wu=Ir(),D_=o((t,e)=>{t=new L_(t,e);let r=new Li("0.0.0");if(t.test(r)||(r=new Li("0.0.0-0"),t.test(r)))return r;r=null;for(let n=0;n<t.set.length;++n){let s=t.set[n],i=null;s.forEach(a=>{let c=new Li(a.semver.version);switch(a.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!i||Wu(c,i))&&(i=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${a.operator}`)}}),i&&(!r||Wu(r,i))&&(r=i)}return r&&t.test(r)?r:null},"minVersion");qu.exports=D_});var Ju=P((TN,Zu)=>{"use strict";var $_=ze(),U_=o((t,e)=>{try{return new $_(t,e).range||"*"}catch{return null}},"validRange");Zu.exports=U_});var Un=P((SN,ed)=>{"use strict";var F_=Se(),Qu=xr(),{ANY:B_}=Qu,j_=ze(),H_=Cr(),Yu=Ir(),Xu=kn(),G_=Ln(),z_=Pn(),V_=o((t,e,r,n)=>{t=new F_(t,n),e=new j_(e,n);let s,i,a,c,l;switch(r){case">":s=Yu,i=G_,a=Xu,c=">",l=">=";break;case"<":s=Xu,i=z_,a=Yu,c="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(H_(t,e,n))return!1;for(let u=0;u<e.set.length;++u){let d=e.set[u],p=null,_=null;if(d.forEach(g=>{g.semver===B_&&(g=new Qu(">=0.0.0")),p=p||g,_=_||g,s(g.semver,p.semver,n)?p=g:a(g.semver,_.semver,n)&&(_=g)}),p.operator===c||p.operator===l||(!_.operator||_.operator===c)&&i(t,_.semver))return!1;if(_.operator===l&&a(t,_.semver))return!1}return!0},"outside");ed.exports=V_});var rd=P((xN,td)=>{"use strict";var W_=Un(),q_=o((t,e,r)=>W_(t,e,">",r),"gtr");td.exports=q_});var sd=P((CN,nd)=>{"use strict";var K_=Un(),Z_=o((t,e,r)=>K_(t,e,"<",r),"ltr");nd.exports=Z_});var od=P((ON,ad)=>{"use strict";var id=ze(),J_=o((t,e,r)=>(t=new id(t,r),e=new id(e,r),t.intersects(e,r)),"intersects");ad.exports=J_});var ld=P((MN,cd)=>{"use strict";var Y_=Cr(),X_=Ge();cd.exports=(t,e,r)=>{let n=[],s=null,i=null,a=t.sort((d,p)=>X_(d,p,r));for(let d of a)Y_(d,e,r)?(i=d,s||(s=d)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let c=[];for(let[d,p]of n)d===p?c.push(d):!p&&d===a[0]?c.push("*"):p?d===a[0]?c.push(`<=${p}`):c.push(`${d} - ${p}`):c.push(`>=${d}`);let l=c.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var hd=P((kN,md)=>{"use strict";var ud=ze(),$i=xr(),{ANY:Di}=$i,Rr=Cr(),Ui=Ge(),Q_=o((t,e,r={})=>{if(t===e)return!0;t=new ud(t,r),e=new ud(e,r);let n=!1;e:for(let s of t.set){for(let i of e.set){let a=tb(s,i,r);if(n=n||a!==null,a)continue e}if(n)return!1}return!0},"subset"),eb=[new $i(">=0.0.0-0")],dd=[new $i(">=0.0.0")],tb=o((t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Di){if(e.length===1&&e[0].semver===Di)return!0;r.includePrerelease?t=eb:t=dd}if(e.length===1&&e[0].semver===Di){if(r.includePrerelease)return!0;e=dd}let n=new Set,s,i;for(let g of t)g.operator===">"||g.operator===">="?s=fd(s,g,r):g.operator==="<"||g.operator==="<="?i=pd(i,g,r):n.add(g.semver);if(n.size>1)return null;let a;if(s&&i){if(a=Ui(s.semver,i.semver,r),a>0)return null;if(a===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let g of n){if(s&&!Rr(g,String(s),r)||i&&!Rr(g,String(i),r))return null;for(let y of e)if(!Rr(g,String(y),r))return!1;return!0}let c,l,u,d,p=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,_=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;p&&p.prerelease.length===1&&i.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let g of e){if(d=d||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",s){if(_&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===_.major&&g.semver.minor===_.minor&&g.semver.patch===_.patch&&(_=!1),g.operator===">"||g.operator===">="){if(c=fd(s,g,r),c===g&&c!==s)return!1}else if(s.operator===">="&&!Rr(s.semver,String(g),r))return!1}if(i){if(p&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===p.major&&g.semver.minor===p.minor&&g.semver.patch===p.patch&&(p=!1),g.operator==="<"||g.operator==="<="){if(l=pd(i,g,r),l===g&&l!==i)return!1}else if(i.operator==="<="&&!Rr(i.semver,String(g),r))return!1}if(!g.operator&&(i||s)&&a!==0)return!1}return!(s&&u&&!i&&a!==0||i&&d&&!s&&a!==0||_||p)},"simpleSubset"),fd=o((t,e,r)=>{if(!t)return e;let n=Ui(t.semver,e.semver,r);return n>0?t:n<0||e.operator===">"&&t.operator===">="?e:t},"higherGT"),pd=o((t,e,r)=>{if(!t)return e;let n=Ui(t.semver,e.semver,r);return n<0?t:n>0||e.operator==="<"&&t.operator==="<="?e:t},"lowerLT");md.exports=Q_});var bd=P((LN,_d)=>{"use strict";var Fi=Xt(),gd=vr(),rb=Se(),yd=vi(),nb=Dt(),sb=Gl(),ib=Vl(),ab=Kl(),ob=Yl(),cb=Ql(),lb=tu(),ub=nu(),db=iu(),fb=Ge(),pb=lu(),mb=du(),hb=Mn(),gb=hu(),yb=yu(),_b=Ir(),bb=kn(),Eb=xi(),wb=Ai(),Tb=Pn(),vb=Ln(),Sb=Ci(),Ib=xu(),xb=xr(),Ab=ze(),Cb=Cr(),Rb=ju(),Ob=Gu(),Nb=Vu(),Mb=Ku(),kb=Ju(),Pb=Un(),Lb=rd(),Db=sd(),$b=od(),Ub=ld(),Fb=hd();_d.exports={parse:nb,valid:sb,clean:ib,inc:ab,diff:ob,major:cb,minor:lb,patch:ub,prerelease:db,compare:fb,rcompare:pb,compareLoose:mb,compareBuild:hb,sort:gb,rsort:yb,gt:_b,lt:bb,eq:Eb,neq:wb,gte:Tb,lte:vb,cmp:Sb,coerce:Ib,Comparator:xb,Range:Ab,satisfies:Cb,toComparators:Rb,maxSatisfying:Ob,minSatisfying:Nb,minVersion:Mb,validRange:kb,outside:Pb,gtr:Lb,ltr:Db,intersects:$b,simplifyRange:Ub,subset:Fb,SemVer:rb,re:Fi.re,src:Fi.src,tokens:Fi.t,SEMVER_SPEC_VERSION:gd.SEMVER_SPEC_VERSION,RELEASE_TYPES:gd.RELEASE_TYPES,compareIdentifiers:yd.compareIdentifiers,rcompareIdentifiers:yd.rcompareIdentifiers}});var hf=P(Qn=>{"use strict";Qn.byteLength=uw;Qn.toByteArray=fw;Qn.fromByteArray=hw;var dt=[],We=[],lw=typeof Uint8Array<"u"?Uint8Array:Array,la="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Bt=0,pf=la.length;Bt<pf;++Bt)dt[Bt]=la[Bt],We[la.charCodeAt(Bt)]=Bt;var Bt,pf;We[45]=62;We[95]=63;function mf(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}o(mf,"getLens");function uw(t){var e=mf(t),r=e[0],n=e[1];return(r+n)*3/4-n}o(uw,"byteLength");function dw(t,e,r){return(e+r)*3/4-r}o(dw,"_byteLength");function fw(t){var e,r=mf(t),n=r[0],s=r[1],i=new lw(dw(t,n,s)),a=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=We[t.charCodeAt(l)]<<18|We[t.charCodeAt(l+1)]<<12|We[t.charCodeAt(l+2)]<<6|We[t.charCodeAt(l+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=We[t.charCodeAt(l)]<<2|We[t.charCodeAt(l+1)]>>4,i[a++]=e&255),s===1&&(e=We[t.charCodeAt(l)]<<10|We[t.charCodeAt(l+1)]<<4|We[t.charCodeAt(l+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}o(fw,"toByteArray");function pw(t){return dt[t>>18&63]+dt[t>>12&63]+dt[t>>6&63]+dt[t&63]}o(pw,"tripletToBase64");function mw(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(pw(n));return s.join("")}o(mw,"encodeChunk");function hw(t){for(var e,r=t.length,n=r%3,s=[],i=16383,a=0,c=r-n;a<c;a+=i)s.push(mw(t,a,a+i>c?c:a+i));return n===1?(e=t[r-1],s.push(dt[e>>2]+dt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(dt[e>>10]+dt[e>>4&63]+dt[e<<2&63]+"=")),s.join("")}o(hw,"fromByteArray")});var kf=P((J3,gt)=>{var ga=require("fs"),ts=require("path"),Fw=require("os"),Bw=require("crypto"),Cf=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function jw(){return Cf[Math.floor(Math.random()*Cf.length)]}o(jw,"_getRandomTip");function rr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(rr,"parseBoolean");function Hw(){return process.stdout.isTTY}o(Hw,"supportsAnsi");function Gw(t){return Hw()?`\x1B[2m${t}\x1B[0m`:t}o(Gw,"dim");var zw=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Vw(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
2
|
+
`);let n;for(;(n=zw.exec(r))!=null;){let s=n[1],i=n[2]||"";i=i.trim();let a=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),a==='"'&&(i=i.replace(/\\n/g,`
|
|
3
|
+
`),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(Vw,"parse");function Ww(t){t=t||{};let e=Mf(t);t.path=e;let r=pe.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=Nf(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=Kw(r,c);i=pe.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return pe.parse(i)}o(Ww,"_parseVault");function qw(t){console.error(`\u26A0 ${t}`)}o(qw,"_warn");function Fr(t){console.log(`\u2506 ${t}`)}o(Fr,"_debug");function Of(t){console.log(`\u25C7 ${t}`)}o(Of,"_log");function Nf(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(Nf,"_dotenvKey");function Kw(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(Kw,"_instructions");function Mf(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)ga.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=ts.resolve(process.cwd(),".env.vault");return ga.existsSync(e)?e:null}o(Mf,"_vaultPath");function Rf(t){return t[0]==="~"?ts.join(Fw.homedir(),t.slice(1)):t}o(Rf,"_resolveHome");function Zw(t){let e=rr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=rr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Of("loading env from encrypted .env.vault");let n=pe._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),pe.populate(s,n,t),{parsed:n}}o(Zw,"_configVault");function Jw(t){let e=ts.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=rr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=rr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&Fr("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[Rf(t.path)];else{a=[];for(let d of t.path)a.push(Rf(d))}let c,l={};for(let d of a)try{let p=pe.parse(ga.readFileSync(d,{encoding:r}));pe.populate(l,p,t)}catch(p){s&&Fr(`failed to load ${d} ${p.message}`),c=p}let u=pe.populate(n,l,t);if(s=rr(n.DOTENV_CONFIG_DEBUG||s),i=rr(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,p=[];for(let _ of a)try{let g=ts.relative(process.cwd(),_);p.push(g)}catch(g){s&&Fr(`failed to load ${_} ${g.message}`),c=g}Of(`injected env (${d}) from ${p.join(",")} ${Gw(`// tip: ${jw()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o(Jw,"configDotenv");function Yw(t){if(Nf(t).length===0)return pe.configDotenv(t);let e=Mf(t);return e?pe._configVault(t):(qw(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),pe.configDotenv(t))}o(Yw,"config");function Xw(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=Bw.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o(Xw,"decrypt");function Qw(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&Fr(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(Qw,"populate");var pe={configDotenv:Jw,_configVault:Zw,_parseVault:Ww,config:Yw,decrypt:Xw,parse:Vw,populate:Qw};gt.exports.configDotenv=pe.configDotenv;gt.exports._configVault=pe._configVault;gt.exports._parseVault=pe._parseVault;gt.exports.config=pe.config;gt.exports.decrypt=pe.decrypt;gt.exports.parse=pe.parse;gt.exports.populate=pe.populate;gt.exports=pe});var ya=P((I5,Ff)=>{Ff.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var rs=P(jf=>{var Bf={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function s0(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}o(s0,"E");for(let t of Object.keys(Bf))jf[t]=s0(Bf[t])});var Wf=P((C5,Vf)=>{var i0=require("fs"),de=require("path"),Hf=ya(),a0=rs(),o0=typeof process=="object"&&process.platform==="win32",Gf=o(t=>typeof t=="object"&&t!==null,"is_Obj"),zf=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ne(t){this.sep=de.sep,this.fs=i0,Gf(t)&&Gf(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}o(ne,"Utils");Vf.exports=ne;ne.prototype.makeDir=function(t){let e=this;function r(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(i){if(!(!i||i.substr(-1,1)===":")){s+=e.sep+i;var a;try{a=e.fs.statSync(s)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw c}if(a&&a.isFile())throw a0.FILE_IN_THE_WAY(`"${s}"`)}})}o(r,"mkdirSync"),r(t)};ne.prototype.writeFileTo=function(t,e,r,n){let s=this;if(s.fs.existsSync(t)){if(!r)return!1;var i=s.fs.statSync(t);if(i.isDirectory())return!1}var a=de.dirname(t);s.fs.existsSync(a)||s.makeDir(a);var c;try{c=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),c=s.fs.openSync(t,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(t,n||438),!0};ne.prototype.writeFileToAsync=function(t,e,r,n,s){typeof n=="function"&&(s=n,n=void 0);let i=this;i.fs.exists(t,function(a){if(a&&!r)return s(!1);i.fs.stat(t,function(c,l){if(a&&l&&l.isDirectory())return s(!1);var u=de.dirname(t);i.fs.exists(u,function(d){if(!d)try{i.makeDir(u)}catch{return s(!1)}let p=o(function(_){i.fs.write(_,e,0,e.length,0,function(g){i.fs.close(_,function(){if(g)return s(!1);i.fs.chmod(t,n||438,function(){s(!0)})})})},"writeToFd");i.fs.open(t,"w",438,function(_,g){_?i.fs.chmod(t,438,function(){i.fs.open(t,"w",438,function(y,E){if(y||!E)return s(!1);p(E)})}):g?p(g):s(!1)})})})})};ne.prototype.findFiles=function(t){let e=this;function r(n,s,i,a){typeof s=="boolean"&&(i=s,s=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(l){let u=de.join(n,l),d=e.fs.statSync(u);if((!s||s.test(u))&&c.push(de.normalize(u)+(d.isDirectory()?e.sep:"")),d.isDirectory()&&i){let p=e.fs.realpathSync(u);a.has(p)||(a.add(p),c=c.concat(r(u,s,i,a)))}}),c}return o(r,"findSync"),r(t,void 0,!0,new Set([e.fs.realpathSync(t)]))};ne.prototype.findFilesAsync=function(t,e){let r=this,n=[],s=!1,i=o(function(c){s||(s=!0,e(c,c?void 0:n))},"finish"),a=o(function(c,l,u){r.fs.readdir(c,function(d,p){if(d)return u(d);let _=p.length;if(!_)return u();p.forEach(function(g){let y=de.join(c,g);r.fs.stat(y,function(E,w){if(E)return u(E);if(!w){--_||u();return}if(n.push(de.normalize(y)+(w.isDirectory()?r.sep:"")),!w.isDirectory()){--_||u();return}r.fs.realpath(y,function(S,I){if(S)return u(S);if(l.has(I)){--_||u();return}l.add(I),a(y,l,function(m){if(m)return u(m);--_||u()})})})})})},"walk");r.fs.realpath(t,function(c,l){if(c)return i(c);a(t,new Set([l]),i)})};ne.prototype.getAttributes=function(){};ne.prototype.setAttributes=function(){};ne.crc32update=function(t,e){return zf[(t^e)&255]^t>>>8};ne.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=ne.crc32update(r,t[n++]);return~r>>>0};ne.methodToString=function(t){switch(t){case Hf.STORED:return"STORED ("+t+")";case Hf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ne.canonical=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.join(".",e)};ne.zipnamefix=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.posix.join(".",e)};ne.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};ne.sanitize=function(t,e){t=de.resolve(de.normalize(t));for(var r=e.split("/"),n=0,s=r.length;n<s;n++){var i=de.normalize(de.join(t,r.slice(n,s).join(de.sep)));if(i===t||i.startsWith(t+de.sep))return i}return de.normalize(de.join(t,de.basename(e)))};ne.toBuffer=o(function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)},"toBuffer");ne.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ne.writeBigUInt64LE=function(t,e,r){let n=e>>>0,s=Math.floor(e/4294967296)>>>0;t.writeUInt32LE(n,r),t.writeUInt32LE(s,r+4)};ne.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ne.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};ne.isWin=o0;ne.crcTable=zf});var Kf=P((O5,qf)=>{var c0=require("path");qf.exports=function(t,{fs:e}){var r=t||"",n=i(),s=null;function i(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return o(i,"newAttr"),r&&e.existsSync(r)?(s=e.statSync(r),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=c0.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:o(function(){},"decodeAttributes"),encodeAttributes:o(function(){},"encodeAttributes"),toJSON:o(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Jf=P((M5,Zf)=>{Zf.exports={efs:!0,encode:o(t=>Buffer.from(t,"utf8"),"encode"),decode:o(t=>t.toString("utf8"),"decode")}});var sr=P((P5,nr)=>{nr.exports=Wf();nr.exports.Constants=ya();nr.exports.Errors=rs();nr.exports.FileAttr=Kf();nr.exports.decoder=Jf()});var Xf=P((L5,Yf)=>{var It=sr(),M=It.Constants;Yf.exports=function(){var t=20,e=10,r=0,n=0,s=0,i=0,a=0,c=0,l=0,u=0,d=0,p=0,_=0,g=0,y=0;t|=It.isWin?2560:768,r|=M.FLG_EFS;let E={extraLen:0},w=o(m=>Math.max(0,m)>>>0,"uint32"),S=o(m=>Math.max(0,m)&65535,"uint16"),I=o(m=>Math.max(0,m)&255,"uint8");return s=It.fromDate2DOS(new Date),{get made(){return t},set made(m){t=m},get version(){return e},set version(m){e=m},get flags(){return r},set flags(m){r=m},get flags_efs(){return(r&M.FLG_EFS)>0},set flags_efs(m){m?r|=M.FLG_EFS:r&=~M.FLG_EFS},get flags_desc(){return(r&M.FLG_DESC)>0},set flags_desc(m){m?r|=M.FLG_DESC:r&=~M.FLG_DESC},get method(){return n},set method(m){switch(m){case M.STORED:this.version=10;break;case M.DEFLATED:default:this.version=20}n=m},get time(){return It.fromDOS2Date(this.timeval)},set time(m){m=new Date(m),this.timeval=It.fromDate2DOS(m)},get timeval(){return s},set timeval(m){s=w(m)},get timeHighByte(){return I(s>>>8)},get crc(){return i},set crc(m){i=w(m)},get compressedSize(){return a},set compressedSize(m){a=w(m)},get size(){return c},set size(m){c=w(m)},get fileNameLength(){return l},set fileNameLength(m){l=m},get extraLength(){return u},set extraLength(m){u=m},get extraLocalLength(){return E.extraLen},set extraLocalLength(m){E.extraLen=m},get commentLength(){return d},set commentLength(m){d=m},get diskNumStart(){return p},set diskNumStart(m){p=w(m)},get inAttr(){return _},set inAttr(m){_=w(m)},get attr(){return g},set attr(m){g=w(m)},get fileAttr(){return(g||0)>>16&4095},get offset(){return y},set offset(m){y=w(m)},get encrypted(){return(r&M.FLG_ENC)===M.FLG_ENC},get centralHeaderSize(){return M.CENHDR+l+u+d},get realDataOffset(){return y+M.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:o(function(m){var T=m.slice(y,y+M.LOCHDR);if(T.readUInt32LE(0)!==M.LOCSIG)throw It.Errors.INVALID_LOC();E.version=T.readUInt16LE(M.LOCVER),E.flags=T.readUInt16LE(M.LOCFLG),E.flags_desc=(E.flags&M.FLG_DESC)>0,E.method=T.readUInt16LE(M.LOCHOW),E.time=T.readUInt32LE(M.LOCTIM),E.crc=T.readUInt32LE(M.LOCCRC),E.compressedSize=T.readUInt32LE(M.LOCSIZ),E.size=T.readUInt32LE(M.LOCLEN),E.fnameLen=T.readUInt16LE(M.LOCNAM),E.extraLen=T.readUInt16LE(M.LOCEXT);let A=y+M.LOCHDR+E.fnameLen,N=A+E.extraLen;return m.slice(A,N)},"loadLocalHeaderFromBinary"),loadFromBinary:o(function(m){if(m.length!==M.CENHDR||m.readUInt32LE(0)!==M.CENSIG)throw It.Errors.INVALID_CEN();t=m.readUInt16LE(M.CENVEM),e=m.readUInt16LE(M.CENVER),r=m.readUInt16LE(M.CENFLG),n=m.readUInt16LE(M.CENHOW),s=m.readUInt32LE(M.CENTIM),i=m.readUInt32LE(M.CENCRC),a=m.readUInt32LE(M.CENSIZ),c=m.readUInt32LE(M.CENLEN),l=m.readUInt16LE(M.CENNAM),u=m.readUInt16LE(M.CENEXT),d=m.readUInt16LE(M.CENCOM),p=m.readUInt16LE(M.CENDSK),_=m.readUInt16LE(M.CENATT),g=m.readUInt32LE(M.CENATX),y=m.readUInt32LE(M.CENOFF)},"loadFromBinary"),localHeaderToBinary:o(function(){var m=Buffer.alloc(M.LOCHDR);return m.writeUInt32LE(M.LOCSIG,0),m.writeUInt16LE(e,M.LOCVER),m.writeUInt16LE(r&~M.FLG_DESC,M.LOCFLG),m.writeUInt16LE(n,M.LOCHOW),m.writeUInt32LE(s,M.LOCTIM),m.writeUInt32LE(i,M.LOCCRC),m.writeUInt32LE(a,M.LOCSIZ),m.writeUInt32LE(c,M.LOCLEN),m.writeUInt16LE(l,M.LOCNAM),m.writeUInt16LE(E.extraLen,M.LOCEXT),m},"localHeaderToBinary"),centralHeaderToBinary:o(function(){var m=Buffer.alloc(M.CENHDR+l+u+d);return m.writeUInt32LE(M.CENSIG,0),m.writeUInt16LE(t,M.CENVEM),m.writeUInt16LE(e,M.CENVER),m.writeUInt16LE(r&~M.FLG_DESC,M.CENFLG),m.writeUInt16LE(n,M.CENHOW),m.writeUInt32LE(s,M.CENTIM),m.writeUInt32LE(i,M.CENCRC),m.writeUInt32LE(a,M.CENSIZ),m.writeUInt32LE(c,M.CENLEN),m.writeUInt16LE(l,M.CENNAM),m.writeUInt16LE(u,M.CENEXT),m.writeUInt16LE(d,M.CENCOM),m.writeUInt16LE(p,M.CENDSK),m.writeUInt16LE(_,M.CENATT),m.writeUInt32LE(g,M.CENATX),m.writeUInt32LE(y,M.CENOFF),m},"centralHeaderToBinary"),toJSON:o(function(){let m=o(function(T){return T+" bytes"},"bytes");return{made:t,version:e,flags:r,method:It.methodToString(n),time:this.time,crc:"0x"+i.toString(16).toUpperCase(),compressedSize:m(a),size:m(c),fileNameLength:m(l),extraLength:m(u),commentLength:m(d),diskNumStart:p,inAttr:_,attr:g,offset:y,centralHeaderSize:m(M.CENHDR+l+u+d)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ep=P(($5,Qf)=>{var qe=sr(),H=qe.Constants;Qf.exports=function(){var t=0,e=0,r=0,n=0,s=0;let i=o(()=>t>H.EF_ZIP64_OR_16||e>H.EF_ZIP64_OR_16||r>H.EF_ZIP64_OR_32||n>H.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return r},set size(a){r=a},get offset(){return n},set offset(a){n=a},get commentLength(){return s},set commentLength(a){s=a},get mainHeaderSize(){return(i()?H.ZIP64HDR+H.END64HDR:0)+H.ENDHDR+s},loadFromBinary:o(function(a){if((a.length!==H.ENDHDR||a.readUInt32LE(0)!==H.ENDSIG)&&(a.length<H.ZIP64HDR||a.readUInt32LE(0)!==H.ZIP64SIG))throw qe.Errors.INVALID_END();a.readUInt32LE(0)===H.ENDSIG?(t=a.readUInt16LE(H.ENDSUB),e=a.readUInt16LE(H.ENDTOT),r=a.readUInt32LE(H.ENDSIZ),n=a.readUInt32LE(H.ENDOFF),s=a.readUInt16LE(H.ENDCOM)):(t=qe.readBigUInt64LE(a,H.ZIP64SUB),e=qe.readBigUInt64LE(a,H.ZIP64TOT),r=qe.readBigUInt64LE(a,H.ZIP64SIZB),n=qe.readBigUInt64LE(a,H.ZIP64OFF),s=0)},"loadFromBinary"),toBinary:o(function(){if(!i()){var a=Buffer.alloc(H.ENDHDR+s);return a.writeUInt32LE(H.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,H.ENDSUB),a.writeUInt16LE(e,H.ENDTOT),a.writeUInt32LE(r,H.ENDSIZ),a.writeUInt32LE(n,H.ENDOFF),a.writeUInt16LE(s,H.ENDCOM),a.fill(" ",H.ENDHDR),a}var a=Buffer.alloc(this.mainHeaderSize);let c=0;a.writeUInt32LE(H.ZIP64SIG,c),qe.writeBigUInt64LE(a,H.ZIP64HDR-H.ZIP64LEAD,c+H.ZIP64SIZE),a.writeUInt16LE(45,c+H.ZIP64VEM),a.writeUInt16LE(45,c+H.ZIP64VER),a.writeUInt32LE(0,c+H.ZIP64DSK),a.writeUInt32LE(0,c+H.ZIP64DSKDIR),qe.writeBigUInt64LE(a,t,c+H.ZIP64SUB),qe.writeBigUInt64LE(a,e,c+H.ZIP64TOT),qe.writeBigUInt64LE(a,r,c+H.ZIP64SIZB),qe.writeBigUInt64LE(a,n,c+H.ZIP64OFF);let l=n+r;return c+=H.ZIP64HDR,a.writeUInt32LE(H.END64SIG,c),a.writeUInt32LE(0,c+H.END64START),qe.writeBigUInt64LE(a,l,c+H.END64OFF),a.writeUInt32LE(1,c+H.END64NUMDISKS),c+=H.END64HDR,a.writeUInt32LE(H.ENDSIG,c),a.writeUInt32LE(0,c+4),a.writeUInt16LE(Math.min(t,H.EF_ZIP64_OR_16),c+H.ENDSUB),a.writeUInt16LE(Math.min(e,H.EF_ZIP64_OR_16),c+H.ENDTOT),a.writeUInt32LE(Math.min(r,H.EF_ZIP64_OR_32),c+H.ENDSIZ),a.writeUInt32LE(Math.min(n,H.EF_ZIP64_OR_32),c+H.ENDOFF),a.writeUInt16LE(s,c+H.ENDCOM),a.fill(" ",c+H.ENDHDR),a},"toBinary"),toJSON:o(function(){let a=o(function(c,l){let u=c.toString(16).toUpperCase();for(;u.length<l;)u="0"+u;return"0x"+u},"offset");return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:a(n,4),commentLength:s}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ba=P(_a=>{_a.EntryHeader=Xf();_a.MainHeader=ep()});var rp=P((B5,tp)=>{tp.exports=function(t){var e=require("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:o(function(){return e.deflateRawSync(t,r)},"deflate"),deflateAsync:o(function(n){var s=e.createDeflateRaw(r),i=[],a=0;s.on("data",function(c){i.push(c),a+=c.length}),s.on("end",function(){var c=Buffer.alloc(a),l=0;c.fill(0);for(var u=0;u<i.length;u++){var d=i[u];d.copy(c,l),l+=d.length}n&&n(c)}),s.end(t)},"deflateAsync")}}});var sp=P((H5,np)=>{var l0=+(process?.versions?.node??"").split(".")[0]||0;np.exports=function(t,e){var r=require("zlib");let n=l0>=15&&e>0?{maxOutputLength:e}:{};return{inflate:o(function(){return r.inflateRawSync(t,n)},"inflate"),inflateAsync:o(function(s){var i=r.createInflateRaw(n),a=[],c=0;i.on("data",function(l){a.push(l),c+=l.length}),i.on("end",function(){var l=Buffer.alloc(c),u=0;l.fill(0);for(var d=0;d<a.length;d++){var p=a[d];p.copy(l,u),u+=p.length}s&&s(l)}),i.end(t)},"inflateAsync")}}});var lp=P((z5,cp)=>{"use strict";var{randomFillSync:ip}=require("crypto"),u0=rs(),d0=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),op=o((t,e)=>Math.imul(t,e)>>>0,"uMul"),ap=o((t,e)=>d0[(t^e)&255]^t>>>8,"crc32update"),Br=o(()=>typeof ip=="function"?ip(Buffer.alloc(12)):Br.node(),"genSalt");Br.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ns={genSalt:Br};function ss(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}o(ss,"Initkeys");ss.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ap(e[0],t),e[1]+=e[0]&255,e[1]=op(e[1],134775813)+1,e[2]=ap(e[2],e[1]>>>24),t};ss.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return op(t,t^1)>>8&255};function f0(t){let e=new ss(t);return function(r){let n=Buffer.alloc(r.length),s=0;for(let i of r)n[s++]=e.updateKeys(i^e.next());return n}}o(f0,"make_decrypter");function p0(t){let e=new ss(t);return function(r,n,s=0){n||(n=Buffer.alloc(r.length));for(let i of r){let a=e.next();n[s++]=i^a,e.updateKeys(i)}return n}}o(p0,"make_encrypter");function m0(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=f0(r),s=n(t.slice(0,12)),i=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==i)throw u0.WRONG_PASSWORD();return n(t.slice(12))}o(m0,"decrypt");function h0(t){Buffer.isBuffer(t)&&t.length>=12?ns.genSalt=function(){return t.slice(0,12)}:t==="node"?ns.genSalt=Br.node:ns.genSalt=Br}o(h0,"_salter");function g0(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=p0(r),i=ns.genSalt();i[11]=e.crc>>>24&255,n&&(i[10]=e.crc>>>16&255);let a=Buffer.alloc(t.length+12);return s(i,a),s(t,a,12)}o(g0,"encrypt");cp.exports={decrypt:m0,encrypt:g0,_salter:h0}});var up=P(is=>{is.Deflater=rp();is.Inflater=sp();is.ZipCrypto=lp()});var wa=P((q5,dp)=>{var X=sr(),y0=ba(),je=X.Constants,Ea=up();dp.exports=function(t,e){var r=new y0.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),i=!1,a=null,c=Buffer.alloc(0),l=Buffer.alloc(0),u=!0;let d=t,p=typeof d.decoder=="object"?d.decoder:X.decoder;u=p.hasOwnProperty("efs")?p.efs:!1;function _(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}o(_,"getCompressedDataFromZip");function g(m){let T=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return X.crc32(m)===T}o(g,"crc32OK");function y(m,T,A){if(typeof T>"u"&&typeof m=="string"&&(A=m,m=void 0),i)return m&&T&&T(Buffer.alloc(0),X.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var N=_();if(N.length===0)return m&&T&&T(N),N;if(r.encrypted){if(typeof A!="string"&&!Buffer.isBuffer(A))throw X.Errors.INVALID_PASS_PARAM();N=Ea.ZipCrypto.decrypt(N,r,A)}var O;switch(r.method){case X.Constants.STORED:if(O=Buffer.alloc(N.length),N.copy(O),g(O))return m&&T&&T(O),O;throw m&&T&&T(O,X.Errors.BAD_CRC()),X.Errors.BAD_CRC();case X.Constants.DEFLATED:var b=new Ea.Inflater(N,r.size);if(m)b.inflateAsync(function(j){T&&(g(j)?T(j):T(j,X.Errors.BAD_CRC()))});else{if(O=b.inflate(),!g(O))throw X.Errors.BAD_CRC(`"${p.decode(n)}"`);return O}break;default:throw m&&T&&T(Buffer.alloc(0),X.Errors.UNKNOWN_METHOD()),X.Errors.UNKNOWN_METHOD()}}o(y,"decompress");function E(m,T){if((!a||!a.length)&&Buffer.isBuffer(e))return m&&T&&T(_()),_();if(a.length&&!i){var A;switch(r.method){case X.Constants.STORED:return r.compressedSize=r.size,A=Buffer.alloc(a.length),a.copy(A),m&&T&&T(A),A;default:case X.Constants.DEFLATED:var N=new Ea.Deflater(a);if(m)N.deflateAsync(function(b){A=Buffer.alloc(b.length),r.compressedSize=b.length,b.copy(A),T&&T(A)});else{var O=N.deflate();return r.compressedSize=O.length,O}N=null;break}}else if(m&&T)T(Buffer.alloc(0));else return Buffer.alloc(0)}o(E,"compress");function w(m,T){return X.readBigUInt64LE(m,T)}o(w,"readUInt64LE");function S(m){try{for(var T=0,A,N,O;T+4<m.length;)A=m.readUInt16LE(T),T+=2,N=m.readUInt16LE(T),T+=2,O=m.slice(T,T+N),T+=N,je.ID_ZIP64===A&&I(O)}catch{throw X.Errors.EXTRA_FIELD_PARSE_ERROR()}}o(S,"parseExtra");function I(m){var T,A,N,O;m.length>=je.EF_ZIP64_SCOMP&&(T=w(m,je.EF_ZIP64_SUNCOMP),r.size===je.EF_ZIP64_OR_32&&(r.size=T)),m.length>=je.EF_ZIP64_RHO&&(A=w(m,je.EF_ZIP64_SCOMP),r.compressedSize===je.EF_ZIP64_OR_32&&(r.compressedSize=A)),m.length>=je.EF_ZIP64_DSN&&(N=w(m,je.EF_ZIP64_RHO),r.offset===je.EF_ZIP64_OR_32&&(r.offset=N)),m.length>=je.EF_ZIP64_DSN+4&&(O=m.readUInt32LE(je.EF_ZIP64_DSN),r.diskNumStart===je.EF_ZIP64_OR_16&&(r.diskNumStart=O))}return o(I,"parseZip64ExtendedInformation"),{get entryName(){return p.decode(n)},get rawEntryName(){return n},set entryName(m){n=X.toBuffer(m,p.encode);var T=n[n.length-1];i=T===47||T===92,r.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return c},set extra(m){c=m,r.extraLength=m.length,S(m)},get comment(){return p.decode(s)},set comment(m){if(s=X.toBuffer(m,p.encode),r.commentLength=s.length,s.length>65535)throw X.Errors.COMMENT_TOO_LONG()},get name(){let m=p.decode(n);return i?m.replace(/[/\\]$/,"").split("/").pop():m.split("/").pop()},get isDirectory(){return i},getCompressedData:o(function(){return E(!1,null)},"getCompressedData"),getCompressedDataAsync:o(function(m){E(!0,m)},"getCompressedDataAsync"),setData:o(function(m){a=X.toBuffer(m,X.decoder.encode),!i&&a.length?(r.size=a.length,r.method=X.Constants.DEFLATED,r.crc=X.crc32(m),r.changed=!0):r.method=X.Constants.STORED},"setData"),getData:o(function(m){return r.changed?a:y(!1,null,m)},"getData"),getDataAsync:o(function(m,T){r.changed?m(a):y(!0,m,T)},"getDataAsync"),set attr(m){r.attr=m},get attr(){return r.attr},set header(m){r.loadFromBinary(m)},get header(){return r},packCentralHeader:o(function(){r.flags_efs=this.efs,r.extraLength=c.length;var m=r.centralHeaderToBinary(),T=X.Constants.CENHDR;return n.copy(m,T),T+=n.length,c.copy(m,T),T+=r.extraLength,s.copy(m,T),m},"packCentralHeader"),packLocalHeader:o(function(){let m=0;r.flags_efs=this.efs,r.extraLocalLength=l.length;let T=r.localHeaderToBinary(),A=Buffer.alloc(T.length+n.length+r.extraLocalLength);return T.copy(A,m),m+=T.length,n.copy(A,m),m+=n.length,l.copy(A,m),m+=l.length,A},"packLocalHeader"),toJSON:o(function(){let m=o(function(T){return"<"+(T&&T.length+" bytes buffer"||"null")+">"},"bytes");return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:m(e),data:m(a)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var mp=P((Z5,pp)=>{var fp=wa(),_0=ba(),Ne=sr();pp.exports=function(t,e){var r=[],n=Object.create(null),s=Buffer.alloc(0),i=new _0.MainHeader,a=!1,c=null;let l=new Set,u=e,{noSort:d,decoder:p}=u;t?y(u.readEntries):a=!0;function _(){let w=new Set;for(let S of Object.keys(n)){let I=S.split("/");if(I.pop(),!!I.length)for(let m=0;m<I.length;m++){let T=I.slice(0,m+1).join("/")+"/";w.add(T)}}for(let S of w)if(!(S in n)){let I=new fp(u);I.entryName=S,I.attr=16,I.temporary=!0,r.push(I),n[I.entryName]=I,l.add(I)}}o(_,"makeTemporaryFolders");function g(){if(a=!0,n=Object.create(null),i.diskEntries>(t.length-i.offset)/Ne.Constants.CENHDR)throw Ne.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(i.diskEntries);for(var w=i.offset,S=0;S<r.length;S++){var I=w,m=new fp(u,t);m.header=t.slice(I,I+=Ne.Constants.CENHDR),m.entryName=t.slice(I,I+=m.header.fileNameLength),m.header.extraLength&&(m.extra=t.slice(I,I+=m.header.extraLength)),m.header.commentLength&&(m.comment=t.slice(I,I+m.header.commentLength)),w+=m.header.centralHeaderSize,r[S]=m,n[m.entryName]=m}l.clear(),_()}o(g,"readEntries");function y(w){var S=t.length-Ne.Constants.ENDHDR,I=Math.max(0,S-65535),m=I,T=t.length,A=-1,N=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(I=0),S;S>=m;S--)if(t[S]===80){if(t.readUInt32LE(S)===Ne.Constants.ENDSIG){A=S,N=S,T=S+Ne.Constants.ENDHDR,m=S-Ne.Constants.END64HDR;continue}if(t.readUInt32LE(S)===Ne.Constants.END64SIG){m=I;continue}if(t.readUInt32LE(S)===Ne.Constants.ZIP64SIG){A=S,T=S+Ne.readBigUInt64LE(t,S+Ne.Constants.ZIP64SIZE)+Ne.Constants.ZIP64LEAD;break}}if(A==-1)throw Ne.Errors.INVALID_FORMAT();i.loadFromBinary(t.slice(A,T)),i.commentLength&&(s=t.slice(N+Ne.Constants.ENDHDR)),w&&g()}o(y,"readMainHeader");function E(){r.length>1&&!d&&(r=r.map(w=>({entry:w,key:w.entryName.toLowerCase()})).sort((w,S)=>w.key.localeCompare(S.key)).map(w=>w.entry))}return o(E,"sortEntries"),{get entries(){return a||g(),r.filter(w=>!l.has(w))},get comment(){return p.decode(s)},set comment(w){s=Ne.toBuffer(w,p.encode),i.commentLength=s.length},getEntryCount:o(function(){return a?r.length:i.diskEntries},"getEntryCount"),forEach:o(function(w){this.entries.forEach(w)},"forEach"),getEntry:o(function(w){return a||g(),n[w]||null},"getEntry"),setEntry:o(function(w){a||g(),r.push(w),n[w.entryName]=w,i.totalEntries=r.length},"setEntry"),deleteFile:o(function(w,S=!0){a||g();let I=n[w];this.getEntryChildren(I,S).map(T=>T.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:o(function(w){a||g();let S=n[w],I=r.indexOf(S);I>=0&&(r.splice(I,1),delete n[w],i.totalEntries=r.length)},"deleteEntry"),getEntryChildren:o(function(w,S=!0){if(a||g(),typeof w=="object")if(w.isDirectory&&S){let I=[],m=w.entryName;for(let T of r)T.entryName.startsWith(m)&&I.push(T);return I}else return[w];return[]},"getEntryChildren"),getChildCount:o(function(w){if(w&&w.isDirectory){let S=this.getEntryChildren(w);return S.includes(w)?S.length-1:S.length}return 0},"getChildCount"),compressToBuffer:o(function(){a||g(),E();let w=[],S=[],I=0,m=0;i.size=0,i.offset=0;let T=0;for(let O of this.entries){let b=O.getCompressedData();O.header.offset=m;let j=O.packLocalHeader(),G=j.length+b.length;m+=G,w.push(j),w.push(b);let B=O.packCentralHeader();S.push(B),i.size+=B.length,I+=G+B.length,T++}I+=i.mainHeaderSize,i.offset=m,i.totalEntries=T,m=0;let A=Buffer.alloc(I);for(let O of w)O.copy(A,m),m+=O.length;for(let O of S)O.copy(A,m),m+=O.length;let N=i.toBinary();return s&&s.copy(N,N.length-s.length),N.copy(A,m),t=A,a=!1,A},"compressToBuffer"),toAsyncBuffer:o(function(w,S,I,m){try{a||g(),E();let T=[],A=[],N=0,O=0,b=0;i.size=0,i.offset=0;let j=o(function(G){if(G.length>0){let B=G.shift(),Z=B.entryName+B.extra.toString();I&&I(Z),B.getCompressedDataAsync(function(ce){m&&m(Z),B.header.offset=O;let ke=B.packLocalHeader(),xt=ke.length+ce.length;O+=xt,T.push(ke),T.push(ce);let K=B.packCentralHeader();A.push(K),i.size+=K.length,N+=xt+K.length,b++,j(G)})}else{N+=i.mainHeaderSize,i.offset=O,i.totalEntries=b,O=0;let B=Buffer.alloc(N);T.forEach(function(ce){ce.copy(B,O),O+=ce.length}),A.forEach(function(ce){ce.copy(B,O),O+=ce.length});let Z=i.toBinary();s&&s.copy(Z,Z.length-s.length),Z.copy(B,O),t=B,a=!1,w(B)}},"compress2Buffer");j(Array.from(this.entries))}catch(T){S(T)}},"toAsyncBuffer")}}});var yp=P((Y5,gp)=>{var ae=sr(),ie=require("path"),b0=wa(),E0=mp(),jt=o((...t)=>ae.findLast(t,e=>typeof e=="boolean"),"get_Bool"),hp=o((...t)=>ae.findLast(t,e=>typeof e=="string"),"get_Str"),w0=o((...t)=>ae.findLast(t,e=>typeof e=="function"),"get_Fun"),T0={noSort:!1,readEntries:!1,method:ae.Constants.NONE,fs:null};gp.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),T0);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=ae.Constants.BUFFER,t=void 0)),Object.assign(n,e);let s=new ae(n),i=o(y=>{y.filter(E=>E.attr).sort((E,w)=>w.path.length-E.path.length).forEach(E=>s.fs.chmodSync(E.path,E.attr))},"applyDirAttributes");if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=ae.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))n.method=ae.Constants.FILE,n.filename=t,r=s.fs.readFileSync(t);else throw ae.Errors.INVALID_FILENAME();let a=new E0(r,n),{canonical:c,sanitize:l,zipnamefix:u}=ae;function d(y){if(y&&a){var E;if(typeof y=="string"&&(E=a.getEntry(ie.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(E=a.getEntry(y.entryName)),E)return E}return null}o(d,"getEntry");function p(y){let{join:E,normalize:w,sep:S}=ie.posix;return E(ie.isAbsolute(y)?"/":".",w(S+y.split("\\").join(S)+S))}o(p,"fixPath");function _(y){return y instanceof RegExp?(function(E){return function(w){return E.test(w)}})(y):typeof y!="function"?()=>!0:y}o(_,"filenameFilter");let g=o((y,E)=>{let w=E.slice(-1);return w=w===s.sep?s.sep:"",ie.relative(y,E)+w},"relativePath");return{readFile:o(function(y,E){var w=d(y);return w&&w.getData(E)||null},"readFile"),childCount:o(function(y){let E=d(y);if(E)return a.getChildCount(E)},"childCount"),readFileAsync:o(function(y,E){var w=d(y);w?w.getDataAsync(E):E(null,"getEntry failed for:"+y)},"readFileAsync"),readAsText:o(function(y,E){var w=d(y);if(w){var S=w.getData();if(S&&S.length)return S.toString(E||"utf8")}return""},"readAsText"),readAsTextAsync:o(function(y,E,w){var S=d(y);S?S.getDataAsync(function(I,m){if(m){E(I,m);return}I&&I.length?E(I.toString(w||"utf8")):E("")}):E("")},"readAsTextAsync"),deleteFile:o(function(y,E=!0){var w=d(y);w&&a.deleteFile(w.entryName,E)},"deleteFile"),deleteEntry:o(function(y){var E=d(y);E&&a.deleteEntry(E.entryName)},"deleteEntry"),addZipComment:o(function(y){a.comment=y},"addZipComment"),getZipComment:o(function(){return a.comment||""},"getZipComment"),addZipEntryComment:o(function(y,E){var w=d(y);w&&(w.comment=E)},"addZipEntryComment"),getZipEntryComment:o(function(y){var E=d(y);return E&&E.comment||""},"getZipEntryComment"),updateFile:o(function(y,E){var w=d(y);w&&w.setData(E)},"updateFile"),addLocalFile:o(function(y,E,w,S){if(s.fs.existsSync(y)){E=E?p(E):"";let I=ie.win32.basename(ie.win32.normalize(y));E+=w||I;let m=s.fs.statSync(y),T=m.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);m.isDirectory()&&(E+=s.sep),this.addFile(E,T,S,m)}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFile"),addLocalFileAsync:o(function(y,E){y=typeof y=="object"?y:{localPath:y};let w=ie.resolve(y.localPath),{comment:S}=y,{zipPath:I,zipName:m}=y,T=this;s.fs.stat(w,function(A,N){if(A)return E(A,!1);I=I?p(I):"";let O=ie.win32.basename(ie.win32.normalize(w));if(I+=m||O,N.isFile())s.fs.readFile(w,function(b,j){return b?E(b,!1):(T.addFile(I,j,S,N),setImmediate(E,void 0,!0))});else if(N.isDirectory())return I+=s.sep,T.addFile(I,Buffer.alloc(0),S,N),setImmediate(E,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:o(function(y,E,w){if(w=_(w),E=E?p(E):"",y=ie.normalize(y),s.fs.existsSync(y)){let S=s.findFiles(y),I=this;if(S.length)for(let m of S){let T=ie.join(E,g(y,m));w(T)&&I.addLocalFile(m,ie.dirname(T))}}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFolder"),addLocalFolderAsync:o(function(y,E,w,S){S=_(S),w=w?p(w):"",y=ie.normalize(y);var I=this;s.fs.open(y,"r",function(m){if(m&&m.code==="ENOENT")E(void 0,ae.Errors.FILE_NOT_FOUND(y));else if(m)E(void 0,m);else{var T=s.findFiles(y),A=-1,N=o(function(){if(A+=1,A<T.length){var O=T[A],b=g(y,O).split("\\").join("/");b=b.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),S(b)?s.fs.stat(O,function(j,G){j&&E(void 0,j),G.isFile()?s.fs.readFile(O,function(B,Z){B?E(void 0,B):(I.addFile(w+b,Z,"",G),N())}):(I.addFile(w+b+"/",Buffer.alloc(0),"",G),N())}):process.nextTick(()=>{N()})}else E(!0,void 0)},"next");N()}})},"addLocalFolderAsync"),addLocalFolderAsync2:o(function(y,E){let w=this;y=typeof y=="object"?y:{localPath:y};let S=ie.resolve(p(y.localPath)),{zipPath:I,filter:m,namefix:T}=y;m instanceof RegExp?m=(function(O){return function(b){return O.test(b)}})(m):typeof m!="function"&&(m=o(function(){return!0},"filter")),I=I?p(I):"",T==="latin1"&&(T=o(O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof T!="function"&&(T=o(O=>O,"namefix"));let A=o(O=>ie.join(I,T(g(S,O))),"relPathFix"),N=o(O=>ie.win32.basename(ie.win32.normalize(T(O))),"fileNameFix");s.fs.open(S,"r",function(O){O&&O.code==="ENOENT"?E(void 0,ae.Errors.FILE_NOT_FOUND(S)):O?E(void 0,O):s.findFilesAsync(S,function(b,j){if(b)return E(b);j=j.filter(G=>m(A(G))),j.length||E(void 0,!1),setImmediate(j.reverse().reduce(function(G,B){return function(Z,ce){if(Z||ce===!1)return setImmediate(G,Z,!1);w.addLocalFileAsync({localPath:B,zipPath:ie.dirname(A(B)),zipName:N(B)},G)}},E))})})},"addLocalFolderAsync2"),addLocalFolderPromise:o(function(y,E){return new Promise((w,S)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},E),(I,m)=>{I&&S(I),m&&w(this)})})},"addLocalFolderPromise"),addFile:o(function(y,E,w,S){y=u(y);let I=d(y),m=I!=null;m||(I=new b0(n),I.entryName=y),I.comment=w||"";let T=typeof S=="object"&&S instanceof s.fs.Stats;T&&(I.header.time=S.mtime);var A=I.isDirectory?16:0;let N=I.isDirectory?16384:32768;return T?N|=4095&S.mode:typeof S=="number"?N|=4095&S:N|=I.isDirectory?493:420,A=(A|N<<16)>>>0,I.attr=A,I.setData(E),m||a.setEntry(I),I},"addFile"),getEntries:o(function(y){return a.password=y,a?a.entries:[]},"getEntries"),getEntry:o(function(y){return d(y)},"getEntry"),getEntryCount:o(function(){return a.getEntryCount()},"getEntryCount"),forEach:o(function(y){return a.forEach(y)},"forEach"),extractEntryTo:o(function(y,E,w,S,I,m){S=jt(!1,S),I=jt(!1,I),w=jt(!0,w),m=hp(I,m);var T=d(y);if(!T)throw ae.Errors.NO_ENTRY();var A=c(T.entryName),N=l(E,m&&!T.isDirectory?c(m):w?A:ie.basename(A));if(T.isDirectory){var O=a.getEntryChildren(T);return O.forEach(function(G){if(G.isDirectory)return;var B=G.getData();if(!B)throw ae.Errors.CANT_EXTRACT_FILE();var Z=c(w?G.entryName:G.entryName.substring(T.entryName.length)),ce=l(E,Z);let ke=I?G.header.fileAttr:void 0;s.writeFileTo(ce,B,S,ke)}),!0}var b=T.getData(a.password);if(!b)throw ae.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(N)&&!S)throw ae.Errors.CANT_OVERRIDE();let j=I?y.header.fileAttr:void 0;return s.writeFileTo(N,b,S,j),!0},"extractEntryTo"),test:o(function(y){if(!a)return!1;for(var E of a.entries)try{if(E.isDirectory)continue;var w=E.getData(y);if(!w)return!1}catch{return!1}return!0},"test"),extractAllTo:o(function(y,E,w,S){if(w=jt(!1,w),S=hp(w,S),E=jt(!1,E),!a)throw ae.Errors.NO_ZIP();let I=[];a.entries.forEach(function(m){var T=l(y,c(m.entryName));if(m.isDirectory){s.makeDir(T),w&&I.push({path:T,attr:m.header.fileAttr});return}var A=m.getData(S);if(!A)throw ae.Errors.CANT_EXTRACT_FILE();let N=w?m.header.fileAttr:void 0;s.writeFileTo(T,A,E,N);try{s.fs.utimesSync(T,m.header.time,m.header.time)}catch{}}),i(I)},"extractAllTo"),extractAllToAsync:o(function(y,E,w,S){if(S=w0(E,w,S),w=jt(!1,w),E=jt(!1,E),!S)return new Promise((b,j)=>{this.extractAllToAsync(y,E,w,function(G){G?j(G):b(this)})});if(!a){S(ae.Errors.NO_ZIP());return}y=ie.resolve(y);let I=o(b=>l(y,ie.normalize(c(b.entryName))),"getPath"),m=o((b,j)=>new Error(b+': "'+j+'"'),"getError"),T=[],A=[];a.entries.forEach(b=>{b.isDirectory?T.push(b):A.push(b)});let N=[];for(let b of T){let j=I(b),G=w?b.header.fileAttr:void 0;try{s.makeDir(j)}catch{S(m("Unable to create folder",j));continue}G&&N.push({path:j,attr:G});try{s.fs.utimesSync(j,b.header.time,b.header.time)}catch{}}let O=o(b=>{if(!b)try{i(N)}catch(j){return S(m("Unable to set folder permissions",j.path||""))}S(b)},"done");A.reverse().reduce(function(b,j){return function(G){if(G)b(G);else{let B=ie.normalize(c(j.entryName)),Z=l(y,B);j.getDataAsync(function(ce,ke){if(ke)b(ke);else if(!ce)b(ae.Errors.CANT_EXTRACT_FILE());else{let xt=w?j.header.fileAttr:void 0;s.writeFileToAsync(Z,ce,E,xt,function(K){if(!K)return b(m("Unable to write file",Z));s.fs.utimes(Z,j.header.time,j.header.time,function(){b()})})}})}}},O)()},"extractAllToAsync"),writeZip:o(function(y,E){if(arguments.length===1&&typeof y=="function"&&(E=y,y=""),!y&&n.filename&&(y=n.filename),!!y){var w=a.compressToBuffer();if(w){var S=s.writeFileTo(y,w,!0);typeof E=="function"&&E(S?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:o(function(y,E){let{overwrite:w,perm:S}=Object.assign({overwrite:!0},E);return new Promise((I,m)=>{!y&&n.filename&&(y=n.filename),y||m("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(T=>{let A=o(N=>N?I(N):m("ADM-ZIP: Wasn't able to write zip file"),"ret");s.writeFileToAsync(y,T,w,S,A)},m)})},"writeZipPromise"),toBufferPromise:o(function(){return new Promise((y,E)=>{a.toAsyncBuffer(y,E)})},"toBufferPromise"),toBuffer:o(function(y,E,w,S){return typeof y=="function"?(a.toAsyncBuffer(y,E,w,S),null):a.compressToBuffer()},"toBuffer")}}});var Sp=P((tH,yt)=>{var va=require("fs"),os=require("path"),S0=require("os"),I0=require("crypto"),bp=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function x0(){return bp[Math.floor(Math.random()*bp.length)]}o(x0,"_getRandomTip");function ir(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(ir,"parseBoolean");function A0(){return process.stdout.isTTY}o(A0,"supportsAnsi");function C0(t){return A0()?`\x1B[2m${t}\x1B[0m`:t}o(C0,"dim");var R0=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function O0(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
4
|
+
`);let n;for(;(n=R0.exec(r))!=null;){let s=n[1],i=n[2]||"";i=i.trim();let a=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),a==='"'&&(i=i.replace(/\\n/g,`
|
|
5
|
+
`),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(O0,"parse");function N0(t){t=t||{};let e=vp(t);t.path=e;let r=me.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=Tp(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=k0(r,c);i=me.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return me.parse(i)}o(N0,"_parseVault");function M0(t){console.error(`\u26A0 ${t}`)}o(M0,"_warn");function jr(t){console.log(`\u2506 ${t}`)}o(jr,"_debug");function wp(t){console.log(`\u25C7 ${t}`)}o(wp,"_log");function Tp(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(Tp,"_dotenvKey");function k0(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(k0,"_instructions");function vp(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)va.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=os.resolve(process.cwd(),".env.vault");return va.existsSync(e)?e:null}o(vp,"_vaultPath");function Ep(t){return t[0]==="~"?os.join(S0.homedir(),t.slice(1)):t}o(Ep,"_resolveHome");function P0(t){let e=ir(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=ir(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&wp("loading env from encrypted .env.vault");let n=me._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),me.populate(s,n,t),{parsed:n}}o(P0,"_configVault");function L0(t){let e=os.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=ir(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=ir(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&jr("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[Ep(t.path)];else{a=[];for(let d of t.path)a.push(Ep(d))}let c,l={};for(let d of a)try{let p=me.parse(va.readFileSync(d,{encoding:r}));me.populate(l,p,t)}catch(p){s&&jr(`failed to load ${d} ${p.message}`),c=p}let u=me.populate(n,l,t);if(s=ir(n.DOTENV_CONFIG_DEBUG||s),i=ir(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,p=[];for(let _ of a)try{let g=os.relative(process.cwd(),_);p.push(g)}catch(g){s&&jr(`failed to load ${_} ${g.message}`),c=g}wp(`injected env (${d}) from ${p.join(",")} ${C0(`// tip: ${x0()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o(L0,"configDotenv");function D0(t){if(Tp(t).length===0)return me.configDotenv(t);let e=vp(t);return e?me._configVault(t):(M0(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),me.configDotenv(t))}o(D0,"config");function $0(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=I0.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o($0,"decrypt");function U0(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&jr(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(U0,"populate");var me={configDotenv:L0,_configVault:P0,_parseVault:N0,config:D0,decrypt:$0,parse:O0,populate:U0};yt.exports.configDotenv=me.configDotenv;yt.exports._configVault=me._configVault;yt.exports._parseVault=me._parseVault;yt.exports.config=me.config;yt.exports.decrypt=me.decrypt;yt.exports.parse=me.parse;yt.exports.populate=me.populate;yt.exports=me});var tv={};Pm(tv,{TestRunMonitor:()=>Ts});module.exports=Lm(tv);var As=o(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");var d5=require("@playwright/test");var k3=require("@playwright/test");var Uv=require("@playwright/test");var Pv=require("@playwright/test");var to=Object.defineProperty,q=o((t,e)=>{let r={};for(var n in t)to(r,n,{get:t[n],enumerable:!0});return e||to(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function ro(t){let e=Symbol.for(t);return{brand(r,n){let s=n?Symbol.for(`${t}.${n}`):e;class i extends r{static{o(this,"_Branded")}[s]=!0;constructor(...c){super(...c)}static isInstance(c){return typeof c=="object"&&c!==null&&s in c&&c[s]===!0}}return Object.defineProperty(i,"name",{value:r.name}),i},sub(r){return ro(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}o(ro,"createNamespace");var no=ro("langchain");var Cs=no.sub("error"),so=class extends Cs.brand(Error){static{o(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},$m=class extends Cs.brand(so,"model-abort"){static{o(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},Kv=class io extends Cs.brand(so,"context-overflow"){static{o(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new io(e.message);return r.cause=e,r}};var Um=/([A-Z]+)([A-Z][a-z0-9]+)/g,Fm=/([a-z0-9])([A-Z])/g,Bm=/[-_\s]+/g;function jm(t){return t.replace(Um,"$1_$2").replace(Fm,"$1_$2").replace(Bm,"_").toLowerCase()}o(jm,"snakeCase");function ao(t,e){return e?.[t]||jm(t)}o(ao,"keyToJson");function oo(t,e,r){let n={};for(let s in t)Object.hasOwn(t,s)&&(n[e(s,r)]=t[s]);return n}o(oo,"mapKeys");var Hm="__lc_escaped__";function Gm(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}o(Gm,"needsEscaping");function zm(t){return{[Hm]:t}}o(zm,"escapeObject");function Vm(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}o(Vm,"isSerializableLike");function Wm(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}o(Wm,"createNotImplemented");function Wr(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Wm(t);if(Vm(t))return t;e.add(t);let r=t;if(Gm(r))return e.delete(t),zm(r);let n={};for(let[s,i]of Object.entries(r))n[s]=Wr(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Wr(r,e)):t}o(Wr,"escapeIfNeeded");function co(t){return Array.isArray(t)?[...t]:{...t}}o(co,"shallowCopy");function qm(t,e){let r=co(t);for(let[n,s]of Object.entries(e)){let[i,...a]=n.split(".").reverse(),c=r;for(let l of a.reverse()){if(c[l]===void 0)break;c[l]=co(c[l]),c=c[l]}c[i]!==void 0&&(c[i]={lc:1,type:"secret",id:[s]})}return r}o(qm,"replaceSecrets");function Rs(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}o(Rs,"get_lc_unique_name");var Ot=class lo{static{o(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Rs(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof lo||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((c,l)=>(c[l]=l in this?this[l]:this.lc_kwargs[l],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let l=this,u=n,[d,...p]=c.split(".").reverse();for(let _ of p.reverse()){if(!(_ in l)||l[_]===void 0)return;(!(_ in u)||u[_]===void 0)&&(typeof l[_]=="object"&&l[_]!=null?u[_]={}:Array.isArray(l[_])&&(u[_]=[])),l=l[_],u=u[_]}d in l&&l[d]!==void 0&&(u[d]=u[d]||l[d])});let s={},i=new WeakSet;i.add(this);for(let[c,l]of Object.entries(n))s[c]=Wr(l,i);let a=oo(Object.keys(r).length?qm(s,r):s,ao,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function fr(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}o(fr,"isDataContentBlock");function qr(t){return fr(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}o(qr,"isURLContentBlock");function Kr(t){return fr(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}o(Kr,"isBase64ContentBlock");function Os(t){return fr(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}o(Os,"isIDContentBlock");function Zr({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let s=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:s}}}o(Zr,"parseBase64DataUrl");function k(t,e){return F(t)&&t.type===e}o(k,"_isContentBlock");function F(t){return typeof t=="object"&&t!==null}o(F,"_isObject");function fe(t){return Array.isArray(t)}o(fe,"_isArray");function x(t){return typeof t=="string"}o(x,"_isString");function Ue(t){return typeof t=="number"}o(Ue,"_isNumber");function Jr(t){return t instanceof Uint8Array}o(Jr,"_isBytesArray");function Ns(t){try{return JSON.parse(t)}catch{return}}o(Ns,"safeParseJson");var Fe=o(t=>t(),"iife");function Km(t){if(t.type==="char_location"&&x(t.document_title)&&Ue(t.start_char_index)&&Ue(t.end_char_index)&&x(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="page_location"&&x(t.document_title)&&Ue(t.start_page_number)&&Ue(t.end_page_number)&&x(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="content_block_location"&&x(t.document_title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="web_search_result_location"&&x(t.url)&&x(t.title)&&x(t.encrypted_index)&&x(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:s}}if(t.type==="search_result_location"&&x(t.source)&&x(t.title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:s,cited_text:i,...a}=t;return{...a,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:s,citedText:i}}}o(Km,"convertAnthropicAnnotation");function fo(t){if(k(t,"document")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&x(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(k(t,"image")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}o(fo,"convertToV1FromAnthropicContentBlock");function po(t){function*e(){for(let r of t){let n=fo(r);n?yield n:yield r}}return o(e,"iterateContent"),Array.from(e())}o(po,"convertToV1FromAnthropicInput");function uo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){let{text:s,citations:i,...a}=n;if(fe(i)&&i.length){let c=i.reduce((l,u)=>{let d=Km(u);return d?[...l,d]:l},[]);yield{...a,type:"text",text:s,annotations:c};continue}else{yield{...a,type:"text",text:s};continue}}else if(k(n,"thinking")&&x(n.thinking)){let{thinking:s,signature:i,...a}=n;yield{...a,type:"reasoning",reasoning:s,signature:i};continue}else if(k(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_use")&&x(n.name)&&x(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(k(n,"input_json_delta")){if(Zm(t)&&t.tool_call_chunks?.length){let s=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(k(n,"server_tool_use")&&x(n.name)&&x(n.id)){let{name:s,id:i}=n;if(s==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.query))return n.input.query;if(x(n.partial_json)){let a=Ns(n.partial_json);if(a?.query)return a.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.code))return n.input.code;if(x(n.partial_json)){let a=Ns(n.partial_json);if(a?.code)return a.code}return""})}};continue}}else if(k(n,"web_search_tool_result")&&x(n.tool_use_id)&&fe(n.content)){let{content:s,tool_use_id:i}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:s.reduce((a,c)=>k(c,"web_search_result")?[...a,c.url]:a,[])}};continue}else if(k(n,"code_execution_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(k(n,"mcp_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(k(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(k(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let s=fo(n);if(s){yield s;continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(uo,"convertToV1FromAnthropicMessage");var mo={translateContent:uo,translateContentChunk:uo};function Zm(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}o(Zm,"_isAIMessageChunk");function Jm(t){return qr(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Kr(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:Os(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}o(Jm,"convertToV1FromDataContentBlock");function ho(t){return t.map(Jm)}o(ho,"convertToV1FromDataContent");function go(t){return!!(k(t,"image_url")&&F(t.image_url)||k(t,"input_audio")&&F(t.input_audio)||k(t,"file")&&F(t.file))}o(go,"isOpenAIDataBlock");function yo(t){if(k(t,"image_url")&&F(t.image_url)&&x(t.image_url.url)){let e=Zr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(k(t,"input_audio")&&F(t.input_audio)&&x(t.input_audio.data)&&x(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(k(t,"file")&&F(t.file)&&x(t.file.data)){let e=Zr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(x(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}o(yo,"convertToV1FromOpenAIDataBlock");function Ym(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Ym,"convertToV1FromChatCompletions");function Xm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Xm,"convertToV1FromChatCompletionsChunk");function Yr(t){let e=[];for(let r of t)go(r)?e.push(yo(r)):e.push(r);return e}o(Yr,"convertToV1FromChatCompletionsInput");function Qm(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:s}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:s}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}o(Qm,"convertResponsesAnnotation");function _o(t){function*e(){F(t.additional_kwargs?.reasoning)&&fe(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,s)=>F(s)&&x(s.text)?`${n}${s.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(k(n,"text")){let{text:s,annotations:i,phase:a,extras:c,...l}=n,u=F(c)?{...c}:{};x(a)&&(u.phase=a);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(i)?yield{...l,...d,type:"text",text:String(s),annotations:i.map(Qm)}:yield{...l,...d,type:"text",text:String(s)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(F(t.additional_kwargs)&&fe(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(k(n,"web_search_call")){let s={};if(F(n.action)&&x(n.action.query)&&(s.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:s},n.status==="completed"||n.status==="failed"){let i={};F(n.action)&&(i.action=n.action),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:i}}continue}else if(k(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:fe(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:fe(n.results)?{results:n.results}:{}});continue}else if(k(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(k(n,"code_interpreter_call")){if(x(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),fe(n.outputs)){let s=Fe(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let i of n.outputs)if(k(i,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(i.logs),stdout:[0,void 0].includes(s)?String(i.logs):void 0}};continue}}continue}else if(k(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(k(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(k(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_search_call")){let s={};F(n.arguments)&&Object.assign(s,n.arguments);let i={};x(n.execution)&&(i.execution=n.execution),x(n.status)&&(i.status=n.status),x(n.call_id)&&(i.call_id=n.call_id),yield{id:x(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:s,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(k(n,"tool_search_output")){let s={name:"tool_search"};x(n.execution)&&(s.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:fe(n.tools)?n.tools:[]},extras:s};continue}else if(k(n,"image_generation_call")){x(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:x(n.id)?n.id:void 0,metadata:{status:x(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}F(n)&&(yield{type:"non_standard",value:n})}}return o(e,"iterateContent"),Array.from(e())}o(_o,"convertToV1FromResponses");function eh(t){function*e(){yield*_o(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return o(e,"iterateContent"),Array.from(e())}o(eh,"convertToV1FromResponsesChunk");var bo={translateContent:o(t=>typeof t.content=="string"?Ym(t):_o(t),"translateContent"),translateContentChunk:o(t=>typeof t.content=="string"?Xm(t):eh(t),"translateContentChunk")};function Ms(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}o(Ms,"isMessage");function Eo(t,e="pretty"){return e==="pretty"?th(t):JSON.stringify(t)}o(Eo,"convertToFormattedString");function th(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),s="=".repeat(n),i=r.length%2===0?s:`${s}=`;if(e.push(`${s}${r}${i}`),t.type==="ai"){let a=t;if(a.tool_calls&&a.tool_calls.length>0){e.push("Tool Calls:");for(let c of a.tool_calls){e.push(` ${c.name} (${c.id})`),e.push(` Call ID: ${c.id}`),e.push(" Args:");for(let[l,u]of Object.entries(c.args))e.push(` ${l}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){let a=t;a.name&&e.push(`Name: ${a.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
6
|
+
`)}o(th,"convertToPrettyString");var ks=Symbol.for("langchain.message");function rh(t,e){function r(n,s){if(typeof n!="object"||n===null||n===void 0)return n;if(s>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,s+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],s+1);return i}return o(r,"helper"),JSON.stringify(r(t,0),null,2)}o(rh,"stringifyWithDepthLimit");var ft=class extends Ot{static{o(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[ks]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[ho,Yr,po].reduce((e,r)=>r(e),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&ks in t&&t[ks]===!0&&Ms(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=rh(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Eo(this,t)}};function Ps(t){let e=[],r=[];for(let n of t)if(n.function){let s=n.function.name;try{let i=JSON.parse(n.function.arguments);e.push({name:s||"",args:i||{},id:n.id})}catch{r.push({name:s,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}o(Ps,"defaultToolCallParser");function Ls(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}o(Ls,"convertFileFormatToMimeType");function ih(t){if(F(t.document)&&F(t.document.source)){let e=Ls(F(t.document)&&x(t.document.format)?t.document.format:"");if(F(t.document.source)){if(F(t.document.source.s3Location)&&x(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Jr(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(x(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(fe(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>F(n)&&x(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}o(ih,"convertConverseDocumentBlock");function ah(t){if(k(t,"image")&&F(t.image)){let e=Ls(F(t.image)&&x(t.image.format)?t.image.format:"");if(F(t.image.source)){if(F(t.image.source.s3Location)&&x(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Jr(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}o(ah,"convertConverseImageBlock");function oh(t){if(k(t,"video")&&F(t.video)){let e=Ls(F(t.video)&&x(t.video.format)?t.video.format:"");if(F(t.video.source)){if(F(t.video.source.s3Location)&&x(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Jr(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}o(oh,"convertConverseVideoBlock");function wo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(k(n,"citations_content")&&F(n.citationsContent)){yield{type:"text",text:fe(n.citationsContent.content)?n.citationsContent.content.reduce((s,i)=>F(i)&&x(i.text)?s+i.text:s,""):"",annotations:fe(n.citationsContent.citations)?n.citationsContent.citations.reduce((s,i)=>{if(F(i)){let a=fe(i.sourceContent)?i.sourceContent.reduce((l,u)=>F(u)&&x(u.text)?l+u.text:l,""):"",c=Fe(()=>{if(F(i.location)){let l=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(F(l))return{source:Ue(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Ue(l.start)?l.start:void 0,endIndex:Ue(l.end)?l.end:void 0}}return{}});s.push({type:"citation",citedText:a,...c})}return s},[]):[]};continue}else if(k(n,"document")&&F(n.document)){yield ih(n);continue}else if(k(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(k(n,"image")&&F(n.image)){yield ah(n);continue}else if(k(n,"reasoning_content")&&x(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(k(n,"tool_call"))continue;if(k(n,"video")&&F(n.video)){yield oh(n);continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(wo,"convertToV1FromChatBedrockConverseMessage");var To={translateContent:wo,translateContentChunk:wo};function vo(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(vo,"convertToV1FromDeepSeekMessage");var So={translateContent:vo,translateContentChunk:vo};function Io(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(k(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(k(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(k(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Io,"convertToV1FromChatGoogleMessage");var xo={translateContent:Io,translateContentChunk:Io};function Ao(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"reasoning")&&x(n.reasoning)){let s=Fe(()=>{let i=r.indexOf(n);if(fe(t.additional_kwargs?.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});x(s)?yield{type:"reasoning",reasoning:n.reasoning,signature:s}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"image_url")){if(x(n.image_url))if(n.image_url.startsWith("data:")){let s=n.image_url.match(/^data:([^;]+);base64,(.+)$/);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(k(n,"media")&&x(n.mimeType)&&x(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Ao,"convertToV1FromChatVertexMessage");var Co={translateContent:Ao,translateContentChunk:Ao};function Ro(t){let e=[],r=t.additional_kwargs?.reasoning;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,s=n.match(/<think>([\s\S]*?)<\/think>/);if(s){let i=s[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)){let s=n.text,i=s.match(/<think>([\s\S]*?)<\/think>/);if(i){let a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),s=s.replace(/<think>[\s\S]*?<\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Ro,"convertToV1FromGroqMessage");var Oo={translateContent:Ro,translateContentChunk:Ro};function No(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(No,"convertToV1FromOllamaMessage");var Mo={translateContent:No,translateContentChunk:No};function ko(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let s of r){if(s==null||typeof s!="object")continue;let i=s.type;if(i==="reasoning.summary"){let a=s.summary;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}else if(i==="reasoning.text"){let a=s.text;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}}if(!n){let s=t.additional_kwargs?.reasoning_content;x(s)&&s.length>0&&e.push({type:"reasoning",reasoning:s})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&x(s.text)&&e.push({type:"text",text:s.text});for(let s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}o(ko,"convertToV1FromOpenRouterMessage");var Po={translateContent:ko,translateContentChunk:ko};function Lo(t){let e=[];if(F(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(fe(n.summary)){let s=n.summary.reduce((i,a)=>F(a)&&x(a.text)?`${i}${a.text}`:i,"");s.length>0&&e.push({type:"reasoning",reasoning:s})}}let r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Lo,"convertToV1FromXAIMessage");var Do={translateContent:Lo,translateContentChunk:Lo};function $o(t){function*e(){let r=Fe(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let n=t.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!t.content.some(s=>"thoughtSignature"in s)){let s=[...t.content];for(let i=s.length-1;i>=0;i--){let a=s[i];if(a.type==="text"&&!a.thought)return a.thoughtSignature=n.thoughtSignature,s}}return t.content}});for(let n of r){let s=Fe(()=>k(n,"text")&&x(n.text)?{type:"text",text:n.text}:k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:k(n,"functionResponse")?{type:"non_standard",value:n}:k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:k(n,"executableCode")?{type:"non_standard",value:n}:k(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),i=Fe(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:s.type==="text"?s.text:"",reasoningContentBlock:s}:s),a={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...i};for(let c in a)a[c]===void 0&&delete a[c];yield a}}return o(e,"iterateContent"),Array.from(e())}o($o,"convertToV1FromChatGoogleMessage");var Uo={translateContent:$o,translateContentChunk:$o};globalThis.lc_block_translators_registry??=new Map([["anthropic",mo],["bedrock-converse",To],["deepseek",So],["google",Uo],["google-genai",xo],["google-vertexai",Co],["groq",Oo],["ollama",Mo],["openai",bo],["openrouter",Po],["xai",Do]]);function Fo(t){return globalThis.lc_block_translators_registry.get(t)}o(Fo,"getTranslator");function Bo(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}o(Bo,"mergeModalitiesTokenDetails");function ch(t,e){let r={...Bo(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}o(ch,"mergeInputTokenDetails");function lh(t,e){let r={...Bo(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}o(lh,"mergeOutputTokenDetails");function Xr(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:ch(t?.input_token_details,e?.input_token_details),output_token_details:lh(t?.output_token_details,e?.output_token_details)}}o(Xr,"mergeUsageMetadata");var bt=class extends ft{static{o(this,"AIMessage")}type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
7
7
|
|
|
8
|
-
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[s,i]=Ps(r);e.tool_calls=s??[],e.invalid_tool_calls=i??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){if(e.tool_calls){let i=e.tool_calls.filter(a=>!e.contentBlocks?.some(c=>c.type==="tool_call"&&c.id===a.id&&c.name===a.name));e.contentBlocks.push(...i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let s=e.contentBlocks.filter(i=>i.type==="tool_call").filter(i=>!e.tool_calls?.some(a=>a.id===i.id&&a.name===i.name));s.length>0&&(e.tool_calls=[...e.tool_calls??[],...s.map(i=>({type:"tool_call",id:i.id,name:i.name,args:i.args}))])}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=Fo(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function
|
|
9
|
-
`)}o(tn,"getBufferString");var $="0123456789abcdef".split(""),mh=[-2147483648,8388608,32768,128],Ze=[24,16,8,0],rn=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],ge=[];function rt(t,e){e?(ge[0]=ge[16]=ge[1]=ge[2]=ge[3]=ge[4]=ge[5]=ge[6]=ge[7]=ge[8]=ge[9]=ge[10]=ge[11]=ge[12]=ge[13]=ge[14]=ge[15]=0,this.blocks=ge):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}o(rt,"Sha256");rt.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,s=0,i,a=t.length,c=this.blocks;s<a;){if(this.hashed&&(this.hashed=!1,c[0]=this.block,this.block=c[16]=c[1]=c[2]=c[3]=c[4]=c[5]=c[6]=c[7]=c[8]=c[9]=c[10]=c[11]=c[12]=c[13]=c[14]=c[15]=0),e)for(i=this.start;s<a&&i<64;++s)c[i>>>2]|=t[s]<<Ze[i++&3];else for(i=this.start;s<a&&i<64;++s)n=t.charCodeAt(s),n<128?c[i>>>2]|=n<<Ze[i++&3]:n<2048?(c[i>>>2]|=(192|n>>>6)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):n<55296||n>=57344?(c[i>>>2]|=(224|n>>>12)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++s)&1023),c[i>>>2]|=(240|n>>>18)<<Ze[i++&3],c[i>>>2]|=(128|n>>>12&63)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=c[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};rt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=mh[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};rt.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=this.blocks,u,d,p,_,g,y,E,w,S,I,m;for(u=16;u<64;++u)g=l[u-15],d=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=l[u-2],p=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,l[u]=l[u-16]+d+l[u-7]+p<<0;for(m=e&r,u=0;u<64;u+=4)this.first?(this.is224?(w=300032,g=l[0]-1413257819,c=g-150054599<<0,n=g+24177077<<0):(w=704751109,g=l[0]-210244248,c=g-1521486534<<0,n=g+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),w=t&e,_=w^t&r^m,E=s&i^~s&a,g=c+p+E+rn[u]+l[u],y=d+_,c=n+g<<0,n=g+y<<0),d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),S=n&t,_=S^n&e^w,E=a&c^~a&s,g=i+p+E+rn[u+1]+l[u+1],y=d+_,a=r+g<<0,r=g+y<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),I=r&n,_=I^r&t^S,E=i&a^~i&c,g=s+p+E+rn[u+2]+l[u+2],y=d+_,i=e+g<<0,e=g+y<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),m=e&r,_=m^e&n^I,E=i&a^~i&c,g=s+p+E+rn[u+3]+l[u+3],y=d+_,s=t+g<<0,t=g+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+s<<0,this.h5=this.h5+i<<0,this.h6=this.h6+a<<0,this.h7=this.h7+c<<0};rt.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=$[t>>>28&15]+$[t>>>24&15]+$[t>>>20&15]+$[t>>>16&15]+$[t>>>12&15]+$[t>>>8&15]+$[t>>>4&15]+$[t&15]+$[e>>>28&15]+$[e>>>24&15]+$[e>>>20&15]+$[e>>>16&15]+$[e>>>12&15]+$[e>>>8&15]+$[e>>>4&15]+$[e&15]+$[r>>>28&15]+$[r>>>24&15]+$[r>>>20&15]+$[r>>>16&15]+$[r>>>12&15]+$[r>>>8&15]+$[r>>>4&15]+$[r&15]+$[n>>>28&15]+$[n>>>24&15]+$[n>>>20&15]+$[n>>>16&15]+$[n>>>12&15]+$[n>>>8&15]+$[n>>>4&15]+$[n&15]+$[s>>>28&15]+$[s>>>24&15]+$[s>>>20&15]+$[s>>>16&15]+$[s>>>12&15]+$[s>>>8&15]+$[s>>>4&15]+$[s&15]+$[i>>>28&15]+$[i>>>24&15]+$[i>>>20&15]+$[i>>>16&15]+$[i>>>12&15]+$[i>>>8&15]+$[i>>>4&15]+$[i&15]+$[a>>>28&15]+$[a>>>24&15]+$[a>>>20&15]+$[a>>>16&15]+$[a>>>12&15]+$[a>>>8&15]+$[a>>>4&15]+$[a&15];return this.is224||(l+=$[c>>>28&15]+$[c>>>24&15]+$[c>>>20&15]+$[c>>>16&15]+$[c>>>12&15]+$[c>>>8&15]+$[c>>>4&15]+$[c&15]),l};rt.prototype.toString=rt.prototype.hex;rt.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255];return this.is224||l.push(c>>>24&255,c>>>16&255,c>>>8&255,c&255),l};rt.prototype.array=rt.prototype.digest;rt.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};var Ah=_e(cn(),1);var ac=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function mr(t){return typeof t=="string"&&ac.test(t)}o(mr,"validate");function hr(t){if(!mr(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}o(hr,"parse");var be=[];for(let t=0;t<256;++t)be.push((t+256).toString(16).slice(1));function Et(t,e=0){return(be[t[e+0]]+be[t[e+1]]+be[t[e+2]]+be[t[e+3]]+"-"+be[t[e+4]]+be[t[e+5]]+"-"+be[t[e+6]]+be[t[e+7]]+"-"+be[t[e+8]]+be[t[e+9]]+"-"+be[t[e+10]]+be[t[e+11]]+be[t[e+12]]+be[t[e+13]]+be[t[e+14]]+be[t[e+15]]).toLowerCase()}o(Et,"unsafeStringify");var Rh=new Uint8Array(16);function gr(){return crypto.getRandomValues(Rh)}o(gr,"rng");function Ch(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}o(Ch,"f");function Hs(t,e){return t<<e|t>>>32-e}o(Hs,"ROTL");function oc(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let s=t.length/4+2,i=Math.ceil(s/16),a=new Array(i);for(let c=0;c<i;++c){let l=new Uint32Array(16);for(let u=0;u<16;++u)l[u]=t[c*64+u*4]<<24|t[c*64+u*4+1]<<16|t[c*64+u*4+2]<<8|t[c*64+u*4+3];a[c]=l}a[i-1][14]=(t.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<i;++c){let l=new Uint32Array(80);for(let y=0;y<16;++y)l[y]=a[c][y];for(let y=16;y<80;++y)l[y]=Hs(l[y-3]^l[y-8]^l[y-14]^l[y-16],1);let u=r[0],d=r[1],p=r[2],_=r[3],g=r[4];for(let y=0;y<80;++y){let E=Math.floor(y/20),w=Hs(u,5)+Ch(E,d,p,_)+g+e[E]+l[y]>>>0;g=_,_=p,p=Hs(d,30)>>>0,d=u,u=w}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+p>>>0,r[3]=r[3]+_>>>0,r[4]=r[4]+g>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}o(oc,"sha1");function Oh(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}o(Oh,"stringToBytes");var cc="6ba7b810-9dad-11d1-80b4-00c04fd430c8",lc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function uc(t,e,r,n,s,i){let a=typeof r=="string"?Oh(r):r,c=typeof n=="string"?hr(n):n;if(typeof n=="string"&&(n=hr(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+a.length);if(l.set(c),l.set(a,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,s){if(i??=0,i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[i+u]=l[u];return s}return Et(l)}o(uc,"v35");function Gs(t,e,r,n){return uc(80,oc,t,e,r,n)}o(Gs,"v5");Gs.DNS=cc;Gs.URL=lc;var zs={};function fc(t,e,r){let n;if(t)n=dc(t.random??t.rng?.()??gr(),t.msecs,t.seq,e,r);else{let s=Date.now(),i=gr();Mh(zs,s,i),n=dc(i,zs.msecs,zs.seq,e,r)}return e??Et(n)}o(fc,"v7");function Mh(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}o(Mh,"updateV7State");function dc(t,e,r,n,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),s=0;else if(s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[s++]=e/1099511627776&255,n[s++]=e/4294967296&255,n[s++]=e/16777216&255,n[s++]=e/65536&255,n[s++]=e/256&255,n[s++]=e&255,n[s++]=112|r>>>28&15,n[s++]=r>>>20&255,n[s++]=128|r>>>14&63,n[s++]=r>>>6&255,n[s++]=r<<2&255|t[10]&3,n[s++]=t[11],n[s++]=t[12],n[s++]=t[13],n[s++]=t[14],n[s++]=t[15],n}o(dc,"v7Bytes");var nt=fc;var pc=Symbol.for("ls:tracing_async_local_storage"),Mt=Symbol.for("lc:context_variables"),mc=o(t=>{globalThis[pc]=t},"setGlobalAsyncLocalStorageInstance"),wt=o(()=>globalThis[pc],"getGlobalAsyncLocalStorageInstance");var kh=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),Ph=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Lh=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),qs=o(()=>typeof Deno<"u","isDeno"),Dh=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!qs(),"isNode"),$h=o(()=>{let t;return kh()?t="browser":Dh()?t="node":Ph()?t="webworker":Lh()?t="jsdom":qs()?t="deno":t="other",t},"getEnv"),Vs;function hc(){return Vs===void 0&&(Vs={library:"langchain-js",runtime:$h()}),Vs}o(hc,"getRuntimeEnvironment");function Je(t){try{return typeof process<"u"?process.env?.[t]:qs()?Deno?.env.get(t):void 0}catch{return}}o(Je,"getEnvironmentVariable");var Uh=class{static{o(this,"BaseCallbackHandlerMethodsClass")}};var Wt=class extends Uh{static{o(this,"BaseCallbackHandler")}lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Cs(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Ot.prototype.toJSON.call(this)}toJSONNotImplemented(){return Ot.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Wt{static{o(this,"Handler")}name=nt();constructor(){super(),Object.assign(this,t)}}return new e}},gc=o(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var yc=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Fh(t){return typeof t=="string"&&yc.test(t)}o(Fh,"validate");var _c=Fh;function Bh(t){if(!_c(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}o(Bh,"parse");var bc=Bh;var Ee=[];for(let t=0;t<256;++t)Ee.push((t+256).toString(16).slice(1));function Kt(t,e=0){return(Ee[t[e+0]]+Ee[t[e+1]]+Ee[t[e+2]]+Ee[t[e+3]]+"-"+Ee[t[e+4]]+Ee[t[e+5]]+"-"+Ee[t[e+6]]+Ee[t[e+7]]+"-"+Ee[t[e+8]]+Ee[t[e+9]]+"-"+Ee[t[e+10]]+Ee[t[e+11]]+Ee[t[e+12]]+Ee[t[e+13]]+Ee[t[e+14]]+Ee[t[e+15]]).toLowerCase()}o(Kt,"unsafeStringify");var Ec=_e(require("node:crypto"));var un=new Uint8Array(256),ln=un.length;function yr(){return ln>un.length-16&&(Ec.default.randomFillSync(un),ln=0),un.slice(ln,ln+=16)}o(yr,"rng");function jh(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}o(jh,"stringToBytes");var Hh="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Gh="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ws(t,e,r){function n(s,i,a,c){var l;if(typeof s=="string"&&(s=jh(s)),typeof i=="string"&&(i=bc(i)),((l=i)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+s.length);if(u.set(i),u.set(s,i.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,a){c=c||0;for(let d=0;d<16;++d)a[c+d]=u[d];return a}return Kt(u)}o(n,"generateUUID");try{n.name=t}catch{}return n.DNS=Hh,n.URL=Gh,n}o(Ws,"v35");var wc=_e(require("node:crypto")),Ks={randomUUID:wc.default.randomUUID};function zh(t,e,r){if(Ks.randomUUID&&!e&&!t)return Ks.randomUUID();t=t||{};let n=t.random||(t.rng||yr)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let s=0;s<16;++s)e[r+s]=n[s];return e}return Kt(n)}o(zh,"v4");var kt=zh;var Tc=_e(require("node:crypto"));function Vh(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),Tc.default.createHash("sha1").update(t).digest()}o(Vh,"sha1");var vc=Vh;var qh=Ws("v5",80,vc),Zs=qh;var Sc=null,Ic=null,Ye=0;function Wh(t,e,r){t=t||{};let n=e&&r||0,s=e||new Uint8Array(16),i=t.random||(t.rng||yr)(),a=t.msecs!==void 0?t.msecs:Date.now(),c=t.seq!==void 0?t.seq:null,l=Ic,u=Sc;return a>Ye&&t.msecs===void 0&&(Ye=a,c!==null&&(l=null,u=null)),c!==null&&(c>2147483647&&(c=2147483647),l=c>>>19&4095,u=c&524287),(l===null||u===null)&&(l=i[6]&127,l=l<<8|i[7],u=i[8]&63,u=u<<8|i[9],u=u<<5|i[10]>>>3),a+1e4>Ye&&c===null?++u>524287&&(u=0,++l>4095&&(l=0,Ye++)):Ye=a,Ic=l,Sc=u,s[n++]=Ye/1099511627776&255,s[n++]=Ye/4294967296&255,s[n++]=Ye/16777216&255,s[n++]=Ye/65536&255,s[n++]=Ye/256&255,s[n++]=Ye&255,s[n++]=l>>>4&15|112,s[n++]=l&255,s[n++]=u>>>13&63|128,s[n++]=u>>>5&255,s[n++]=u<<3&255|i[10]&7,s[n++]=i[11],s[n++]=i[12],s[n++]=i[13],s[n++]=i[14],s[n++]=i[15],e||Kt(s)}o(Wh,"v7");var _r=Wh;var xc="gen_ai.operation.name",Ac="gen_ai.system",Js="gen_ai.request.model",Rc="gen_ai.response.model",Ys="gen_ai.usage.input_tokens",Xs="gen_ai.usage.output_tokens",Qs="gen_ai.usage.total_tokens",Cc="gen_ai.request.max_tokens",Oc="gen_ai.request.temperature",Nc="gen_ai.request.top_p",Mc="gen_ai.request.frequency_penalty",kc="gen_ai.request.presence_penalty",Pc="gen_ai.response.finish_reasons",Lc="gen_ai.prompt",Dc="gen_ai.completion",$c="gen_ai.request.extra_query",Uc="gen_ai.request.extra_body",Fc="gen_ai.serialized.name",Bc="gen_ai.serialized.signature",jc="gen_ai.serialized.doc",Hc="gen_ai.response.id",Gc="gen_ai.response.service_tier",zc="gen_ai.response.system_fingerprint",Vc="gen_ai.usage.input_token_details",qc="gen_ai.usage.output_token_details",Wc="langsmith.trace.session_id",Kc="langsmith.trace.session_name",Zc="langsmith.span.kind",Jc="langsmith.trace.name",Yc="langsmith.metadata",ei="langsmith.span.tags";var Xc="langsmith.request.streaming",Qc="langsmith.request.headers";var Jh=o((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),Yh,el=Symbol.for("ls:fetch_implementation");var tl=o(()=>globalThis[el]===void 0?!0:Yh??!1,"_shouldStreamForGlobalFetchImplementation"),rl=o(t=>async(...e)=>{if(t||te("DEBUG")==="true"){let[n,s]=e;console.log(`\u2192 ${s?.method||"GET"} ${n}`)}let r=await(globalThis[el]??Jh)(...e);return(t||te("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var br=o(()=>te("PROJECT")??Be("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var nl={};function Pt(t){nl[t]||(console.warn(t),nl[t]=!0)}o(Pt,"warnOnce");var C=o(t=>BigInt(t),"n"),ol=C("0x9E3779B1"),cl=C("0x85EBCA77"),Xh=C("0xC2B2AE3D"),Tt=C("0x9E3779B185EBCA87"),Lt=C("0xC2B2AE3D27D4EB4F"),ll=C("0x165667B19E3779F9"),si=C("0x85EBCA77C2B2AE63"),Qh=C("0x27D4EB2F165667C5"),eg=C("0x165667919E3779F9"),tg=C("0x9FB21C651E98DF25");function rg(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}o(rg,"hexToBytes");var st=rg("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Jt=(C(1)<<C(128))-C(1),q=(C(1)<<C(64))-C(1),mn=(C(1)<<C(32))-C(1),pt=64,ul=pt/8,ng=8,dn=4;function Y(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}o(Y,"getView");function Q(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}o(Q,"readBigUInt64LE");function Zt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}o(Zt,"readUInt32LE");function ti(t,e=0){return t[e]}o(ti,"readUInt8");var sg=o(t=>(t&C(255))<<C(56)|(t&C(65280))<<C(40)|(t&C(16711680))<<C(24)|(t&C(4278190080))<<C(8)|(t&C(0xff00000000))>>C(8)|(t&C(0xff0000000000))>>C(24)|(t&C(0xff000000000000))>>C(40)|(t&C(0xff00000000000000))>>C(56),"bswap64"),ig=o(t=>(t=(t&C(65535))<<C(16)|(t&C(4294901760))>>C(16),t=(t&C(16711935))<<C(8)|(t&C(4278255360))>>C(8),t),"bswap32"),ag=o((t,e)=>(t&mn)*(e&mn)&q,"XXH_mult32to64"),Yt=o(t=>{if(!t)throw new Error("Assert failed")},"assert");function og(t,e){return(t<<e|t>>C(32)-e)&mn}o(og,"rotl32");function dl(t,e,r){for(let n=0;n<ul;n++){let s=Q(e,n*8),i=s^Q(r,n*8);t[n^1]+=s,t[n]+=ag(i,i>>C(32))}return t}o(dl,"XXH3_accumulate_512");function sl(t,e,r,n){for(let s=0;s<n;s++)dl(t,Y(e,s*pt),Y(r,s*8));return t}o(sl,"XXH3_accumulate");function cg(t,e){for(let r=0;r<ul;r++){let n=Q(e,r*8),s=t[r];s=ri(s,C(47)),s^=n,s*=ol,t[r]=s&q}return t}o(cg,"XXH3_scrambleAcc");function fn(t,e){return fl(t[0]^Q(e,0),t[1]^Q(e,ng))}o(fn,"XXH3_mix2Accs");function il(t,e,r){let n=r;return n+=fn(t.slice(0),Y(e,0*dn)),n+=fn(t.slice(2),Y(e,4*dn)),n+=fn(t.slice(4),Y(e,8*dn)),n+=fn(t.slice(6),Y(e,12*dn)),it(n&q)}o(il,"XXH3_mergeAccs");function lg(t,e,r,n,s){let i=Math.floor((r.byteLength-pt)/8),a=pt*i,c=Math.floor((e.byteLength-1)/a);for(let l=0;l<c;l++)t=sl(t,Y(e,l*a),r,i),t=s(t,Y(r,r.byteLength-pt));{let l=Math.floor((e.byteLength-1-a*c)/pt);t=sl(t,Y(e,c*a),r,l),t=n(t,Y(e,e.byteLength-pt),Y(r,r.byteLength-pt-7))}return t}o(lg,"XXH3_hashLong");function ug(t,e,r){let n=new BigUint64Array([Xh,Tt,Lt,ll,si,cl,Qh,ol]);Yt(t.length>128),n=lg(n,t,e,dl,cg),Yt(n.length*8==64);{let s=il(n,Y(e,11),C(t.byteLength)*Tt&q);return il(n,Y(e,e.byteLength-pt-11),~(C(t.byteLength)*Lt)&q)<<C(64)|s}}o(ug,"XXH3_hashLong_128b");function fl(t,e){let r=t*e&Jt;return r&q^r>>C(64)}o(fl,"XXH3_mul128_fold64");function al(t,e,r){return fl((Q(t,0)^Q(e,0)+r)&q,(Q(t,8)^Q(e,8)-r)&q)}o(al,"XXH3_mix16B");function pn(t,e,r,n,s){let i=t&q,a=t>>C(64)&q;return i+=al(e,n,s),i^=Q(r,0)+Q(r,8),i&=q,a+=al(r,Y(n,16),s),a^=Q(e,0)+Q(e,8),a&=q,a<<C(64)|i}o(pn,"XXH3_mix32B");function it(t){return t^=t>>C(37),t*=eg,t&=q,t^=t>>C(32),t}o(it,"XXH3_avalanche");function hn(t){return t^=t>>C(33),t*=Lt,t&=q,t^=t>>C(29),t*=ll,t&=q,t^=t>>C(32),t}o(hn,"XXH3_avalanche64");function dg(t,e,r){let n=t.byteLength;Yt(n>0&&n<=3);let s=C(ti(t,n-1))|C(n<<8)|C(ti(t,0)<<16)|C(ti(t,n>>1)<<24),i=(C(Zt(e,0))^C(Zt(e,4)))+r,a=(s^i)&q,c=(C(Zt(e,8))^C(Zt(e,12)))-r,l=(og(ig(s),C(13))^c)&q;return(hn(l)&q)<<C(64)|hn(a)}o(dg,"XXH3_len_1to3_128b");function ri(t,e){return t^t>>e}o(ri,"xorshift64");function fg(t,e,r){let n=t.byteLength;Yt(n>=4&&n<=8);{let s=Zt(t,0),i=Zt(t,n-4),a=C(s)|C(i)<<C(32),c=(Q(e,16)^Q(e,24))+r&q,u=(a^c)*(Tt+(C(n)<<C(2)))&Jt;return u+=(u&q)<<C(65),u&=Jt,u^=u>>C(67),ri(ri(u&q,C(35))*tg&q,C(28))|it(u>>C(64))<<C(64)}}o(fg,"XXH3_len_4to8_128b");function pg(t,e,r){let n=t.byteLength;Yt(n>=9&&n<=16);{let s=(Q(e,32)^Q(e,40))+r&q,i=(Q(e,48)^Q(e,56))-r&q,a=Q(t),c=Q(t,n-8),l=(a^c^s)*Tt,u=(l&q)+(C(n-1)<<C(54));l=l&(Jt^q)|u,c^=i,l+=c+(c&mn)*(cl-C(1))<<C(64),l&=Jt,l^=sg(l>>C(64));let d=(l&q)*Lt;return d+=(l>>C(64))*Lt<<C(64),d&=Jt,it(d&q)|it(d>>C(64))<<C(64)}}o(pg,"XXH3_len_9to16_128b");function mg(t,e){let r=t.byteLength;return Yt(r<=16),r>8?pg(t,st,e):r>=4?fg(t,st,e):r>0?dg(t,st,e):hn(e^Q(st,64)^Q(st,72))|hn(e^Q(st,80)^Q(st,88))<<C(64)}o(mg,"XXH3_len_0to16_128b");function ni(t){return~t+C(1)&q}o(ni,"inv64");function hg(t,e,r){let n=C(t.byteLength)*Tt&q,s=C(t.byteLength-1)/C(32);for(;s>=0;){let c=Number(s);n=pn(n,Y(t,16*c),Y(t,t.byteLength-16*(c+1)),Y(e,32*c),r),s--}let i=n+(n>>C(64))&q;i=it(i);let a=(n&q)*Tt+(n>>C(64))*si+(C(t.byteLength)-r&q)*Lt;return a&=q,a=ni(it(a)),i|a<<C(64)}o(hg,"XXH3_len_17to128_128b");function gg(t,e,r){let n=C(t.byteLength)*Tt&q;for(let a=32;a<160;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,a-32),r);n=it(n&q)|it(n>>C(64))<<C(64);for(let a=160;a<=t.byteLength;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,3+a-160),r);n=pn(n,Y(t,t.byteLength-16),Y(t,t.byteLength-32),Y(e,103),ni(r));let s=n+(n>>C(64))&q;s=it(s);let i=(n&q)*Tt+(n>>C(64))*si+(C(t.byteLength)-r&q)*Lt;return i&=q,i=ni(it(i)),s|i<<C(64)}o(gg,"XXH3_len_129to240_128b");function pl(t,e=C(0)){let r=t.byteLength;return r<=16?mg(t,e):r<=128?hg(t,st,e):r<=240?gg(t,st,e):ug(t,st,e)}o(pl,"XXH3_128");function ml(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&q,s=t>>C(64);return r.setBigUint64(0,s,!1),r.setBigUint64(8,n,!1),e}o(ml,"xxh128ToBytes");var hl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function z(t,e){if(!hl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}o(z,"assertUuid");function gn(t){let e=typeof t=="string"?Date.parse(t):t;return _r({msecs:e,seq:0})}o(gn,"uuid7FromTime");function yg(t){if(!hl.test(t))return null;let e=t[14];return parseInt(e,16)}o(yg,"getUuidVersion");function _g(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}o(_g,"uuidToBytes");function bg(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}o(bg,"bytesToUuid");var Eg=new TextEncoder;function wg(t){let e=Eg.encode(t),r=pl(e);return ml(r)}o(wg,"_fastHash128");function Er(t,e){let r=`${t}:${e}`,n=wg(r),s=new Uint8Array(16);if(yg(t)===7){let a=_g(t);s.set(a.slice(0,6),0)}else{let a=Date.now();s[0]=a/1099511627776&255,s[1]=a/4294967296&255,s[2]=a/16777216&255,s[3]=a/65536&255,s[4]=a/256&255,s[5]=a&255}return s[6]=112|n[0]&15,s[7]=n[1],s[8]=128|n[2]&63,s.set(n.slice(3,10),9),bg(s)}o(Er,"nonCryptographicUuid7Deterministic");var He=_e(require("node:fs"),1),Xe=_e(require("node:fs/promises"),1),Tg=_e(require("node:path"),1);var wr=Tg;async function gl(t){await Xe.mkdir(t,{recursive:!0})}o(gl,"mkdir");async function yl(t,e){let r=`${t}.tmp`;await Xe.writeFile(r,e,{encoding:"utf8",mode:384}),await Xe.rename(r,t)}o(yl,"writeFileAtomic");async function _l(t){return Xe.readdir(t)}o(_l,"readdir");async function bl(t){return Xe.stat(t)}o(bl,"stat");function yn(t){return He.existsSync(t)}o(yn,"existsSync");function El(t){He.mkdirSync(t,{recursive:!0})}o(El,"mkdirSync");function wl(t,e){He.writeFileSync(t,e)}o(wl,"writeFileSync");function Tl(t,e){He.renameSync(t,e)}o(Tl,"renameSync");function vl(t){He.unlinkSync(t)}o(vl,"unlinkSync");function Sl(t){return He.readFileSync(t,"utf-8")}o(Sl,"readFileSync");function Sg(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}o(Sg,"isStale");var _n=class{static{o(this,"PromptCache")}constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let s={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,s)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[i,a]of this.cache.entries())r[i]=a.value;let n=wr.dirname(e);yn(n)||El(n);let s=`${e}.tmp`;try{wl(s,JSON.stringify({entries:r},null,2)),Tl(s,e)}catch(i){throw yn(s)&&vl(s),i}}load(e){if(!yn(e))return 0;let r;try{let i=Sl(e);r=JSON.parse(i).entries??null}catch{return 0}if(!r)return 0;let n=0,s=Date.now();for(let[i,a]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let c={value:a,createdAt:s};this.cache.set(i,c),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())Sg(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let s=await n.refreshFunc();this.set(r,s,n.refreshFunc),this._metrics.refreshes+=1}catch(s){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,s)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},bn=new _n;var En="0.5.16";var at,Ig=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),xg=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Ag=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Il=o(()=>typeof Deno<"u","isDeno"),Rg=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Il(),"isNode"),oi=o(()=>at||(typeof Bun<"u"?at="bun":Ig()?at="browser":Rg()?at="node":xg()?at="webworker":Ag()?at="jsdom":Il()?at="deno":at="other",at),"getEnv"),ii;function wn(){if(ii===void 0){let t=oi(),e=Og();ii={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:En,...e}}return ii}o(wn,"getRuntimeEnvironment");function ci(){let t=Cg(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,s]of Object.entries(t))typeof s=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[n]=s);return e}o(ci,"getLangSmithEnvVarsMetadata");function Cg(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}o(Cg,"getLangSmithEnvironmentVariables");function Be(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}o(Be,"getEnvironmentVariable");function te(t){return Be(`LANGSMITH_${t}`)||Be(`LANGCHAIN_${t}`)}o(te,"getLangSmithEnvironmentVariable");var ai;function Og(){if(ai!==void 0)return ai;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let r of t){let n=Be(r);n!==void 0&&(e[r]=n)}return ai=e,e}o(Og,"getShas");function Tn(){return Be("OTEL_ENABLED")==="true"||te("OTEL_ENABLED")==="true"}o(Tn,"getOtelEnabled");var di=class{static{o(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Tn()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},fi=class{static{o(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new di})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},pi=class{static{o(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},li=Symbol.for("ls:otel_trace"),ui=Symbol.for("ls:otel_context"),xl=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Ng=new fi,Mg=new pi,mi=class{static{o(this,"OTELProvider")}getTraceInstance(){return globalThis[li]??Ng}getContextInstance(){return globalThis[ui]??Mg}initializeGlobalInstances(e){globalThis[li]===void 0&&(globalThis[li]=e.trace),globalThis[ui]===void 0&&(globalThis[ui]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[xl]=e}getDefaultOTLPTracerComponents(){return globalThis[xl]??void 0}},hi=new mi;function vn(){return hi.getTraceInstance()}o(vn,"getOTELTrace");function Al(){return hi.getContextInstance()}o(Al,"getOTELContext");function Rl(){return hi.getDefaultOTLPTracerComponents()}o(Rl,"getDefaultOTLPTracerComponents");var kg={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Pg(t){return kg[t]||t}o(Pg,"getOperationName");var Sn=class{static{o(this,"LangSmithToOTELTranslator")}constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let s=this.createSpanForRun(n,n.run,r.get(n.id));s&&!n.run.end_time&&this.spans.set(n.id,s)}else this.updateSpanForRun(n,n.run)}catch(s){console.error(`Error processing operation ${n.id}:`,s)}}createSpanForRun(e,r,n){let s=n&&vn().getSpan(n);if(s)try{return this.finishSpanSetup(s,r,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let s=r.end_time;s&&(n.end(new Date(s)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(Zc,r.run_type);let c=Pg(r.run_type||"chain");e.setAttribute(xc,c)}"name"in r&&r.name&&e.setAttribute(Jc,r.name),"session_id"in r&&r.session_id&&e.setAttribute(Wc,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(Kc,r.session_name),this.setGenAiSystem(e,r);let s=this.extractModelName(r);s&&e.setAttribute(Js,s),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ys,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Xs,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Qs,r.total_tokens),this.setInvocationParameters(e,r);let i=r.extra?.metadata||{};for(let[c,l]of Object.entries(i))l!=null&&e.setAttribute(`${Yc}.${c}`,String(l));let a=r.tags;if(a&&Array.isArray(a)?e.setAttribute(ei,a.join(", ")):a&&e.setAttribute(ei,String(a)),"serialized"in r&&typeof r.serialized=="object"){let c=r.serialized;c.name&&e.setAttribute(Fc,String(c.name)),c.signature&&e.setAttribute(Bc,String(c.signature)),c.doc&&e.setAttribute(jc,String(c.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",s=this.extractModelName(r);if(s){let i=s.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?n="anthropic":i.includes("bedrock")?n="aws.bedrock":i.includes("azure")&&i.includes("openai")?n="az.ai.openai":i.includes("azure")&&i.includes("inference")?n="az.ai.inference":i.includes("cohere")?n="cohere":i.includes("deepseek")?n="deepseek":i.includes("gemini")?n="gemini":i.includes("groq")?n="groq":i.includes("watson")||i.includes("ibm")?n="ibm.watsonx.ai":i.includes("mistral")?n="mistral_ai":i.includes("gpt")||i.includes("openai")?n="openai":i.includes("perplexity")||i.includes("sonar")?n="perplexity":i.includes("vertex")?n="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(n="xai")}e.setAttribute(Ac,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Cc,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Oc,n.temperature),n.top_p!==void 0&&e.setAttribute(Nc,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Mc,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(kc,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Js,n.model),n.stream!==void 0&&e.setAttribute(Xc,n.stream),n.extra_headers&&e.setAttribute(Qc,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute($c,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Uc,JSON.stringify(n.extra_body))),e.setAttribute(Lc,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,s=this.getUnifiedRunTokens(n);if(s&&(e.setAttribute(Ys,s[0]),e.setAttribute(Xs,s[1]),e.setAttribute(Qs,s[0]+s[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Rc,String(n.model)),n.id&&e.setAttribute(Hc,n.id),n.choices&&Array.isArray(n.choices)){let i=n.choices.map(a=>a.finish_reason).filter(a=>a).map(String);i.length>0&&e.setAttribute(Pc,i.join(", "))}if(n.service_tier&&e.setAttribute(Gc,n.service_tier),n.system_fingerprint&&e.setAttribute(zc,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let i=n.usage_metadata;i.input_token_details&&e.setAttribute(Vc,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(qc,JSON.stringify(i.output_token_details))}}e.setAttribute(Dc,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let a of n){let c=e[a];if(!(!c||typeof c!="object")&&(r=this.extractUnifiedRunTokens(c.usage_metadata),r||c.lc===1&&c.kwargs&&typeof c.kwargs=="object"&&(r=this.extractUnifiedRunTokens(c.kwargs.usage_metadata),r)))return r}let s=e.generations||[];if(!Array.isArray(s))return null;let i=Array.isArray(s[0])?s.flat():s;for(let a of i)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}};var Lg=Object.prototype.toString,Dg=o(t=>Lg.call(t)==="[object Error]","isError"),$g=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function gi(t){if(!(t&&Dg(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:$g.has(r)}o(gi,"isNetworkError");function Ug(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}o(Ug,"validateRetries");function In(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}o(In,"validateNumberOption");var yi=class extends Error{static{o(this,"AbortError")}constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Fg(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(r-1));return s=Math.min(s,e.maxTimeout),s}o(Fg,"calculateDelay");function Cl(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}o(Cl,"calculateRemainingTime");async function Bg({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:s}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof yi)throw i.originalError;let a=Number.isFinite(s.retries)?Math.max(0,s.retries-r):s.retries,c=s.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:r});if(await s.onFailedAttempt(l),Cl(n,c)<=0)throw i;let u=await s.shouldConsumeRetry(l),d=Cl(n,c);if(d<=0||a<=0)throw i;if(i instanceof TypeError&&!gi(i)){if(u)throw i;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(l))throw i;if(!u)return s.signal?.throwIfAborted(),!1;let p=Fg(r,s),_=Math.min(p,d);return _>0&&await new Promise((g,y)=>{let E=o(()=>{clearTimeout(w),s.signal?.removeEventListener("abort",E),y(s.signal.reason)},"onAbort"),w=setTimeout(()=>{s.signal?.removeEventListener("abort",E),g()},_);s.unref&&w.unref?.(),s.signal?.addEventListener("abort",E,{once:!0})}),s.signal?.throwIfAborted(),!0}o(Bg,"onAttemptFailure");async function _i(t,e={}){if(e={...e},Ug(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,In("factor",e.factor,{min:0,allowInfinity:!1}),In("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),In("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),In("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let i=await t(r);return e.signal?.throwIfAborted(),i}catch(i){await Bg({error:i,attemptNumber:r,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}o(_i,"pRetry");var xn=_e(cn(),1),Ol="default"in xn.default?xn.default.default:xn.default;var jg=[408,425,429,500,502,503,504],Tr=class{static{o(this,"AsyncCaller")}constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new Ol({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let s=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&s>0&&this.queueSizeBytes+s>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${s} bytes.`));s>0&&(this.queueSizeBytes+=s);let i=this.onFailedResponseHook,a=this.queue.add(()=>_i(()=>r(...n).catch(c=>{throw c instanceof Error?c:new Error(c)}),{async onFailedAttempt({error:c}){if(typeof c!="object"||c==null)throw c;let l="message"in c&&typeof c.message=="string"?c.message:void 0;if(l?.startsWith("Cancel")||l?.startsWith("TimeoutError")||l?.startsWith("AbortError")||"name"in c&&c.name==="TimeoutError"||"code"in c&&c.code==="ECONNABORTED")throw c;let u="response"in c?c.response:void 0;if(i&&await i(u))return;let d=u?.status??("status"in c?c.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!jg.includes(+d))throw c},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return s>0&&(a=a.finally(()=>{this.queueSizeBytes-=s})),e.signal?Promise.race([a,new Promise((c,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):a}};function bi(t){return typeof t?._getType=="function"}o(bi,"isLangChainMessage");function Ei(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}o(Ei,"convertLangChainMessageToExample");var $b=_e(bd(),1);function Bn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
|
|
8
|
+
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[s,i]=Ps(r);e.tool_calls=s??[],e.invalid_tool_calls=i??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){if(e.tool_calls){let i=e.tool_calls.filter(a=>!e.contentBlocks?.some(c=>c.type==="tool_call"&&c.id===a.id&&c.name===a.name));e.contentBlocks.push(...i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let s=e.contentBlocks.filter(i=>i.type==="tool_call").filter(i=>!e.tool_calls?.some(a=>a.id===i.id&&a.name===i.name));s.length>0&&(e.tool_calls=[...e.tool_calls??[],...s.map(i=>({type:"tool_call",id:i.id,name:i.name,args:i.args}))])}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=Fo(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function gh(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}o(gh,"_contentBlockToString");function tn(t,e="Human",r="AI"){let n=[];for(let s of t){let i;if(s.type==="human")i=e;else if(s.type==="ai")i=r;else if(s.type==="system")i="System";else if(s.type==="tool")i="Tool";else if(s.type==="generic")i=s.role;else throw new Error(`Got unsupported message type: ${s.type}`);let a=s.name?`${s.name}, `:"",c=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(gh).filter(Boolean).join(""):"",l=`${i}: ${a}${c}`;if(s.type==="ai"){let u=s;u.tool_calls&&u.tool_calls.length>0?l+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(l+=JSON.stringify(u.additional_kwargs.function_call))}n.push(l)}return n.join(`
|
|
9
|
+
`)}o(tn,"getBufferString");var $="0123456789abcdef".split(""),yh=[-2147483648,8388608,32768,128],Ze=[24,16,8,0],rn=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],ge=[];function rt(t,e){e?(ge[0]=ge[16]=ge[1]=ge[2]=ge[3]=ge[4]=ge[5]=ge[6]=ge[7]=ge[8]=ge[9]=ge[10]=ge[11]=ge[12]=ge[13]=ge[14]=ge[15]=0,this.blocks=ge):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}o(rt,"Sha256");rt.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,s=0,i,a=t.length,c=this.blocks;s<a;){if(this.hashed&&(this.hashed=!1,c[0]=this.block,this.block=c[16]=c[1]=c[2]=c[3]=c[4]=c[5]=c[6]=c[7]=c[8]=c[9]=c[10]=c[11]=c[12]=c[13]=c[14]=c[15]=0),e)for(i=this.start;s<a&&i<64;++s)c[i>>>2]|=t[s]<<Ze[i++&3];else for(i=this.start;s<a&&i<64;++s)n=t.charCodeAt(s),n<128?c[i>>>2]|=n<<Ze[i++&3]:n<2048?(c[i>>>2]|=(192|n>>>6)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):n<55296||n>=57344?(c[i>>>2]|=(224|n>>>12)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++s)&1023),c[i>>>2]|=(240|n>>>18)<<Ze[i++&3],c[i>>>2]|=(128|n>>>12&63)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=c[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};rt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=yh[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};rt.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=this.blocks,u,d,p,_,g,y,E,w,S,I,m;for(u=16;u<64;++u)g=l[u-15],d=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=l[u-2],p=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,l[u]=l[u-16]+d+l[u-7]+p<<0;for(m=e&r,u=0;u<64;u+=4)this.first?(this.is224?(w=300032,g=l[0]-1413257819,c=g-150054599<<0,n=g+24177077<<0):(w=704751109,g=l[0]-210244248,c=g-1521486534<<0,n=g+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),w=t&e,_=w^t&r^m,E=s&i^~s&a,g=c+p+E+rn[u]+l[u],y=d+_,c=n+g<<0,n=g+y<<0),d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),S=n&t,_=S^n&e^w,E=a&c^~a&s,g=i+p+E+rn[u+1]+l[u+1],y=d+_,a=r+g<<0,r=g+y<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),I=r&n,_=I^r&t^S,E=i&a^~i&c,g=s+p+E+rn[u+2]+l[u+2],y=d+_,i=e+g<<0,e=g+y<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),m=e&r,_=m^e&n^I,E=i&a^~i&c,g=s+p+E+rn[u+3]+l[u+3],y=d+_,s=t+g<<0,t=g+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+s<<0,this.h5=this.h5+i<<0,this.h6=this.h6+a<<0,this.h7=this.h7+c<<0};rt.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=$[t>>>28&15]+$[t>>>24&15]+$[t>>>20&15]+$[t>>>16&15]+$[t>>>12&15]+$[t>>>8&15]+$[t>>>4&15]+$[t&15]+$[e>>>28&15]+$[e>>>24&15]+$[e>>>20&15]+$[e>>>16&15]+$[e>>>12&15]+$[e>>>8&15]+$[e>>>4&15]+$[e&15]+$[r>>>28&15]+$[r>>>24&15]+$[r>>>20&15]+$[r>>>16&15]+$[r>>>12&15]+$[r>>>8&15]+$[r>>>4&15]+$[r&15]+$[n>>>28&15]+$[n>>>24&15]+$[n>>>20&15]+$[n>>>16&15]+$[n>>>12&15]+$[n>>>8&15]+$[n>>>4&15]+$[n&15]+$[s>>>28&15]+$[s>>>24&15]+$[s>>>20&15]+$[s>>>16&15]+$[s>>>12&15]+$[s>>>8&15]+$[s>>>4&15]+$[s&15]+$[i>>>28&15]+$[i>>>24&15]+$[i>>>20&15]+$[i>>>16&15]+$[i>>>12&15]+$[i>>>8&15]+$[i>>>4&15]+$[i&15]+$[a>>>28&15]+$[a>>>24&15]+$[a>>>20&15]+$[a>>>16&15]+$[a>>>12&15]+$[a>>>8&15]+$[a>>>4&15]+$[a&15];return this.is224||(l+=$[c>>>28&15]+$[c>>>24&15]+$[c>>>20&15]+$[c>>>16&15]+$[c>>>12&15]+$[c>>>8&15]+$[c>>>4&15]+$[c&15]),l};rt.prototype.toString=rt.prototype.hex;rt.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255];return this.is224||l.push(c>>>24&255,c>>>16&255,c>>>8&255,c&255),l};rt.prototype.array=rt.prototype.digest;rt.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};var Oh=_e(cn(),1);var ac=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function mr(t){return typeof t=="string"&&ac.test(t)}o(mr,"validate");function hr(t){if(!mr(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}o(hr,"parse");var be=[];for(let t=0;t<256;++t)be.push((t+256).toString(16).slice(1));function Et(t,e=0){return(be[t[e+0]]+be[t[e+1]]+be[t[e+2]]+be[t[e+3]]+"-"+be[t[e+4]]+be[t[e+5]]+"-"+be[t[e+6]]+be[t[e+7]]+"-"+be[t[e+8]]+be[t[e+9]]+"-"+be[t[e+10]]+be[t[e+11]]+be[t[e+12]]+be[t[e+13]]+be[t[e+14]]+be[t[e+15]]).toLowerCase()}o(Et,"unsafeStringify");var Nh=new Uint8Array(16);function gr(){return crypto.getRandomValues(Nh)}o(gr,"rng");function Mh(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}o(Mh,"f");function Hs(t,e){return t<<e|t>>>32-e}o(Hs,"ROTL");function oc(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let s=t.length/4+2,i=Math.ceil(s/16),a=new Array(i);for(let c=0;c<i;++c){let l=new Uint32Array(16);for(let u=0;u<16;++u)l[u]=t[c*64+u*4]<<24|t[c*64+u*4+1]<<16|t[c*64+u*4+2]<<8|t[c*64+u*4+3];a[c]=l}a[i-1][14]=(t.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<i;++c){let l=new Uint32Array(80);for(let y=0;y<16;++y)l[y]=a[c][y];for(let y=16;y<80;++y)l[y]=Hs(l[y-3]^l[y-8]^l[y-14]^l[y-16],1);let u=r[0],d=r[1],p=r[2],_=r[3],g=r[4];for(let y=0;y<80;++y){let E=Math.floor(y/20),w=Hs(u,5)+Mh(E,d,p,_)+g+e[E]+l[y]>>>0;g=_,_=p,p=Hs(d,30)>>>0,d=u,u=w}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+p>>>0,r[3]=r[3]+_>>>0,r[4]=r[4]+g>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}o(oc,"sha1");function kh(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}o(kh,"stringToBytes");var cc="6ba7b810-9dad-11d1-80b4-00c04fd430c8",lc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function uc(t,e,r,n,s,i){let a=typeof r=="string"?kh(r):r,c=typeof n=="string"?hr(n):n;if(typeof n=="string"&&(n=hr(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+a.length);if(l.set(c),l.set(a,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,s){if(i??=0,i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[i+u]=l[u];return s}return Et(l)}o(uc,"v35");function Gs(t,e,r,n){return uc(80,oc,t,e,r,n)}o(Gs,"v5");Gs.DNS=cc;Gs.URL=lc;var zs={};function fc(t,e,r){let n;if(t)n=dc(t.random??t.rng?.()??gr(),t.msecs,t.seq,e,r);else{let s=Date.now(),i=gr();Lh(zs,s,i),n=dc(i,zs.msecs,zs.seq,e,r)}return e??Et(n)}o(fc,"v7");function Lh(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}o(Lh,"updateV7State");function dc(t,e,r,n,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),s=0;else if(s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[s++]=e/1099511627776&255,n[s++]=e/4294967296&255,n[s++]=e/16777216&255,n[s++]=e/65536&255,n[s++]=e/256&255,n[s++]=e&255,n[s++]=112|r>>>28&15,n[s++]=r>>>20&255,n[s++]=128|r>>>14&63,n[s++]=r>>>6&255,n[s++]=r<<2&255|t[10]&3,n[s++]=t[11],n[s++]=t[12],n[s++]=t[13],n[s++]=t[14],n[s++]=t[15],n}o(dc,"v7Bytes");var nt=fc;var pc=Symbol.for("ls:tracing_async_local_storage"),Mt=Symbol.for("lc:context_variables"),mc=o(t=>{globalThis[pc]=t},"setGlobalAsyncLocalStorageInstance"),wt=o(()=>globalThis[pc],"getGlobalAsyncLocalStorageInstance");var Dh=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),$h=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Uh=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Ws=o(()=>typeof Deno<"u","isDeno"),Fh=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ws(),"isNode"),Bh=o(()=>{let t;return Dh()?t="browser":Fh()?t="node":$h()?t="webworker":Uh()?t="jsdom":Ws()?t="deno":t="other",t},"getEnv"),Vs;function hc(){return Vs===void 0&&(Vs={library:"langchain-js",runtime:Bh()}),Vs}o(hc,"getRuntimeEnvironment");function Je(t){try{return typeof process<"u"?process.env?.[t]:Ws()?Deno?.env.get(t):void 0}catch{return}}o(Je,"getEnvironmentVariable");var jh=class{static{o(this,"BaseCallbackHandlerMethodsClass")}};var qt=class extends jh{static{o(this,"BaseCallbackHandler")}lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Rs(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Ot.prototype.toJSON.call(this)}toJSONNotImplemented(){return Ot.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends qt{static{o(this,"Handler")}name=nt();constructor(){super(),Object.assign(this,t)}}return new e}},gc=o(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var yc=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Hh(t){return typeof t=="string"&&yc.test(t)}o(Hh,"validate");var _c=Hh;function Gh(t){if(!_c(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}o(Gh,"parse");var bc=Gh;var Ee=[];for(let t=0;t<256;++t)Ee.push((t+256).toString(16).slice(1));function Kt(t,e=0){return(Ee[t[e+0]]+Ee[t[e+1]]+Ee[t[e+2]]+Ee[t[e+3]]+"-"+Ee[t[e+4]]+Ee[t[e+5]]+"-"+Ee[t[e+6]]+Ee[t[e+7]]+"-"+Ee[t[e+8]]+Ee[t[e+9]]+"-"+Ee[t[e+10]]+Ee[t[e+11]]+Ee[t[e+12]]+Ee[t[e+13]]+Ee[t[e+14]]+Ee[t[e+15]]).toLowerCase()}o(Kt,"unsafeStringify");var Ec=_e(require("node:crypto"));var un=new Uint8Array(256),ln=un.length;function yr(){return ln>un.length-16&&(Ec.default.randomFillSync(un),ln=0),un.slice(ln,ln+=16)}o(yr,"rng");function zh(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}o(zh,"stringToBytes");var Vh="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Wh="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function qs(t,e,r){function n(s,i,a,c){var l;if(typeof s=="string"&&(s=zh(s)),typeof i=="string"&&(i=bc(i)),((l=i)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+s.length);if(u.set(i),u.set(s,i.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,a){c=c||0;for(let d=0;d<16;++d)a[c+d]=u[d];return a}return Kt(u)}o(n,"generateUUID");try{n.name=t}catch{}return n.DNS=Vh,n.URL=Wh,n}o(qs,"v35");var wc=_e(require("node:crypto")),Ks={randomUUID:wc.default.randomUUID};function qh(t,e,r){if(Ks.randomUUID&&!e&&!t)return Ks.randomUUID();t=t||{};let n=t.random||(t.rng||yr)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let s=0;s<16;++s)e[r+s]=n[s];return e}return Kt(n)}o(qh,"v4");var kt=qh;var Tc=_e(require("node:crypto"));function Kh(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),Tc.default.createHash("sha1").update(t).digest()}o(Kh,"sha1");var vc=Kh;var Zh=qs("v5",80,vc),Zs=Zh;var Sc=null,Ic=null,Ye=0;function Jh(t,e,r){t=t||{};let n=e&&r||0,s=e||new Uint8Array(16),i=t.random||(t.rng||yr)(),a=t.msecs!==void 0?t.msecs:Date.now(),c=t.seq!==void 0?t.seq:null,l=Ic,u=Sc;return a>Ye&&t.msecs===void 0&&(Ye=a,c!==null&&(l=null,u=null)),c!==null&&(c>2147483647&&(c=2147483647),l=c>>>19&4095,u=c&524287),(l===null||u===null)&&(l=i[6]&127,l=l<<8|i[7],u=i[8]&63,u=u<<8|i[9],u=u<<5|i[10]>>>3),a+1e4>Ye&&c===null?++u>524287&&(u=0,++l>4095&&(l=0,Ye++)):Ye=a,Ic=l,Sc=u,s[n++]=Ye/1099511627776&255,s[n++]=Ye/4294967296&255,s[n++]=Ye/16777216&255,s[n++]=Ye/65536&255,s[n++]=Ye/256&255,s[n++]=Ye&255,s[n++]=l>>>4&15|112,s[n++]=l&255,s[n++]=u>>>13&63|128,s[n++]=u>>>5&255,s[n++]=u<<3&255|i[10]&7,s[n++]=i[11],s[n++]=i[12],s[n++]=i[13],s[n++]=i[14],s[n++]=i[15],e||Kt(s)}o(Jh,"v7");var _r=Jh;var xc="gen_ai.operation.name",Ac="gen_ai.system",Js="gen_ai.request.model",Cc="gen_ai.response.model",Ys="gen_ai.usage.input_tokens",Xs="gen_ai.usage.output_tokens",Qs="gen_ai.usage.total_tokens",Rc="gen_ai.request.max_tokens",Oc="gen_ai.request.temperature",Nc="gen_ai.request.top_p",Mc="gen_ai.request.frequency_penalty",kc="gen_ai.request.presence_penalty",Pc="gen_ai.response.finish_reasons",Lc="gen_ai.prompt",Dc="gen_ai.completion",$c="gen_ai.request.extra_query",Uc="gen_ai.request.extra_body",Fc="gen_ai.serialized.name",Bc="gen_ai.serialized.signature",jc="gen_ai.serialized.doc",Hc="gen_ai.response.id",Gc="gen_ai.response.service_tier",zc="gen_ai.response.system_fingerprint",Vc="gen_ai.usage.input_token_details",Wc="gen_ai.usage.output_token_details",qc="langsmith.trace.session_id",Kc="langsmith.trace.session_name",Zc="langsmith.span.kind",Jc="langsmith.trace.name",Yc="langsmith.metadata",ei="langsmith.span.tags";var Xc="langsmith.request.streaming",Qc="langsmith.request.headers";var Qh=o((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),eg,el=Symbol.for("ls:fetch_implementation");var tl=o(()=>globalThis[el]===void 0?!0:eg??!1,"_shouldStreamForGlobalFetchImplementation"),rl=o(t=>async(...e)=>{if(t||te("DEBUG")==="true"){let[n,s]=e;console.log(`\u2192 ${s?.method||"GET"} ${n}`)}let r=await(globalThis[el]??Qh)(...e);return(t||te("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var br=o(()=>te("PROJECT")??Be("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var nl={};function Pt(t){nl[t]||(console.warn(t),nl[t]=!0)}o(Pt,"warnOnce");var R=o(t=>BigInt(t),"n"),ol=R("0x9E3779B1"),cl=R("0x85EBCA77"),tg=R("0xC2B2AE3D"),Tt=R("0x9E3779B185EBCA87"),Lt=R("0xC2B2AE3D27D4EB4F"),ll=R("0x165667B19E3779F9"),si=R("0x85EBCA77C2B2AE63"),rg=R("0x27D4EB2F165667C5"),ng=R("0x165667919E3779F9"),sg=R("0x9FB21C651E98DF25");function ig(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}o(ig,"hexToBytes");var st=ig("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Jt=(R(1)<<R(128))-R(1),W=(R(1)<<R(64))-R(1),mn=(R(1)<<R(32))-R(1),pt=64,ul=pt/8,ag=8,dn=4;function Y(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}o(Y,"getView");function Q(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}o(Q,"readBigUInt64LE");function Zt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}o(Zt,"readUInt32LE");function ti(t,e=0){return t[e]}o(ti,"readUInt8");var og=o(t=>(t&R(255))<<R(56)|(t&R(65280))<<R(40)|(t&R(16711680))<<R(24)|(t&R(4278190080))<<R(8)|(t&R(0xff00000000))>>R(8)|(t&R(0xff0000000000))>>R(24)|(t&R(0xff000000000000))>>R(40)|(t&R(0xff00000000000000))>>R(56),"bswap64"),cg=o(t=>(t=(t&R(65535))<<R(16)|(t&R(4294901760))>>R(16),t=(t&R(16711935))<<R(8)|(t&R(4278255360))>>R(8),t),"bswap32"),lg=o((t,e)=>(t&mn)*(e&mn)&W,"XXH_mult32to64"),Yt=o(t=>{if(!t)throw new Error("Assert failed")},"assert");function ug(t,e){return(t<<e|t>>R(32)-e)&mn}o(ug,"rotl32");function dl(t,e,r){for(let n=0;n<ul;n++){let s=Q(e,n*8),i=s^Q(r,n*8);t[n^1]+=s,t[n]+=lg(i,i>>R(32))}return t}o(dl,"XXH3_accumulate_512");function sl(t,e,r,n){for(let s=0;s<n;s++)dl(t,Y(e,s*pt),Y(r,s*8));return t}o(sl,"XXH3_accumulate");function dg(t,e){for(let r=0;r<ul;r++){let n=Q(e,r*8),s=t[r];s=ri(s,R(47)),s^=n,s*=ol,t[r]=s&W}return t}o(dg,"XXH3_scrambleAcc");function fn(t,e){return fl(t[0]^Q(e,0),t[1]^Q(e,ag))}o(fn,"XXH3_mix2Accs");function il(t,e,r){let n=r;return n+=fn(t.slice(0),Y(e,0*dn)),n+=fn(t.slice(2),Y(e,4*dn)),n+=fn(t.slice(4),Y(e,8*dn)),n+=fn(t.slice(6),Y(e,12*dn)),it(n&W)}o(il,"XXH3_mergeAccs");function fg(t,e,r,n,s){let i=Math.floor((r.byteLength-pt)/8),a=pt*i,c=Math.floor((e.byteLength-1)/a);for(let l=0;l<c;l++)t=sl(t,Y(e,l*a),r,i),t=s(t,Y(r,r.byteLength-pt));{let l=Math.floor((e.byteLength-1-a*c)/pt);t=sl(t,Y(e,c*a),r,l),t=n(t,Y(e,e.byteLength-pt),Y(r,r.byteLength-pt-7))}return t}o(fg,"XXH3_hashLong");function pg(t,e,r){let n=new BigUint64Array([tg,Tt,Lt,ll,si,cl,rg,ol]);Yt(t.length>128),n=fg(n,t,e,dl,dg),Yt(n.length*8==64);{let s=il(n,Y(e,11),R(t.byteLength)*Tt&W);return il(n,Y(e,e.byteLength-pt-11),~(R(t.byteLength)*Lt)&W)<<R(64)|s}}o(pg,"XXH3_hashLong_128b");function fl(t,e){let r=t*e&Jt;return r&W^r>>R(64)}o(fl,"XXH3_mul128_fold64");function al(t,e,r){return fl((Q(t,0)^Q(e,0)+r)&W,(Q(t,8)^Q(e,8)-r)&W)}o(al,"XXH3_mix16B");function pn(t,e,r,n,s){let i=t&W,a=t>>R(64)&W;return i+=al(e,n,s),i^=Q(r,0)+Q(r,8),i&=W,a+=al(r,Y(n,16),s),a^=Q(e,0)+Q(e,8),a&=W,a<<R(64)|i}o(pn,"XXH3_mix32B");function it(t){return t^=t>>R(37),t*=ng,t&=W,t^=t>>R(32),t}o(it,"XXH3_avalanche");function hn(t){return t^=t>>R(33),t*=Lt,t&=W,t^=t>>R(29),t*=ll,t&=W,t^=t>>R(32),t}o(hn,"XXH3_avalanche64");function mg(t,e,r){let n=t.byteLength;Yt(n>0&&n<=3);let s=R(ti(t,n-1))|R(n<<8)|R(ti(t,0)<<16)|R(ti(t,n>>1)<<24),i=(R(Zt(e,0))^R(Zt(e,4)))+r,a=(s^i)&W,c=(R(Zt(e,8))^R(Zt(e,12)))-r,l=(ug(cg(s),R(13))^c)&W;return(hn(l)&W)<<R(64)|hn(a)}o(mg,"XXH3_len_1to3_128b");function ri(t,e){return t^t>>e}o(ri,"xorshift64");function hg(t,e,r){let n=t.byteLength;Yt(n>=4&&n<=8);{let s=Zt(t,0),i=Zt(t,n-4),a=R(s)|R(i)<<R(32),c=(Q(e,16)^Q(e,24))+r&W,u=(a^c)*(Tt+(R(n)<<R(2)))&Jt;return u+=(u&W)<<R(65),u&=Jt,u^=u>>R(67),ri(ri(u&W,R(35))*sg&W,R(28))|it(u>>R(64))<<R(64)}}o(hg,"XXH3_len_4to8_128b");function gg(t,e,r){let n=t.byteLength;Yt(n>=9&&n<=16);{let s=(Q(e,32)^Q(e,40))+r&W,i=(Q(e,48)^Q(e,56))-r&W,a=Q(t),c=Q(t,n-8),l=(a^c^s)*Tt,u=(l&W)+(R(n-1)<<R(54));l=l&(Jt^W)|u,c^=i,l+=c+(c&mn)*(cl-R(1))<<R(64),l&=Jt,l^=og(l>>R(64));let d=(l&W)*Lt;return d+=(l>>R(64))*Lt<<R(64),d&=Jt,it(d&W)|it(d>>R(64))<<R(64)}}o(gg,"XXH3_len_9to16_128b");function yg(t,e){let r=t.byteLength;return Yt(r<=16),r>8?gg(t,st,e):r>=4?hg(t,st,e):r>0?mg(t,st,e):hn(e^Q(st,64)^Q(st,72))|hn(e^Q(st,80)^Q(st,88))<<R(64)}o(yg,"XXH3_len_0to16_128b");function ni(t){return~t+R(1)&W}o(ni,"inv64");function _g(t,e,r){let n=R(t.byteLength)*Tt&W,s=R(t.byteLength-1)/R(32);for(;s>=0;){let c=Number(s);n=pn(n,Y(t,16*c),Y(t,t.byteLength-16*(c+1)),Y(e,32*c),r),s--}let i=n+(n>>R(64))&W;i=it(i);let a=(n&W)*Tt+(n>>R(64))*si+(R(t.byteLength)-r&W)*Lt;return a&=W,a=ni(it(a)),i|a<<R(64)}o(_g,"XXH3_len_17to128_128b");function bg(t,e,r){let n=R(t.byteLength)*Tt&W;for(let a=32;a<160;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,a-32),r);n=it(n&W)|it(n>>R(64))<<R(64);for(let a=160;a<=t.byteLength;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,3+a-160),r);n=pn(n,Y(t,t.byteLength-16),Y(t,t.byteLength-32),Y(e,103),ni(r));let s=n+(n>>R(64))&W;s=it(s);let i=(n&W)*Tt+(n>>R(64))*si+(R(t.byteLength)-r&W)*Lt;return i&=W,i=ni(it(i)),s|i<<R(64)}o(bg,"XXH3_len_129to240_128b");function pl(t,e=R(0)){let r=t.byteLength;return r<=16?yg(t,e):r<=128?_g(t,st,e):r<=240?bg(t,st,e):pg(t,st,e)}o(pl,"XXH3_128");function ml(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&W,s=t>>R(64);return r.setBigUint64(0,s,!1),r.setBigUint64(8,n,!1),e}o(ml,"xxh128ToBytes");var hl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function z(t,e){if(!hl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}o(z,"assertUuid");function gn(t){let e=typeof t=="string"?Date.parse(t):t;return _r({msecs:e,seq:0})}o(gn,"uuid7FromTime");function Eg(t){if(!hl.test(t))return null;let e=t[14];return parseInt(e,16)}o(Eg,"getUuidVersion");function wg(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}o(wg,"uuidToBytes");function Tg(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}o(Tg,"bytesToUuid");var vg=new TextEncoder;function Sg(t){let e=vg.encode(t),r=pl(e);return ml(r)}o(Sg,"_fastHash128");function Er(t,e){let r=`${t}:${e}`,n=Sg(r),s=new Uint8Array(16);if(Eg(t)===7){let a=wg(t);s.set(a.slice(0,6),0)}else{let a=Date.now();s[0]=a/1099511627776&255,s[1]=a/4294967296&255,s[2]=a/16777216&255,s[3]=a/65536&255,s[4]=a/256&255,s[5]=a&255}return s[6]=112|n[0]&15,s[7]=n[1],s[8]=128|n[2]&63,s.set(n.slice(3,10),9),Tg(s)}o(Er,"nonCryptographicUuid7Deterministic");var He=_e(require("node:fs"),1),Xe=_e(require("node:fs/promises"),1),Ig=_e(require("node:path"),1);var wr=Ig;async function gl(t){await Xe.mkdir(t,{recursive:!0})}o(gl,"mkdir");async function yl(t,e){let r=`${t}.tmp`;await Xe.writeFile(r,e,{encoding:"utf8",mode:384}),await Xe.rename(r,t)}o(yl,"writeFileAtomic");async function _l(t){return Xe.readdir(t)}o(_l,"readdir");async function bl(t){return Xe.stat(t)}o(bl,"stat");function yn(t){return He.existsSync(t)}o(yn,"existsSync");function El(t){He.mkdirSync(t,{recursive:!0})}o(El,"mkdirSync");function wl(t,e){He.writeFileSync(t,e)}o(wl,"writeFileSync");function Tl(t,e){He.renameSync(t,e)}o(Tl,"renameSync");function vl(t){He.unlinkSync(t)}o(vl,"unlinkSync");function Sl(t){return He.readFileSync(t,"utf-8")}o(Sl,"readFileSync");function Ag(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}o(Ag,"isStale");var _n=class{static{o(this,"PromptCache")}constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let s={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,s)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[i,a]of this.cache.entries())r[i]=a.value;let n=wr.dirname(e);yn(n)||El(n);let s=`${e}.tmp`;try{wl(s,JSON.stringify({entries:r},null,2)),Tl(s,e)}catch(i){throw yn(s)&&vl(s),i}}load(e){if(!yn(e))return 0;let r;try{let i=Sl(e);r=JSON.parse(i).entries??null}catch{return 0}if(!r)return 0;let n=0,s=Date.now();for(let[i,a]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let c={value:a,createdAt:s};this.cache.set(i,c),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())Ag(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let s=await n.refreshFunc();this.set(r,s,n.refreshFunc),this._metrics.refreshes+=1}catch(s){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,s)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},bn=new _n;var En="0.5.16";var at,Cg=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),Rg=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Og=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Il=o(()=>typeof Deno<"u","isDeno"),Ng=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Il(),"isNode"),oi=o(()=>at||(typeof Bun<"u"?at="bun":Cg()?at="browser":Ng()?at="node":Rg()?at="webworker":Og()?at="jsdom":Il()?at="deno":at="other",at),"getEnv"),ii;function wn(){if(ii===void 0){let t=oi(),e=kg();ii={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:En,...e}}return ii}o(wn,"getRuntimeEnvironment");function ci(){let t=Mg(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,s]of Object.entries(t))typeof s=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[n]=s);return e}o(ci,"getLangSmithEnvVarsMetadata");function Mg(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}o(Mg,"getLangSmithEnvironmentVariables");function Be(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}o(Be,"getEnvironmentVariable");function te(t){return Be(`LANGSMITH_${t}`)||Be(`LANGCHAIN_${t}`)}o(te,"getLangSmithEnvironmentVariable");var ai;function kg(){if(ai!==void 0)return ai;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let r of t){let n=Be(r);n!==void 0&&(e[r]=n)}return ai=e,e}o(kg,"getShas");function Tn(){return Be("OTEL_ENABLED")==="true"||te("OTEL_ENABLED")==="true"}o(Tn,"getOtelEnabled");var di=class{static{o(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Tn()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},fi=class{static{o(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new di})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},pi=class{static{o(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},li=Symbol.for("ls:otel_trace"),ui=Symbol.for("ls:otel_context"),xl=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Pg=new fi,Lg=new pi,mi=class{static{o(this,"OTELProvider")}getTraceInstance(){return globalThis[li]??Pg}getContextInstance(){return globalThis[ui]??Lg}initializeGlobalInstances(e){globalThis[li]===void 0&&(globalThis[li]=e.trace),globalThis[ui]===void 0&&(globalThis[ui]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[xl]=e}getDefaultOTLPTracerComponents(){return globalThis[xl]??void 0}},hi=new mi;function vn(){return hi.getTraceInstance()}o(vn,"getOTELTrace");function Al(){return hi.getContextInstance()}o(Al,"getOTELContext");function Cl(){return hi.getDefaultOTLPTracerComponents()}o(Cl,"getDefaultOTLPTracerComponents");var Dg={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function $g(t){return Dg[t]||t}o($g,"getOperationName");var Sn=class{static{o(this,"LangSmithToOTELTranslator")}constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let s=this.createSpanForRun(n,n.run,r.get(n.id));s&&!n.run.end_time&&this.spans.set(n.id,s)}else this.updateSpanForRun(n,n.run)}catch(s){console.error(`Error processing operation ${n.id}:`,s)}}createSpanForRun(e,r,n){let s=n&&vn().getSpan(n);if(s)try{return this.finishSpanSetup(s,r,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let s=r.end_time;s&&(n.end(new Date(s)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(Zc,r.run_type);let c=$g(r.run_type||"chain");e.setAttribute(xc,c)}"name"in r&&r.name&&e.setAttribute(Jc,r.name),"session_id"in r&&r.session_id&&e.setAttribute(qc,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(Kc,r.session_name),this.setGenAiSystem(e,r);let s=this.extractModelName(r);s&&e.setAttribute(Js,s),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ys,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Xs,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Qs,r.total_tokens),this.setInvocationParameters(e,r);let i=r.extra?.metadata||{};for(let[c,l]of Object.entries(i))l!=null&&e.setAttribute(`${Yc}.${c}`,String(l));let a=r.tags;if(a&&Array.isArray(a)?e.setAttribute(ei,a.join(", ")):a&&e.setAttribute(ei,String(a)),"serialized"in r&&typeof r.serialized=="object"){let c=r.serialized;c.name&&e.setAttribute(Fc,String(c.name)),c.signature&&e.setAttribute(Bc,String(c.signature)),c.doc&&e.setAttribute(jc,String(c.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",s=this.extractModelName(r);if(s){let i=s.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?n="anthropic":i.includes("bedrock")?n="aws.bedrock":i.includes("azure")&&i.includes("openai")?n="az.ai.openai":i.includes("azure")&&i.includes("inference")?n="az.ai.inference":i.includes("cohere")?n="cohere":i.includes("deepseek")?n="deepseek":i.includes("gemini")?n="gemini":i.includes("groq")?n="groq":i.includes("watson")||i.includes("ibm")?n="ibm.watsonx.ai":i.includes("mistral")?n="mistral_ai":i.includes("gpt")||i.includes("openai")?n="openai":i.includes("perplexity")||i.includes("sonar")?n="perplexity":i.includes("vertex")?n="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(n="xai")}e.setAttribute(Ac,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Rc,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Oc,n.temperature),n.top_p!==void 0&&e.setAttribute(Nc,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Mc,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(kc,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Js,n.model),n.stream!==void 0&&e.setAttribute(Xc,n.stream),n.extra_headers&&e.setAttribute(Qc,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute($c,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Uc,JSON.stringify(n.extra_body))),e.setAttribute(Lc,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,s=this.getUnifiedRunTokens(n);if(s&&(e.setAttribute(Ys,s[0]),e.setAttribute(Xs,s[1]),e.setAttribute(Qs,s[0]+s[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Cc,String(n.model)),n.id&&e.setAttribute(Hc,n.id),n.choices&&Array.isArray(n.choices)){let i=n.choices.map(a=>a.finish_reason).filter(a=>a).map(String);i.length>0&&e.setAttribute(Pc,i.join(", "))}if(n.service_tier&&e.setAttribute(Gc,n.service_tier),n.system_fingerprint&&e.setAttribute(zc,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let i=n.usage_metadata;i.input_token_details&&e.setAttribute(Vc,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(Wc,JSON.stringify(i.output_token_details))}}e.setAttribute(Dc,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let a of n){let c=e[a];if(!(!c||typeof c!="object")&&(r=this.extractUnifiedRunTokens(c.usage_metadata),r||c.lc===1&&c.kwargs&&typeof c.kwargs=="object"&&(r=this.extractUnifiedRunTokens(c.kwargs.usage_metadata),r)))return r}let s=e.generations||[];if(!Array.isArray(s))return null;let i=Array.isArray(s[0])?s.flat():s;for(let a of i)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}};var Ug=Object.prototype.toString,Fg=o(t=>Ug.call(t)==="[object Error]","isError"),Bg=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function gi(t){if(!(t&&Fg(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:Bg.has(r)}o(gi,"isNetworkError");function jg(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}o(jg,"validateRetries");function In(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}o(In,"validateNumberOption");var yi=class extends Error{static{o(this,"AbortError")}constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Hg(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(r-1));return s=Math.min(s,e.maxTimeout),s}o(Hg,"calculateDelay");function Rl(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}o(Rl,"calculateRemainingTime");async function Gg({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:s}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof yi)throw i.originalError;let a=Number.isFinite(s.retries)?Math.max(0,s.retries-r):s.retries,c=s.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:r});if(await s.onFailedAttempt(l),Rl(n,c)<=0)throw i;let u=await s.shouldConsumeRetry(l),d=Rl(n,c);if(d<=0||a<=0)throw i;if(i instanceof TypeError&&!gi(i)){if(u)throw i;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(l))throw i;if(!u)return s.signal?.throwIfAborted(),!1;let p=Hg(r,s),_=Math.min(p,d);return _>0&&await new Promise((g,y)=>{let E=o(()=>{clearTimeout(w),s.signal?.removeEventListener("abort",E),y(s.signal.reason)},"onAbort"),w=setTimeout(()=>{s.signal?.removeEventListener("abort",E),g()},_);s.unref&&w.unref?.(),s.signal?.addEventListener("abort",E,{once:!0})}),s.signal?.throwIfAborted(),!0}o(Gg,"onAttemptFailure");async function _i(t,e={}){if(e={...e},jg(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,In("factor",e.factor,{min:0,allowInfinity:!1}),In("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),In("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),In("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let i=await t(r);return e.signal?.throwIfAborted(),i}catch(i){await Gg({error:i,attemptNumber:r,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}o(_i,"pRetry");var xn=_e(cn(),1),Ol="default"in xn.default?xn.default.default:xn.default;var zg=[408,425,429,500,502,503,504],Tr=class{static{o(this,"AsyncCaller")}constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new Ol({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let s=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&s>0&&this.queueSizeBytes+s>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${s} bytes.`));s>0&&(this.queueSizeBytes+=s);let i=this.onFailedResponseHook,a=this.queue.add(()=>_i(()=>r(...n).catch(c=>{throw c instanceof Error?c:new Error(c)}),{async onFailedAttempt({error:c}){if(typeof c!="object"||c==null)throw c;let l="message"in c&&typeof c.message=="string"?c.message:void 0;if(l?.startsWith("Cancel")||l?.startsWith("TimeoutError")||l?.startsWith("AbortError")||"name"in c&&c.name==="TimeoutError"||"code"in c&&c.code==="ECONNABORTED")throw c;let u="response"in c?c.response:void 0;if(i&&await i(u))return;let d=u?.status??("status"in c?c.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!zg.includes(+d))throw c},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return s>0&&(a=a.finally(()=>{this.queueSizeBytes-=s})),e.signal?Promise.race([a,new Promise((c,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):a}};function bi(t){return typeof t?._getType=="function"}o(bi,"isLangChainMessage");function Ei(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}o(Ei,"convertLangChainMessageToExample");var Bb=_e(bd(),1);function Bn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
|
|
10
10
|
- "prompt-name" (for private prompts)
|
|
11
11
|
- "owner/prompt-name" (for prompts with explicit owner)
|
|
12
12
|
- "prompt-name:commit-hash" (with commit reference)
|
|
13
|
-
- "owner/prompt-name:commit-hash" (with owner and commit)`}o(Bn,"getInvalidPromptIdentifierMsg");var Bi=class extends Error{static{o(this,"LangSmithConflictError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},ji=class extends Error{static{o(this,"LangSmithNotFoundError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function Hi(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}o(Hi,"isLangSmithNotFoundError");async function U(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let c=new Error(`${t.status} ${t.statusText}`);throw c.status=t?.status,c}if(n===void 0)try{n=await t.text()}catch{n=""}let s=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new ji(s);if(t.status===409)throw new Bi(s);let i=new Error(s);throw i.status=t.status,i}o(U,"raiseForStatus");var Ed="ERR_CONFLICTING_ENDPOINTS",Fn=class extends Error{static{o(this,"ConflictingEndpointsError")}constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Ed}),this.name="ConflictingEndpointsError"}};function wd(t){return typeof t=="object"&&t!==null&&t.code===Ed}o(wd,"isConflictingEndpointsError");function ct(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(Bn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[s,i]=e.split("/",2);if(!s||!i)throw new Error(Bn(t));return[s,i,n]}else{if(!e)throw new Error(Bn(t));return["-",e,n]}}o(ct,"parsePromptIdentifier");var Td="[...]",
|
|
13
|
+
- "owner/prompt-name:commit-hash" (with owner and commit)`}o(Bn,"getInvalidPromptIdentifierMsg");var Bi=class extends Error{static{o(this,"LangSmithConflictError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},ji=class extends Error{static{o(this,"LangSmithNotFoundError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function Hi(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}o(Hi,"isLangSmithNotFoundError");async function U(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let c=new Error(`${t.status} ${t.statusText}`);throw c.status=t?.status,c}if(n===void 0)try{n=await t.text()}catch{n=""}let s=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new ji(s);if(t.status===409)throw new Bi(s);let i=new Error(s);throw i.status=t.status,i}o(U,"raiseForStatus");var Ed="ERR_CONFLICTING_ENDPOINTS",Fn=class extends Error{static{o(this,"ConflictingEndpointsError")}constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Ed}),this.name="ConflictingEndpointsError"}};function wd(t){return typeof t=="object"&&t!==null&&t.code===Ed}o(wd,"isConflictingEndpointsError");function ct(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(Bn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[s,i]=e.split("/",2);if(!s||!i)throw new Error(Bn(t));return[s,i,n]}else{if(!e)throw new Error(Bn(t));return["-",e,n]}}o(ct,"parsePromptIdentifier");var Td="[...]",jb={result:"[Circular]"},Hn=[],Qt=[],Hb=new TextEncoder;function Gb(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}o(Gb,"defaultOptions");function jn(t){return Hb.encode(t)}o(jn,"encodeString");function vd(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}o(vd,"serializeWellKnownTypes");function zb(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return vd(r)}}o(zb,"createDefaultReplacer");function Pe(t,e,r,n,s){try{let i=JSON.stringify(t,zb(r),n);return jn(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
14
14
|
Context: ${e}`:""}`),jn("[Unserializable]");te("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
15
|
-
Context: ${e}`:""}`),typeof s>"u"&&(s=Bb()),zi(t,"",0,[],void 0,0,s);let a;try{Qt.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Hb(r),n)}catch{return jn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Hn.length!==0;){let c=Hn.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return jn(a)}}o(Pe,"serialize");function Gi(t,e,r,n){var s=Object.getOwnPropertyDescriptor(n,r);s.get!==void 0?s.configurable?(Object.defineProperty(n,r,{value:t}),Hn.push([n,r,e,s])):Qt.push([e,r,t]):(n[r]=t,Hn.push([n,r,e]))}o(Gi,"setReplace");function zi(t,e,r,n,s,i,a){i+=1;var c;if(typeof t=="object"&&t!==null){for(c=0;c<n.length;c++)if(n[c]===t){Gi(Ub,t,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Gi(Td,t,e,s);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Gi(Td,t,e,s);return}if(n.push(t),Array.isArray(t))for(c=0;c<t.length;c++)zi(t[c],c,c,n,t,i,a);else{t=vd(t);var l=Object.keys(t);for(c=0;c<l.length;c++){var u=l[c];zi(t[u],u,c,n,t,i,a)}}n.pop()}}o(zi,"decirc");function Hb(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Qt.length>0)for(var n=0;n<Qt.length;n++){var s=Qt[n];if(s[1]===e&&s[0]===r){r=s[2],Qt.splice(n,1);break}}return t.call(this,e,r)}}o(Hb,"replaceGetterValues");function Sd(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}o(Sd,"_ensureUTCTimestamp");function Or(t){return{...t,start_time:Sd(t.start_time),end_time:Sd(t.end_time)}}o(Or,"_normalizeRunTimestamps");function Id(t,e,r){if(r)return t;let n=wn(),s=e??ci(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...n,...i?.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...a}},t}o(Id,"mergeRuntimeEnvIntoRun");var Gb=o(t=>{let e=t?.toString()??te("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},"getTracingSamplingRate"),zb=o(t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"},"isLocalhost");async function Vb(t){let e=[];for await(let r of t)e.push(r);return e}o(Vb,"toArray");function Gn(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}o(Gn,"trimQuotes");var qb=o(async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1},"handle429");function xd(t){return typeof t=="number"?Number(t.toFixed(4)):t}o(xd,"_formatFeedbackScore");var Wb=24*1024*1024,Cd=1024*1024*1024,Kb=1e4,Zb=100,Ad="https://api.smith.langchain.com",Vi=class{static{o(this,"AutoBatchQueue")}constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??Cd}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),s=Pe(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+s>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${s} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:s}),this.sizeBytes+=s,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),s+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),s+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>n.forEach(i=>i.itemPromiseResolve())]}},vt=class t{static{o(this,"Client")}get _fetch(){return this.fetchImplementation||rl(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Be("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:te("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Be("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();if(this.tracingSampleRate=Gb(e.tracingSamplingRate),this.apiUrl=Gn(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Gn(e.apiKey??r.apiKey),this.webUrl=Gn(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Gn(e.workspaceId??te("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Tr({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=te("FAILED_TRACES_DIR")||void 0;let n=te("FAILED_TRACES_MAX_MB");if(n){let i=parseInt(n,10);Number.isFinite(i)&&i>0&&(this.failedTracesMaxBytes=i*1024*1024)}let s=e.maxIngestMemoryBytes??Cd;this.batchIngestCaller=new Tr({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:qb,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Vi(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Tn()&&(this.langSmithToOTELTranslator=new Sn),this.cachedLSEnvVarsForMetadata=ci(),e.cache!==void 0&&e.disablePromptCache&&Pt("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(Pt("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=bn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=bn)}static getDefaultClientConfig(){let e=te("API_KEY"),r=te("ENDPOINT")??Ad,n=te("HIDE_INPUTS")==="true",s=te("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:zb(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let e={"User-Agent":`langsmith-js/${En}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){let r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){let n=r?.toString()??"",s=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let a=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,`fetch ${e}`),a})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let s=Number(r.get("offset"))||0,i=Number(r.get("limit"))||100;for(;;){r.set("offset",String(s)),r.set("limit",String(i));let a=`${this.apiUrl}${e}?${r}`,c=await this.caller.call(async()=>{let u=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(u,`fetch ${e}`),u}),l=n?n(await c.json()):await c.json();if(l.length===0||(yield l,l.length<i))break;s+=l.length}}async*_getCursorPaginatedList(e,r=null,n="POST",s="runs"){let i=r?{...r}:{};for(;;){let a=JSON.stringify(i),l=await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(d,`fetch ${e}`),d})).json();if(!l||!l[s])break;yield l[s];let u=l.cursors;if(!u||!u.next)break;i.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){let n=[];for(let s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):n.push(s);return n}else{let n=[];for(let s of e){let i=s.trace_id??s.id;this.filteredPostUuids.has(i)||(s.id===i?this._shouldSample()?n.push(s):this.filteredPostUuids.add(i):n.push(s))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Wb}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Zb}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[s,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!s.length){i();break}let a=s.reduce((u,d)=>{let p=d.apiUrl??this.apiUrl,_=d.apiKey??this.apiKey,y=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl?"default":`${p}|${_}`;return u[y]||(u[y]=[]),u[y].push(d),u},{}),c=[];for(let[u,d]of Object.entries(a)){let p=this._processBatch(d,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});c.push(p)}let l=Promise.all(c).finally(i);n.push(l)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,s,i){try{let a=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),c=JSON.stringify({version:1,endpoint:s,headers:n,body_base64:a.toString("base64")}),l=`trace_${Date.now()}_${kt().slice(0,8)}.json`,u=wr.join(e,l);if(t._fallbackDirsCreated.has(e)||(await gl(e),t._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{let p=(await _l(e)).filter(g=>g.startsWith("trace_")&&g.endsWith(".json")),_=0;for(let g of p){let{size:y}=await bl(wr.join(e,g));_+=y}if(_>=i){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${_} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await yl(u,c),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(a){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,a)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((s,i)=>s+(i.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let s={runCreates:e.filter(c=>c.action==="create").map(c=>c.item),runUpdates:e.filter(c=>c.action==="update").map(c=>c.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let c=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(s,{...r,useGzip:c,sizeBytes:n})}catch(l){if(Hi(l))this._multipartDisabled=!0,await this.batchIngestRuns(s,{...r,sizeBytes:n});else throw l}}else await this.batchIngestRuns(s,{...r,sizeBytes:n})}}catch(s){console.error("Error exporting batch:",s)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let s of e)s.item.id&&s.otelContext&&(r.set(s.item.id,s.otelContext),s.action==="create"?n.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):n.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Id(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Kb),...this.fetchOptions});return await U(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
15
|
+
Context: ${e}`:""}`),typeof s>"u"&&(s=Gb()),zi(t,"",0,[],void 0,0,s);let a;try{Qt.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Vb(r),n)}catch{return jn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Hn.length!==0;){let c=Hn.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return jn(a)}}o(Pe,"serialize");function Gi(t,e,r,n){var s=Object.getOwnPropertyDescriptor(n,r);s.get!==void 0?s.configurable?(Object.defineProperty(n,r,{value:t}),Hn.push([n,r,e,s])):Qt.push([e,r,t]):(n[r]=t,Hn.push([n,r,e]))}o(Gi,"setReplace");function zi(t,e,r,n,s,i,a){i+=1;var c;if(typeof t=="object"&&t!==null){for(c=0;c<n.length;c++)if(n[c]===t){Gi(jb,t,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Gi(Td,t,e,s);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Gi(Td,t,e,s);return}if(n.push(t),Array.isArray(t))for(c=0;c<t.length;c++)zi(t[c],c,c,n,t,i,a);else{t=vd(t);var l=Object.keys(t);for(c=0;c<l.length;c++){var u=l[c];zi(t[u],u,c,n,t,i,a)}}n.pop()}}o(zi,"decirc");function Vb(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Qt.length>0)for(var n=0;n<Qt.length;n++){var s=Qt[n];if(s[1]===e&&s[0]===r){r=s[2],Qt.splice(n,1);break}}return t.call(this,e,r)}}o(Vb,"replaceGetterValues");function Sd(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}o(Sd,"_ensureUTCTimestamp");function Or(t){return{...t,start_time:Sd(t.start_time),end_time:Sd(t.end_time)}}o(Or,"_normalizeRunTimestamps");function Id(t,e,r){if(r)return t;let n=wn(),s=e??ci(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...n,...i?.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...a}},t}o(Id,"mergeRuntimeEnvIntoRun");var Wb=o(t=>{let e=t?.toString()??te("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},"getTracingSamplingRate"),qb=o(t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"},"isLocalhost");async function Kb(t){let e=[];for await(let r of t)e.push(r);return e}o(Kb,"toArray");function Gn(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}o(Gn,"trimQuotes");var Zb=o(async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1},"handle429");function xd(t){return typeof t=="number"?Number(t.toFixed(4)):t}o(xd,"_formatFeedbackScore");var Jb=24*1024*1024,Rd=1024*1024*1024,Yb=1e4,Xb=100,Ad="https://api.smith.langchain.com",Vi=class{static{o(this,"AutoBatchQueue")}constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??Rd}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),s=Pe(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+s>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${s} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:s}),this.sizeBytes+=s,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),s+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),s+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>n.forEach(i=>i.itemPromiseResolve())]}},vt=class t{static{o(this,"Client")}get _fetch(){return this.fetchImplementation||rl(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Be("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:te("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Be("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();if(this.tracingSampleRate=Wb(e.tracingSamplingRate),this.apiUrl=Gn(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Gn(e.apiKey??r.apiKey),this.webUrl=Gn(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Gn(e.workspaceId??te("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Tr({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=te("FAILED_TRACES_DIR")||void 0;let n=te("FAILED_TRACES_MAX_MB");if(n){let i=parseInt(n,10);Number.isFinite(i)&&i>0&&(this.failedTracesMaxBytes=i*1024*1024)}let s=e.maxIngestMemoryBytes??Rd;this.batchIngestCaller=new Tr({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:Zb,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Vi(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Tn()&&(this.langSmithToOTELTranslator=new Sn),this.cachedLSEnvVarsForMetadata=ci(),e.cache!==void 0&&e.disablePromptCache&&Pt("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(Pt("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=bn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=bn)}static getDefaultClientConfig(){let e=te("API_KEY"),r=te("ENDPOINT")??Ad,n=te("HIDE_INPUTS")==="true",s=te("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:qb(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let e={"User-Agent":`langsmith-js/${En}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){let r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){let n=r?.toString()??"",s=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let a=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,`fetch ${e}`),a})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let s=Number(r.get("offset"))||0,i=Number(r.get("limit"))||100;for(;;){r.set("offset",String(s)),r.set("limit",String(i));let a=`${this.apiUrl}${e}?${r}`,c=await this.caller.call(async()=>{let u=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(u,`fetch ${e}`),u}),l=n?n(await c.json()):await c.json();if(l.length===0||(yield l,l.length<i))break;s+=l.length}}async*_getCursorPaginatedList(e,r=null,n="POST",s="runs"){let i=r?{...r}:{};for(;;){let a=JSON.stringify(i),l=await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(d,`fetch ${e}`),d})).json();if(!l||!l[s])break;yield l[s];let u=l.cursors;if(!u||!u.next)break;i.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){let n=[];for(let s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):n.push(s);return n}else{let n=[];for(let s of e){let i=s.trace_id??s.id;this.filteredPostUuids.has(i)||(s.id===i?this._shouldSample()?n.push(s):this.filteredPostUuids.add(i):n.push(s))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Jb}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Xb}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[s,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!s.length){i();break}let a=s.reduce((u,d)=>{let p=d.apiUrl??this.apiUrl,_=d.apiKey??this.apiKey,y=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl?"default":`${p}|${_}`;return u[y]||(u[y]=[]),u[y].push(d),u},{}),c=[];for(let[u,d]of Object.entries(a)){let p=this._processBatch(d,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});c.push(p)}let l=Promise.all(c).finally(i);n.push(l)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,s,i){try{let a=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),c=JSON.stringify({version:1,endpoint:s,headers:n,body_base64:a.toString("base64")}),l=`trace_${Date.now()}_${kt().slice(0,8)}.json`,u=wr.join(e,l);if(t._fallbackDirsCreated.has(e)||(await gl(e),t._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{let p=(await _l(e)).filter(g=>g.startsWith("trace_")&&g.endsWith(".json")),_=0;for(let g of p){let{size:y}=await bl(wr.join(e,g));_+=y}if(_>=i){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${_} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await yl(u,c),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(a){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,a)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((s,i)=>s+(i.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let s={runCreates:e.filter(c=>c.action==="create").map(c=>c.item),runUpdates:e.filter(c=>c.action==="update").map(c=>c.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let c=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(s,{...r,useGzip:c,sizeBytes:n})}catch(l){if(Hi(l))this._multipartDisabled=!0,await this.batchIngestRuns(s,{...r,sizeBytes:n});else throw l}}else await this.batchIngestRuns(s,{...r,sizeBytes:n})}}catch(s){console.error("Error exporting batch:",s)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let s of e)s.item.id&&s.otelContext&&(r.set(s.item.id,s.otelContext),s.action==="create"?n.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):n.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Id(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Yb),...this.fetchOptions});return await U(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
16
16
|
=== LangSmith Server Configuration ===
|
|
17
17
|
`+JSON.stringify(r,null,2)+`
|
|
18
18
|
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=vn(),r=Al();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let a=Id(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let c=Pe(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let s=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(r?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(s.length>0&&i.length>0){let l=s.reduce((d,p)=>(p.id&&(d[p.id]=p),d),{}),u=[];for(let d of i)d.id!==void 0&&l[d.id]?l[d.id]={...l[d.id],...d}:u.push(d);s=Object.values(l),i=u}let a={post:s,patch:i};if(!a.post.length&&!a.patch.length)return;let c={post:[],patch:[]};for(let l of["post","patch"]){let u=l,d=a[u].reverse(),p=d.pop();for(;p!==void 0;)c[u].push(p),p=d.pop()}if(c.post.length>0||c.patch.length>0){let l=c.post.map(u=>u.id).concat(c.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Pe(c,`Ingesting runs with ids: ${l}`),n)}}async _postBatchIngestRuns(e,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let s=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await U(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let s={},i=[];for(let p of e??[]){let _=await this.prepareRunCreateOrUpdateInputs(p);_.id!==void 0&&_.attachments!==void 0&&(s[_.id]=_.attachments),delete _.attachments,i.push(_)}let a=[];for(let p of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(p));if(i.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){let p=i.reduce((g,y)=>(y.id&&(g[y.id]=y),g),{}),_=[];for(let g of a)g.id!==void 0&&p[g.id]?p[g.id]={...p[g.id],...g}:_.push(g);i=Object.values(p),a=_}if(i.length===0&&a.length===0)return;let u=[],d=[];for(let[p,_]of[["post",i],["patch",a]])for(let g of _){let{inputs:y,outputs:E,events:w,extra:S,error:I,serialized:m,attachments:T,...A}=g,N={inputs:y,outputs:E,events:w,extra:S,error:I,serialized:m},O=Pe(A,`Serializing for multipart ingestion of run with id: ${A.id}`);d.push({name:`${p}.${A.id}`,payload:new Blob([O],{type:`application/json; length=${O.length}`})});for(let[b,j]of Object.entries(N)){if(j===void 0)continue;let G=Pe(j,`Serializing ${b} for multipart ingestion of run with id: ${A.id}`);d.push({name:`${p}.${A.id}.${b}`,payload:new Blob([G],{type:`application/json; length=${G.length}`})})}if(A.id!==void 0){let b=s[A.id];if(b){delete s[A.id];for(let[j,G]of Object.entries(b)){let B,Z;if(Array.isArray(G)?[B,Z]=G:(B=G.mimeType,Z=G.data),j.includes(".")){console.warn(`Skipping attachment '${j}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${A.id}.${j}`,payload:new Blob([Z],{type:`${B}; length=${Z.byteLength}`})})}}}u.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(d,u.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let a of e)n.push(new Blob([`--${r}\r
|
|
@@ -29,11 +29,11 @@ Context: ${e}`:""}`),typeof s>"u"&&(s=Bb()),zi(t,"",0,[],void 0,0,s);let a;try{Q
|
|
|
29
29
|
`)}await a(`--${r}--\r
|
|
30
30
|
`),i.close()}})}async _sendMultipartRequest(e,r,n){let s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=o(()=>this._createNodeFetchBody(e,s),"buildBuffered"),a=o(()=>this._createMultipartStream(e,s),"buildStream"),c=o(async l=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await l(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let p=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(p=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let _=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:p,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(_,"Failed to send multipart request",!0),_}),"sendWithRetry");try{let l,u=!1;tl()&&!this.multipartStreamingDisabled&&oi()!=="bun"?(u=!0,l=await c(a)):l=await c(i),(!this.multipartStreamingDisabled||u)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==Ad&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=await c(i))}catch(l){if(Hi(l))throw l;if(console.warn(`${l.message.trim()}
|
|
31
31
|
|
|
32
|
-
Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,s).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${s}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){z(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let s={...r,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=Pe(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(c,"update run",!0),c})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){z(e);let n=Or(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let s;r.session_id?s=r.session_id:n?.projectName?s=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?s=n?.projectId:s=(await this.readProject({projectName:te("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${s}/r/${r.id}?poll=true`}else if(e!==void 0){let s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await Vb(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},s={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),s[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(s[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:s,traceId:i,referenceExampleId:a,startTime:c,executionOrder:l,isRoot:u,runType:d,error:p,id:_,query:g,filter:y,traceFilter:E,treeFilter:w,limit:S,select:I,order:m}=e,T=[];if(r&&(T=Array.isArray(r)?r:[r]),n){let b=Array.isArray(n)?n:[n],j=await Promise.all(b.map(G=>this.readProject({projectName:G}).then(B=>B.id)));T.push(...j)}let A=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],N={session:T.length?T:null,run_type:d,reference_example:a,query:g,filter:y,trace_filter:E,tree_filter:w,execution_order:l,parent_run:s,start_time:c?c.toISOString():null,error:p,id:_,limit:S,trace:i,select:I||A,is_root:u,order:m};N.select.includes("child_run_ids")&&Pt("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let O=0;for await(let b of this._getCursorPaginatedList("/runs/query",N)){let j=b.map(Or);if(S){if(O>=S)break;if(j.length+O>S){yield*j.slice(0,S-O);break}O+=j.length,yield*j}else yield*j}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:s,filter:i,startTime:a,endTime:c,limit:l,offset:u}=e,p={session_id:r||(await this.readProject({projectName:n})).id,group_by:s,filter:i,start_time:a?a.toISOString():null,end_time:c?c.toISOString():null,limit:Number(l)||100},_=Number(u)||0,g="/runs/group",y=`${this.apiUrl}${g}`;for(;;){let E={...p,offset:_},w=Object.fromEntries(Object.entries(E).filter(([N,O])=>O!==void 0)),S=JSON.stringify(w),m=await(await this.caller.call(async()=>{let N=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await U(N,`Failed to fetch ${g}`),N})).json(),{groups:T,total:A}=m;if(T.length===0)break;for(let N of T)yield N;if(_+=T.length,_>=A)break}}async*readThread(e){let{threadId:r,projectId:n,projectName:s,isRoot:i=!0,limit:a,filter:c,order:l="asc"}=e;if(!n&&!s)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,d=c?`and(${u}, ${c})`:u;yield*this.listRuns({projectId:n??void 0,projectName:s??void 0,isRoot:i,limit:a,filter:d,order:l})}async listThreads(e){let{projectId:r,projectName:n,limit:s,offset:i=0,filter:a,startTime:c,isRoot:l=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let u=r??(await this.readProject({projectName:n})).id,d=c??new Date(Date.now()-1440*60*1e3),_={session:[u],is_root:l,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:d.toISOString()};a!=null&&(_.filter=a);let g=new Map;for await(let S of this._getCursorPaginatedList("/runs/query",_))for(let I of S){let m=Or(I),T=m.thread_id;if(T){let A=g.get(T)??[];A.push(m),g.set(T,A)}}let y=[];for(let[S,I]of g.entries()){I.sort((O,b)=>{let j=O,G=b,B=j.start_time??"",Z=G.start_time??"";if(B!==Z)return B.localeCompare(Z);let ce=j.dotted_order??"",ke=G.dotted_order??"";return ce.localeCompare(ke)});let T=[...I.map(O=>O.start_time).filter(Boolean)].sort(),A=T.length?T[0]:"",N=T.length?T[T.length-1]:"";y.push({thread_id:S,runs:I,count:I.length,filter:"",total_tokens:0,total_cost:null,min_start_time:A,max_start_time:N,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}y.sort((S,I)=>{let m=S.max_start_time??"";return(I.max_start_time??"").localeCompare(m)});let E=i>0?y.slice(i):y;return s!==void 0?E.slice(0,s):E}async getRunStats({id:e,trace:r,parentRun:n,runType:s,projectNames:i,projectIds:a,referenceExampleIds:c,startTime:l,endTime:u,error:d,query:p,filter:_,traceFilter:g,treeFilter:y,isRoot:E,dataSourceType:w}){let S=a||[];i&&(S=[...a||[],...await Promise.all(i.map(O=>this.readProject({projectName:O}).then(b=>b.id)))]);let m=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:s,session:S,reference_example:c,start_time:l,end_time:u,error:d,query:p,filter:_,trace_filter:g,tree_filter:y,is_root:E,data_source_type:w}).filter(([O,b])=>b!==void 0)),T=JSON.stringify(m);return await(await this.caller.call(async()=>{let O=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await U(O,"get run stats"),O})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||kt()};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(c,"share run"),c})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare run",!0),r})}async readRunSharedLink(e){z(e);let n=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read run shared link"),s})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let a of r)n.append("id",a);return z(e),(await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"list shared runs"),a})).json()).map(Or)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),z(e);let s=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,"read dataset shared schema"),i})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(c,"share dataset"),c})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare dataset",!0),r})}async readSharedDataset(e){return z(e),await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read shared dataset"),s})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let s=new URLSearchParams;Object.entries(n).forEach(([c,l])=>{Array.isArray(l)?l.forEach(u=>s.append(c,u)):s.append(c,l)});let i=await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(c,"list shared examples"),c}),a=await i.json();if(!i.ok)throw"detail"in a?new Error(`Failed to list shared examples.
|
|
32
|
+
Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,s).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${s}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){z(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let s={...r,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=Pe(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(c,"update run",!0),c})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){z(e);let n=Or(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let s;r.session_id?s=r.session_id:n?.projectName?s=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?s=n?.projectId:s=(await this.readProject({projectName:te("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${s}/r/${r.id}?poll=true`}else if(e!==void 0){let s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await Kb(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},s={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),s[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(s[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:s,traceId:i,referenceExampleId:a,startTime:c,executionOrder:l,isRoot:u,runType:d,error:p,id:_,query:g,filter:y,traceFilter:E,treeFilter:w,limit:S,select:I,order:m}=e,T=[];if(r&&(T=Array.isArray(r)?r:[r]),n){let b=Array.isArray(n)?n:[n],j=await Promise.all(b.map(G=>this.readProject({projectName:G}).then(B=>B.id)));T.push(...j)}let A=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],N={session:T.length?T:null,run_type:d,reference_example:a,query:g,filter:y,trace_filter:E,tree_filter:w,execution_order:l,parent_run:s,start_time:c?c.toISOString():null,error:p,id:_,limit:S,trace:i,select:I||A,is_root:u,order:m};N.select.includes("child_run_ids")&&Pt("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let O=0;for await(let b of this._getCursorPaginatedList("/runs/query",N)){let j=b.map(Or);if(S){if(O>=S)break;if(j.length+O>S){yield*j.slice(0,S-O);break}O+=j.length,yield*j}else yield*j}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:s,filter:i,startTime:a,endTime:c,limit:l,offset:u}=e,p={session_id:r||(await this.readProject({projectName:n})).id,group_by:s,filter:i,start_time:a?a.toISOString():null,end_time:c?c.toISOString():null,limit:Number(l)||100},_=Number(u)||0,g="/runs/group",y=`${this.apiUrl}${g}`;for(;;){let E={...p,offset:_},w=Object.fromEntries(Object.entries(E).filter(([N,O])=>O!==void 0)),S=JSON.stringify(w),m=await(await this.caller.call(async()=>{let N=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await U(N,`Failed to fetch ${g}`),N})).json(),{groups:T,total:A}=m;if(T.length===0)break;for(let N of T)yield N;if(_+=T.length,_>=A)break}}async*readThread(e){let{threadId:r,projectId:n,projectName:s,isRoot:i=!0,limit:a,filter:c,order:l="asc"}=e;if(!n&&!s)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,d=c?`and(${u}, ${c})`:u;yield*this.listRuns({projectId:n??void 0,projectName:s??void 0,isRoot:i,limit:a,filter:d,order:l})}async listThreads(e){let{projectId:r,projectName:n,limit:s,offset:i=0,filter:a,startTime:c,isRoot:l=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let u=r??(await this.readProject({projectName:n})).id,d=c??new Date(Date.now()-1440*60*1e3),_={session:[u],is_root:l,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:d.toISOString()};a!=null&&(_.filter=a);let g=new Map;for await(let S of this._getCursorPaginatedList("/runs/query",_))for(let I of S){let m=Or(I),T=m.thread_id;if(T){let A=g.get(T)??[];A.push(m),g.set(T,A)}}let y=[];for(let[S,I]of g.entries()){I.sort((O,b)=>{let j=O,G=b,B=j.start_time??"",Z=G.start_time??"";if(B!==Z)return B.localeCompare(Z);let ce=j.dotted_order??"",ke=G.dotted_order??"";return ce.localeCompare(ke)});let T=[...I.map(O=>O.start_time).filter(Boolean)].sort(),A=T.length?T[0]:"",N=T.length?T[T.length-1]:"";y.push({thread_id:S,runs:I,count:I.length,filter:"",total_tokens:0,total_cost:null,min_start_time:A,max_start_time:N,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}y.sort((S,I)=>{let m=S.max_start_time??"";return(I.max_start_time??"").localeCompare(m)});let E=i>0?y.slice(i):y;return s!==void 0?E.slice(0,s):E}async getRunStats({id:e,trace:r,parentRun:n,runType:s,projectNames:i,projectIds:a,referenceExampleIds:c,startTime:l,endTime:u,error:d,query:p,filter:_,traceFilter:g,treeFilter:y,isRoot:E,dataSourceType:w}){let S=a||[];i&&(S=[...a||[],...await Promise.all(i.map(O=>this.readProject({projectName:O}).then(b=>b.id)))]);let m=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:s,session:S,reference_example:c,start_time:l,end_time:u,error:d,query:p,filter:_,trace_filter:g,tree_filter:y,is_root:E,data_source_type:w}).filter(([O,b])=>b!==void 0)),T=JSON.stringify(m);return await(await this.caller.call(async()=>{let O=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await U(O,"get run stats"),O})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||kt()};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(c,"share run"),c})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare run",!0),r})}async readRunSharedLink(e){z(e);let n=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read run shared link"),s})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let a of r)n.append("id",a);return z(e),(await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"list shared runs"),a})).json()).map(Or)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),z(e);let s=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,"read dataset shared schema"),i})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(c,"share dataset"),c})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare dataset",!0),r})}async readSharedDataset(e){return z(e),await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read shared dataset"),s})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let s=new URLSearchParams;Object.entries(n).forEach(([c,l])=>{Array.isArray(l)?l.forEach(u=>s.append(c,u)):s.append(c,l)});let i=await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(c,"list shared examples"),c}),a=await i.json();if(!i.ok)throw"detail"in a?new Error(`Failed to list shared examples.
|
|
33
33
|
Status: ${i.status}
|
|
34
34
|
Message: ${Array.isArray(a.detail)?a.detail.join(`
|
|
35
35
|
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(c=>({...c,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:s=!1,projectExtra:i=null,referenceDatasetId:a=null}){let c=s?"?upsert=true":"",l=`${this.apiUrl}/sessions${c}`,u=i||{};n&&(u.metadata=n);let d={name:e,extra:u,description:r};a!==null&&(d.reference_dataset_id=a);let p=JSON.stringify(d);return await(await this.caller.call(async()=>{let y=await this._fetch(l,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:p});return await U(y,"create project"),y})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:s=null,projectExtra:i=null,endTime:a=null}){let c=`${this.apiUrl}/sessions/${e}`,l=i;s&&(l={...l||{},metadata:s});let u=JSON.stringify({name:r,extra:l,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let _=await this._fetch(c,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(_,"update project"),_})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)z(e),n+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"has project"),a});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let s="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)z(e),s+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(s,i),c;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);c=a[0]}else c=a;return c}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:s,referenceDatasetName:i,includeStats:a,datasetVersion:c,referenceFree:l,metadata:u}={}){let d=new URLSearchParams;if(e!==void 0)for(let p of e)d.append("id",p);if(r!==void 0&&d.append("name",r),n!==void 0&&d.append("name_contains",n),s!==void 0)d.append("reference_dataset",s);else if(i!==void 0){let p=await this.readDataset({datasetName:i});d.append("reference_dataset",p.id)}a!==void 0&&d.append("include_stats",a.toString()),c!==void 0&&d.append("dataset_version",c),l!==void 0&&d.append("reference_free",l.toString()),u!==void 0&&d.append("metadata",JSON.stringify(u));for await(let p of this._getPaginated("/sessions",d))yield*p}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,z(n),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,`delete session ${n} (${r})`,!0),s})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:s,description:i,dataType:a,name:c}){let l=`${this.apiUrl}/datasets/upload`,u=new FormData,d=new Blob([e],{type:"text/csv"});return u.append("file",d,r),n.forEach(g=>{u.append("input_keys",g)}),s.forEach(g=>{u.append("output_keys",g)}),i&&u.append("description",i),a&&u.append("data_type",a),c&&u.append("name",c),await(await this.caller.call(async()=>{let g=await this._fetch(l,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(g,"upload CSV"),g})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:s,outputsSchema:i,metadata:a}={}){let c={name:e,description:r,extra:{source:"sdk",...a?{metadata:a}:{}}};n&&(c.data_type=n),s&&(c.inputs_schema_definition=s),i&&(c.outputs_schema_definition=i);let l=JSON.stringify(c);return await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(p,"create dataset"),p})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",s=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)z(e),n+=`/${e}`;else if(r)s.append("name",r);else throw new Error("Must provide datasetName or datasetId");let i=await this._get(n,s),a;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:s}){let i=e;if(i===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:r})).id);let a=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){let n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
|
|
36
|
-
`).map(c=>JSON.parse(c))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:s,datasetNameContains:i,metadata:a}={}){let c="/datasets",l=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)l.append("id",u);s!==void 0&&l.append("name",s),i!==void 0&&l.append("name_contains",i),a!==void 0&&l.append("metadata",JSON.stringify(a));for await(let u of this._getPaginated(c,l))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;z(i);let a=JSON.stringify(s);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:s,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;z(a);let c=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",s=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(s=(await this.readDataset({datasetName:r})).id),s!==void 0)z(s),n+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let s=e;if(!s&&!r)throw new Error("Must provide either datasetName or datasetId");if(s&&r)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:r})).id),z(s);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"index dataset"),l})).json()}async similarExamples(e,r,n,{filter:s}={}){let i={limit:n,inputs:e};s!==void 0&&(i.filter=s),z(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await U(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Rd(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(s===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,c;Rd(e)?c=e:c={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let l=await this._uploadExamplesMultipart(s,[c]);return await this.readExample(l.example_ids?.[0]??kt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let I=e,m=I[0].dataset_id,T=I[0].dataset_name;if(m===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(m!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");m===void 0&&(m=(await this.readDataset({datasetName:T})).id);let A=await this._uploadExamplesMultipart(m,I);return await Promise.all(A.example_ids.map(O=>this.readExample(O)))}let{inputs:r,outputs:n,metadata:s,splits:i,sourceRunIds:a,useSourceRunIOs:c,useSourceRunAttachments:l,attachments:u,exampleIds:d,datasetId:p,datasetName:_}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let g=p,y=_;if(g===void 0&&y===void 0)throw new Error("Must provide either datasetName or datasetId");if(g!==void 0&&y!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");g===void 0&&(g=(await this.readDataset({datasetName:y})).id);let E=r.map((I,m)=>({dataset_id:g,inputs:I,outputs:n?.[m],metadata:s?.[m],split:i?.[m],id:d?.[m],attachments:u?.[m],source_run_id:a?.[m],use_source_run_io:c?.[m],use_source_run_attachments:l?.[m]})),w=await this._uploadExamplesMultipart(g,E);return await Promise.all(w.example_ids.map(I=>this.readExample(I)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let s=e.map(a=>bi(a)?Ei(a):a),i=bi(r)?Ei(r):r;return this.createExample({input:s},{output:i},n)}async readExample(e){z(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:s,...i}=n,a=i;return s&&(a.attachments=Object.entries(s).reduce((c,[l,u])=>(c[l.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},c),{})),a}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:s,splits:i,inlineS3Urls:a,metadata:c,limit:l,offset:u,filter:d,includeAttachments:p}={}){let _;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)_=e;else if(r!==void 0)_=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let g=new URLSearchParams({dataset:_}),y=s?typeof s=="string"?s:s?.toISOString():void 0;y&&g.append("as_of",y);let E=a??!0;if(g.append("inline_s3_urls",E.toString()),n!==void 0)for(let S of n)g.append("id",S);if(i!==void 0)for(let S of i)g.append("splits",S);if(c!==void 0){let S=JSON.stringify(c);g.append("metadata",S)}l!==void 0&&g.append("limit",l.toString()),u!==void 0&&g.append("offset",u.toString()),d!==void 0&&g.append("filter",d),p===!0&&["attachment_urls","outputs","metadata"].forEach(S=>g.append("select",S));let w=0;for await(let S of this._getPaginated("/examples",g)){for(let I of S){let{attachment_urls:m,...T}=I,A=T;m&&(A.attachments=Object.entries(m).reduce((N,[O,b])=>(N[O.slice(11)]={presigned_url:b.presigned_url,mime_type:b.mime_type||void 0},N),{})),yield A,w++}if(l!==void 0&&w>=l)break}}async deleteExample(e){z(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>z(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"hard delete examples",!0),s})}else{let n=new URLSearchParams;e.forEach(s=>n.append("example_ids",s)),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"delete examples",!0),s})}}async updateExample(e,r){let n;r?n=e:n=e.id,z(n);let s;r?s={id:n,...r}:s=e;let i;return s.dataset_id!==void 0?i=s.dataset_id:i=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(i,[s])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:s}){let i;if(e?i=e:i=(await this.readDataset({datasetName:r})).id,z(i),n&&s||!n&&!s)throw new Error("Exactly one of asOf and tag must be specified.");let a=new URLSearchParams;return n!==void 0&&a.append("as_of",typeof n=="string"?n:n.toISOString()),s!==void 0&&a.append("tag",s),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let s;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:r})).id:s=e,z(s);let i=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&i.append("as_of",a),await this._get(`/datasets/${s}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:s,remove:i=!1}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,z(a);let c={split_name:n,examples:s.map(u=>(z(u),u)),remove:i},l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(u,"update dataset splits",!0),u})}async createFeedback(e,r,{score:n,value:s,correction:i,comment:a,sourceInfo:c,feedbackSourceType:l="api",sourceRunId:u,feedbackId:d,feedbackConfig:p,projectId:_,comparativeExperimentId:g,sessionId:y,startTime:E}){if(!e&&!_)throw new Error("One of runId or projectId must be provided");if(e&&_)throw new Error("Only one of runId or projectId can be provided");let w={type:l??"api",metadata:c??{}};u!==void 0&&w?.metadata!==void 0&&!w.metadata.__run&&(w.metadata.__run={run_id:u}),w?.metadata!==void 0&&w.metadata.__run?.run_id!==void 0&&z(w.metadata.__run.run_id);let S={id:d??_r(),run_id:e,key:r,score:xd(n),value:s,correction:i,comment:a,feedback_source:w,comparative_experiment_id:g,feedbackConfig:p,session_id:y??_,start_time:E},I=JSON.stringify(S),m=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let T=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await U(T,"create feedback",!0),T}),S}async updateFeedback(e,{score:r,value:n,correction:s,comment:i}){let a={};r!=null&&(a.score=xd(r)),n!=null&&(a.value=n),s!=null&&(a.correction=s),i!=null&&(a.comment=i),z(e);let c=JSON.stringify(a);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"update feedback",!0),l})}async readFeedback(e){z(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){z(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let s=new URLSearchParams;if(e)for(let i of e)z(i),s.append("run",i);if(r)for(let i of r)s.append("key",i);if(n)for(let i of n)s.append("source",i);for await(let i of this._getPaginated("/feedback",s))yield*i}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:s}={}){let i={run_id:e,feedback_key:r,feedback_config:s};n?typeof n=="string"?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:s,description:i,metadata:a,id:c}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let l={id:c,name:e,experiment_ids:r,reference_dataset_id:n,description:i,created_at:(s??new Date)?.toISOString(),extra:{}};a&&(l.extra.metadata=a);let u=JSON.stringify(l);return(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(e){z(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){let s=this._selectEvalResults(e),i=[];for(let a of s){let c=n||{};a.evaluatorInfo&&(c={...a.evaluatorInfo,...c});let l=null;a.targetRunId?l=a.targetRunId:r&&(l=r.id),i.push(await this.createFeedback(l,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:c,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id,startTime:r?.start_time}))}return[s,i]}async logEvaluationFeedback(e,r,n){let[s]=await this._logEvaluationFeedback(e,r,n);return s}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:s=!1}=e,i={feedback_key:r,feedback_config:n,is_lower_score_better:s};return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"create feedback config"),c})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:s}=e,i=new URLSearchParams;r&&r.forEach(c=>{i.append("key",c)}),n&&i.append("name_contains",n),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let a=0;for await(let c of this._getPaginated("/feedback-configs",i))if(yield*c,a+=c.length,s!==void 0&&a>=s)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:s}=r,i={feedback_key:e};return n!==void 0&&(i.feedback_config=n),s!==void 0&&(i.is_lower_score_better=s),(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"update feedback config"),c})).json()}async deleteFeedbackConfig(e){let r=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs?${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:s,limit:i}=e,a=new URLSearchParams;r&&r.forEach((l,u)=>{z(l,`queueIds[${u}]`),a.append("ids",l)}),n&&a.append("name",n),s&&a.append("name_contains",s),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let c=0;for await(let l of this._getPaginated("/annotation-queues",a))if(yield*l,c++,i!==void 0&&c>=i)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:s,rubricInstructions:i,rubricItems:a}=e,c={name:r,description:n,id:s||kt(),rubric_instructions:i,rubric_items:a},l=JSON.stringify(Object.fromEntries(Object.entries(c).filter(([d,p])=>p!==void 0)));return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:s,rubricInstructions:i,rubricItems:a}=r,c={};n!==void 0&&(c.name=n),s!==void 0&&(c.description=s),i!==void 0&&(c.rubric_instructions=i),a!==void 0&&(c.rubric_items=a);let l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=JSON.stringify(r.map((s,i)=>z(s,`runIds[${i}]`).toString()));await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${z(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"get run from annotation queue"),a})).json();return Or(i)}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/runs/${z(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
36
|
+
`).map(c=>JSON.parse(c))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:s,datasetNameContains:i,metadata:a}={}){let c="/datasets",l=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)l.append("id",u);s!==void 0&&l.append("name",s),i!==void 0&&l.append("name_contains",i),a!==void 0&&l.append("metadata",JSON.stringify(a));for await(let u of this._getPaginated(c,l))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;z(i);let a=JSON.stringify(s);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:s,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;z(a);let c=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",s=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(s=(await this.readDataset({datasetName:r})).id),s!==void 0)z(s),n+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let s=e;if(!s&&!r)throw new Error("Must provide either datasetName or datasetId");if(s&&r)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:r})).id),z(s);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"index dataset"),l})).json()}async similarExamples(e,r,n,{filter:s}={}){let i={limit:n,inputs:e};s!==void 0&&(i.filter=s),z(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await U(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Cd(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(s===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,c;Cd(e)?c=e:c={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let l=await this._uploadExamplesMultipart(s,[c]);return await this.readExample(l.example_ids?.[0]??kt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let I=e,m=I[0].dataset_id,T=I[0].dataset_name;if(m===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(m!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");m===void 0&&(m=(await this.readDataset({datasetName:T})).id);let A=await this._uploadExamplesMultipart(m,I);return await Promise.all(A.example_ids.map(O=>this.readExample(O)))}let{inputs:r,outputs:n,metadata:s,splits:i,sourceRunIds:a,useSourceRunIOs:c,useSourceRunAttachments:l,attachments:u,exampleIds:d,datasetId:p,datasetName:_}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let g=p,y=_;if(g===void 0&&y===void 0)throw new Error("Must provide either datasetName or datasetId");if(g!==void 0&&y!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");g===void 0&&(g=(await this.readDataset({datasetName:y})).id);let E=r.map((I,m)=>({dataset_id:g,inputs:I,outputs:n?.[m],metadata:s?.[m],split:i?.[m],id:d?.[m],attachments:u?.[m],source_run_id:a?.[m],use_source_run_io:c?.[m],use_source_run_attachments:l?.[m]})),w=await this._uploadExamplesMultipart(g,E);return await Promise.all(w.example_ids.map(I=>this.readExample(I)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let s=e.map(a=>bi(a)?Ei(a):a),i=bi(r)?Ei(r):r;return this.createExample({input:s},{output:i},n)}async readExample(e){z(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:s,...i}=n,a=i;return s&&(a.attachments=Object.entries(s).reduce((c,[l,u])=>(c[l.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},c),{})),a}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:s,splits:i,inlineS3Urls:a,metadata:c,limit:l,offset:u,filter:d,includeAttachments:p}={}){let _;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)_=e;else if(r!==void 0)_=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let g=new URLSearchParams({dataset:_}),y=s?typeof s=="string"?s:s?.toISOString():void 0;y&&g.append("as_of",y);let E=a??!0;if(g.append("inline_s3_urls",E.toString()),n!==void 0)for(let S of n)g.append("id",S);if(i!==void 0)for(let S of i)g.append("splits",S);if(c!==void 0){let S=JSON.stringify(c);g.append("metadata",S)}l!==void 0&&g.append("limit",l.toString()),u!==void 0&&g.append("offset",u.toString()),d!==void 0&&g.append("filter",d),p===!0&&["attachment_urls","outputs","metadata"].forEach(S=>g.append("select",S));let w=0;for await(let S of this._getPaginated("/examples",g)){for(let I of S){let{attachment_urls:m,...T}=I,A=T;m&&(A.attachments=Object.entries(m).reduce((N,[O,b])=>(N[O.slice(11)]={presigned_url:b.presigned_url,mime_type:b.mime_type||void 0},N),{})),yield A,w++}if(l!==void 0&&w>=l)break}}async deleteExample(e){z(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>z(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"hard delete examples",!0),s})}else{let n=new URLSearchParams;e.forEach(s=>n.append("example_ids",s)),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"delete examples",!0),s})}}async updateExample(e,r){let n;r?n=e:n=e.id,z(n);let s;r?s={id:n,...r}:s=e;let i;return s.dataset_id!==void 0?i=s.dataset_id:i=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(i,[s])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:s}){let i;if(e?i=e:i=(await this.readDataset({datasetName:r})).id,z(i),n&&s||!n&&!s)throw new Error("Exactly one of asOf and tag must be specified.");let a=new URLSearchParams;return n!==void 0&&a.append("as_of",typeof n=="string"?n:n.toISOString()),s!==void 0&&a.append("tag",s),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let s;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:r})).id:s=e,z(s);let i=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&i.append("as_of",a),await this._get(`/datasets/${s}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:s,remove:i=!1}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,z(a);let c={split_name:n,examples:s.map(u=>(z(u),u)),remove:i},l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(u,"update dataset splits",!0),u})}async createFeedback(e,r,{score:n,value:s,correction:i,comment:a,sourceInfo:c,feedbackSourceType:l="api",sourceRunId:u,feedbackId:d,feedbackConfig:p,projectId:_,comparativeExperimentId:g,sessionId:y,startTime:E}){if(!e&&!_)throw new Error("One of runId or projectId must be provided");if(e&&_)throw new Error("Only one of runId or projectId can be provided");let w={type:l??"api",metadata:c??{}};u!==void 0&&w?.metadata!==void 0&&!w.metadata.__run&&(w.metadata.__run={run_id:u}),w?.metadata!==void 0&&w.metadata.__run?.run_id!==void 0&&z(w.metadata.__run.run_id);let S={id:d??_r(),run_id:e,key:r,score:xd(n),value:s,correction:i,comment:a,feedback_source:w,comparative_experiment_id:g,feedbackConfig:p,session_id:y??_,start_time:E},I=JSON.stringify(S),m=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let T=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await U(T,"create feedback",!0),T}),S}async updateFeedback(e,{score:r,value:n,correction:s,comment:i}){let a={};r!=null&&(a.score=xd(r)),n!=null&&(a.value=n),s!=null&&(a.correction=s),i!=null&&(a.comment=i),z(e);let c=JSON.stringify(a);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"update feedback",!0),l})}async readFeedback(e){z(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){z(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let s=new URLSearchParams;if(e)for(let i of e)z(i),s.append("run",i);if(r)for(let i of r)s.append("key",i);if(n)for(let i of n)s.append("source",i);for await(let i of this._getPaginated("/feedback",s))yield*i}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:s}={}){let i={run_id:e,feedback_key:r,feedback_config:s};n?typeof n=="string"?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:s,description:i,metadata:a,id:c}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let l={id:c,name:e,experiment_ids:r,reference_dataset_id:n,description:i,created_at:(s??new Date)?.toISOString(),extra:{}};a&&(l.extra.metadata=a);let u=JSON.stringify(l);return(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(e){z(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){let s=this._selectEvalResults(e),i=[];for(let a of s){let c=n||{};a.evaluatorInfo&&(c={...a.evaluatorInfo,...c});let l=null;a.targetRunId?l=a.targetRunId:r&&(l=r.id),i.push(await this.createFeedback(l,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:c,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id,startTime:r?.start_time}))}return[s,i]}async logEvaluationFeedback(e,r,n){let[s]=await this._logEvaluationFeedback(e,r,n);return s}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:s=!1}=e,i={feedback_key:r,feedback_config:n,is_lower_score_better:s};return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"create feedback config"),c})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:s}=e,i=new URLSearchParams;r&&r.forEach(c=>{i.append("key",c)}),n&&i.append("name_contains",n),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let a=0;for await(let c of this._getPaginated("/feedback-configs",i))if(yield*c,a+=c.length,s!==void 0&&a>=s)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:s}=r,i={feedback_key:e};return n!==void 0&&(i.feedback_config=n),s!==void 0&&(i.is_lower_score_better=s),(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"update feedback config"),c})).json()}async deleteFeedbackConfig(e){let r=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs?${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:s,limit:i}=e,a=new URLSearchParams;r&&r.forEach((l,u)=>{z(l,`queueIds[${u}]`),a.append("ids",l)}),n&&a.append("name",n),s&&a.append("name_contains",s),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let c=0;for await(let l of this._getPaginated("/annotation-queues",a))if(yield*l,c++,i!==void 0&&c>=i)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:s,rubricInstructions:i,rubricItems:a}=e,c={name:r,description:n,id:s||kt(),rubric_instructions:i,rubric_items:a},l=JSON.stringify(Object.fromEntries(Object.entries(c).filter(([d,p])=>p!==void 0)));return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:s,rubricInstructions:i,rubricItems:a}=r,c={};n!==void 0&&(c.name=n),s!==void 0&&(c.description=s),i!==void 0&&(c.rubric_instructions=i),a!==void 0&&(c.rubric_items=a);let l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=JSON.stringify(r.map((s,i)=>z(s,`runIds[${i}]`).toString()));await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${z(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"get run from annotation queue"),a})).json();return Or(i)}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/runs/${z(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
37
37
|
|
|
38
38
|
Current tenant: ${n.tenant_handle}
|
|
39
39
|
|
|
@@ -42,31 +42,31 @@ Message: ${Array.isArray(a.detail)?a.detail.join(`
|
|
|
42
42
|
creating a LangChain Hub handle.
|
|
43
43
|
You can add a handle by creating a public prompt at:
|
|
44
44
|
|
|
45
|
-
https://smith.langchain.com/prompts`);let[s,i,a]=ct(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);let c={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},l=JSON.stringify(c),u=await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(p,"create prompt"),p}),{repo:d}=await u.json();return d}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[s,i,a]=ct(e),c=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${s}/${i}`):n?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(r)),parent_commit:c},u=JSON.stringify(l),p=await(await this.caller.call(async()=>{let _=await this._fetch(`${this.apiUrl}/commits/${s}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(_,"create commit"),_})).json();return this._getPromptUrl(`${s}/${i}${p.commit_hash?`:${p.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let a of r){let c=a.id,l={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},u=Pe(l,`Serializing body for example with id: ${c}`),d=new Blob([u],{type:"application/json"});if(n.append(c,d),a.inputs){let p=Pe(a.inputs,`Serializing inputs for example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.inputs`,_)}if(a.outputs){let p=Pe(a.outputs,`Serializing outputs whle updating example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.outputs`,_)}if(a.attachments)for(let[p,_]of Object.entries(a.attachments)){let g,y;Array.isArray(_)?[g,y]=_:(g=_.mimeType,y=_.data);let E=new Blob([y],{type:`${g}; length=${y.byteLength}`});n.append(`${c}.attachment.${p}`,E)}if(a.attachments_operations){let p=Pe(a.attachments_operations,`Serializing attachments while updating example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.attachments_operations`,_)}}let s=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let i of r){let a=(i.id??kt()).toString(),c={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=Pe(c,`Serializing body for uploaded example with id: ${a}`),u=new Blob([l],{type:"application/json"});if(n.append(a,u),i.inputs){let d=Pe(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),p=new Blob([d],{type:"application/json"});n.append(`${a}.inputs`,p)}if(i.outputs){let d=Pe(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),p=new Blob([d],{type:"application/json"});n.append(`${a}.outputs`,p)}if(i.attachments)for(let[d,p]of Object.entries(i.attachments)){let _,g;Array.isArray(p)?[_,g]=p:(_=p.mimeType,g=p.data);let y=new Blob([g],{type:`${_}; length=${g.byteLength}`});n.append(`${a}.attachment.${d}`,y)}}return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(i,"upload examples"),i})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,s]=ct(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=JSON.stringify(i);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${n}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,s]=ct(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"delete prompt"),a})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,s,i]=ct(e),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${n}/${s}/${i}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"pull prompt commit"),l})).json();return{owner:n,repo:s,commit_hash:c.commit_hash,manifest:c.manifest,examples:c.examples}}async pullPromptCommit(e,r){let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let s=this._getPromptCacheKey(e,r?.includeModel),i=this._promptCache.get(s,n);if(i)return i;let a=await n();return this._promptCache.set(s,a,n),a}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(s=>s!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:s}=r,[i,a]=this.parseTokenOrUrl(e,n),c=new t({apiUrl:i,apiKey:"placeholder"}),l=await c.readSharedDataset(a),u=s||l.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let d=await c.listSharedExamples(a),p=await this.createDataset(u,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(_=>_.inputs),outputs:d.flatMap(_=>_.outputs?[_.outputs]:[]),datasetId:p.id})}catch(_){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),_}}parseTokenOrUrl(e,r,n=2,s="dataset"){try{return z(e),[r,e]}catch{}try{let a=new URL(e).pathname.split("/").filter(c=>c!=="");if(a.length>=n){let c=a[a.length-n];return[r,c]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Rl()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};Object.defineProperty(vt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Rd(t){return"dataset_id"in t||"dataset_name"in t}o(Rd,"isExampleCreate");var Od=o(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>te(r)==="true"),"isTracingEnabled");var lt=Symbol.for("lc:context_variables");var zn=Symbol.for("langsmith:replica_trace_roots");function qi(t,e){if(lt in t)return t[lt][e]}o(qi,"getContextVar");function Nd(t,e,r){let n=lt in t?t[lt]:{};n[e]=r,t[lt]=n}o(Nd,"setContextVar");var Nr=36,Jb="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Md(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Zs(r,Jb)}o(Md,"getReplicaKey");function Yb(t){return t.replace(/[-:.]/g,"")}o(Yb,"stripNonAlphanumeric");function Pd(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}o(Pd,"getMicrosecondPrecisionDatestring");function Wi(t,e,r=1){let n=Pd(t,r);return{dottedOrder:Yb(n)+e,microsecondPrecisionDatestring:n}}o(Wi,"convertToDottedOrderFormat");var Xb=new Set(["projectName","updates","reroot"]);function Qb(t){let e={};for(let r of Object.keys(t))Xb.has(r)&&(e[r]=t[r]);return e}o(Qb,"filterReplicaForHeaders");var Vn=class t{static{o(this,"Baggage")}constructor(e,r,n,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=s}static fromHeader(e){let r=e.split(","),n={},s=[],i,a;for(let c of r){let[l,u]=c.split("="),d=decodeURIComponent(u);l==="langsmith-metadata"?n=JSON.parse(d):l==="langsmith-tags"?s=d.split(","):l==="langsmith-project"?i=d:l==="langsmith-replicas"&&(a=JSON.parse(d).map(_=>Array.isArray(_)?_:Qb(_)))}return new t(n,s,i,a)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},Qe=class t{static{o(this,"RunTree")}constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ld(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...s}=e,i=s.client??t.getSharedClient(),a={...n,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:a},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...r,...s,client:i}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Pd(this.start_time,this.execution_order)),this.id||(this.id=gn(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=nE(this.replicas),!this.dotted_order){let{dottedOrder:c}=Wi(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:br(),child_runs:[],api_url:Be("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Be("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new vt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(_=>{let{reroot:g,...y}=_;return y}),s=e.replicas??n,i=new t({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),a=this.extra?.metadata??{},c=i.extra?.metadata??{};Object.keys(a).length>0&&(i.extra={...i.extra,metadata:{...a,...c}}),lt in this&&(i[lt]=this[lt]);let l=Symbol.for("lc:child_config"),u=e.extra?.[l]??this.extra[l];if(tE(u)){let _={...u},g=eE(_.callbacks)?_.callbacks.copy?.():void 0;g&&(Object.assign(g,{_parentRunId:i.id}),g.handlers?.find(Dd)?.updateFromRunTree?.(i),_.callbacks=g),i.extra[l]=_}let d=new Set,p=this;for(;p!=null&&!d.has(p.id);)d.add(p.id),p.child_execution_order=Math.max(p.child_execution_order,r),p=p.parent_run;return this.child_runs.push(i),i}async end(e,r,n=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,r,n=!0){let s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),r))for(let[c,l]of Object.entries(r))s.runtime[c]||(s.runtime[c]=l);let i=e.parent_run?.id??e.parent_run_id,a;return n?a=[]:a=e.child_runs.map(c=>this._convertToCreate(c,r,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),s=null;for(let i=0;i<n.length;i++)if(n[i].slice(-Nr)===e){s=i;break}if(s!==null){let i=n.slice(s+1);r.dotted_order=i.join("."),i.length>0?r.trace_id=i[0].slice(-Nr):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=qi(this,zn)??{};n[e]=r,Nd(this,zn,n);for(let s of this.child_runs)s._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,runtimeEnv:n,excludeChildRuns:s=!0,reroot:i=!1,distributedParentId:a,apiUrl:c,apiKey:l,workspaceId:u}=e,d=this._convertToCreate(this,n,s);if(r===this.project_name)return{...d,session_name:r};if(i){if(a)this._sliceParentId(a,d);else if(d.parent_run_id=void 0,d.dotted_order){let I=d.dotted_order.split(".");I.length>0&&(d.dotted_order=I[I.length-1],d.trace_id=d.id)}let S=Md({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});this._setReplicaTraceRoot(S,d.id)}let p;if(!i){let S=qi(this,zn)??{},I=Md({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});if(p=S[I],p&&(d.trace_id=p,d.dotted_order)){let m=d.dotted_order.split("."),T=null;for(let A=0;A<m.length;A++)if(m[A].slice(-Nr)===p){T=A;break}if(T!==null){let A=m.slice(T);d.dotted_order=A.join(".")}}}let _=d.id,g=Er(_,r),y;d.trace_id?y=Er(d.trace_id,r):y=g;let E;d.parent_run_id&&(E=Er(d.parent_run_id,r));let w;return d.dotted_order&&(w=d.dotted_order.split(".").map(m=>{let T=m.slice(-Nr),A=Er(T,r);return m.slice(0,-Nr)+A}).join(".")),{...d,id:g,trace_id:y,parent_run_id:E,dotted_order:w,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=wn();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:s,apiUrl:i,workspaceId:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:s,workspaceId:a});await this.client.createRun(l,{apiKey:s,apiUrl:i,workspaceId:a})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Pt("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:s,workspaceId:i,updates:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:n,workspaceId:i}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...a};e?.excludeInputs||(u.inputs=l.inputs),await this.client.updateRun(l.id,u,{apiKey:n,apiUrl:s,workspaceId:i})}else try{let r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){let n=e?.callbacks,s,i,a,c=Od();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(p=>p?.name=="langchain_tracer");s=d?.getRun?.(u),i=d?.projectName,a=d?.client,c=c||!!d}return s?new t({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:a,tracingEnabled:c,project_name:i,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:a,tracingEnabled:c,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=n["langsmith-trace"];if(!s||typeof s!="string")return;let i=s.trim(),a=i.split(".").map(d=>{let[p,_]=d.split("Z");return{strTime:p,time:Date.parse(p+"Z"),uuid:_}}),c=a[0].uuid,l={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:c,dotted_order:i};if(n.baggage&&typeof n.baggage=="string"){let d=Vn.fromHeader(n.baggage);l.metadata=d.metadata,l.tags=d.tags,l.project_name=d.project_name,l.replicas=d.replicas}let u=new t(l);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Vn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,s]of Object.entries(r))e.set(n,s);return r}};Object.defineProperty(Qe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Ld(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}o(Ld,"isRunTree");function Dd(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}o(Dd,"isLangChainTracerLike");function kd(t){return Array.isArray(t)&&t.some(e=>Dd(e))}o(kd,"containsLangChainTracerLike");function eE(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}o(eE,"isCallbackManagerLike");function tE(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(kd(e?.handlers)||kd(e))}o(tE,"isRunnableConfigLike");function rE(){let t=Be("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){sE(e);let r=[];for(let[n,s]of Object.entries(e)){let i=n.replace(/\/$/,"");if(typeof s=="string")r.push({apiUrl:i,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof s}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(wd(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}o(rE,"_getWriteReplicasFromEnv");function nE(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):rE()}o(nE,"_ensureWriteReplicas");function sE(t){if(Object.keys(t).length>0&&te("ENDPOINT"))throw new Fn}o(sE,"_checkEndpointEnvUnset");var iE=o(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function Zi(t,e){if(t)return new Qe({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Zi(e),child_runs:t.child_runs.map(r=>Zi(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:hc()},tracingEnabled:!1})}o(Zi,"convertRunToRunTree");function Ki(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}o(Ki,"_coerceToDict");function er(t){return typeof t._addRunToRunMap=="function"}o(er,"isBaseTracer");var $t=class extends Wt{static{o(this,"BaseTracer")}runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?iE(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
|
|
45
|
+
https://smith.langchain.com/prompts`);let[s,i,a]=ct(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);let c={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},l=JSON.stringify(c),u=await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(p,"create prompt"),p}),{repo:d}=await u.json();return d}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[s,i,a]=ct(e),c=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${s}/${i}`):n?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(r)),parent_commit:c},u=JSON.stringify(l),p=await(await this.caller.call(async()=>{let _=await this._fetch(`${this.apiUrl}/commits/${s}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(_,"create commit"),_})).json();return this._getPromptUrl(`${s}/${i}${p.commit_hash?`:${p.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let a of r){let c=a.id,l={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},u=Pe(l,`Serializing body for example with id: ${c}`),d=new Blob([u],{type:"application/json"});if(n.append(c,d),a.inputs){let p=Pe(a.inputs,`Serializing inputs for example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.inputs`,_)}if(a.outputs){let p=Pe(a.outputs,`Serializing outputs whle updating example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.outputs`,_)}if(a.attachments)for(let[p,_]of Object.entries(a.attachments)){let g,y;Array.isArray(_)?[g,y]=_:(g=_.mimeType,y=_.data);let E=new Blob([y],{type:`${g}; length=${y.byteLength}`});n.append(`${c}.attachment.${p}`,E)}if(a.attachments_operations){let p=Pe(a.attachments_operations,`Serializing attachments while updating example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.attachments_operations`,_)}}let s=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let i of r){let a=(i.id??kt()).toString(),c={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=Pe(c,`Serializing body for uploaded example with id: ${a}`),u=new Blob([l],{type:"application/json"});if(n.append(a,u),i.inputs){let d=Pe(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),p=new Blob([d],{type:"application/json"});n.append(`${a}.inputs`,p)}if(i.outputs){let d=Pe(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),p=new Blob([d],{type:"application/json"});n.append(`${a}.outputs`,p)}if(i.attachments)for(let[d,p]of Object.entries(i.attachments)){let _,g;Array.isArray(p)?[_,g]=p:(_=p.mimeType,g=p.data);let y=new Blob([g],{type:`${_}; length=${g.byteLength}`});n.append(`${a}.attachment.${d}`,y)}}return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(i,"upload examples"),i})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,s]=ct(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=JSON.stringify(i);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${n}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,s]=ct(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"delete prompt"),a})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,s,i]=ct(e),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${n}/${s}/${i}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"pull prompt commit"),l})).json();return{owner:n,repo:s,commit_hash:c.commit_hash,manifest:c.manifest,examples:c.examples}}async pullPromptCommit(e,r){let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let s=this._getPromptCacheKey(e,r?.includeModel),i=this._promptCache.get(s,n);if(i)return i;let a=await n();return this._promptCache.set(s,a,n),a}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(s=>s!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:s}=r,[i,a]=this.parseTokenOrUrl(e,n),c=new t({apiUrl:i,apiKey:"placeholder"}),l=await c.readSharedDataset(a),u=s||l.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let d=await c.listSharedExamples(a),p=await this.createDataset(u,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(_=>_.inputs),outputs:d.flatMap(_=>_.outputs?[_.outputs]:[]),datasetId:p.id})}catch(_){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),_}}parseTokenOrUrl(e,r,n=2,s="dataset"){try{return z(e),[r,e]}catch{}try{let a=new URL(e).pathname.split("/").filter(c=>c!=="");if(a.length>=n){let c=a[a.length-n];return[r,c]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Cl()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};Object.defineProperty(vt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Cd(t){return"dataset_id"in t||"dataset_name"in t}o(Cd,"isExampleCreate");var Od=o(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>te(r)==="true"),"isTracingEnabled");var lt=Symbol.for("lc:context_variables");var zn=Symbol.for("langsmith:replica_trace_roots");function Wi(t,e){if(lt in t)return t[lt][e]}o(Wi,"getContextVar");function Nd(t,e,r){let n=lt in t?t[lt]:{};n[e]=r,t[lt]=n}o(Nd,"setContextVar");var Nr=36,Qb="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Md(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Zs(r,Qb)}o(Md,"getReplicaKey");function eE(t){return t.replace(/[-:.]/g,"")}o(eE,"stripNonAlphanumeric");function Pd(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}o(Pd,"getMicrosecondPrecisionDatestring");function qi(t,e,r=1){let n=Pd(t,r);return{dottedOrder:eE(n)+e,microsecondPrecisionDatestring:n}}o(qi,"convertToDottedOrderFormat");var tE=new Set(["projectName","updates","reroot"]);function rE(t){let e={};for(let r of Object.keys(t))tE.has(r)&&(e[r]=t[r]);return e}o(rE,"filterReplicaForHeaders");var Vn=class t{static{o(this,"Baggage")}constructor(e,r,n,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=s}static fromHeader(e){let r=e.split(","),n={},s=[],i,a;for(let c of r){let[l,u]=c.split("="),d=decodeURIComponent(u);l==="langsmith-metadata"?n=JSON.parse(d):l==="langsmith-tags"?s=d.split(","):l==="langsmith-project"?i=d:l==="langsmith-replicas"&&(a=JSON.parse(d).map(_=>Array.isArray(_)?_:rE(_)))}return new t(n,s,i,a)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},Qe=class t{static{o(this,"RunTree")}constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ld(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...s}=e,i=s.client??t.getSharedClient(),a={...n,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:a},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...r,...s,client:i}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Pd(this.start_time,this.execution_order)),this.id||(this.id=gn(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=aE(this.replicas),!this.dotted_order){let{dottedOrder:c}=qi(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:br(),child_runs:[],api_url:Be("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Be("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new vt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(_=>{let{reroot:g,...y}=_;return y}),s=e.replicas??n,i=new t({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),a=this.extra?.metadata??{},c=i.extra?.metadata??{};Object.keys(a).length>0&&(i.extra={...i.extra,metadata:{...a,...c}}),lt in this&&(i[lt]=this[lt]);let l=Symbol.for("lc:child_config"),u=e.extra?.[l]??this.extra[l];if(sE(u)){let _={...u},g=nE(_.callbacks)?_.callbacks.copy?.():void 0;g&&(Object.assign(g,{_parentRunId:i.id}),g.handlers?.find(Dd)?.updateFromRunTree?.(i),_.callbacks=g),i.extra[l]=_}let d=new Set,p=this;for(;p!=null&&!d.has(p.id);)d.add(p.id),p.child_execution_order=Math.max(p.child_execution_order,r),p=p.parent_run;return this.child_runs.push(i),i}async end(e,r,n=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,r,n=!0){let s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),r))for(let[c,l]of Object.entries(r))s.runtime[c]||(s.runtime[c]=l);let i=e.parent_run?.id??e.parent_run_id,a;return n?a=[]:a=e.child_runs.map(c=>this._convertToCreate(c,r,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),s=null;for(let i=0;i<n.length;i++)if(n[i].slice(-Nr)===e){s=i;break}if(s!==null){let i=n.slice(s+1);r.dotted_order=i.join("."),i.length>0?r.trace_id=i[0].slice(-Nr):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Wi(this,zn)??{};n[e]=r,Nd(this,zn,n);for(let s of this.child_runs)s._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,runtimeEnv:n,excludeChildRuns:s=!0,reroot:i=!1,distributedParentId:a,apiUrl:c,apiKey:l,workspaceId:u}=e,d=this._convertToCreate(this,n,s);if(r===this.project_name)return{...d,session_name:r};if(i){if(a)this._sliceParentId(a,d);else if(d.parent_run_id=void 0,d.dotted_order){let I=d.dotted_order.split(".");I.length>0&&(d.dotted_order=I[I.length-1],d.trace_id=d.id)}let S=Md({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});this._setReplicaTraceRoot(S,d.id)}let p;if(!i){let S=Wi(this,zn)??{},I=Md({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});if(p=S[I],p&&(d.trace_id=p,d.dotted_order)){let m=d.dotted_order.split("."),T=null;for(let A=0;A<m.length;A++)if(m[A].slice(-Nr)===p){T=A;break}if(T!==null){let A=m.slice(T);d.dotted_order=A.join(".")}}}let _=d.id,g=Er(_,r),y;d.trace_id?y=Er(d.trace_id,r):y=g;let E;d.parent_run_id&&(E=Er(d.parent_run_id,r));let w;return d.dotted_order&&(w=d.dotted_order.split(".").map(m=>{let T=m.slice(-Nr),A=Er(T,r);return m.slice(0,-Nr)+A}).join(".")),{...d,id:g,trace_id:y,parent_run_id:E,dotted_order:w,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=wn();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:s,apiUrl:i,workspaceId:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:s,workspaceId:a});await this.client.createRun(l,{apiKey:s,apiUrl:i,workspaceId:a})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Pt("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:s,workspaceId:i,updates:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:n,workspaceId:i}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...a};e?.excludeInputs||(u.inputs=l.inputs),await this.client.updateRun(l.id,u,{apiKey:n,apiUrl:s,workspaceId:i})}else try{let r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){let n=e?.callbacks,s,i,a,c=Od();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(p=>p?.name=="langchain_tracer");s=d?.getRun?.(u),i=d?.projectName,a=d?.client,c=c||!!d}return s?new t({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:a,tracingEnabled:c,project_name:i,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:a,tracingEnabled:c,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=n["langsmith-trace"];if(!s||typeof s!="string")return;let i=s.trim(),a=i.split(".").map(d=>{let[p,_]=d.split("Z");return{strTime:p,time:Date.parse(p+"Z"),uuid:_}}),c=a[0].uuid,l={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:c,dotted_order:i};if(n.baggage&&typeof n.baggage=="string"){let d=Vn.fromHeader(n.baggage);l.metadata=d.metadata,l.tags=d.tags,l.project_name=d.project_name,l.replicas=d.replicas}let u=new t(l);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Vn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,s]of Object.entries(r))e.set(n,s);return r}};Object.defineProperty(Qe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Ld(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}o(Ld,"isRunTree");function Dd(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}o(Dd,"isLangChainTracerLike");function kd(t){return Array.isArray(t)&&t.some(e=>Dd(e))}o(kd,"containsLangChainTracerLike");function nE(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}o(nE,"isCallbackManagerLike");function sE(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(kd(e?.handlers)||kd(e))}o(sE,"isRunnableConfigLike");function iE(){let t=Be("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){oE(e);let r=[];for(let[n,s]of Object.entries(e)){let i=n.replace(/\/$/,"");if(typeof s=="string")r.push({apiUrl:i,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof s}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(wd(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}o(iE,"_getWriteReplicasFromEnv");function aE(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):iE()}o(aE,"_ensureWriteReplicas");function oE(t){if(Object.keys(t).length>0&&te("ENDPOINT"))throw new Fn}o(oE,"_checkEndpointEnvUnset");var cE=o(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function Zi(t,e){if(t)return new Qe({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Zi(e),child_runs:t.child_runs.map(r=>Zi(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:hc()},tracingEnabled:!1})}o(Zi,"convertRunToRunTree");function Ki(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}o(Ki,"_coerceToDict");function er(t){return typeof t._addRunToRunMap=="function"}o(er,"isBaseTracer");var $t=class extends qt{static{o(this,"BaseTracer")}runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?cE(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
|
|
46
46
|
|
|
47
|
-
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=Wi(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},s=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?s?(this._addChildRun(s,n),s.child_execution_order=Math.max(s.child_execution_order,n.child_execution_order),n.trace_id=s.trace_id,s.dotted_order!==void 0&&(n.dotted_order=[s.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let i=Zi(n,s);i!==void 0&&this.runTreeMap.set(n.id,i)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(p)}async handleLLMStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(p)}async handleChatModelStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=t,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(t,e,r,n,s,i,a,c,l){let u=this._getExecutionOrder(n),d=Date.now(),p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:i?{...l,metadata:i}:{...l},tags:s||[]};return this._addRunToRunMap(p)}async handleChainStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Ki(t,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=Ki(s.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=Ki(s.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:e},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onToolStart?.(c),c}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:e},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onRetrieverStart?.(c),c}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,s,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:i?.chunk}}),await this.onLLMNewToken?.(a,t,{chunk:i?.chunk}),a}};var Ud={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function Oe(t,e){return`${t.open}${e}${t.close}`}o(Oe,"wrap");function Ve(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}o(Ve,"tryJsonStringify");function $d(t){return typeof t=="string"?t.trim():t==null?t:Ve(t,t.toString())}o($d,"formatKVMapItem");function St(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}o(St,"elapsed");var{color:Le}=Ud,Ji=class extends $t{static{o(this,"ConsoleCallbackHandler")}name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,s)=>{let i=`${r.execution_order}:${r.run_type}:${r.name}`;return n===s.length-1?Oe(Ud.bold,i):i}).join(" > ");return Oe(Le.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ve(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[chain/end]")} [${e}] [${St(t)}] Exiting Chain run with output: ${Ve(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[chain/error]")} [${e}] [${St(t)}] Chain run errored with error: ${Ve(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Oe(Le.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ve(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[llm/end]")} [${e}] [${St(t)}] Exiting LLM run with output: ${Ve(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[llm/error]")} [${e}] [${St(t)}] LLM run errored with error: ${Ve(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[tool/start]")} [${e}] Entering Tool run with input: "${$d(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[tool/end]")} [${e}] [${St(t)}] Exiting Tool run with output: "${$d(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[tool/error]")} [${e}] [${St(t)}] Tool run errored with error: ${Ve(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ve(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[retriever/end]")} [${e}] [${St(t)}] Exiting Retriever run with output: ${Ve(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[retriever/error]")} [${e}] [${St(t)}] Retriever run errored with error: ${Ve(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${Oe(Le.blue,"[agent/action]")} [${r}] Agent selected action: ${Ve(e.actions[e.actions.length-1],"[action]")}`)}};var Yi,Xi=o(()=>(Yi===void 0&&(Yi=new vt(Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Yi),"getDefaultLangChainClientSingleton");var ea=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Qi=Symbol.for("ls:tracing_async_local_storage"),aE=new ea,ta=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Qi]??aE}initializeGlobalInstance(e){globalThis[Qi]===void 0&&(globalThis[Qi]=e)}},oE=new ta;function Fd(t=!1){let e=oE.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
47
|
+
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=qi(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},s=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?s?(this._addChildRun(s,n),s.child_execution_order=Math.max(s.child_execution_order,n.child_execution_order),n.trace_id=s.trace_id,s.dotted_order!==void 0&&(n.dotted_order=[s.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let i=Zi(n,s);i!==void 0&&this.runTreeMap.set(n.id,i)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(p)}async handleLLMStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(p)}async handleChatModelStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=t,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(t,e,r,n,s,i,a,c,l){let u=this._getExecutionOrder(n),d=Date.now(),p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:i?{...l,metadata:i}:{...l},tags:s||[]};return this._addRunToRunMap(p)}async handleChainStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Ki(t,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=Ki(s.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=Ki(s.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:e},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onToolStart?.(c),c}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:e},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onRetrieverStart?.(c),c}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,s,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:i?.chunk}}),await this.onLLMNewToken?.(a,t,{chunk:i?.chunk}),a}};var Ud={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function Oe(t,e){return`${t.open}${e}${t.close}`}o(Oe,"wrap");function Ve(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}o(Ve,"tryJsonStringify");function $d(t){return typeof t=="string"?t.trim():t==null?t:Ve(t,t.toString())}o($d,"formatKVMapItem");function St(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}o(St,"elapsed");var{color:Le}=Ud,Ji=class extends $t{static{o(this,"ConsoleCallbackHandler")}name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,s)=>{let i=`${r.execution_order}:${r.run_type}:${r.name}`;return n===s.length-1?Oe(Ud.bold,i):i}).join(" > ");return Oe(Le.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ve(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[chain/end]")} [${e}] [${St(t)}] Exiting Chain run with output: ${Ve(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[chain/error]")} [${e}] [${St(t)}] Chain run errored with error: ${Ve(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Oe(Le.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ve(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[llm/end]")} [${e}] [${St(t)}] Exiting LLM run with output: ${Ve(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[llm/error]")} [${e}] [${St(t)}] LLM run errored with error: ${Ve(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[tool/start]")} [${e}] Entering Tool run with input: "${$d(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[tool/end]")} [${e}] [${St(t)}] Exiting Tool run with output: "${$d(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[tool/error]")} [${e}] [${St(t)}] Tool run errored with error: ${Ve(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ve(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[retriever/end]")} [${e}] [${St(t)}] Exiting Retriever run with output: ${Ve(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[retriever/error]")} [${e}] [${St(t)}] Retriever run errored with error: ${Ve(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${Oe(Le.blue,"[agent/action]")} [${r}] Agent selected action: ${Ve(e.actions[e.actions.length-1],"[action]")}`)}};var Yi,Xi=o(()=>(Yi===void 0&&(Yi=new vt(Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Yi),"getDefaultLangChainClientSingleton");var ea=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Qi=Symbol.for("ls:tracing_async_local_storage"),lE=new ea,ta=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Qi]??lE}initializeGlobalInstance(e){globalThis[Qi]===void 0&&(globalThis[Qi]=e)}},uE=new ta;function Fd(t=!1){let e=uE.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
48
48
|
|
|
49
|
-
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}o(Fd,"getCurrentRunTree");var jd=new Set(["ls_agent_type"]);function cE(t){let e;for(let r of t)for(let n of r)bt.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Xr(e,n.message.usage_metadata));return e}o(cE,"_getUsageMetadataFromGenerations");var Mr=class ra extends $t{static{o(this,"LangChainTracer")}name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(e={}){super(e),this.fields=e;let{exampleId:r,projectName:n,client:s,replicas:i,metadata:a,tags:c}=e;this.projectName=n??br(),this.replicas=i,this.exampleId=r,this.client=s??Xi(),this.tracingMetadata=a?{...a}:void 0,this.tracingTags=c??[];let l=ra.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){Bd(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Bd(this,e);let r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=cE(r.generations);if(n!==void 0){e.extra=e.extra??{};let s=e.extra.metadata??{};s.usage_metadata=n,e.extra.metadata=s}}}copyWithTracingConfig({metadata:e,tags:r}){let n;if(e===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...e};else{n={...this.tracingMetadata};for(let[a,c]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,a)||jd.has(a))&&(n[a]=c)}let s=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new ra({...this.fields,metadata:n,tags:s});return i.runMap=this.runMap,i.runTreeMap=this.runTreeMap,i}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let s=[r];for(;s.length>0;){let i=s.shift();!i||n.has(i.id)||(n.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&s.push(...i.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new Qe({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Fd(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!="object"||e===null)return!1;let r=e;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function Bd(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[s,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,s)||jd.has(s))&&r[s]!==i&&(r[s]=i,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}o(Bd,"_patchMissingTracingDefaults");var qn=_e(cn(),1);var kr;function lE(){return new("default"in qn.default?qn.default.default:qn.default)({autoStart:!0,concurrency:1})}o(lE,"createQueue");function uE(){return typeof kr>"u"&&(kr=lE()),kr}o(uE,"getQueue");async function re(t,e){if(e===!0){let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()}else kr=uE(),kr.add(async()=>{let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()})}o(re,"consumeCallback");var Hd=o(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Je(e)==="true"),"isTracingEnabled");function na(t){let e=wt();if(e!==void 0)return e.getStore()?.[Mt]?.[t]}o(na,"getContextVariable");var dE=Symbol("lc:configure_hooks"),Gd=o(()=>na(dE)||[],"_getConfigureHooks");var fE=class{static{o(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},Wn=class{static{o(this,"BaseRunManager")}constructor(t,e,r,n,s,i,a,c){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=s,this.metadata=i,this.inheritableMetadata=a,this._parentRunId=c}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>re(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{try{await i.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},pE=class extends Wn{static{o(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},zd=class extends Wn{static{o(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreLLM)try{await a.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleLLMEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},mE=class extends Wn{static{o(this,"CallbackManagerForChainRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleChainEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},hE=class extends Wn{static{o(this,"CallbackManagerForToolRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Ut=class Pr extends fE{static{o(this,"CallbackManager")}handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:nt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return er(_)&&_._createRunForLLMStart(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{await _.handleLLMStart?.(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l)}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new zd(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:nt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return er(_)&&_._createRunForChatModelStart(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{if(_.handleChatModelStart)await _.handleChatModelStart?.(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l);else if(_.handleLLMStart){let g=tn(u);await _.handleLLMStart?.(e,[g],p,this._parentRunId,i,this.tags,this.metadata,l)}}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new zd(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return er(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u),re(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u)}catch(p){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${p}`),d.raiseError)throw p}},d.awaitHandlers)})),new mE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return er(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c,l)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new hE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return er(l)&&l._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await l.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c)}catch(u){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleRetrieverStart: ${u}`),l.raiseError)throw u}},l.awaitHandlers)})),new pE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new Pr(this._parentRunId);for(let s of this.handlers){let i=this.inheritableHandlers.includes(s);n.addHandler(s,i)}for(let s of this.tags){let i=this.inheritableTags.includes(s);n.addTags([s],i)}for(let s of Object.keys(this.metadata)){let i=Object.keys(this.inheritableMetadata).includes(s);n.addMetadata({[s]:this.metadata[s]},i)}for(let s of e)n.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===s.name)||n.addHandler(s,r);return n}static fromHandlers(e){class r extends Wt{static{o(this,"Handler")}name=nt();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,s,i,a,c){return this._configureSync(e,r,n,s,i,a,c)}static _configureSync(e,r,n,s,i,a,c){let l;(e||r)&&(Array.isArray(e)||!e?(l=new Pr,l.setHandlers(e?.map(sa)??[],!0)):l=e,l=l.copy(Array.isArray(r)?r.map(sa):r?.handlers,!1));let u=Je("LANGCHAIN_VERBOSE")==="true"||c?.verbose,d=Mr.getTraceableRunTree(),p=d?.tracingEnabled??Hd();if(d?.tracingEnabled===!1&&l){let E=l.handlers.filter(w=>w.name==="langchain_tracer");for(let w of E)l.removeHandler(w)}let _=p||(Je("LANGCHAIN_TRACING")??!1);if(u||_){if(l||(l=new Pr),u&&!l.handlers.some(E=>E.name===Ji.prototype.name)){let E=new Ji;l.addHandler(E,!0)}if(_&&!l.handlers.some(E=>E.name==="langchain_tracer")&&p){let E=new Mr;l.addHandler(E,!0)}p&&d&&l._parentRunId===void 0&&(l._parentRunId=d.id,l.handlers.find(E=>E.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:E,inheritable:w=!0,handlerClass:S,envVar:I}of Gd()){let m=I&&Je(I)==="true"&&S,T,A=E!==void 0?na(E):void 0;A&&gc(A)?T=A:m&&(T=new S({})),T!==void 0&&(l||(l=new Pr),l.handlers.some(N=>N.name===T.name)||l.addHandler(T,w))}(n||s)&&l&&(l.addTags(n??[]),l.addTags(s??[],!1)),(i||a)&&l&&(l.addMetadata(i??{}),l.addMetadata(a??{},!1));let g=c?.tracerInheritableMetadata,y=c?.tracerInheritableTags;return l&&(g||y)&&(l.handlers=l.handlers.map(E=>E instanceof Mr?E.copyWithTracingConfig({metadata:g,tags:y}):E),l.inheritableHandlers=l.inheritableHandlers.map(E=>E instanceof Mr?E.copyWithTracingConfig({metadata:g,tags:y}):E)),l}};function sa(t){return"name"in t?t:Wt.fromMethods(t)}o(sa,"ensureHandler");var qd=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},gE=new qd,Vd=Symbol.for("lc:child_config"),yE=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return wt()??gE}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Vd]}runWithConfig(t,e,r){let n=Ut._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),s=this.getInstance(),i=s.getStore(),a=n?.getParentRunId(),c=n?.handlers?.find(u=>u?.name==="langchain_tracer"),l;return c&&a?l=c.getRunTreeWithTracingConfig(a):r||(l=new Qe({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[Vd]:t}),i!==void 0&&i[Mt]!==void 0&&(l===void 0&&(l={}),l[Mt]=i[Mt]),s.run(l,e)}initializeGlobalInstance(t){wt()===void 0&&mc(t)}},Lr=new yE;var _E=Object.prototype.hasOwnProperty;function Zd(t,e){return _E.call(t,e)}o(Zd,"hasOwnProperty");function Jd(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)Zd(t,r)&&e.push(r);return e}o(Jd,"_objectKeys");function mt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}o(mt,"_deepClone");function Zn(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}o(Zn,"isInteger");function Yd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}o(Yd,"unescapePathComponent");function Kn(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Kn(t[r]))return!0}else if(typeof t=="object"){let r=Jd(t),n=r.length;for(var e=0;e<n;e++)if(Kn(t[r[e]]))return!0}}return!1}o(Kn,"hasUndefined");function Kd(t,e){let r=[t];for(let n in e){let s=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof s<"u"&&r.push(`${n}: ${s}`)}return r.join(`
|
|
50
|
-
`)}o(Kd,"patchErrorMessageFormatter");var Xd=class extends Error{static{o(this,"PatchError")}constructor(t,e,r,n,s){super(Kd(t,{name:e,index:r,operation:n,tree:s})),this.name=e,this.index=r,this.operation=n,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=Kd(t,{name:e,index:r,operation:n,tree:s})}};var Qd=W({JsonPatchError:o(()=>se,"JsonPatchError"),_areEquals:o(()=>Dr,"_areEquals"),applyOperation:o(()=>Ft,"applyOperation"),applyPatch:o(()=>Xn,"applyPatch"),applyReducer:o(()=>wE,"applyReducer"),deepClone:o(()=>bE,"deepClone"),getValueByPointer:o(()=>Jn,"getValueByPointer"),validate:o(()=>ef,"validate"),validator:o(()=>Yn,"validator")}),se=Xd,bE=mt,tr={add:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},"add"),remove:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},"remove"),replace:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:o(function(t,e,r){let n=Jn(r,this.path);n&&(n=mt(n));let s=Ft(r,{op:"remove",path:this.from}).removed;return Ft(r,{op:"add",path:this.path,value:s}),{newDocument:r,removed:n}},"move"),copy:o(function(t,e,r){let n=Jn(r,this.from);return Ft(r,{op:"add",path:this.path,value:mt(n)}),{newDocument:r}},"copy"),test:o(function(t,e,r){return{newDocument:r,test:Dr(t[e],this.value)}},"test"),_get:o(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},EE={add:o(function(t,e,r){return Zn(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:o(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:o(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:tr.move,copy:tr.copy,test:tr.test,_get:tr._get};function Jn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ft(t,r),r.value}o(Jn,"getValueByPointer");function Ft(t,e,r=!1,n=!0,s=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Yn(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Jn(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=Dr(t,e.value),a.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=mt(t));let a=(e.path||"").split("/"),c=t,l=1,u=a.length,d,p,_;for(typeof r=="function"?_=r:_=Yn;;){if(p=a[l],p&&p.indexOf("~")!=-1&&(p=Yd(p)),s&&(p=="__proto__"||p=="prototype"&&l>0&&a[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(c[p]===void 0?d=a.slice(0,l).join("/"):l==u-1&&(d=e.path),d!==void 0&&_(e,0,t,d)),l++,Array.isArray(c)){if(p==="-")p=c.length;else{if(r&&!Zn(p))throw new se("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Zn(p)&&(p=~~p)}if(l>=u){if(r&&e.op==="add"&&p>c.length)throw new se("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let g=EE[e.op].call(e,c,p,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}}else if(l>=u){let g=tr[e.op].call(e,c,p,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}if(c=c[p],r&&l<u&&(!c||typeof c!="object"))throw new se("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}o(Ft,"applyOperation");function Xn(t,e,r,n=!0,s=!0){if(r&&!Array.isArray(e))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=mt(t));let i=new Array(e.length);for(let a=0,c=e.length;a<c;a++)i[a]=Ft(t,e[a],r,!0,s,a),t=i[a].newDocument;return i.newDocument=t,i}o(Xn,"applyPatch");function wE(t,e,r){let n=Ft(t,e);if(n.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}o(wE,"applyReducer");function Yn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new se("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(tr[t.op]){if(typeof t.path!="string")throw new se("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new se('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new se("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Kn(t.value))throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var s=t.path.split("/").length,i=n.split("/").length;if(s!==i+1&&s!==i)throw new se("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new se("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a=ef([{op:"_get",path:t.from,value:void 0}],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new se("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}o(Yn,"validator");function ef(t,e,r){try{if(!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xn(mt(e),mt(t),r||!0);else{r=r||Yn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(s){if(s instanceof se)return s;throw s}}o(ef,"validate");function Dr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),s,i,a;if(r&&n){if(i=t.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!Dr(t[s],e[s]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!Dr(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}o(Dr,"_areEquals");({...Qd});var rU=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var RE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,CE=[0,31,28,31,30,31,30,31,31,30,31,30,31],OE=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,NE=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ME=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,kE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,PE=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,LE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,DE=/^(?:\/(?:[^~/]|~0|~1)*)*$/,$E=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,UE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,FE=o(t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),BE=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,jE=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,HE=o(t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),"DURATION");function ut(t){return t.test.bind(t)}o(ut,"bind");var GE={date:tf,time:rf.bind(void 0,!1),"date-time":qE,duration:HE,uri:ZE,"uri-reference":ut(ME),"uri-template":ut(kE),url:ut(PE),email:FE,hostname:ut(NE),ipv4:ut(BE),ipv6:ut(jE),regex:YE,uuid:ut(LE),"json-pointer":ut(DE),"json-pointer-uri-fragment":ut($E),"relative-json-pointer":ut(UE)};function zE(t){return t%4===0&&(t%100!==0||t%400===0)}o(zE,"isLeapYear");function tf(t){let e=t.match(RE);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&zE(r)?29:CE[n])}o(tf,"date");function rf(t,e){let r=e.match(OE);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!t||a)}o(rf,"time");var VE=/t|\s/i;function qE(t){let e=t.split(VE);return e.length==2&&tf(e[0])&&rf(!0,e[1])}o(qE,"date_time");var WE=/\/|:/,KE=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ZE(t){return WE.test(t)&&KE.test(t)}o(ZE,"uri");var JE=/[^\\]\\Z/;function YE(t){if(JE.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}o(YE,"regex");var nf;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(nf||(nf={}));var gf=_e(hf(),1);var pw=Object.defineProperty,mw=o((t,e,r)=>e in t?pw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),hw=o((t,e,r)=>(mw(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function gw(t,e){let r=Array.from({length:t.length},(n,s)=>({start:s,end:s+1}));for(;r.length>1;){let n=null;for(let s=0;s<r.length-1;s++){let i=t.slice(r[s].start,r[s+1].end),a=e.get(i.join(","));a!=null&&(n==null||a<n[0])&&(n=[a,s])}if(n!=null){let s=n[1];r[s]={start:r[s].start,end:r[s+1].end},r.splice(s+1,1)}else break}return r}o(gw,"bytePairMerge");function yw(t,e){return t.length===1?[e.get(t.join(","))]:gw(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}o(yw,"bytePairEncode");function _w(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}o(_w,"escapeRegex");var ua=class{static{o(this,"_Tiktoken")}specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;let r=t.bpe_ranks.split(`
|
|
51
|
-
`).filter(Boolean).reduce((n,s)=>{let[i,a,...c]=s.split(" "),l=Number.parseInt(a,10);return c.forEach((u,d)=>n[u]=l+d),n},{});for(let[n,s]of Object.entries(r)){let i=gf.default.toByteArray(n);this.rankMap.set(i.join(","),s),this.textMap.set(s,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[s,i])=>(n[i]=this.textEncoder.encode(s),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),s=ua.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),c=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!a.has(u)):r);if(c.size>0){let u=ua.specialTokenRegex([...c]),d=t.match(u);if(d!=null)throw new Error(`The text contains a special token that is not allowed: ${d[0]}`)}let l=0;for(;;){let u=null,d=l;for(;s.lastIndex=d,u=s.exec(t),!(u==null||a.has(u[0]));)d=u.index+1;let p=u?.index??t.length;for(let g of t.substring(l,p).matchAll(n)){let y=this.textEncoder.encode(g[0]),E=this.rankMap.get(y.join(","));if(E!=null){i.push(E);continue}i.push(...
|
|
52
|
-
`||h==="\r"||h===" "}o(m,"isWhitespace");function T(h){return h==='"'||h==="'"}o(T,"isQuote");function A(h){return h===">"||m(h)}o(A,"isAttribEnd");function N(h,f){return h.test(f)}o(N,"isMatch");function O(h,f){return!N(h,f)}o(O,"notMatch");var b=0;t.STATE={BEGIN:b++,BEGIN_WHITESPACE:b++,TEXT:b++,TEXT_ENTITY:b++,OPEN_WAKA:b++,SGML_DECL:b++,SGML_DECL_QUOTED:b++,DOCTYPE:b++,DOCTYPE_QUOTED:b++,DOCTYPE_DTD:b++,DOCTYPE_DTD_QUOTED:b++,COMMENT_STARTING:b++,COMMENT:b++,COMMENT_ENDING:b++,COMMENT_ENDED:b++,CDATA:b++,CDATA_ENDING:b++,CDATA_ENDING_2:b++,PROC_INST:b++,PROC_INST_BODY:b++,PROC_INST_ENDING:b++,OPEN_TAG:b++,OPEN_TAG_SLASH:b++,ATTRIB:b++,ATTRIB_NAME:b++,ATTRIB_NAME_SAW_WHITE:b++,ATTRIB_VALUE:b++,ATTRIB_VALUE_QUOTED:b++,ATTRIB_VALUE_CLOSED:b++,ATTRIB_VALUE_UNQUOTED:b++,ATTRIB_VALUE_ENTITY_Q:b++,ATTRIB_VALUE_ENTITY_U:b++,CLOSE_TAG:b++,CLOSE_TAG_SAW_WHITE:b++,SCRIPT:b++,SCRIPT_ENDING:b++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(h){var f=t.ENTITIES[h],
|
|
49
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}o(Fd,"getCurrentRunTree");var jd=new Set(["ls_agent_type"]);function dE(t){let e;for(let r of t)for(let n of r)bt.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Xr(e,n.message.usage_metadata));return e}o(dE,"_getUsageMetadataFromGenerations");var Mr=class ra extends $t{static{o(this,"LangChainTracer")}name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(e={}){super(e),this.fields=e;let{exampleId:r,projectName:n,client:s,replicas:i,metadata:a,tags:c}=e;this.projectName=n??br(),this.replicas=i,this.exampleId=r,this.client=s??Xi(),this.tracingMetadata=a?{...a}:void 0,this.tracingTags=c??[];let l=ra.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){Bd(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Bd(this,e);let r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=dE(r.generations);if(n!==void 0){e.extra=e.extra??{};let s=e.extra.metadata??{};s.usage_metadata=n,e.extra.metadata=s}}}copyWithTracingConfig({metadata:e,tags:r}){let n;if(e===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...e};else{n={...this.tracingMetadata};for(let[a,c]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,a)||jd.has(a))&&(n[a]=c)}let s=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new ra({...this.fields,metadata:n,tags:s});return i.runMap=this.runMap,i.runTreeMap=this.runTreeMap,i}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let s=[r];for(;s.length>0;){let i=s.shift();!i||n.has(i.id)||(n.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&s.push(...i.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new Qe({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Fd(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!="object"||e===null)return!1;let r=e;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function Bd(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[s,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,s)||jd.has(s))&&r[s]!==i&&(r[s]=i,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}o(Bd,"_patchMissingTracingDefaults");var Wn=_e(cn(),1);var kr;function fE(){return new("default"in Wn.default?Wn.default.default:Wn.default)({autoStart:!0,concurrency:1})}o(fE,"createQueue");function pE(){return typeof kr>"u"&&(kr=fE()),kr}o(pE,"getQueue");async function re(t,e){if(e===!0){let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()}else kr=pE(),kr.add(async()=>{let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()})}o(re,"consumeCallback");var Hd=o(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Je(e)==="true"),"isTracingEnabled");function na(t){let e=wt();if(e!==void 0)return e.getStore()?.[Mt]?.[t]}o(na,"getContextVariable");var mE=Symbol("lc:configure_hooks"),Gd=o(()=>na(mE)||[],"_getConfigureHooks");var hE=class{static{o(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},qn=class{static{o(this,"BaseRunManager")}constructor(t,e,r,n,s,i,a,c){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=s,this.metadata=i,this.inheritableMetadata=a,this._parentRunId=c}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>re(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{try{await i.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},gE=class extends qn{static{o(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},zd=class extends qn{static{o(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreLLM)try{await a.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleLLMEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},yE=class extends qn{static{o(this,"CallbackManagerForChainRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleChainEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},_E=class extends qn{static{o(this,"CallbackManagerForToolRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Ut=class Pr extends hE{static{o(this,"CallbackManager")}handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:nt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return er(_)&&_._createRunForLLMStart(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{await _.handleLLMStart?.(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l)}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new zd(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:nt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return er(_)&&_._createRunForChatModelStart(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{if(_.handleChatModelStart)await _.handleChatModelStart?.(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l);else if(_.handleLLMStart){let g=tn(u);await _.handleLLMStart?.(e,[g],p,this._parentRunId,i,this.tags,this.metadata,l)}}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new zd(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return er(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u),re(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u)}catch(p){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${p}`),d.raiseError)throw p}},d.awaitHandlers)})),new yE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return er(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c,l)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new _E(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return er(l)&&l._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await l.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c)}catch(u){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleRetrieverStart: ${u}`),l.raiseError)throw u}},l.awaitHandlers)})),new gE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new Pr(this._parentRunId);for(let s of this.handlers){let i=this.inheritableHandlers.includes(s);n.addHandler(s,i)}for(let s of this.tags){let i=this.inheritableTags.includes(s);n.addTags([s],i)}for(let s of Object.keys(this.metadata)){let i=Object.keys(this.inheritableMetadata).includes(s);n.addMetadata({[s]:this.metadata[s]},i)}for(let s of e)n.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===s.name)||n.addHandler(s,r);return n}static fromHandlers(e){class r extends qt{static{o(this,"Handler")}name=nt();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,s,i,a,c){return this._configureSync(e,r,n,s,i,a,c)}static _configureSync(e,r,n,s,i,a,c){let l;(e||r)&&(Array.isArray(e)||!e?(l=new Pr,l.setHandlers(e?.map(sa)??[],!0)):l=e,l=l.copy(Array.isArray(r)?r.map(sa):r?.handlers,!1));let u=Je("LANGCHAIN_VERBOSE")==="true"||c?.verbose,d=Mr.getTraceableRunTree(),p=d?.tracingEnabled??Hd();if(d?.tracingEnabled===!1&&l){let E=l.handlers.filter(w=>w.name==="langchain_tracer");for(let w of E)l.removeHandler(w)}let _=p||(Je("LANGCHAIN_TRACING")??!1);if(u||_){if(l||(l=new Pr),u&&!l.handlers.some(E=>E.name===Ji.prototype.name)){let E=new Ji;l.addHandler(E,!0)}if(_&&!l.handlers.some(E=>E.name==="langchain_tracer")&&p){let E=new Mr;l.addHandler(E,!0)}p&&d&&l._parentRunId===void 0&&(l._parentRunId=d.id,l.handlers.find(E=>E.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:E,inheritable:w=!0,handlerClass:S,envVar:I}of Gd()){let m=I&&Je(I)==="true"&&S,T,A=E!==void 0?na(E):void 0;A&&gc(A)?T=A:m&&(T=new S({})),T!==void 0&&(l||(l=new Pr),l.handlers.some(N=>N.name===T.name)||l.addHandler(T,w))}(n||s)&&l&&(l.addTags(n??[]),l.addTags(s??[],!1)),(i||a)&&l&&(l.addMetadata(i??{}),l.addMetadata(a??{},!1));let g=c?.tracerInheritableMetadata,y=c?.tracerInheritableTags;return l&&(g||y)&&(l.handlers=l.handlers.map(E=>E instanceof Mr?E.copyWithTracingConfig({metadata:g,tags:y}):E),l.inheritableHandlers=l.inheritableHandlers.map(E=>E instanceof Mr?E.copyWithTracingConfig({metadata:g,tags:y}):E)),l}};function sa(t){return"name"in t?t:qt.fromMethods(t)}o(sa,"ensureHandler");var Wd=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},bE=new Wd,Vd=Symbol.for("lc:child_config"),EE=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return wt()??bE}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Vd]}runWithConfig(t,e,r){let n=Ut._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),s=this.getInstance(),i=s.getStore(),a=n?.getParentRunId(),c=n?.handlers?.find(u=>u?.name==="langchain_tracer"),l;return c&&a?l=c.getRunTreeWithTracingConfig(a):r||(l=new Qe({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[Vd]:t}),i!==void 0&&i[Mt]!==void 0&&(l===void 0&&(l={}),l[Mt]=i[Mt]),s.run(l,e)}initializeGlobalInstance(t){wt()===void 0&&mc(t)}},Lr=new EE;var wE=Object.prototype.hasOwnProperty;function Zd(t,e){return wE.call(t,e)}o(Zd,"hasOwnProperty");function Jd(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)Zd(t,r)&&e.push(r);return e}o(Jd,"_objectKeys");function mt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}o(mt,"_deepClone");function Zn(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}o(Zn,"isInteger");function Yd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}o(Yd,"unescapePathComponent");function Kn(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Kn(t[r]))return!0}else if(typeof t=="object"){let r=Jd(t),n=r.length;for(var e=0;e<n;e++)if(Kn(t[r[e]]))return!0}}return!1}o(Kn,"hasUndefined");function Kd(t,e){let r=[t];for(let n in e){let s=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof s<"u"&&r.push(`${n}: ${s}`)}return r.join(`
|
|
50
|
+
`)}o(Kd,"patchErrorMessageFormatter");var Xd=class extends Error{static{o(this,"PatchError")}constructor(t,e,r,n,s){super(Kd(t,{name:e,index:r,operation:n,tree:s})),this.name=e,this.index=r,this.operation=n,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=Kd(t,{name:e,index:r,operation:n,tree:s})}};var Qd=q({JsonPatchError:o(()=>se,"JsonPatchError"),_areEquals:o(()=>Dr,"_areEquals"),applyOperation:o(()=>Ft,"applyOperation"),applyPatch:o(()=>Xn,"applyPatch"),applyReducer:o(()=>SE,"applyReducer"),deepClone:o(()=>TE,"deepClone"),getValueByPointer:o(()=>Jn,"getValueByPointer"),validate:o(()=>ef,"validate"),validator:o(()=>Yn,"validator")}),se=Xd,TE=mt,tr={add:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},"add"),remove:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},"remove"),replace:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:o(function(t,e,r){let n=Jn(r,this.path);n&&(n=mt(n));let s=Ft(r,{op:"remove",path:this.from}).removed;return Ft(r,{op:"add",path:this.path,value:s}),{newDocument:r,removed:n}},"move"),copy:o(function(t,e,r){let n=Jn(r,this.from);return Ft(r,{op:"add",path:this.path,value:mt(n)}),{newDocument:r}},"copy"),test:o(function(t,e,r){return{newDocument:r,test:Dr(t[e],this.value)}},"test"),_get:o(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},vE={add:o(function(t,e,r){return Zn(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:o(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:o(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:tr.move,copy:tr.copy,test:tr.test,_get:tr._get};function Jn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ft(t,r),r.value}o(Jn,"getValueByPointer");function Ft(t,e,r=!1,n=!0,s=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Yn(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Jn(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=Dr(t,e.value),a.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=mt(t));let a=(e.path||"").split("/"),c=t,l=1,u=a.length,d,p,_;for(typeof r=="function"?_=r:_=Yn;;){if(p=a[l],p&&p.indexOf("~")!=-1&&(p=Yd(p)),s&&(p=="__proto__"||p=="prototype"&&l>0&&a[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(c[p]===void 0?d=a.slice(0,l).join("/"):l==u-1&&(d=e.path),d!==void 0&&_(e,0,t,d)),l++,Array.isArray(c)){if(p==="-")p=c.length;else{if(r&&!Zn(p))throw new se("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Zn(p)&&(p=~~p)}if(l>=u){if(r&&e.op==="add"&&p>c.length)throw new se("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let g=vE[e.op].call(e,c,p,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}}else if(l>=u){let g=tr[e.op].call(e,c,p,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}if(c=c[p],r&&l<u&&(!c||typeof c!="object"))throw new se("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}o(Ft,"applyOperation");function Xn(t,e,r,n=!0,s=!0){if(r&&!Array.isArray(e))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=mt(t));let i=new Array(e.length);for(let a=0,c=e.length;a<c;a++)i[a]=Ft(t,e[a],r,!0,s,a),t=i[a].newDocument;return i.newDocument=t,i}o(Xn,"applyPatch");function SE(t,e,r){let n=Ft(t,e);if(n.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}o(SE,"applyReducer");function Yn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new se("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(tr[t.op]){if(typeof t.path!="string")throw new se("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new se('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new se("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Kn(t.value))throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var s=t.path.split("/").length,i=n.split("/").length;if(s!==i+1&&s!==i)throw new se("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new se("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a=ef([{op:"_get",path:t.from,value:void 0}],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new se("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}o(Yn,"validator");function ef(t,e,r){try{if(!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xn(mt(e),mt(t),r||!0);else{r=r||Yn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(s){if(s instanceof se)return s;throw s}}o(ef,"validate");function Dr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),s,i,a;if(r&&n){if(i=t.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!Dr(t[s],e[s]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!Dr(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}o(Dr,"_areEquals");({...Qd});var cU=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var NE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ME=[0,31,28,31,30,31,30,31,31,30,31,30,31],kE=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,PE=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,LE=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,DE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,$E=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,UE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,FE=/^(?:\/(?:[^~/]|~0|~1)*)*$/,BE=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,jE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,HE=o(t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),GE=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,zE=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,VE=o(t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),"DURATION");function ut(t){return t.test.bind(t)}o(ut,"bind");var WE={date:tf,time:rf.bind(void 0,!1),"date-time":ZE,duration:VE,uri:XE,"uri-reference":ut(LE),"uri-template":ut(DE),url:ut($E),email:HE,hostname:ut(PE),ipv4:ut(GE),ipv6:ut(zE),regex:ew,uuid:ut(UE),"json-pointer":ut(FE),"json-pointer-uri-fragment":ut(BE),"relative-json-pointer":ut(jE)};function qE(t){return t%4===0&&(t%100!==0||t%400===0)}o(qE,"isLeapYear");function tf(t){let e=t.match(NE);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&qE(r)?29:ME[n])}o(tf,"date");function rf(t,e){let r=e.match(kE);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!t||a)}o(rf,"time");var KE=/t|\s/i;function ZE(t){let e=t.split(KE);return e.length==2&&tf(e[0])&&rf(!0,e[1])}o(ZE,"date_time");var JE=/\/|:/,YE=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function XE(t){return JE.test(t)&&YE.test(t)}o(XE,"uri");var QE=/[^\\]\\Z/;function ew(t){if(QE.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}o(ew,"regex");var nf;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(nf||(nf={}));var gf=_e(hf(),1);var gw=Object.defineProperty,yw=o((t,e,r)=>e in t?gw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),_w=o((t,e,r)=>(yw(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function bw(t,e){let r=Array.from({length:t.length},(n,s)=>({start:s,end:s+1}));for(;r.length>1;){let n=null;for(let s=0;s<r.length-1;s++){let i=t.slice(r[s].start,r[s+1].end),a=e.get(i.join(","));a!=null&&(n==null||a<n[0])&&(n=[a,s])}if(n!=null){let s=n[1];r[s]={start:r[s].start,end:r[s+1].end},r.splice(s+1,1)}else break}return r}o(bw,"bytePairMerge");function Ew(t,e){return t.length===1?[e.get(t.join(","))]:bw(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}o(Ew,"bytePairEncode");function ww(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}o(ww,"escapeRegex");var ua=class{static{o(this,"_Tiktoken")}specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;let r=t.bpe_ranks.split(`
|
|
51
|
+
`).filter(Boolean).reduce((n,s)=>{let[i,a,...c]=s.split(" "),l=Number.parseInt(a,10);return c.forEach((u,d)=>n[u]=l+d),n},{});for(let[n,s]of Object.entries(r)){let i=gf.default.toByteArray(n);this.rankMap.set(i.join(","),s),this.textMap.set(s,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[s,i])=>(n[i]=this.textEncoder.encode(s),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),s=ua.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),c=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!a.has(u)):r);if(c.size>0){let u=ua.specialTokenRegex([...c]),d=t.match(u);if(d!=null)throw new Error(`The text contains a special token that is not allowed: ${d[0]}`)}let l=0;for(;;){let u=null,d=l;for(;s.lastIndex=d,u=s.exec(t),!(u==null||a.has(u[0]));)d=u.index+1;let p=u?.index??t.length;for(let g of t.substring(l,p).matchAll(n)){let y=this.textEncoder.encode(g[0]),E=this.rankMap.get(y.join(","));if(E!=null){i.push(E);continue}i.push(...Ew(y,this.rankMap))}if(u==null)break;let _=this.specialTokens[u[0]];i.push(_),l=u.index+u[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let a=t[i],c=this.textMap.get(a)??this.inverseSpecialTokens[a];c!=null&&(e.push(c),r+=c.length)}let n=new Uint8Array(r),s=0;for(let i of e)n.set(i,s),s+=i.length;return this.textDecoder.decode(n)}},da=ua;_w(da,"specialTokenRegex",t=>new RegExp(t.map(e=>ww(e)).join("|"),"g"));var Ef=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var wf=["image","video","audio","text-plain","file"];var Sw=["text","reasoning",...Ef,...wf];var Mw=o(function(){let t={};t.parser=function(h,f){return new r(h,f)},t.SAXParser=r,t.SAXStream=u,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(h,f){if(!(this instanceof r))return new r(h,f);var C=this;s(C),C.q=C.c="",C.bufferCheckPosition=t.MAX_BUFFER_LENGTH,C.opt=f||{},C.opt.lowercase=C.opt.lowercase||C.opt.lowercasetags,C.looseCase=C.opt.lowercase?"toLowerCase":"toUpperCase",C.tags=[],C.closed=C.closedRoot=C.sawRoot=!1,C.tag=C.error=null,C.strict=!!h,C.noscript=!!(h||C.opt.noscript),C.state=b.BEGIN,C.strictEntities=C.opt.strictEntities,C.ENTITIES=C.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),C.attribList=[],C.opt.xmlns&&(C.ns=Object.create(y)),C.trackPosition=C.opt.position!==!1,C.trackPosition&&(C.position=C.line=C.column=0),G(C,"onready")}o(r,"SAXParser"),Object.create||(Object.create=function(h){function f(){}return o(f,"F"),f.prototype=h,new f}),Object.keys||(Object.keys=function(h){var f=[];for(var C in h)h.hasOwnProperty(C)&&f.push(C);return f});function n(h){for(var f=Math.max(t.MAX_BUFFER_LENGTH,10),C=0,v=0,J=e.length;v<J;v++){var le=h[e[v]].length;if(le>f)switch(e[v]){case"textNode":Z(h);break;case"cdata":B(h,"oncdata",h.cdata),h.cdata="";break;case"script":B(h,"onscript",h.script),h.script="";break;default:ke(h,"Max buffer length exceeded: "+e[v])}C=Math.max(C,le)}h.bufferCheckPosition=t.MAX_BUFFER_LENGTH-C+h.position}o(n,"checkBufferLength");function s(h){for(var f=0,C=e.length;f<C;f++)h[e[f]]=""}o(s,"clearBuffers");function i(h){Z(h),h.cdata!==""&&(B(h,"oncdata",h.cdata),h.cdata=""),h.script!==""&&(B(h,"onscript",h.script),h.script="")}o(i,"flushBuffers"),r.prototype={end:o(function(){xt(this)},"end"),write:Am,resume:o(function(){return this.error=null,this},"resume"),close:o(function(){return this.write(null)},"close"),flush:o(function(){i(this)},"flush")};var a=ReadableStream;a||(a=o(function(){},"Stream"));var c=t.EVENTS.filter(function(h){return h!=="error"&&h!=="end"});function l(h,f){return new u(h,f)}o(l,"createStream");function u(h,f){if(!(this instanceof u))return new u(h,f);a.apply(this),this._parser=new r(h,f),this.writable=!0,this.readable=!0;var C=this;this._parser.onend=function(){C.emit("end")},this._parser.onerror=function(v){C.emit("error",v),C._parser.error=null},this._decoder=null,c.forEach(function(v){Object.defineProperty(C,"on"+v,{get:o(function(){return C._parser["on"+v]},"get"),set:o(function(J){if(!J)return C.removeAllListeners(v),C._parser["on"+v]=J,J;C.on(v,J)},"set"),enumerable:!0,configurable:!1})})}o(u,"SAXStream"),u.prototype=Object.create(a.prototype,{constructor:{value:u}}),u.prototype.write=function(h){return this._parser.write(h.toString()),this.emit("data",h),!0},u.prototype.end=function(h){return h&&h.length&&this.write(h),this._parser.end(),!0},u.prototype.on=function(h,f){var C=this;return!C._parser["on"+h]&&c.indexOf(h)!==-1&&(C._parser["on"+h]=function(){var v=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);v.splice(0,0,h),C.emit.apply(C,v)}),a.prototype.on.call(C,h,f)};var d="[CDATA[",p="DOCTYPE",_="http://www.w3.org/XML/1998/namespace",g="http://www.w3.org/2000/xmlns/",y={xml:_,xmlns:g},E=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,w=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,S=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function m(h){return h===" "||h===`
|
|
52
|
+
`||h==="\r"||h===" "}o(m,"isWhitespace");function T(h){return h==='"'||h==="'"}o(T,"isQuote");function A(h){return h===">"||m(h)}o(A,"isAttribEnd");function N(h,f){return h.test(f)}o(N,"isMatch");function O(h,f){return!N(h,f)}o(O,"notMatch");var b=0;t.STATE={BEGIN:b++,BEGIN_WHITESPACE:b++,TEXT:b++,TEXT_ENTITY:b++,OPEN_WAKA:b++,SGML_DECL:b++,SGML_DECL_QUOTED:b++,DOCTYPE:b++,DOCTYPE_QUOTED:b++,DOCTYPE_DTD:b++,DOCTYPE_DTD_QUOTED:b++,COMMENT_STARTING:b++,COMMENT:b++,COMMENT_ENDING:b++,COMMENT_ENDED:b++,CDATA:b++,CDATA_ENDING:b++,CDATA_ENDING_2:b++,PROC_INST:b++,PROC_INST_BODY:b++,PROC_INST_ENDING:b++,OPEN_TAG:b++,OPEN_TAG_SLASH:b++,ATTRIB:b++,ATTRIB_NAME:b++,ATTRIB_NAME_SAW_WHITE:b++,ATTRIB_VALUE:b++,ATTRIB_VALUE_QUOTED:b++,ATTRIB_VALUE_CLOSED:b++,ATTRIB_VALUE_UNQUOTED:b++,ATTRIB_VALUE_ENTITY_Q:b++,ATTRIB_VALUE_ENTITY_U:b++,CLOSE_TAG:b++,CLOSE_TAG_SAW_WHITE:b++,SCRIPT:b++,SCRIPT_ENDING:b++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(h){var f=t.ENTITIES[h],C=typeof f=="number"?String.fromCharCode(f):f;t.ENTITIES[h]=C});for(var j in t.STATE)t.STATE[t.STATE[j]]=j;b=t.STATE;function G(h,f,C){h[f]&&h[f](C)}o(G,"emit");function B(h,f,C){h.textNode&&Z(h),G(h,f,C)}o(B,"emitNode");function Z(h){h.textNode=ce(h.opt,h.textNode),h.textNode&&G(h,"ontext",h.textNode),h.textNode=""}o(Z,"closeText");function ce(h,f){return h.trim&&(f=f.trim()),h.normalize&&(f=f.replace(/\s+/g," ")),f}o(ce,"textopts");function ke(h,f){return Z(h),h.trackPosition&&(f+=`
|
|
53
53
|
Line: `+h.line+`
|
|
54
54
|
Column: `+h.column+`
|
|
55
|
-
Char: `+h.c),f=new Error(f),h.error=f,G(h,"onerror",f),h}o(ke,"error");function xt(h){return h.sawRoot&&!h.closedRoot&&K(h,"Unclosed root tag"),h.state!==b.BEGIN&&h.state!==b.BEGIN_WHITESPACE&&h.state!==b.TEXT&&ke(h,"Unexpected end"),Z(h),h.c="",h.closed=!0,G(h,"onend"),r.call(h,h.strict,h.opt),h}o(xt,"end");function K(h,f){if(typeof h!="object"||!(h instanceof r))throw new Error("bad call to strictFail");h.strict&&ke(h,f)}o(K,"strictFail");function
|
|
55
|
+
Char: `+h.c),f=new Error(f),h.error=f,G(h,"onerror",f),h}o(ke,"error");function xt(h){return h.sawRoot&&!h.closedRoot&&K(h,"Unclosed root tag"),h.state!==b.BEGIN&&h.state!==b.BEGIN_WHITESPACE&&h.state!==b.TEXT&&ke(h,"Unexpected end"),Z(h),h.c="",h.closed=!0,G(h,"onend"),r.call(h,h.strict,h.opt),h}o(xt,"end");function K(h,f){if(typeof h!="object"||!(h instanceof r))throw new Error("bad call to strictFail");h.strict&&ke(h,f)}o(K,"strictFail");function xm(h){h.strict||(h.tagName=h.tagName[h.looseCase]());var f=h.tags[h.tags.length-1]||h,C=h.tag={name:h.tagName,attributes:{}};h.opt.xmlns&&(C.ns=f.ns),h.attribList.length=0,B(h,"onopentagstart",C)}o(xm,"newTag");function vs(h,f){var C=h.indexOf(":")<0?["",h]:h.split(":"),v=C[0],J=C[1];return f&&h==="xmlns"&&(v="xmlns",J=""),{prefix:v,local:J}}o(vs,"qname");function Ss(h){if(h.strict||(h.attribName=h.attribName[h.looseCase]()),h.attribList.indexOf(h.attribName)!==-1||h.tag.attributes.hasOwnProperty(h.attribName)){h.attribName=h.attribValue="";return}if(h.opt.xmlns){var f=vs(h.attribName,!0),C=f.prefix,v=f.local;if(C==="xmlns")if(v==="xml"&&h.attribValue!==_)K(h,"xml: prefix must be bound to "+_+`
|
|
56
56
|
Actual: `+h.attribValue);else if(v==="xmlns"&&h.attribValue!==g)K(h,"xmlns: prefix must be bound to "+g+`
|
|
57
|
-
Actual: `+h.attribValue);else{var J=h.tag,le=h.tags[h.tags.length-1]||h;J.ns===le.ns&&(J.ns=Object.create(le.ns)),J.ns[v]=h.attribValue}h.attribList.push([h.attribName,h.attribValue])}else h.tag.attributes[h.attribName]=h.attribValue,B(h,"onattribute",{name:h.attribName,value:h.attribValue});h.attribName=h.attribValue=""}o(Ss,"attrib");function At(h,f){if(h.opt.xmlns){var
|
|
58
|
-
`?(f.line++,f.column=0):f.column++),f.state){case b.BEGIN:if(f.state=b.BEGIN_WHITESPACE,v==="\uFEFF")continue;Ja(f,v);continue;case b.BEGIN_WHITESPACE:Ja(f,v);continue;case b.TEXT:if(f.sawRoot&&!f.closedRoot){for(var J=
|
|
59
|
-
`?(f.line++,f.column=0):f.column++);f.textNode+=h.substring(J,R-1)}v==="<"&&!(f.sawRoot&&f.closedRoot&&!f.strict)?(f.state=b.OPEN_WAKA,f.startTagPosition=f.position):(!m(v)&&(!f.sawRoot||f.closedRoot)&&K(f,"Text data outside of root node."),v==="&"?f.state=b.TEXT_ENTITY:f.textNode+=v);continue;case b.SCRIPT:v==="<"?f.state=b.SCRIPT_ENDING:f.script+=v;continue;case b.SCRIPT_ENDING:v==="/"?f.state=b.CLOSE_TAG:(f.script+="<"+v,f.state=b.SCRIPT);continue;case b.OPEN_WAKA:if(v==="!")f.state=b.SGML_DECL,f.sgmlDecl="";else if(!m(v))if(N(E,v))f.state=b.OPEN_TAG,f.tagName=v;else if(v==="/")f.state=b.CLOSE_TAG,f.tagName="";else if(v==="?")f.state=b.PROC_INST,f.procInstName=f.procInstBody="";else{if(K(f,"Unencoded <"),f.startTagPosition+1<f.position){var le=f.position-f.startTagPosition;v=new Array(le).join(" ")+v}f.textNode+="<"+v,f.state=b.TEXT}continue;case b.SGML_DECL:(f.sgmlDecl+v).toUpperCase()===d?(B(f,"onopencdata"),f.state=b.CDATA,f.sgmlDecl="",f.cdata=""):f.sgmlDecl+v==="--"?(f.state=b.COMMENT,f.comment="",f.sgmlDecl=""):(f.sgmlDecl+v).toUpperCase()===p?(f.state=b.DOCTYPE,(f.doctype||f.sawRoot)&&K(f,"Inappropriately located doctype declaration"),f.doctype="",f.sgmlDecl=""):v===">"?(B(f,"onsgmldeclaration",f.sgmlDecl),f.sgmlDecl="",f.state=b.TEXT):(T(v)&&(f.state=b.SGML_DECL_QUOTED),f.sgmlDecl+=v);continue;case b.SGML_DECL_QUOTED:v===f.q&&(f.state=b.SGML_DECL,f.q=""),f.sgmlDecl+=v;continue;case b.DOCTYPE:v===">"?(f.state=b.TEXT,B(f,"ondoctype",f.doctype),f.doctype=!0):(f.doctype+=v,v==="["?f.state=b.DOCTYPE_DTD:T(v)&&(f.state=b.DOCTYPE_QUOTED,f.q=v));continue;case b.DOCTYPE_QUOTED:f.doctype+=v,v===f.q&&(f.q="",f.state=b.DOCTYPE);continue;case b.DOCTYPE_DTD:f.doctype+=v,v==="]"?f.state=b.DOCTYPE:T(v)&&(f.state=b.DOCTYPE_DTD_QUOTED,f.q=v);continue;case b.DOCTYPE_DTD_QUOTED:f.doctype+=v,v===f.q&&(f.state=b.DOCTYPE_DTD,f.q="");continue;case b.COMMENT:v==="-"?f.state=b.COMMENT_ENDING:f.comment+=v;continue;case b.COMMENT_ENDING:v==="-"?(f.state=b.COMMENT_ENDED,f.comment=ce(f.opt,f.comment),f.comment&&B(f,"oncomment",f.comment),f.comment=""):(f.comment+="-"+v,f.state=b.COMMENT);continue;case b.COMMENT_ENDED:v!==">"?(K(f,"Malformed comment"),f.comment+="--"+v,f.state=b.COMMENT):f.state=b.TEXT;continue;case b.CDATA:v==="]"?f.state=b.CDATA_ENDING:f.cdata+=v;continue;case b.CDATA_ENDING:v==="]"?f.state=b.CDATA_ENDING_2:(f.cdata+="]"+v,f.state=b.CDATA);continue;case b.CDATA_ENDING_2:v===">"?(f.cdata&&B(f,"oncdata",f.cdata),B(f,"onclosecdata"),f.cdata="",f.state=b.TEXT):v==="]"?f.cdata+="]":(f.cdata+="]]"+v,f.state=b.CDATA);continue;case b.PROC_INST:v==="?"?f.state=b.PROC_INST_ENDING:m(v)?f.state=b.PROC_INST_BODY:f.procInstName+=v;continue;case b.PROC_INST_BODY:if(!f.procInstBody&&m(v))continue;v==="?"?f.state=b.PROC_INST_ENDING:f.procInstBody+=v;continue;case b.PROC_INST_ENDING:v===">"?(B(f,"onprocessinginstruction",{name:f.procInstName,body:f.procInstBody}),f.procInstName=f.procInstBody="",f.state=b.TEXT):(f.procInstBody+="?"+v,f.state=b.PROC_INST_BODY);continue;case b.OPEN_TAG:N(w,v)?f.tagName+=v:(vm(f),v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:(m(v)||K(f,"Invalid character in tag name"),f.state=b.ATTRIB));continue;case b.OPEN_TAG_SLASH:v===">"?(At(f,!0),Is(f)):(K(f,"Forward-slash in opening tag not followed by >"),f.state=b.ATTRIB);continue;case b.ATTRIB:if(m(v))continue;v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:N(E,v)?(f.attribName=v,f.attribValue="",f.state=b.ATTRIB_NAME):K(f,"Invalid attribute name");continue;case b.ATTRIB_NAME:v==="="?f.state=b.ATTRIB_VALUE:v===">"?(K(f,"Attribute without value"),f.attribValue=f.attribName,Ss(f),At(f)):m(v)?f.state=b.ATTRIB_NAME_SAW_WHITE:N(w,v)?f.attribName+=v:K(f,"Invalid attribute name");continue;case b.ATTRIB_NAME_SAW_WHITE:if(v==="=")f.state=b.ATTRIB_VALUE;else{if(m(v))continue;K(f,"Attribute without value"),f.tag.attributes[f.attribName]="",f.attribValue="",B(f,"onattribute",{name:f.attribName,value:""}),f.attribName="",v===">"?At(f):N(E,v)?(f.attribName=v,f.state=b.ATTRIB_NAME):(K(f,"Invalid attribute name"),f.state=b.ATTRIB)}continue;case b.ATTRIB_VALUE:if(m(v))continue;T(v)?(f.q=v,f.state=b.ATTRIB_VALUE_QUOTED):(K(f,"Unquoted attribute value"),f.state=b.ATTRIB_VALUE_UNQUOTED,f.attribValue=v);continue;case b.ATTRIB_VALUE_QUOTED:if(v!==f.q){v==="&"?f.state=b.ATTRIB_VALUE_ENTITY_Q:f.attribValue+=v;continue}Ss(f),f.q="",f.state=b.ATTRIB_VALUE_CLOSED;continue;case b.ATTRIB_VALUE_CLOSED:m(v)?f.state=b.ATTRIB:v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:N(E,v)?(K(f,"No whitespace between attributes"),f.attribName=v,f.attribValue="",f.state=b.ATTRIB_NAME):K(f,"Invalid attribute name");continue;case b.ATTRIB_VALUE_UNQUOTED:if(!A(v)){v==="&"?f.state=b.ATTRIB_VALUE_ENTITY_U:f.attribValue+=v;continue}Ss(f),v===">"?At(f):f.state=b.ATTRIB;continue;case b.CLOSE_TAG:if(f.tagName)v===">"?Is(f):N(w,v)?f.tagName+=v:f.script?(f.script+="</"+f.tagName,f.tagName="",f.state=b.SCRIPT):(m(v)||K(f,"Invalid tagname in closing tag"),f.state=b.CLOSE_TAG_SAW_WHITE);else{if(m(v))continue;O(E,v)?f.script?(f.script+="</"+v,f.state=b.SCRIPT):K(f,"Invalid tagname in closing tag."):f.tagName=v}continue;case b.CLOSE_TAG_SAW_WHITE:if(m(v))continue;v===">"?Is(f):K(f,"Invalid characters in closing tag");continue;case b.TEXT_ENTITY:case b.ATTRIB_VALUE_ENTITY_Q:case b.ATTRIB_VALUE_ENTITY_U:var $e,xe;switch(f.state){case b.TEXT_ENTITY:$e=b.TEXT,xe="textNode";break;case b.ATTRIB_VALUE_ENTITY_Q:$e=b.ATTRIB_VALUE_QUOTED,xe="attribValue";break;case b.ATTRIB_VALUE_ENTITY_U:$e=b.ATTRIB_VALUE_UNQUOTED,xe="attribValue";break}if(v===";")if(f.opt.unparsedEntities){var Ke=Za(f);f.entity="",f.state=$e,f.write(Ke)}else f[xe]+=Za(f),f.entity="",f.state=$e;else N(f.entity.length?I:S,v)?f.entity+=v:(K(f,"Invalid character in entity name"),f[xe]+="&"+f.entity+v,f.entity="",f.state=$e);continue;default:throw new Error(f,"Unknown state: "+f.state)}return f.position>=f.bufferCheckPosition&&n(f),f}o(Sm,"write");return String.fromCodePoint||(function(){var h=String.fromCharCode,f=Math.floor,R=o(function(){var v=16384,J=[],le,$e,xe=-1,Ke=arguments.length;if(!Ke)return"";for(var Rt="";++xe<Ke;){var Te=Number(arguments[xe]);if(!isFinite(Te)||Te<0||Te>1114111||f(Te)!==Te)throw RangeError("Invalid code point: "+Te);Te<=65535?J.push(Te):(Te-=65536,le=(Te>>10)+55296,$e=Te%1024+56320,J.push(le,$e)),(xe+1===Ke||J.length>v)&&(Rt+=h.apply(null,J),J.length=0)}return Rt},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:R,configurable:!0,writable:!0}):String.fromCodePoint=R})(),t},"initializeSax"),Ow=Cw();var X3=require("@playwright/test");var H3={openai_gpt_4_1:{model:"gpt-4.1-2025-04-14",type:"openai"},openai_gpt_4_1_mini:{model:"gpt-4.1-mini-2025-04-14",type:"openai"},openai_gpt_4_1_nano:{model:"gpt-4.1-nano-2025-04-14",type:"openai"},gemini_2_0_flash:{model:"gemini-2.0-flash",type:"gemini"},gemini_2_5_pro_exp:{model:"gemini-2.5-pro-exp-03-25",type:"gemini"},gemini_2_5_flash:{model:"gemini-2.5-flash",type:"gemini"},gemini_2_5_pro_preview_05_06:{model:"gemini-2.5-pro-preview-05-06",type:"gemini"},claude_sonnet_4:{model:"claude-sonnet-4@20250514",type:"anthropic-vertexai"},claude_sonnet_4_6:{model:"claude-sonnet-4-6",type:"anthropic-vertexai"},claude_sonnet_5:{model:"claude-sonnet-5",type:"anthropic-vertexai"},claude_opus_4_8:{model:"claude-opus-4-8",type:"anthropic-vertexai"},gemini_2_5_flash_lite:{model:"gemini-2.5-flash-lite",type:"gemini"},gemini_3_5_flash:{model:"gemini-3.5-flash",type:"gemini"},gemini_3_1_flash_lite:{model:"gemini-3.1-flash-lite",type:"gemini"}};var Pf=_e(kf());Pf.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var Yw="claude_4",Xw={gemini20flash:{name:"google-vertexai/gemini-2.0-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt41:{name:"openai/gpt-4.1",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25flash:{name:"google-vertexai/gemini-2.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:.7},gemini25flash_lite:{name:"google-vertexai/gemini-2.5-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt4onano:{name:"openai/gpt-4o-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41nano:{name:"openai/gpt-4.1-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41mini:{name:"openai/gpt-4.1-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o3mini:{name:"openai/o3-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o4mini:{name:"openai/o4-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25pro:{name:"google-vertexai/gemini-2.5-pro-preview-05-06",inputTokenLimit:8e5,provider:"gemini",temperature:0},claude37sonnet:{name:"google-vertexai/claude-3-7-sonnet@20250219",inputTokenLimit:15e4,provider:"anthropic",temperature:0},claude4sonnet:{name:"google-vertexai/claude-sonnet-4@20250514",inputTokenLimit:15e4,provider:"anthropic",temperature:1},claudeSonnet46:{name:"google-vertexai/claude-sonnet-4-6",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeSonnet5:{name:"google-vertexai/claude-sonnet-5",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeOpus48:{name:"google-vertexai/claude-opus-4-8",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},gemini35flash:{name:"google-vertexai/gemini-3.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gemini31flashLite:{name:"google-vertexai/gemini-3.1-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gpt4omini:{name:"openai/gpt-4o-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5mini:{name:"openai/gpt-5-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5nano:{name:"openai/gpt-5-nano",inputTokenLimit:8e5,provider:"openai",temperature:0}},Qw=o(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:Yw},models:Xw,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ue=Qw();var Z3={claude_4:ue.models.claude4sonnet,"claude_3.7":ue.models.claude37sonnet,claude_sonnet_4_6:ue.models.claudeSonnet46,claude_sonnet_5:ue.models.claudeSonnet5,claude_opus_4_8:ue.models.claudeOpus48,"gemini_2.5_pro":ue.models.gemini25pro,"gemini_2.0_flash":ue.models.gemini20flash,"gemini_2.5_flash_lite":ue.models.gemini25flash_lite,"gemini_2.5_flash":ue.models.gemini25flash,"gemini_3.5_flash":ue.models.gemini35flash,"gemini_3.1_flash_lite":ue.models.gemini31flashLite,gpt_4o_mini:ue.models.gpt4omini,gpt_4o_nano:ue.models.gpt4onano,gpt_41_nano:ue.models.gpt41nano,gpt_5_mini:ue.models.gpt5mini,gpt_5_nano:ue.models.gpt5nano,gpt_41_mini:ue.models.gpt41mini,gpt_41:ue.models.gpt41,o4_mini:ue.models.o4mini,o3_mini:ue.models.o3mini};var gm=require("child_process"),Vr=require("crypto"),oe=require("fs"),ym=require("fs/promises"),_m=require("stream/promises"),bm=require("http"),Em=_e(require("net")),wm=require("os"),De=require("path");function e0(t){if(t)return{...t,...t.tests?{tests:t.tests.map(e=>{let{errorMessage:r,...n}=e;return n})}:{}}}o(e0,"projectReportStatsForTelemetry");function Lf(t,e,r){t.emit({outcome:e,stats:e0(r)})}o(Lf,"emitReportProcessingStatsTelemetry");var Df=["script","template"],$f='<script id="playwrightReportBase64" type="application/zip">',Uf="</script>";var Vp=require("htmlparser2"),qp=_e(yp()),ye=require("node:fs"),Ht=require("node:path"),Wp=require("node:os"),Kp=require("node:crypto");var _t=_e(require("path")),Ia=require("fs");var Ta=require("path"),as=require("fs");function E0(t,e,r=10){let n=t;for(let s=0;s<r;s++){let i=(0,Ta.join)(n,"package.json");if((0,as.existsSync)(i))try{if(JSON.parse((0,as.readFileSync)(i,"utf8")).name===e)return n}catch{}n=(0,Ta.join)(n,"..")}}o(E0,"findRepositoryRoot");function _p(t,e=10){return E0(t,"checksum-customer-engineering-workspace",e)}o(_p,"findCustomerEngineeringRoot");var xa=_e(Sp());var Me=o((t,e)=>{if(t==null||t==="")return e?.default??!1;let r=t.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:e?.default??!1},"parseBoolean");function Ip(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}o(Ip,"resolveMaxRRwebBytes");var D0=__dirname,xp=_t.join(__dirname,".."),Rp=(0,Ia.existsSync)(xp)?xp:D0;(0,xa.config)({path:_t.resolve(Rp,".env")});var Ap=Me(process.env.CHECKSUM_RUNTIME_DEV_MODE);function $0(){let t=__dirname;for(;!(0,Ia.existsSync)(_t.join(t,"package.json"));)t=_t.join(t,"..");return t}o($0,"findRoot");var Hr=$0(),U0=_p(Hr,10);(0,xa.config)({path:[Rp,U0].filter(t=>!!t).map(t=>_t.resolve(t,".env")),override:!1});var Sa=Me(process.env.CHECKSUM_RUNTIME_REPO_MODE),F0=Sa?_t.join(Hr,"package","pw-report-template.html"):_t.join(Hr,"pw-report-template.html"),B0=Me(process.env.CHECKSUM_DEBUG_ANALYTICS),j0=Me(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),H0=Ip(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),cs={isDevMode:Ap,isRepoMode:Sa,CI:!!process.env.CI,checksumRootFolderBypass:Sa&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(Ap?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:Hr+"/checksumlib.js"},runtimeRoot:Hr,playwrightReporter:{htmlReportTemplatePath:F0},bypassProxyForLocalhost:Me(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:Me(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Me(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Me(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Me(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:H0},monitoring:{debugAnalytics:B0,logToConsole:j0,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Me(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Me(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Me(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:Me(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:Me(process.env.CHECKSUM_RUNTIME_DISABLE_RRWEB_RECORDING),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown"};var vH=require("@playwright/test/reporter");var ar=require("path");var Aa=o((t,e,r)=>`v2:${G0(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),G0=o(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var ls=require("fs"),he=_e(require("typescript"));var z0=/^[0-9a-zA-Z]+$/,V0=5;function Cp(t){return t?t.length===V0&&z0.test(t):!1}o(Cp,"isValidChecksumTestId");var Ra=class{static{o(this,"FileNameExtractionStrategy")}extract(e,r){if(!e)return;let n=e.split("/"),s=n[n.length-1];if(!s||!s.endsWith(".checksum.spec.ts"))return;let a=s.replace(".checksum.spec.ts","").split(" - ").pop();return Cp(a)?a:void 0}},Ca=class{static{o(this,"FileContentExtractionStrategy")}extract(e,r){if(!(!e||!(0,ls.existsSync)(e)))try{let n=(0,ls.readFileSync)(e,"utf-8"),s=he.createSourceFile(e,n,he.ScriptTarget.Latest,!0),i=new Map,a=o(c=>{if(he.isCallExpression(c)&&this.isTestCall(c.expression)){let l=c.arguments[0];if(l&&he.isCallExpression(l)&&he.isIdentifier(l.expression)&&l.expression.text==="defineChecksumTest"){let u=this.extractDefineChecksumTestArgs(l);u&&Cp(u.checksumTestId)&&i.set(u.testTitle,u.checksumTestId)}}he.forEachChild(c,a)},"visit");return a(s),r&&i.has(r)?i.get(r):i.size>0?Array.from(i.values())[0]:void 0}catch{return}}isTestCall(e){return he.isIdentifier(e)&&e.text==="test"?!0:he.isPropertyAccessExpression(e)?he.isIdentifier(e.expression)&&e.expression.text==="test":!1}extractDefineChecksumTestArgs(e){let r=e.arguments;if(r.length<2)return;let n=r[0],s=r[1];if(!n||!s)return;let i=this.extractStringLiteral(n),a=this.extractStringLiteral(s);if(i&&a)return{testTitle:i,checksumTestId:a}}extractStringLiteral(e){if(he.isStringLiteral(e)||he.isNoSubstitutionTemplateLiteral(e))return e.text}},Oa=class{static{o(this,"ChecksumTestIdExtractor")}constructor(e){this.strategies=e??[new Ca,new Ra]}extract(e,r){for(let n of this.strategies){let s=n.extract(e,r);if(s)return s}}};var Op=new Oa;function us(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?Op.extract(t.filePath,t.title):void 0)}o(us,"resolveChecksumTestId");var Ma=o((t,e)=>Object.values(e[t]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),Na=o(t=>typeof t=="number"&&!isNaN(t)?t:0,"getStat");function ka(t,e,r){let n=[],s=0,i=0,a=Na(e.expected)+Na(e.flaky),c=Na(e.unexpected);for(let l of t){let u=q0(l,r);n.push(u),u.recovered&&i++,u.bug&&(s++,u.outcome==="expected"||u.outcome==="flaky"?a--:u.outcome==="unexpected"&&c--)}return{passed:a,failed:c,bug:s,recovered:i,tests:n}}o(ka,"computeReportStats");function q0(t,e){let r=us({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=W0(t),s=K0(t.annotations),i=Ma(t.playwrightTestId,e.playwrightIdToMetadata),a=Z0(r,t,e),c=e.toRelativeFilePath(t.filePath);return{checksumTestId:r,playwrightTestId:t.playwrightTestId,success:t.ok,recovered:i,bug:n,annotations:s,tags:t.tags,outcome:t.outcome,variantKey:Aa(t.filePath,t.titlePath,t.title),...t.filePath!==void 0?{filePath:t.filePath}:{},...c!==void 0?{relativeFilePath:c}:{},...t.projectName?{project:t.projectName}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{},...a!==void 0?{usingChecksumTestIdPlaceholder:a}:{}}}o(q0,"rowToTestWithMetadata");function Np(t,e){let r=t.files,n=o(c=>{let u=us({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},e)??`${c.location.file}::${c.title}`,d=Aa(c.location.file,c.path??[],c.title);return`${u}::${c.projectName}::${d}`},"keyFor"),s=new Map;for(let c of r)for(let l of c.tests)s.set(n(l),l);let i=new Set(s.values()),a={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let c of r){c.tests=c.tests.filter(l=>i.has(l));for(let l of c.tests)a.total++,l.outcome==="expected"?a.expected++:l.outcome==="unexpected"?a.unexpected++:l.outcome==="flaky"?a.flaky++:a.skipped++}t.files=r.filter(c=>c.tests.length>0),t.stats={...t.stats,...a}}o(Np,"dedupeReportByChecksumTestId");var W0=o(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),K0=o(t=>t.filter(e=>!!e?.type).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),Z0=o((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var Mp=o((t,e,r)=>{if(!t)return;let n=r||e,s;if((0,ar.isAbsolute)(t))s=t;else{let i=(0,ar.dirname)(e);s=(0,ar.resolve)(i,t)}return s.replace(n+"/","")},"toRelativeFilePath");var kp=require("node:util");var or=8*1024,Gr=`
|
|
60
|
-
\u2026 [truncated]`,
|
|
57
|
+
Actual: `+h.attribValue);else{var J=h.tag,le=h.tags[h.tags.length-1]||h;J.ns===le.ns&&(J.ns=Object.create(le.ns)),J.ns[v]=h.attribValue}h.attribList.push([h.attribName,h.attribValue])}else h.tag.attributes[h.attribName]=h.attribValue,B(h,"onattribute",{name:h.attribName,value:h.attribValue});h.attribName=h.attribValue=""}o(Ss,"attrib");function At(h,f){if(h.opt.xmlns){var C=h.tag,v=vs(h.tagName);C.prefix=v.prefix,C.local=v.local,C.uri=C.ns[v.prefix]||"",C.prefix&&!C.uri&&(K(h,"Unbound namespace prefix: "+JSON.stringify(h.tagName)),C.uri=v.prefix);var J=h.tags[h.tags.length-1]||h;C.ns&&J.ns!==C.ns&&Object.keys(C.ns).forEach(function(Qa){B(h,"onopennamespace",{prefix:Qa,uri:C.ns[Qa]})});for(var le=0,$e=h.attribList.length;le<$e;le++){var xe=h.attribList[le],Ke=xe[0],Ct=xe[1],Te=vs(Ke,!0),Rt=Te.prefix,Cm=Te.local,Xa=Rt===""?"":C.ns[Rt]||"",xs={name:Ke,value:Ct,prefix:Rt,local:Cm,uri:Xa};Rt&&Rt!=="xmlns"&&!Xa&&(K(h,"Unbound namespace prefix: "+JSON.stringify(Rt)),xs.uri=Rt),h.tag.attributes[Ke]=xs,B(h,"onattribute",xs)}h.attribList.length=0}h.tag.isSelfClosing=!!f,h.sawRoot=!0,h.tags.push(h.tag),B(h,"onopentag",h.tag),f||(!h.noscript&&h.tagName.toLowerCase()==="script"?h.state=b.SCRIPT:h.state=b.TEXT,h.tag=null,h.tagName=""),h.attribName=h.attribValue="",h.attribList.length=0}o(At,"openTag");function Is(h){if(!h.tagName){K(h,"Weird empty close tag."),h.textNode+="</>",h.state=b.TEXT;return}if(h.script){if(h.tagName!=="script"){h.script+="</"+h.tagName+">",h.tagName="",h.state=b.SCRIPT;return}B(h,"onscript",h.script),h.script=""}var f=h.tags.length,C=h.tagName;h.strict||(C=C[h.looseCase]());for(var v=C;f--&&h.tags[f].name!==v;)K(h,"Unexpected close tag");if(f<0){K(h,"Unmatched closing tag: "+h.tagName),h.textNode+="</"+h.tagName+">",h.state=b.TEXT;return}h.tagName=C;for(var J=h.tags.length;J-- >f;){var le=h.tag=h.tags.pop();h.tagName=h.tag.name,B(h,"onclosetag",h.tagName);var $e={};for(var xe in le.ns)$e[xe]=le.ns[xe];var Ke=h.tags[h.tags.length-1]||h;h.opt.xmlns&&le.ns!==Ke.ns&&Object.keys(le.ns).forEach(function(Ct){var Te=le.ns[Ct];B(h,"onclosenamespace",{prefix:Ct,uri:Te})})}f===0&&(h.closedRoot=!0),h.tagName=h.attribValue=h.attribName="",h.attribList.length=0,h.state=b.TEXT}o(Is,"closeTag");function Za(h){var f=h.entity,C=f.toLowerCase(),v,J="";return h.ENTITIES[f]?h.ENTITIES[f]:h.ENTITIES[C]?h.ENTITIES[C]:(f=C,f.charAt(0)==="#"&&(f.charAt(1)==="x"?(f=f.slice(2),v=parseInt(f,16),J=v.toString(16)):(f=f.slice(1),v=parseInt(f,10),J=v.toString(10))),f=f.replace(/^0+/,""),isNaN(v)||J.toLowerCase()!==f?(K(h,"Invalid character entity"),"&"+h.entity+";"):String.fromCodePoint(v))}o(Za,"parseEntity");function Ja(h,f){f==="<"?(h.state=b.OPEN_WAKA,h.startTagPosition=h.position):m(f)||(K(h,"Non-whitespace before first tag."),h.textNode=f,h.state=b.TEXT)}o(Ja,"beginWhiteSpace");function Ya(h,f){var C="";return f<h.length&&(C=h.charAt(f)),C}o(Ya,"charAt");function Am(h){var f=this;if(this.error)throw this.error;if(f.closed)return ke(f,"Cannot write after close. Assign an onready handler.");if(h===null)return xt(f);typeof h=="object"&&(h=h.toString());for(var C=0,v="";v=Ya(h,C++),f.c=v,!!v;)switch(f.trackPosition&&(f.position++,v===`
|
|
58
|
+
`?(f.line++,f.column=0):f.column++),f.state){case b.BEGIN:if(f.state=b.BEGIN_WHITESPACE,v==="\uFEFF")continue;Ja(f,v);continue;case b.BEGIN_WHITESPACE:Ja(f,v);continue;case b.TEXT:if(f.sawRoot&&!f.closedRoot){for(var J=C-1;v&&v!=="<"&&v!=="&";)v=Ya(h,C++),v&&f.trackPosition&&(f.position++,v===`
|
|
59
|
+
`?(f.line++,f.column=0):f.column++);f.textNode+=h.substring(J,C-1)}v==="<"&&!(f.sawRoot&&f.closedRoot&&!f.strict)?(f.state=b.OPEN_WAKA,f.startTagPosition=f.position):(!m(v)&&(!f.sawRoot||f.closedRoot)&&K(f,"Text data outside of root node."),v==="&"?f.state=b.TEXT_ENTITY:f.textNode+=v);continue;case b.SCRIPT:v==="<"?f.state=b.SCRIPT_ENDING:f.script+=v;continue;case b.SCRIPT_ENDING:v==="/"?f.state=b.CLOSE_TAG:(f.script+="<"+v,f.state=b.SCRIPT);continue;case b.OPEN_WAKA:if(v==="!")f.state=b.SGML_DECL,f.sgmlDecl="";else if(!m(v))if(N(E,v))f.state=b.OPEN_TAG,f.tagName=v;else if(v==="/")f.state=b.CLOSE_TAG,f.tagName="";else if(v==="?")f.state=b.PROC_INST,f.procInstName=f.procInstBody="";else{if(K(f,"Unencoded <"),f.startTagPosition+1<f.position){var le=f.position-f.startTagPosition;v=new Array(le).join(" ")+v}f.textNode+="<"+v,f.state=b.TEXT}continue;case b.SGML_DECL:(f.sgmlDecl+v).toUpperCase()===d?(B(f,"onopencdata"),f.state=b.CDATA,f.sgmlDecl="",f.cdata=""):f.sgmlDecl+v==="--"?(f.state=b.COMMENT,f.comment="",f.sgmlDecl=""):(f.sgmlDecl+v).toUpperCase()===p?(f.state=b.DOCTYPE,(f.doctype||f.sawRoot)&&K(f,"Inappropriately located doctype declaration"),f.doctype="",f.sgmlDecl=""):v===">"?(B(f,"onsgmldeclaration",f.sgmlDecl),f.sgmlDecl="",f.state=b.TEXT):(T(v)&&(f.state=b.SGML_DECL_QUOTED),f.sgmlDecl+=v);continue;case b.SGML_DECL_QUOTED:v===f.q&&(f.state=b.SGML_DECL,f.q=""),f.sgmlDecl+=v;continue;case b.DOCTYPE:v===">"?(f.state=b.TEXT,B(f,"ondoctype",f.doctype),f.doctype=!0):(f.doctype+=v,v==="["?f.state=b.DOCTYPE_DTD:T(v)&&(f.state=b.DOCTYPE_QUOTED,f.q=v));continue;case b.DOCTYPE_QUOTED:f.doctype+=v,v===f.q&&(f.q="",f.state=b.DOCTYPE);continue;case b.DOCTYPE_DTD:f.doctype+=v,v==="]"?f.state=b.DOCTYPE:T(v)&&(f.state=b.DOCTYPE_DTD_QUOTED,f.q=v);continue;case b.DOCTYPE_DTD_QUOTED:f.doctype+=v,v===f.q&&(f.state=b.DOCTYPE_DTD,f.q="");continue;case b.COMMENT:v==="-"?f.state=b.COMMENT_ENDING:f.comment+=v;continue;case b.COMMENT_ENDING:v==="-"?(f.state=b.COMMENT_ENDED,f.comment=ce(f.opt,f.comment),f.comment&&B(f,"oncomment",f.comment),f.comment=""):(f.comment+="-"+v,f.state=b.COMMENT);continue;case b.COMMENT_ENDED:v!==">"?(K(f,"Malformed comment"),f.comment+="--"+v,f.state=b.COMMENT):f.state=b.TEXT;continue;case b.CDATA:v==="]"?f.state=b.CDATA_ENDING:f.cdata+=v;continue;case b.CDATA_ENDING:v==="]"?f.state=b.CDATA_ENDING_2:(f.cdata+="]"+v,f.state=b.CDATA);continue;case b.CDATA_ENDING_2:v===">"?(f.cdata&&B(f,"oncdata",f.cdata),B(f,"onclosecdata"),f.cdata="",f.state=b.TEXT):v==="]"?f.cdata+="]":(f.cdata+="]]"+v,f.state=b.CDATA);continue;case b.PROC_INST:v==="?"?f.state=b.PROC_INST_ENDING:m(v)?f.state=b.PROC_INST_BODY:f.procInstName+=v;continue;case b.PROC_INST_BODY:if(!f.procInstBody&&m(v))continue;v==="?"?f.state=b.PROC_INST_ENDING:f.procInstBody+=v;continue;case b.PROC_INST_ENDING:v===">"?(B(f,"onprocessinginstruction",{name:f.procInstName,body:f.procInstBody}),f.procInstName=f.procInstBody="",f.state=b.TEXT):(f.procInstBody+="?"+v,f.state=b.PROC_INST_BODY);continue;case b.OPEN_TAG:N(w,v)?f.tagName+=v:(xm(f),v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:(m(v)||K(f,"Invalid character in tag name"),f.state=b.ATTRIB));continue;case b.OPEN_TAG_SLASH:v===">"?(At(f,!0),Is(f)):(K(f,"Forward-slash in opening tag not followed by >"),f.state=b.ATTRIB);continue;case b.ATTRIB:if(m(v))continue;v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:N(E,v)?(f.attribName=v,f.attribValue="",f.state=b.ATTRIB_NAME):K(f,"Invalid attribute name");continue;case b.ATTRIB_NAME:v==="="?f.state=b.ATTRIB_VALUE:v===">"?(K(f,"Attribute without value"),f.attribValue=f.attribName,Ss(f),At(f)):m(v)?f.state=b.ATTRIB_NAME_SAW_WHITE:N(w,v)?f.attribName+=v:K(f,"Invalid attribute name");continue;case b.ATTRIB_NAME_SAW_WHITE:if(v==="=")f.state=b.ATTRIB_VALUE;else{if(m(v))continue;K(f,"Attribute without value"),f.tag.attributes[f.attribName]="",f.attribValue="",B(f,"onattribute",{name:f.attribName,value:""}),f.attribName="",v===">"?At(f):N(E,v)?(f.attribName=v,f.state=b.ATTRIB_NAME):(K(f,"Invalid attribute name"),f.state=b.ATTRIB)}continue;case b.ATTRIB_VALUE:if(m(v))continue;T(v)?(f.q=v,f.state=b.ATTRIB_VALUE_QUOTED):(K(f,"Unquoted attribute value"),f.state=b.ATTRIB_VALUE_UNQUOTED,f.attribValue=v);continue;case b.ATTRIB_VALUE_QUOTED:if(v!==f.q){v==="&"?f.state=b.ATTRIB_VALUE_ENTITY_Q:f.attribValue+=v;continue}Ss(f),f.q="",f.state=b.ATTRIB_VALUE_CLOSED;continue;case b.ATTRIB_VALUE_CLOSED:m(v)?f.state=b.ATTRIB:v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:N(E,v)?(K(f,"No whitespace between attributes"),f.attribName=v,f.attribValue="",f.state=b.ATTRIB_NAME):K(f,"Invalid attribute name");continue;case b.ATTRIB_VALUE_UNQUOTED:if(!A(v)){v==="&"?f.state=b.ATTRIB_VALUE_ENTITY_U:f.attribValue+=v;continue}Ss(f),v===">"?At(f):f.state=b.ATTRIB;continue;case b.CLOSE_TAG:if(f.tagName)v===">"?Is(f):N(w,v)?f.tagName+=v:f.script?(f.script+="</"+f.tagName,f.tagName="",f.state=b.SCRIPT):(m(v)||K(f,"Invalid tagname in closing tag"),f.state=b.CLOSE_TAG_SAW_WHITE);else{if(m(v))continue;O(E,v)?f.script?(f.script+="</"+v,f.state=b.SCRIPT):K(f,"Invalid tagname in closing tag."):f.tagName=v}continue;case b.CLOSE_TAG_SAW_WHITE:if(m(v))continue;v===">"?Is(f):K(f,"Invalid characters in closing tag");continue;case b.TEXT_ENTITY:case b.ATTRIB_VALUE_ENTITY_Q:case b.ATTRIB_VALUE_ENTITY_U:var $e,xe;switch(f.state){case b.TEXT_ENTITY:$e=b.TEXT,xe="textNode";break;case b.ATTRIB_VALUE_ENTITY_Q:$e=b.ATTRIB_VALUE_QUOTED,xe="attribValue";break;case b.ATTRIB_VALUE_ENTITY_U:$e=b.ATTRIB_VALUE_UNQUOTED,xe="attribValue";break}if(v===";")if(f.opt.unparsedEntities){var Ke=Za(f);f.entity="",f.state=$e,f.write(Ke)}else f[xe]+=Za(f),f.entity="",f.state=$e;else N(f.entity.length?I:S,v)?f.entity+=v:(K(f,"Invalid character in entity name"),f[xe]+="&"+f.entity+v,f.entity="",f.state=$e);continue;default:throw new Error(f,"Unknown state: "+f.state)}return f.position>=f.bufferCheckPosition&&n(f),f}o(Am,"write");return String.fromCodePoint||(function(){var h=String.fromCharCode,f=Math.floor,C=o(function(){var v=16384,J=[],le,$e,xe=-1,Ke=arguments.length;if(!Ke)return"";for(var Ct="";++xe<Ke;){var Te=Number(arguments[xe]);if(!isFinite(Te)||Te<0||Te>1114111||f(Te)!==Te)throw RangeError("Invalid code point: "+Te);Te<=65535?J.push(Te):(Te-=65536,le=(Te>>10)+55296,$e=Te%1024+56320,J.push(le,$e)),(xe+1===Ke||J.length>v)&&(Ct+=h.apply(null,J),J.length=0)}return Ct},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:C,configurable:!0,writable:!0}):String.fromCodePoint=C})(),t},"initializeSax"),kw=Mw();var s5=require("@playwright/test");var K3={openai_gpt_4_1:{model:"gpt-4.1-2025-04-14",type:"openai"},openai_gpt_4_1_mini:{model:"gpt-4.1-mini-2025-04-14",type:"openai"},openai_gpt_4_1_nano:{model:"gpt-4.1-nano-2025-04-14",type:"openai"},gemini_2_0_flash:{model:"gemini-2.0-flash",type:"gemini"},gemini_2_5_pro_exp:{model:"gemini-2.5-pro-exp-03-25",type:"gemini"},gemini_2_5_flash:{model:"gemini-2.5-flash",type:"gemini"},gemini_2_5_pro_preview_05_06:{model:"gemini-2.5-pro-preview-05-06",type:"gemini"},claude_sonnet_4:{model:"claude-sonnet-4@20250514",type:"anthropic-vertexai"},claude_sonnet_4_6:{model:"claude-sonnet-4-6",type:"anthropic-vertexai"},claude_sonnet_5:{model:"claude-sonnet-5",type:"anthropic-vertexai"},claude_opus_4_8:{model:"claude-opus-4-8",type:"anthropic-vertexai"},gemini_2_5_flash_lite:{model:"gemini-2.5-flash-lite",type:"gemini"},gemini_3_5_flash:{model:"gemini-3.5-flash",type:"gemini"},gemini_3_1_flash_lite:{model:"gemini-3.1-flash-lite",type:"gemini"}};var Pf=_e(kf());Pf.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var e0="claude_4",t0={gemini20flash:{name:"google-vertexai/gemini-2.0-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt41:{name:"openai/gpt-4.1",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25flash:{name:"google-vertexai/gemini-2.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:.7},gemini25flash_lite:{name:"google-vertexai/gemini-2.5-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt4onano:{name:"openai/gpt-4o-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41nano:{name:"openai/gpt-4.1-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41mini:{name:"openai/gpt-4.1-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o3mini:{name:"openai/o3-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o4mini:{name:"openai/o4-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25pro:{name:"google-vertexai/gemini-2.5-pro-preview-05-06",inputTokenLimit:8e5,provider:"gemini",temperature:0},claude37sonnet:{name:"google-vertexai/claude-3-7-sonnet@20250219",inputTokenLimit:15e4,provider:"anthropic",temperature:0},claude4sonnet:{name:"google-vertexai/claude-sonnet-4@20250514",inputTokenLimit:15e4,provider:"anthropic",temperature:1},claudeSonnet46:{name:"google-vertexai/claude-sonnet-4-6",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeSonnet5:{name:"google-vertexai/claude-sonnet-5",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeOpus48:{name:"google-vertexai/claude-opus-4-8",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},gemini35flash:{name:"google-vertexai/gemini-3.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gemini31flashLite:{name:"google-vertexai/gemini-3.1-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gpt4omini:{name:"openai/gpt-4o-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5mini:{name:"openai/gpt-5-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5nano:{name:"openai/gpt-5-nano",inputTokenLimit:8e5,provider:"openai",temperature:0}},r0=o(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:e0},models:t0,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ue=r0();var t5={claude_4:ue.models.claude4sonnet,"claude_3.7":ue.models.claude37sonnet,claude_sonnet_4_6:ue.models.claudeSonnet46,claude_sonnet_5:ue.models.claudeSonnet5,claude_opus_4_8:ue.models.claudeOpus48,"gemini_2.5_pro":ue.models.gemini25pro,"gemini_2.0_flash":ue.models.gemini20flash,"gemini_2.5_flash_lite":ue.models.gemini25flash_lite,"gemini_2.5_flash":ue.models.gemini25flash,"gemini_3.5_flash":ue.models.gemini35flash,"gemini_3.1_flash_lite":ue.models.gemini31flashLite,gpt_4o_mini:ue.models.gpt4omini,gpt_4o_nano:ue.models.gpt4onano,gpt_41_nano:ue.models.gpt41nano,gpt_5_mini:ue.models.gpt5mini,gpt_5_nano:ue.models.gpt5nano,gpt_41_mini:ue.models.gpt41mini,gpt_41:ue.models.gpt41,o4_mini:ue.models.o4mini,o3_mini:ue.models.o3mini};var bm=require("child_process"),Vr=require("crypto"),oe=require("fs"),Em=require("fs/promises"),wm=require("stream/promises"),Tm=require("http"),vm=_e(require("net")),Sm=require("os"),De=require("path");function n0(t){if(t)return{...t,...t.tests?{tests:t.tests.map(e=>{let{errorMessage:r,...n}=e;return n})}:{}}}o(n0,"projectReportStatsForTelemetry");function Lf(t,e,r){t.emit({outcome:e,stats:n0(r)})}o(Lf,"emitReportProcessingStatsTelemetry");var Df=["script","template"],$f='<script id="playwrightReportBase64" type="application/zip">',Uf="</script>";var Vp=require("htmlparser2"),Wp=_e(yp()),ye=require("node:fs"),Ht=require("node:path"),qp=require("node:os"),Kp=require("node:crypto");var _t=_e(require("path")),Ia=require("fs");var Ta=require("path"),as=require("fs");function v0(t,e,r=10){let n=t;for(let s=0;s<r;s++){let i=(0,Ta.join)(n,"package.json");if((0,as.existsSync)(i))try{if(JSON.parse((0,as.readFileSync)(i,"utf8")).name===e)return n}catch{}n=(0,Ta.join)(n,"..")}}o(v0,"findRepositoryRoot");function _p(t,e=10){return v0(t,"checksum-customer-engineering-workspace",e)}o(_p,"findCustomerEngineeringRoot");var xa=_e(Sp());var Me=o((t,e)=>{if(t==null||t==="")return e?.default??!1;let r=t.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:e?.default??!1},"parseBoolean");function Ip(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}o(Ip,"resolveMaxRRwebBytes");var F0=__dirname,xp=_t.join(__dirname,".."),Cp=(0,Ia.existsSync)(xp)?xp:F0;(0,xa.config)({path:_t.resolve(Cp,".env")});var Ap=Me(process.env.CHECKSUM_RUNTIME_DEV_MODE);function B0(){let t=__dirname;for(;!(0,Ia.existsSync)(_t.join(t,"package.json"));)t=_t.join(t,"..");return t}o(B0,"findRoot");var Hr=B0(),j0=_p(Hr,10);(0,xa.config)({path:[Cp,j0].filter(t=>!!t).map(t=>_t.resolve(t,".env")),override:!1});var Sa=Me(process.env.CHECKSUM_RUNTIME_REPO_MODE),H0=Sa?_t.join(Hr,"package","pw-report-template.html"):_t.join(Hr,"pw-report-template.html"),G0=Me(process.env.CHECKSUM_DEBUG_ANALYTICS),z0=Me(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),V0=Ip(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),cs={isDevMode:Ap,isRepoMode:Sa,CI:!!process.env.CI,checksumRootFolderBypass:Sa&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(Ap?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:Hr+"/checksumlib.js"},runtimeRoot:Hr,playwrightReporter:{htmlReportTemplatePath:H0},bypassProxyForLocalhost:Me(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:Me(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Me(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Me(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Me(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:V0},monitoring:{debugAnalytics:G0,logToConsole:z0,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Me(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Me(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Me(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:Me(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:Me(process.env.CHECKSUM_RUNTIME_DISABLE_RRWEB_RECORDING),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown"};var RH=require("@playwright/test/reporter");var ar=require("path");var Aa=o((t,e,r)=>`v2:${W0(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),W0=o(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var ls=require("fs"),he=_e(require("typescript"));var q0=/^[0-9a-zA-Z]+$/,K0=5;function Rp(t){return t?t.length===K0&&q0.test(t):!1}o(Rp,"isValidChecksumTestId");var Ca=class{static{o(this,"FileNameExtractionStrategy")}extract(e,r){if(!e)return;let n=e.split("/"),s=n[n.length-1];if(!s||!s.endsWith(".checksum.spec.ts"))return;let a=s.replace(".checksum.spec.ts","").split(" - ").pop();return Rp(a)?a:void 0}},Ra=class{static{o(this,"FileContentExtractionStrategy")}extract(e,r){if(!(!e||!(0,ls.existsSync)(e)))try{let n=(0,ls.readFileSync)(e,"utf-8"),s=he.createSourceFile(e,n,he.ScriptTarget.Latest,!0),i=new Map,a=o(c=>{if(he.isCallExpression(c)&&this.isTestCall(c.expression)){let l=c.arguments[0];if(l&&he.isCallExpression(l)&&he.isIdentifier(l.expression)&&l.expression.text==="defineChecksumTest"){let u=this.extractDefineChecksumTestArgs(l);u&&Rp(u.checksumTestId)&&i.set(u.testTitle,u.checksumTestId)}}he.forEachChild(c,a)},"visit");return a(s),r&&i.has(r)?i.get(r):i.size>0?Array.from(i.values())[0]:void 0}catch{return}}isTestCall(e){return he.isIdentifier(e)&&e.text==="test"?!0:he.isPropertyAccessExpression(e)?he.isIdentifier(e.expression)&&e.expression.text==="test":!1}extractDefineChecksumTestArgs(e){let r=e.arguments;if(r.length<2)return;let n=r[0],s=r[1];if(!n||!s)return;let i=this.extractStringLiteral(n),a=this.extractStringLiteral(s);if(i&&a)return{testTitle:i,checksumTestId:a}}extractStringLiteral(e){if(he.isStringLiteral(e)||he.isNoSubstitutionTemplateLiteral(e))return e.text}},Oa=class{static{o(this,"ChecksumTestIdExtractor")}constructor(e){this.strategies=e??[new Ra,new Ca]}extract(e,r){for(let n of this.strategies){let s=n.extract(e,r);if(s)return s}}};var Op=new Oa;function us(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?Op.extract(t.filePath,t.title):void 0)}o(us,"resolveChecksumTestId");var Ma=o((t,e)=>Object.values(e[t]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),Na=o(t=>typeof t=="number"&&!isNaN(t)?t:0,"getStat");function ka(t,e,r){let n=[],s=0,i=0,a=Na(e.expected)+Na(e.flaky),c=Na(e.unexpected);for(let l of t){let u=Z0(l,r);n.push(u),u.recovered&&i++,u.bug&&(s++,u.outcome==="expected"||u.outcome==="flaky"?a--:u.outcome==="unexpected"&&c--)}return{passed:a,failed:c,bug:s,recovered:i,tests:n}}o(ka,"computeReportStats");function Z0(t,e){let r=us({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=J0(t),s=Y0(t.annotations),i=Ma(t.playwrightTestId,e.playwrightIdToMetadata),a=X0(r,t,e),c=e.toRelativeFilePath(t.filePath);return{checksumTestId:r,playwrightTestId:t.playwrightTestId,success:t.ok,recovered:i,bug:n,annotations:s,tags:t.tags,outcome:t.outcome,variantKey:Aa(t.filePath,t.titlePath,t.title),...t.filePath!==void 0?{filePath:t.filePath}:{},...c!==void 0?{relativeFilePath:c}:{},...t.projectName?{project:t.projectName}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{},...a!==void 0?{usingChecksumTestIdPlaceholder:a}:{}}}o(Z0,"rowToTestWithMetadata");function Np(t,e){let r=t.files,n=o(c=>{let u=us({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},e)??`${c.location.file}::${c.title}`,d=Aa(c.location.file,c.path??[],c.title);return`${u}::${c.projectName}::${d}`},"keyFor"),s=new Map;for(let c of r)for(let l of c.tests)s.set(n(l),l);let i=new Set(s.values()),a={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let c of r){c.tests=c.tests.filter(l=>i.has(l));for(let l of c.tests)a.total++,l.outcome==="expected"?a.expected++:l.outcome==="unexpected"?a.unexpected++:l.outcome==="flaky"?a.flaky++:a.skipped++}t.files=r.filter(c=>c.tests.length>0),t.stats={...t.stats,...a}}o(Np,"dedupeReportByChecksumTestId");var J0=o(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),Y0=o(t=>t.filter(e=>!!e?.type).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),X0=o((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var Mp=o((t,e,r)=>{if(!t)return;let n=r||e,s;if((0,ar.isAbsolute)(t))s=t;else{let i=(0,ar.dirname)(e);s=(0,ar.resolve)(i,t)}return s.replace(n+"/","")},"toRelativeFilePath");var kp=require("node:util");var or=8*1024,Gr=`
|
|
60
|
+
\u2026 [truncated]`,Q0=/[\u001b\u0080-\u009f]/g;function Pa(t){let e=t.replaceAll("\0","");return eT((0,kp.stripVTControlCharacters)(e))}o(Pa,"sanitizeTestErrorMessage");function eT(t){return t.replace(Q0,"")}o(eT,"removeResidualVTControls");function ds(t){let e=Pa(t);if(Buffer.byteLength(e,"utf8")<=or)return{value:e,truncated:!1};let r=or-Buffer.byteLength(Gr,"utf8"),n="",s=0;for(let i of e){let a=Buffer.byteLength(i,"utf8");if(s+a>r)break;n+=i,s+=a}return{value:n+Gr,truncated:!0}}o(ds,"boundTestErrorMessage");var Lp=require("node:crypto");var tT=new Set(["failed","timedOut","interrupted"]),La=new WeakMap;function Dp(){let t={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return La.set(t,new Map),t}o(Dp,"createErrorDetailIndex");function $p(t,e){try{let r=rT(t);if(!r||nT(r.tests))return!1;for(let n of r.tests){if(!cr(n))continue;let s=Hp(n.projectName),i=n.testId;if(s===void 0||!fs(i))continue;let a=sT(n);if(!a)continue;let c=aT(a);c.truncated&&(e.truncatedCount+=1),lT(e,jp(r.fileId,s,i),c.value,cT(a))}return!0}catch{return!1}}o($p,"addTestFileErrorDetails");function Up(t){return cr(t)&&Object.prototype.hasOwnProperty.call(t,"fileId")&&Object.prototype.hasOwnProperty.call(t,"tests")}o(Up,"isTestFileErrorDetailCandidate");function Fp(t,e,r,n){let s=Hp(r);if(!fs(e)||s===void 0||!fs(n))return;let i=jp(e,s,n);if(!t.ambiguousKeys.has(i))return t.messages.get(i)}o(Fp,"getTestErrorMessage");function rT(t){if(!cr(t))return;let e=t.fileId,r=t.tests;if(!(!fs(e)||!Array.isArray(r)))return{fileId:e,tests:r}}o(rT,"parseTestFile");function nT(t){return t.length>0&&!t.some(cr)}o(nT,"hasOnlyMalformedTests");function sT(t){let e=t.results;if(!Array.isArray(e))return;let r=e.at(-1);if(!cr(r))return;let n=r.status;if(typeof n!="string"||!tT.has(n))return;let s=r.errors;if(Array.isArray(s))for(let i of s){let a=iT(i);if(a)return a}}o(sT,"extractFinalErrorDetail");function iT(t){if(typeof t=="string"){let n=Bp(t);return n?{message:n}:void 0}if(!cr(t))return;let e=Pp(t.message,t.value),r=Pp(t.codeframe,t.snippet);return e?!r||e.includes(r)?{message:e}:{message:e,frame:r}:r?{frame:r}:void 0}o(iT,"normalizeError");function aT(t){let{message:e,frame:r}=t;if(!e)return ds(r??"");if(!r)return ds(e);let n=Buffer.byteLength(e,"utf8");if(n>or)return ds(e);let s=`
|
|
61
61
|
|
|
62
|
-
`,i=Buffer.byteLength(s,"utf8"),a=Buffer.byteLength(r,"utf8");if(n+i+a<=or)return{value:`${e}${s}${r}`,truncated:!1};let c=i+Buffer.byteLength(Gr,"utf8"),l=or-n;if(l<c)return{value:e,truncated:!0};let u=
|
|
62
|
+
`,i=Buffer.byteLength(s,"utf8"),a=Buffer.byteLength(r,"utf8");if(n+i+a<=or)return{value:`${e}${s}${r}`,truncated:!1};let c=i+Buffer.byteLength(Gr,"utf8"),l=or-n;if(l<c)return{value:e,truncated:!0};let u=oT(r,l-c);return{value:`${e}${s}${u}${Gr}`,truncated:!0}}o(aT,"boundNormalizedErrorDetail");function oT(t,e){let r="",n=0;for(let s of t){let i=Buffer.byteLength(s,"utf8");if(n+i>e)break;r+=s,n+=i}return r}o(oT,"utf8Prefix");function cT(t){let e=(0,Lp.createHash)("sha256");return t.message&&e.update(t.message,"utf8"),t.message&&t.frame&&e.update(`
|
|
63
63
|
|
|
64
|
-
`,"utf8"),t.frame&&e.update(t.frame,"utf8"),e.digest("hex")}o(iT,"digestNormalizedErrorDetail");function Bp(t){let e=Pa(t);return e.trim().length===0?"":e.replace(/^(?:[^\S\r\n]*(?:\r\n|\r|\n))+/u,"").replace(/(?:(?:\r\n|\r|\n)[^\S\r\n]*)+$/u,"")}o(Bp,"normalizeErrorText");function aT(t,e,r,n){if(t.ambiguousKeys.has(e))return;let s=La.get(t);if(s||(s=new Map,La.set(t,s)),t.messages.get(e)===void 0){t.messages.set(e,r),s.set(e,n);return}s.get(e)!==n&&(t.messages.delete(e),s.delete(e),t.ambiguousKeys.add(e),t.identityConflictCount+=1)}o(aT,"addErrorDetail");function jp(t,e,r){return JSON.stringify([t,e,r])}o(jp,"createIdentityKey");function Pp(...t){for(let e of t){if(typeof e!="string")continue;let r=Bp(e);if(r)return r}}o(Pp,"firstMeaningfulString");function cr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(cr,"isRecord");function Hp(t){return t==null||t===""?"":typeof t=="string"?t:void 0}o(Hp,"normalizeProjectName");function fs(t){return typeof t=="string"&&t.length>0}o(fs,"isNonEmptyString");var oT=o(t=>Number.isSafeInteger(t)&&t>=0?Math.min(t,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),cT=o(t=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(t)}`,"utf8"),"serializedErrorMessagePropertyBytes");function Gp(t,e=8388608){let r=oT(e),n=0,s=t.tests?.map(i=>{if(i.errorMessage===void 0)return i;let a=cT(i.errorMessage);if(a<=r)return r-=a,i;n+=1;let c={...i};return delete c.errorMessage,c});return{stats:{...t,...s!==void 0?{tests:s}:{}},omittedCount:n}}o(Gp,"applyErrorDetailsPayloadBudget");var zp=o(t=>Df.includes(t),"isPayloadTag"),uT=o((t,e)=>t.files.flatMap(r=>r.tests.map(n=>{let s=e?Fp(e,r.fileId,n.projectName,n.testId):void 0;return{playwrightTestId:n.testId,ok:!!n.ok,outcome:n.outcome,title:n.title,titlePath:n.path??[],filePath:n.location?.file,...n.projectName?{projectName:n.projectName}:{},tags:n.tags??[],annotations:n.annotations??[],...s?{errorMessage:s}:{}}})),"htmlReportToRows"),ps=class t{constructor(e,r,n,s={},i={},a,c,l,u={}){this.reportHTMLFilePath=e;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=s;this.channel=a;this.checksumTestIdToUsingPlaceholder=u;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...i},this.checksumRoot=c||(0,Ht.dirname)((0,Ht.dirname)(e)),this.projectRoot=l||this.checksumRoot}static{o(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let e=0;try{e=(0,ye.statSync)(this.reportHTMLFilePath)?.size||0,this.channel.debug(`Report HTML file size approximately ${e} bytes`)}catch(i){this.channel.debug(`Failed to retrieve file size for ${this.reportHTMLFilePath}`,i)}let r=(0,Ht.join)((0,Wp.tmpdir)(),`pw-report-${(0,Kp.randomUUID)()}.zip`),n=o(()=>{try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{}},"cleanupFile"),s={sigterm:o(()=>{n(),process.exit(143)},"sigterm"),sigint:o(()=>{n(),process.exit(130)},"sigint"),exit:n};process.once("SIGTERM",s.sigterm),process.once("SIGINT",s.sigint),process.once("exit",s.exit);try{this.channel.debug("Extracting base64 to temp ZIP file...");let i=Date.now();await this.extractBase64ToFile(r);let a=Date.now()-i;this.channel.debug("Modifying ZIP file...");let c=Date.now(),l=this.modifyZipFile(r),u=Date.now()-c;this.channel.debug("Writing output HTML...");let d=Date.now();await this.writeOutputWithStreamedZip(r);let p=Date.now()-d;return{report_html_bytes:e,extract_ms:a,modify_ms:u,write_ms:p,entry_count:l.entryCount,json_entry_count:l.jsonEntryCount,largest_entry_bytes:l.largestEntryBytes,largest_entry_name:l.largestEntryName,error_details_extracted:l.errorDetailsExtracted,error_details_truncated:l.errorDetailsTruncated,error_detail_parse_failures:l.errorDetailParseFailures,error_detail_identity_conflicts:l.errorDetailIdentityConflicts,error_details_payload_budget_omitted:l.errorDetailsPayloadBudgetOmitted}}finally{process.removeListener("SIGTERM",s.sigterm),process.removeListener("SIGINT",s.sigint),process.removeListener("exit",s.exit);try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{this.channel.debug(`Failed to cleanup temp file: ${r}`)}}}async extractBase64ToFile(e){return new Promise((r,n)=>{let s=!1,i=!1,a=!1,c=[],l=0,u=(0,ye.createWriteStream)(e);u.on("error",g=>{if(!i){i=!0;try{_.destroyed||_.destroy(),p.end()}catch{}n(g)}});let d=o(()=>{if(l<4)return;let g=c.join("");c.length=0,a||(g=g.replace("data:application/zip;base64,",""),a=!0);let y=Math.floor(g.length/4)*4,E=g.slice(0,y),w=g.slice(y);if(w.length>0?(c.push(w),l=w.length):l=0,E.length>0){let S=Buffer.from(E,"base64");u.write(S)}},"flushBuffer"),p=new Vp.Parser({onopentag:o((g,y)=>{zp(g)&&y.id==="playwrightReportBase64"&&(s=!0)},"onopentag"),ontext:o(g=>{s&&(c.push(g),l+=g.length,l>1024*1024&&d())},"ontext"),onclosetag:o(g=>{if(zp(g)&&s&&!i){if(i=!0,l>0){let y=c.join("");if(a||(y=y.replace("data:application/zip;base64,","")),y.length>0){let E=Buffer.from(y,"base64");u.write(E)}}try{_.destroyed||_.destroy()}catch{}u.end(()=>r())}},"onclosetag"),onerror:o(g=>{if(!i){i=!0;try{p.end(),_.destroyed||_.destroy(),u.destroyed||u.destroy()}catch{}n(g)}},"onerror")}),_=(0,ye.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});_.on("data",g=>p.write(g.toString())),_.on("end",()=>{if(p.end(),!i){i=!0;try{u.destroyed||u.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),_.on("error",g=>{if(!i){i=!0;try{p.end(),u.destroyed||u.destroy()}catch{}n(g)}})})}modifyZipFile(e){let r=new qp.default(e),n=r.getEntries(),s=Dp(),i,a,c=0,l=0,u=0,d="";for(let _ of n){if(_.isDirectory||!_.entryName.endsWith(".json"))continue;let g=_.getData().toString("utf8");if(l+=1,g.length>u&&(u=g.length,d=_.entryName),_.entryName==="report.json")i=JSON.parse(g),a=_;else{let y=this.replaceAttachmentPaths(g);_.setData(Buffer.from(y,"utf8"));try{let E=JSON.parse(y);Up(E)&&!$p(E,s)&&(c+=1)}catch{c+=1}}}if(!i||!a)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&Np(i,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(i),this.report=i;let p=this.extractStats(i,s);return a.setData(Buffer.from(JSON.stringify(i),"utf8")),r.writeZip(e),{entryCount:n.length,jsonEntryCount:l,largestEntryBytes:u,largestEntryName:d,errorDetailsExtracted:s.messages.size,errorDetailsTruncated:s.truncatedCount,errorDetailParseFailures:c,errorDetailIdentityConflicts:s.identityConflictCount,errorDetailsPayloadBudgetOmitted:p}}replaceAttachmentPaths(e){return e.replace(/"path"\s*:\s*"([^"]+)"/g,(r,n)=>n.startsWith("http://")||n.startsWith("https://")?r:`"path":"${this.makeAttachmentPath(n)}"`)}async writeOutputWithStreamedZip(e){let r=this.getTemplate(),n=this.getProcessedFilePath(),s=n.replace(".html",".backup.html");(0,ye.copyFileSync)(n,s);let i=(0,ye.createWriteStream)(n);await new Promise((a,c)=>{i.on("error",c),i.write(r),i.write($f+"data:application/zip;base64,");let l=(0,ye.createReadStream)(e,{highWaterMark:3*1024*1024});l.on("data",u=>{let p=(typeof u=="string"?Buffer.from(u):u).toString("base64");i.write(p)||l.pause()}),i.on("drain",()=>{l.resume()}),l.on("end",()=>{i.write(Uf),i.end(()=>a())}),l.on("error",u=>{try{i.destroyed||i.destroy()}catch{}c(u)}),i.on("error",u=>{try{l.destroyed||l.destroy()}catch{}c(u)})})}testHasTrace(e,r){try{if(!this.report)return!0;let n=Object.keys(this.pwTestIdToChecksumTestId??{}).find(i=>this.pwTestIdToChecksumTestId[i]===e);if(!n)return!0;let s=o(i=>i.some(a=>a.attachments?.some(c=>c.name==="trace")),"hasTrace");for(let i of this.report.files)for(let a of i.tests)if(a.testId===n&&a.projectName===r&&s(a.results))return!0;return!1}catch(n){return this.channel.debug("Failed to check if test has trace, assuming trace exists",n),!0}}getProcessedFilePath(){return this.reportHTMLFilePath}getTemplate(){return t.templateCache||(t.templateCache=(0,ye.readFileSync)(cs.playwrightReporter.htmlReportTemplatePath,"utf-8")),t.templateCache}getReportsStats(){return this.stats}extractStats(e,r){if(!e.stats)return 0;let n=ka(uT(e,r),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:o(i=>Mp(i,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),s=Gp(n,this.config.errorDetailsPayloadBudgetBytes??8388608);return this.stats=s.stats,s.omittedCount}makeAttachmentPath(e){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,Ht.basename)(e)}`:e}handleReportJSON(e){let r={},n=o(s=>{let i=s.testId,a=this.playwrightIdToMetadata[i];a&&(r[i]=a);let c=us({playwrightTestId:s.testId,filePath:s.location?.file,title:s.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});c!==void 0&&(s.checksumTestId=c),s.results.forEach(l=>{this.processAttachments(l.attachments)})},"getChecksumMetadataForPWTestId");e.files.forEach(s=>{s.tests.forEach(n)}),e.checksumMetadata=r}processAttachments(e){if(e.forEach(r=>this.updateAttachment(r)),!this.supportVideo){let r=e.findIndex(n=>n.name==="video");r!==-1&&e.splice(r,1)}}updateAttachment(e){e.path&&(e.path=this.makeAttachmentPath(e.path))}};var Da={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},dT={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},KH=Object.fromEntries(Object.entries(dT).map(t=>t.reverse())),fT={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},ZH=Object.fromEntries(Object.entries(fT).map(t=>t.reverse()));var JH={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},YH={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var Es=require("fs"),um=require("path"),dm=require("stream");var Zp=o(t=>{if(t.error!=null)return"ERROR";let e=t.status_code;if(typeof e=="number"&&e>=500)return"ERROR";let r=t.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var $a=require("fs");var Jp="\x1B[31m",pT="\x1B[33m",mT="\x1B[32m",hT="\x1B[36m",gT="\x1B[2m",yT="\x1B[1m",zr="\x1B[0m",_T=o(()=>{let t=process.env.WIDE_EVENT_PRETTY;return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),bT=new Set(["severity","message","kind","timestamp","_startedAtMs"]),ET=o(t=>{let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n})},"safeStringify"),wT=o(t=>t==="ERROR"||t==="CRITICAL"?Jp:t==="WARNING"?pT:mT,"colorForSeverity"),TT=o(t=>{let e=String(t.severity??"INFO"),r=`${wT(e)}${e.padEnd(5)}${zr}`,n=t.kind?`${hT}${t.kind}${zr}`:"",s=String(t.message??""),i=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Jp}${d.type??"Error"}: ${d.message??""}${zr}`})():"",a=["outcome","test_suite_run_id","status"],c=Object.entries(t).filter(([d,p])=>!bT.has(d)&&p!=null&&d!=="error"&&typeof p!="object"),l=o(d=>{let p=a.indexOf(d);return p===-1?a.length:p},"rank"),u=c.sort(([d],[p])=>l(d)-l(p)).slice(0,8).map(([d,p])=>`${gT}${d}=${zr}${p}`).join(" ");return[r,yT+n+zr,s,u,i].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),vT=o(t=>{let e=t.trace_id;if(typeof e!="string"||e==="")return t;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...t,"logging.googleapis.com/trace":`projects/${r}/traces/${e}`}:t},"withGcpTraceField"),Yp=o(t=>{let e=_T()?TT(t):ET(vT(t));(0,$a.writeSync)(1,e+`
|
|
64
|
+
`,"utf8"),t.frame&&e.update(t.frame,"utf8"),e.digest("hex")}o(cT,"digestNormalizedErrorDetail");function Bp(t){let e=Pa(t);return e.trim().length===0?"":e.replace(/^(?:[^\S\r\n]*(?:\r\n|\r|\n))+/u,"").replace(/(?:(?:\r\n|\r|\n)[^\S\r\n]*)+$/u,"")}o(Bp,"normalizeErrorText");function lT(t,e,r,n){if(t.ambiguousKeys.has(e))return;let s=La.get(t);if(s||(s=new Map,La.set(t,s)),t.messages.get(e)===void 0){t.messages.set(e,r),s.set(e,n);return}s.get(e)!==n&&(t.messages.delete(e),s.delete(e),t.ambiguousKeys.add(e),t.identityConflictCount+=1)}o(lT,"addErrorDetail");function jp(t,e,r){return JSON.stringify([t,e,r])}o(jp,"createIdentityKey");function Pp(...t){for(let e of t){if(typeof e!="string")continue;let r=Bp(e);if(r)return r}}o(Pp,"firstMeaningfulString");function cr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(cr,"isRecord");function Hp(t){return t==null||t===""?"":typeof t=="string"?t:void 0}o(Hp,"normalizeProjectName");function fs(t){return typeof t=="string"&&t.length>0}o(fs,"isNonEmptyString");var uT=o(t=>Number.isSafeInteger(t)&&t>=0?Math.min(t,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),dT=o(t=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(t)}`,"utf8"),"serializedErrorMessagePropertyBytes");function Gp(t,e=8388608){let r=uT(e),n=0,s=t.tests?.map(i=>{if(i.errorMessage===void 0)return i;let a=dT(i.errorMessage);if(a<=r)return r-=a,i;n+=1;let c={...i};return delete c.errorMessage,c});return{stats:{...t,...s!==void 0?{tests:s}:{}},omittedCount:n}}o(Gp,"applyErrorDetailsPayloadBudget");var zp=o(t=>Df.includes(t),"isPayloadTag"),pT=o((t,e)=>t.files.flatMap(r=>r.tests.map(n=>{let s=e?Fp(e,r.fileId,n.projectName,n.testId):void 0;return{playwrightTestId:n.testId,ok:!!n.ok,outcome:n.outcome,title:n.title,titlePath:n.path??[],filePath:n.location?.file,...n.projectName?{projectName:n.projectName}:{},tags:n.tags??[],annotations:n.annotations??[],...s?{errorMessage:s}:{}}})),"htmlReportToRows"),ps=class t{constructor(e,r,n,s={},i={},a,c,l,u={}){this.reportHTMLFilePath=e;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=s;this.channel=a;this.checksumTestIdToUsingPlaceholder=u;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...i},this.checksumRoot=c||(0,Ht.dirname)((0,Ht.dirname)(e)),this.projectRoot=l||this.checksumRoot}static{o(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let e=0;try{e=(0,ye.statSync)(this.reportHTMLFilePath)?.size||0,this.channel.debug(`Report HTML file size approximately ${e} bytes`)}catch(i){this.channel.debug(`Failed to retrieve file size for ${this.reportHTMLFilePath}`,i)}let r=(0,Ht.join)((0,qp.tmpdir)(),`pw-report-${(0,Kp.randomUUID)()}.zip`),n=o(()=>{try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{}},"cleanupFile"),s={sigterm:o(()=>{n(),process.exit(143)},"sigterm"),sigint:o(()=>{n(),process.exit(130)},"sigint"),exit:n};process.once("SIGTERM",s.sigterm),process.once("SIGINT",s.sigint),process.once("exit",s.exit);try{this.channel.debug("Extracting base64 to temp ZIP file...");let i=Date.now();await this.extractBase64ToFile(r);let a=Date.now()-i;this.channel.debug("Modifying ZIP file...");let c=Date.now(),l=this.modifyZipFile(r),u=Date.now()-c;this.channel.debug("Writing output HTML...");let d=Date.now();await this.writeOutputWithStreamedZip(r);let p=Date.now()-d;return{report_html_bytes:e,extract_ms:a,modify_ms:u,write_ms:p,entry_count:l.entryCount,json_entry_count:l.jsonEntryCount,largest_entry_bytes:l.largestEntryBytes,largest_entry_name:l.largestEntryName,error_details_extracted:l.errorDetailsExtracted,error_details_truncated:l.errorDetailsTruncated,error_detail_parse_failures:l.errorDetailParseFailures,error_detail_identity_conflicts:l.errorDetailIdentityConflicts,error_details_payload_budget_omitted:l.errorDetailsPayloadBudgetOmitted}}finally{process.removeListener("SIGTERM",s.sigterm),process.removeListener("SIGINT",s.sigint),process.removeListener("exit",s.exit);try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{this.channel.debug(`Failed to cleanup temp file: ${r}`)}}}async extractBase64ToFile(e){return new Promise((r,n)=>{let s=!1,i=!1,a=!1,c=[],l=0,u=(0,ye.createWriteStream)(e);u.on("error",g=>{if(!i){i=!0;try{_.destroyed||_.destroy(),p.end()}catch{}n(g)}});let d=o(()=>{if(l<4)return;let g=c.join("");c.length=0,a||(g=g.replace("data:application/zip;base64,",""),a=!0);let y=Math.floor(g.length/4)*4,E=g.slice(0,y),w=g.slice(y);if(w.length>0?(c.push(w),l=w.length):l=0,E.length>0){let S=Buffer.from(E,"base64");u.write(S)}},"flushBuffer"),p=new Vp.Parser({onopentag:o((g,y)=>{zp(g)&&y.id==="playwrightReportBase64"&&(s=!0)},"onopentag"),ontext:o(g=>{s&&(c.push(g),l+=g.length,l>1024*1024&&d())},"ontext"),onclosetag:o(g=>{if(zp(g)&&s&&!i){if(i=!0,l>0){let y=c.join("");if(a||(y=y.replace("data:application/zip;base64,","")),y.length>0){let E=Buffer.from(y,"base64");u.write(E)}}try{_.destroyed||_.destroy()}catch{}u.end(()=>r())}},"onclosetag"),onerror:o(g=>{if(!i){i=!0;try{p.end(),_.destroyed||_.destroy(),u.destroyed||u.destroy()}catch{}n(g)}},"onerror")}),_=(0,ye.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});_.on("data",g=>p.write(g.toString())),_.on("end",()=>{if(p.end(),!i){i=!0;try{u.destroyed||u.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),_.on("error",g=>{if(!i){i=!0;try{p.end(),u.destroyed||u.destroy()}catch{}n(g)}})})}modifyZipFile(e){let r=new Wp.default(e),n=r.getEntries(),s=Dp(),i,a,c=0,l=0,u=0,d="";for(let _ of n){if(_.isDirectory||!_.entryName.endsWith(".json"))continue;let g=_.getData().toString("utf8");if(l+=1,g.length>u&&(u=g.length,d=_.entryName),_.entryName==="report.json")i=JSON.parse(g),a=_;else{let y=this.replaceAttachmentPaths(g);_.setData(Buffer.from(y,"utf8"));try{let E=JSON.parse(y);Up(E)&&!$p(E,s)&&(c+=1)}catch{c+=1}}}if(!i||!a)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&Np(i,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(i),this.report=i;let p=this.extractStats(i,s);return a.setData(Buffer.from(JSON.stringify(i),"utf8")),r.writeZip(e),{entryCount:n.length,jsonEntryCount:l,largestEntryBytes:u,largestEntryName:d,errorDetailsExtracted:s.messages.size,errorDetailsTruncated:s.truncatedCount,errorDetailParseFailures:c,errorDetailIdentityConflicts:s.identityConflictCount,errorDetailsPayloadBudgetOmitted:p}}replaceAttachmentPaths(e){return e.replace(/"path"\s*:\s*"([^"]+)"/g,(r,n)=>n.startsWith("http://")||n.startsWith("https://")?r:`"path":"${this.makeAttachmentPath(n)}"`)}async writeOutputWithStreamedZip(e){let r=this.getTemplate(),n=this.getProcessedFilePath(),s=n.replace(".html",".backup.html");(0,ye.copyFileSync)(n,s);let i=(0,ye.createWriteStream)(n);await new Promise((a,c)=>{i.on("error",c),i.write(r),i.write($f+"data:application/zip;base64,");let l=(0,ye.createReadStream)(e,{highWaterMark:3*1024*1024});l.on("data",u=>{let p=(typeof u=="string"?Buffer.from(u):u).toString("base64");i.write(p)||l.pause()}),i.on("drain",()=>{l.resume()}),l.on("end",()=>{i.write(Uf),i.end(()=>a())}),l.on("error",u=>{try{i.destroyed||i.destroy()}catch{}c(u)}),i.on("error",u=>{try{l.destroyed||l.destroy()}catch{}c(u)})})}testHasTrace(e,r){try{if(!this.report)return!0;let n=Object.keys(this.pwTestIdToChecksumTestId??{}).find(i=>this.pwTestIdToChecksumTestId[i]===e);if(!n)return!0;let s=o(i=>i.some(a=>a.attachments?.some(c=>c.name==="trace")),"hasTrace");for(let i of this.report.files)for(let a of i.tests)if(a.testId===n&&a.projectName===r&&s(a.results))return!0;return!1}catch(n){return this.channel.debug("Failed to check if test has trace, assuming trace exists",n),!0}}getProcessedFilePath(){return this.reportHTMLFilePath}getTemplate(){return t.templateCache||(t.templateCache=(0,ye.readFileSync)(cs.playwrightReporter.htmlReportTemplatePath,"utf-8")),t.templateCache}getReportsStats(){return this.stats}extractStats(e,r){if(!e.stats)return 0;let n=ka(pT(e,r),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:o(i=>Mp(i,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),s=Gp(n,this.config.errorDetailsPayloadBudgetBytes??8388608);return this.stats=s.stats,s.omittedCount}makeAttachmentPath(e){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,Ht.basename)(e)}`:e}handleReportJSON(e){let r={},n=o(s=>{let i=s.testId,a=this.playwrightIdToMetadata[i];a&&(r[i]=a);let c=us({playwrightTestId:s.testId,filePath:s.location?.file,title:s.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});c!==void 0&&(s.checksumTestId=c),s.results.forEach(l=>{this.processAttachments(l.attachments)})},"getChecksumMetadataForPWTestId");e.files.forEach(s=>{s.tests.forEach(n)}),e.checksumMetadata=r}processAttachments(e){if(e.forEach(r=>this.updateAttachment(r)),!this.supportVideo){let r=e.findIndex(n=>n.name==="video");r!==-1&&e.splice(r,1)}}updateAttachment(e){e.path&&(e.path=this.makeAttachmentPath(e.path))}};var Da={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},mT={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},eG=Object.fromEntries(Object.entries(mT).map(t=>t.reverse())),hT={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},tG=Object.fromEntries(Object.entries(hT).map(t=>t.reverse()));var rG={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},nG={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var bs=require("fs"),fm=require("path"),pm=require("stream");var Zp=o(t=>{if(t.error!=null)return"ERROR";let e=t.status_code;if(typeof e=="number"&&e>=500)return"ERROR";let r=t.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var $a=require("fs");var Jp="\x1B[31m",gT="\x1B[33m",yT="\x1B[32m",_T="\x1B[36m",bT="\x1B[2m",ET="\x1B[1m",zr="\x1B[0m",wT=o(()=>{let t=process.env.WIDE_EVENT_PRETTY;return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),TT=new Set(["severity","message","kind","timestamp","_startedAtMs"]),vT=o(t=>{let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n})},"safeStringify"),ST=o(t=>t==="ERROR"||t==="CRITICAL"?Jp:t==="WARNING"?gT:yT,"colorForSeverity"),IT=o(t=>{let e=String(t.severity??"INFO"),r=`${ST(e)}${e.padEnd(5)}${zr}`,n=t.kind?`${_T}${t.kind}${zr}`:"",s=String(t.message??""),i=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Jp}${d.type??"Error"}: ${d.message??""}${zr}`})():"",a=["outcome","test_suite_run_id","status"],c=Object.entries(t).filter(([d,p])=>!TT.has(d)&&p!=null&&d!=="error"&&typeof p!="object"),l=o(d=>{let p=a.indexOf(d);return p===-1?a.length:p},"rank"),u=c.sort(([d],[p])=>l(d)-l(p)).slice(0,8).map(([d,p])=>`${bT}${d}=${zr}${p}`).join(" ");return[r,ET+n+zr,s,u,i].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),xT=o(t=>{let e=t.trace_id;if(typeof e!="string"||e==="")return t;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...t,"logging.googleapis.com/trace":`projects/${r}/traces/${e}`}:t},"withGcpTraceField"),Yp=o(t=>{let e=wT()?IT(t):vT(xT(t));(0,$a.writeSync)(1,e+`
|
|
65
65
|
`)},"emitEvent");var Xp=o(t=>{(0,$a.writeSync)(2,t.endsWith(`
|
|
66
66
|
`)?t:`${t}
|
|
67
|
-
`)},"writeStderrLine");var ST=o(t=>{let e=t.kind??"event",r=t.outcome?` ${t.outcome}`:"",n=typeof t.duration_ms=="number"?` ${t.duration_ms}ms`:"";return`${e}${r}${n}`.trim()},"defaultMessage"),IT=o((t,e,r)=>{let n=Date.now(),s={timestamp:new Date().toISOString(),kind:t,...e},i=!1,a={set(c){return Object.assign(s,c),a},emit(c){i||(i=!0,c&&Object.assign(s,c),s.duration_ms===void 0&&(s.duration_ms=Date.now()-n),r(s))}};return a},"startHandle"),xT=o((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??ST,n=t.label??"[wide-event]",s=t.sink??(c=>Yp(c)),i=o(c=>{if(!e(c))return;let l={severity:Zp(c),message:c.message??r(c),...c};try{s(l)}catch(u){try{Xp(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:i,emitWideEvent:o((c,l={})=>{i({timestamp:new Date().toISOString(),kind:c,...l})},"emitWideEvent"),wideEvent:o((c,l={})=>IT(c,l,i),"wideEvent"),configureSink:o(c=>{s=c},"configureSink")}},"createWideEvents"),Qp=o(t=>t==="true"||t==="1","truthy"),em=o(()=>Qp(process.env.CHECKSUM_WIDE_EVENTS)||Qp(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Ua=xT({decide:o(()=>em(),"decide")}),Fa=Ua.configureSink,lr=o((t,e={})=>Ua.wideEvent(t,e),"wideEvent"),Gt=o((t,e={})=>{Ua.emitWideEvent(t,e)},"emitWideEvent"),et=o(t=>t instanceof Error?{type:t.name,message:t.message}:{type:"UnknownError",message:String(t)},"toErrorField");async function ms(t,e){let r;try{r=await t.json()}catch{r=void 0}return AT({ok:t.ok,status:t.status,body:r},e)}o(ms,"assertOkJson");function AT(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let s=RT(r?.message);throw CT(new Error(`${e.resource} failed (HTTP ${t.status})`+(s?`: ${s}`:".")),t.status)}if(!r)throw new Error(`${e.resource} (HTTP ${t.status}) returned a non-object body; expected JSON.`);let n=(e.requiredFields??[]).filter(s=>!r[s]);if(n.length>0)throw new Error(`${e.resource} (HTTP ${t.status}) response is missing required field${n.length>1?"s":""}: ${n.join(", ")}.`);return r}o(AT,"assertJsonBody");function RT(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}o(RT,"extractMessage");function CT(t,e){return Object.assign(t,{status:e})}o(CT,"withStatus");var hs=o(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var gs={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:6e4,min:5e3,max:6e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function OT(t,e,r,n){if(t===void 0||t.trim()==="")return e;let s=Number(t);return Number.isInteger(s)?Math.min(n,Math.max(r,s)):e}o(OT,"clampEnvInt");var NT=[["cliHardCapMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function MT(t){let e={...t},r=[];for(let[n,s,i]of NT)for(let a of s){let c=Math.floor(e[n]*i);e[a]>c&&(r.push(`${gs[a].env} (${e[a]}ms) exceeds its bound under ${gs[n].env} (${e[n]}ms); using ${c}ms`),e[a]=c)}return{tunables:e,warnings:r}}o(MT,"coerceScopeHierarchy");function Ba(t){let e={};for(let r of Object.keys(gs)){let n=gs[r];e[r]=OT(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,MT(e)}o(Ba,"resolveUploadTunablesDetailed");function kT(t){return Ba(t).tunables}o(kT,"resolveUploadTunables");var tm=kT({});var ja=new WeakMap;function rm(t,e){t.loadedBytes=0,t.committedBytes??=0,t.lastProgress=e,ja.set(t,t.committedBytes)}o(rm,"beginUpload");function Ha(t){t.loadedBytes=0}o(Ha,"resetAttemptBytes");function nm(t,e,r,n){let s=ja.get(t)??0;return e-s<r?!1:(t.lastProgress=n,ja.set(t,e),!0)}o(nm,"stampIfDurable");function Ga(t,e,r,n){t.loadedBytes=e;let s=t.committedBytes??0;return nm(t,Math.max(s,e),r,n)}o(Ga,"recordSent");function za(t,e,r,n){let s=Math.max(t.committedBytes??0,e);return t.committedBytes=s,nm(t,s,r,n)}o(za,"recordCommitted");var _s=require("fs"),im=require("stream");function ys(t,{baseMs:e,capMs:r,random:n=Math.random}){let s=Math.min(r,e*2**(t-1));return s/2+n()*(s/2)}o(ys,"jitteredBackoffMs");async function ur(t){await t.body?.cancel().catch(()=>{})}o(ur,"drainBody");var Wa=o(t=>t===200||t===201,"isStored"),am=o(t=>t===308,"isResumeIncomplete"),PT=o(t=>t===404||t===410,"isSessionGoneStatus"),om=o((t,e)=>{let r=t?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:e},"nextOffsetFromRange"),LT=o((t,e,r)=>e<=t?`bytes */${r}`:`bytes ${t}-${e-1}/${r}`,"contentRangeFor");function DT(t,e,r){let n=e,s=new TransformStream({transform(i,a){n+=i.byteLength,r?.(n),a.enqueue(i)}});return im.Readable.toWeb(t).pipeThrough(s)}o(DT,"countingBody");var tt=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{o(this,"ResumableUploadError")}},cm=o(t=>t instanceof tt?t.status:void 0,"statusOf"),$T=o(t=>{let e=cm(t);return e!==void 0&&PT(e)},"isSessionGone"),UT=o(t=>hs(cm(t)),"isPermanent");async function FT(t,e,r,n){let s=await r(t,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":e,"Content-Length":"0"},signal:n});if(await ur(s),!Wa(s.status))throw new tt(`resumable init failed with status ${s.status}`,s.status);let i=s.headers.get("Location");if(!i)throw new tt("resumable init returned no Location");return i}o(FT,"initResumableSession");async function BT(t,e,r,n){let s=await r(t,{method:"PUT",headers:{"Content-Range":`bytes */${e}`},signal:n});if(await ur(s),Wa(s.status))return{done:!0,offset:e};if(!am(s.status))throw new tt(`offset query failed with status ${s.status}`,s.status);return{done:!1,offset:om(s.headers.get("Range"),0)}}o(BT,"queryCommittedOffset");async function sm(t,e,{offset:r,endExclusive:n},s){let i=Math.max(0,(0,_s.statSync)(t.filePath).size-r),a=Math.min(Math.max(0,n-r),i),c=r+a,l=a>0?(0,_s.createReadStream)(t.filePath,{start:r,end:c-1}):void 0;try{let u={method:"PUT",headers:{"Content-Range":LT(r,c,t.size),"Content-Length":String(a)},duplex:"half",signal:s,...l?{body:DT(l,r,t.onSent)}:{}},d=await t.fetchImpl(e,u);if(await ur(d),Wa(d.status))return{stored:!0,committed:t.size};if(am(d.status))return{stored:!1,committed:om(d.headers.get("Range"),r)};throw new tt(`resumable PUT failed with status ${d.status}`,d.status)}finally{l?.destroy()}}o(sm,"putChunk");async function jT(t,e,r,n){let s=r;for(;s<t.size;){let a=Math.min(s+t.chunkSizeBytes,t.size),{stored:c,committed:l}=await sm(t,e,{offset:s,endExclusive:a},n);if(c){t.onCommitted?.(t.size);return}if(l<=s)throw new tt("resumable PUT made no forward progress");s=l,t.onCommitted?.(s)}let{stored:i}=await sm(t,e,{offset:t.size,endExclusive:t.size},n);if(!i)throw new tt("resumable upload did not finalize");t.onCommitted?.(t.size)}o(jT,"sendFrom");async function HT(t,e,r){if(e.url)return e.url;if(!t.target.initUrl)throw new tt("no resumable target provided");return e.url=await FT(t.target.initUrl,t.contentType,t.fetchImpl,r),e.used=!1,e.url}o(HT,"openSession");async function GT(t,e,r,n){if(!r)return 0;let s=await BT(e,t.size,t.fetchImpl,n);if(!s.done)return t.onCommitted?.(s.offset),s.offset}o(GT,"resumePoint");async function zT(t,e,r){let n=await HT(t,e,r),s=await GT(t,n,e.used,r);if(e.used=!0,s===void 0){t.onCommitted?.(t.size);return}await jT(t,n,s,r)}o(zT,"runAttempt");function VT(t,e,r){return $T(t)&&e.target.initUrl?(r.url=void 0,r.used=!1,"retry"):UT(t)?"stop":"retry"}o(VT,"afterFailure");async function lm(t){let e={url:t.target.sessionUrl,used:!1},r;for(let n=1;n<=t.maxAttempts&&!(t.now()>=t.deadlineAt);n++)try{await zT(t,e,t.makeSignal());return}catch(s){if(r=s,VT(s,t,e)==="stop"||n>=t.maxAttempts)break;await t.sleep(ys(n,{baseMs:1e3,capMs:16e3,...t.random?{random:t.random}:{}}))}throw r instanceof Error?r:new tt(`resumable upload failed: ${String(r)}`)}o(lm,"uploadResumable");var qT=o(t=>{let e=t;if(e?.name==="TimeoutError")return"timeout";if(e?.name==="AbortError")return"no_progress_abort";let r=e?.cause?.code;if(r==="UND_ERR_CONNECT_TIMEOUT"||r==="UND_ERR_HEADERS_TIMEOUT"||r==="UND_ERR_BODY_TIMEOUT")return"timeout";if(typeof r=="string"&&r.length>0)return`network_error:${r}`;let n=typeof e?.message=="string"?e.message:"";return n.startsWith("Upload failed with status")?"http_error":n.startsWith("get-upload-url")?"signed_url_error":n.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),WT=o(t=>Math.max(1e3,Math.min(1e4,Math.floor(t/4))),"noProgressPollMs"),bs=class{constructor(e,r,n,s,i=!1,a={start:o(u=>{},"start"),complete:o(u=>{},"complete"),error:o((u,d)=>{},"error")},c,l={}){this.apiBaseURL=e;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=s;this.isolationMode=i;this.reporter=a;this.sessionId=c;this.SIGNED_URL_TIMEOUT_MS=3e4;this.tunables=l.tunables??tm,this.fetchImpl=l.fetchImpl??globalThis.fetch,this.now=l.now??Date.now,this.MAX_ATTEMPTS=this.tunables.maxAttempts,this.PUT_NO_PROGRESS_ABORT_MS=this.tunables.noProgressAbortMs,this.ASSET_DEADLINE_MS=this.tunables.assetDeadlineMs,this.MIN_PROGRESS_BYTES=this.tunables.minProgressBytes}static{o(this,"TestAssetUploader")}async uploadAsset(e){if(e.uploadStarted=!0,this.isolationMode){e.lastProgress=Date.now(),e.loadedBytes=0,e.sizeBytes=100,e.response=new Promise(a=>{setTimeout(()=>{e.complete=!0,e.lastProgress=Date.now(),e.loadedBytes=100,a({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=e.info,n=this.now()+this.ASSET_DEADLINE_MS,s=lr("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,um.basename)(r),test_id:e.info.testId,project:e.info.project}),i=[];try{let c=(0,Es.statSync)(r).size;e.sizeBytes=c,rm(e,this.now()),s.set({size_bytes:c}),this.reporter.start(r);let l;for(let u=1;u<=this.MAX_ATTEMPTS&&!(this.now()>=n);u++){let d={attempt:u};try{let p=this.now();if(await this.getSignedURLForUpload(e),d.signed_url_ms=this.now()-p,!e.uploadURL)throw new Error("No upload URL returned");let _=this.now();d.resumable=e.resumable===!0,e.resumable?await this.putResumable(e,r,c,n):await this.putWithWatchdog(e,r,c),d.put_ms=this.now()-_,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,i.push(d),this.reporter.complete(r),e.complete=!0,s.emit({outcome:"success",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes});return}catch(p){l=p,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,d.failure_reason=qT(p),d.error=et(p);let _=hs(p?.status);d.non_retryable=_,delete e.uploadURL;let g=_?"non_retryable":e.resumable?"resumable_owns_retries":u>=this.MAX_ATTEMPTS?"max_attempts":this.now()>=n?"asset_deadline":void 0;if(d.retry_stop_reason=g,i.push(d),g)break;await this.backoff(u,n)}}this.reporter.error(r,l),e.error=!0,s.emit({outcome:"error",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,deadline_exceeded:this.now()>=n,error:et(l)})}catch(a){this.reporter.error(r,a),e.error=!0,s.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:i.length,attempts:i,error:et(a)})}}async putWithWatchdog(e,r,n){let s=e.uploadURL;if(!s)throw new Error("No upload URL returned");let i=new AbortController,a=this.uploadTimeout??void 0;Ha(e);let c=this.armNoProgressWatchdog(e,()=>i.abort()),l=a!==void 0?setTimeout(()=>i.abort(new DOMException("upload attempt timeout","TimeoutError")),a):void 0,u=(0,Es.createReadStream)(r),d=0,p=this.MIN_PROGRESS_BYTES,_=this.now,g=new TransformStream({transform(w,S){d+=w.byteLength,e.sizeBytes=n,Ga(e,d,p,_()),S.enqueue(w)}}),y=dm.Readable.toWeb(u).pipeThrough(g),E={method:"PUT",headers:{"Content-Type":Da[e.info.type]??""},body:y,duplex:"half",signal:i.signal};try{let w=await this.fetchImpl(s,E);if(!w.ok)throw await ur(w),Object.assign(new Error(`Upload failed with status ${w.status}`),{status:w.status});za(e,n,this.MIN_PROGRESS_BYTES,this.now()),e.response=Promise.resolve(await w.text())}finally{clearInterval(c),clearTimeout(l),u.destroy()}}armNoProgressWatchdog(e,r){let n=-1,s=this.now();return setInterval(()=>{let i=Math.max(e.loadedBytes??0,e.committedBytes??0);i>n?(n=i,s=this.now()):this.now()-s>this.PUT_NO_PROGRESS_ABORT_MS&&r()},WT(this.PUT_NO_PROGRESS_ABORT_MS))}async putResumable(e,r,n,s){let i=e.uploadURL;if(!i)throw new Error("No upload URL returned");Ha(e);let a=this.uploadTimeout??this.tunables.uploadTimeoutMs,c,l,u=o(()=>(clearInterval(l),c=new AbortController,l=this.armNoProgressWatchdog(e,()=>c?.abort()),c.signal),"armAttempt");try{await lm({target:{initUrl:i},filePath:r,size:n,contentType:Da[e.info.type]??"",fetchImpl:this.fetchImpl,makeSignal:o(()=>AbortSignal.any([u(),AbortSignal.timeout(a)]),"makeSignal"),maxAttempts:this.MAX_ATTEMPTS,deadlineAt:s,chunkSizeBytes:this.tunables.resumableChunkBytes,now:this.now,sleep:o(d=>new Promise(p=>setTimeout(p,d)),"sleep"),onSent:o(d=>Ga(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onSent"),onCommitted:o(d=>za(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onCommitted")})}finally{clearInterval(l)}e.response=Promise.resolve("OK")}async backoff(e,r){let n=ys(e,{baseMs:1e3,capMs:16e3}),s=Math.max(0,Math.min(n,r-this.now()));s>0&&await new Promise(i=>setTimeout(i,s))}async getSignedURLForUpload(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let s=JSON.stringify(e.info),i=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(e)}`,a={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},c=await this.fetchImpl(i,{method:"POST",headers:a,body:s,signal:r.signal}),{url:l,resumable:u}=await ms(c,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=l,e.resumable=u===!0}catch(s){throw delete e.uploadURL,s}finally{clearTimeout(n)}}};function fm(t,e,r=Date.now()){if(t.length===0)return!1;let n=t.reduce((s,i)=>Math.max(s,i.lastProgress??0),0);return n>0&&r-n>e}o(fm,"isUploadStalled");function ws(t,e,r){return t!==void 0&&r-t>e}o(ws,"hasElapsedSinceTestEnd");function pm(t,e){let r=t.assets.filter(s=>!s.complete&&!s.error),n=o(s=>({reason:s,abandonedAssets:r}),"decide");if(ws(t.testRunEndTime,t.finalizeBudgetMs,e))return n("budget");if(!(t.processingInProgress||!t.doneWaitingForReport)&&!(r.length>0&&!fm(t.assets,t.stallTimeoutMs,e))&&!(t.pendingWatchCount>0&&!ws(t.testRunEndTime,t.watchTimeoutMs,e)))return r.length>0?n("stall"):t.pendingWatchCount>0?n("watch-timeout"):n("complete")}o(pm,"decideFinalize");var mm=require("module");var KT=(0,mm.createRequire)(__filename);function hm(t){let e;try{e=KT("undici")}catch(s){return Gt("monitor_dispatcher_unavailable",{outcome:"error",error:et(s)}),process.emitWarning("@checksum-ai/runtime: undici could not be loaded; upload timeouts fall back to the platform defaults",{detail:String(s)}),globalThis.fetch}let r=new e.Agent({connect:{timeout:t.connectTimeoutMs},headersTimeout:t.headersTimeoutMs,bodyTimeout:t.bodyTimeoutMs,keepAliveTimeout:1e4,keepAliveMaxTimeout:3e4}),n=e.fetch;return(s,i)=>{let a={...i,dispatcher:r};return n(s,a)}}o(hm,"createMonitorFetch");var Ka=class{static{o(this,"CLIChannel")}constructor(){}sendToCLI(...e){let r=`{trm}${e.map(n=>n.toString()).join(`,
|
|
67
|
+
`)},"writeStderrLine");var AT=o(t=>{let e=t.kind??"event",r=t.outcome?` ${t.outcome}`:"",n=typeof t.duration_ms=="number"?` ${t.duration_ms}ms`:"";return`${e}${r}${n}`.trim()},"defaultMessage"),CT=o((t,e,r)=>{let n=Date.now(),s={timestamp:new Date().toISOString(),kind:t,...e},i=!1,a={set(c){return Object.assign(s,c),a},emit(c){i||(i=!0,c&&Object.assign(s,c),s.duration_ms===void 0&&(s.duration_ms=Date.now()-n),r(s))}};return a},"startHandle"),RT=o((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??AT,n=t.label??"[wide-event]",s=t.sink??(c=>Yp(c)),i=o(c=>{if(!e(c))return;let l={severity:Zp(c),message:c.message??r(c),...c};try{s(l)}catch(u){try{Xp(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:i,emitWideEvent:o((c,l={})=>{i({timestamp:new Date().toISOString(),kind:c,...l})},"emitWideEvent"),wideEvent:o((c,l={})=>CT(c,l,i),"wideEvent"),configureSink:o(c=>{s=c},"configureSink")}},"createWideEvents"),Qp=o(t=>t==="true"||t==="1","truthy"),em=o(()=>Qp(process.env.CHECKSUM_WIDE_EVENTS)||Qp(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Ua=RT({decide:o(()=>em(),"decide")}),Fa=Ua.configureSink,lr=o((t,e={})=>Ua.wideEvent(t,e),"wideEvent"),Gt=o((t,e={})=>{Ua.emitWideEvent(t,e)},"emitWideEvent"),et=o(t=>t instanceof Error?{type:t.name,message:t.message}:{type:"UnknownError",message:String(t)},"toErrorField");async function tm(t,e){let r;try{r=await t.json()}catch{r=void 0}return OT({ok:t.ok,status:t.status,body:r},e)}o(tm,"assertOkJson");function OT(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let s=NT(r?.message);throw MT(new Error(`${e.resource} failed (HTTP ${t.status})`+(s?`: ${s}`:".")),t.status)}if(!r)throw new Error(`${e.resource} (HTTP ${t.status}) returned a non-object body; expected JSON.`);let n=(e.requiredFields??[]).filter(s=>!r[s]);if(n.length>0)throw new Error(`${e.resource} (HTTP ${t.status}) response is missing required field${n.length>1?"s":""}: ${n.join(", ")}.`);return r}o(OT,"assertJsonBody");function NT(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}o(NT,"extractMessage");function MT(t,e){return Object.assign(t,{status:e})}o(MT,"withStatus");var ms=o(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var hs={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},finalizeCeilingMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_CEILING_MS",fallback:24e5,min:12e4,max:72e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},watchTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_WATCH_TIMEOUT_MS",fallback:12e4,min:5e3,max:18e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function kT(t,e,r,n){if(t===void 0||t.trim()==="")return e;let s=Number(t);return Number.isInteger(s)?Math.min(n,Math.max(r,s)):e}o(kT,"clampEnvInt");var PT=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function LT(t){let e={...t},r=[];for(let[n,s,i]of PT)for(let a of s){let c=Math.floor(e[n]*i);e[a]>c&&(r.push(`${hs[a].env} (${e[a]}ms) exceeds its bound under ${hs[n].env} (${e[n]}ms); using ${c}ms`),e[a]=c)}return{tunables:e,warnings:r}}o(LT,"coerceScopeHierarchy");function Ba(t){let e={};for(let r of Object.keys(hs)){let n=hs[r];e[r]=kT(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,LT(e)}o(Ba,"resolveUploadTunablesDetailed");function DT(t){return Ba(t).tunables}o(DT,"resolveUploadTunables");var rm=DT({});var nm=new WeakMap,ja=new WeakMap;function sm(t,e){t.loadedBytes=0,t.committedBytes??=0,t.lastProgress=e,nm.set(t,t.committedBytes),ja.set(t,0)}o(sm,"beginUpload");function Ha(t){t.loadedBytes=0,ja.set(t,0)}o(Ha,"resetAttemptBytes");var im=o(t=>(e,r,n,s)=>{let i=t.get(e)??0;return r-i<n?!1:(e.lastProgress=s,t.set(e,r),!0)},"stamperFor"),$T=im(ja),UT=im(nm);function Ga(t,e,r,n){return t.loadedBytes=e,$T(t,e,r,n)}o(Ga,"recordSent");function za(t,e,r,n){let s=Math.max(t.committedBytes??0,e);return t.committedBytes=s,UT(t,s,r,n)}o(za,"recordCommitted");var ys=require("fs"),om=require("stream");function gs(t,{baseMs:e,capMs:r,random:n=Math.random}){let s=Math.min(r,e*2**(t-1));return s/2+n()*(s/2)}o(gs,"jitteredBackoffMs");async function ur(t){await t.body?.cancel().catch(()=>{})}o(ur,"drainBody");var qa=o(t=>t===200||t===201,"isStored"),cm=o(t=>t===308,"isResumeIncomplete"),FT=o(t=>t===404||t===410,"isSessionGoneStatus"),lm=o((t,e)=>{let r=t?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:e},"nextOffsetFromRange"),BT=o((t,e,r)=>e<=t?`bytes */${r}`:`bytes ${t}-${e-1}/${r}`,"contentRangeFor");function jT(t,e,r){let n=e,s=new TransformStream({transform(i,a){n+=i.byteLength,r?.(n),a.enqueue(i)}});return om.Readable.toWeb(t).pipeThrough(s)}o(jT,"countingBody");var tt=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{o(this,"ResumableUploadError")}},um=o(t=>t instanceof tt?t.status:void 0,"statusOf"),HT=o(t=>{let e=um(t);return e!==void 0&&FT(e)},"isSessionGone"),GT=o(t=>ms(um(t)),"isPermanent");async function zT(t,e,r,n){let s=await r(t,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":e,"Content-Length":"0"},signal:n});if(await ur(s),!qa(s.status))throw new tt(`resumable init failed with status ${s.status}`,s.status);let i=s.headers.get("Location");if(!i)throw new tt("resumable init returned no Location");return i}o(zT,"initResumableSession");async function VT(t,e,r,n){let s=await r(t,{method:"PUT",headers:{"Content-Range":`bytes */${e}`},signal:n});if(await ur(s),qa(s.status))return{done:!0,offset:e};if(!cm(s.status))throw new tt(`offset query failed with status ${s.status}`,s.status);return{done:!1,offset:lm(s.headers.get("Range"),0)}}o(VT,"queryCommittedOffset");async function am(t,e,{offset:r,endExclusive:n},s){let i=Math.max(0,(0,ys.statSync)(t.filePath).size-r),a=Math.min(Math.max(0,n-r),i),c=r+a,l=a>0?(0,ys.createReadStream)(t.filePath,{start:r,end:c-1}):void 0;try{let u={method:"PUT",headers:{"Content-Range":BT(r,c,t.size),"Content-Length":String(a)},duplex:"half",signal:s,...l?{body:jT(l,r,t.onSent)}:{}},d=await t.fetchImpl(e,u);if(await ur(d),qa(d.status))return{stored:!0,committed:t.size};if(cm(d.status))return{stored:!1,committed:lm(d.headers.get("Range"),r)};throw new tt(`resumable PUT failed with status ${d.status}`,d.status)}finally{l?.destroy()}}o(am,"putChunk");async function WT(t,e,r,n){let s=r;for(;s<t.size;){let a=Math.min(s+t.chunkSizeBytes,t.size),{stored:c,committed:l}=await am(t,e,{offset:s,endExclusive:a},n);if(c){t.onCommitted?.(t.size);return}if(l<=s)throw new tt("resumable PUT made no forward progress");s=l,t.onCommitted?.(s)}let{stored:i}=await am(t,e,{offset:t.size,endExclusive:t.size},n);if(!i)throw new tt("resumable upload did not finalize");t.onCommitted?.(t.size)}o(WT,"sendFrom");async function qT(t,e,r){if(e.url)return e.url;if(!t.target.initUrl)throw new tt("no resumable target provided");return e.url=await zT(t.target.initUrl,t.contentType,t.fetchImpl,r),e.used=!1,e.url}o(qT,"openSession");async function KT(t,e,r,n){if(!r)return 0;let s=await VT(e,t.size,t.fetchImpl,n);if(!s.done)return t.onCommitted?.(s.offset),s.offset}o(KT,"resumePoint");async function ZT(t,e,r){let n=await qT(t,e,r),s=await KT(t,n,e.used,r);if(e.used=!0,s===void 0){t.onCommitted?.(t.size);return}await WT(t,n,s,r)}o(ZT,"runAttempt");function JT(t,e,r){return HT(t)&&e.target.initUrl?(r.url=void 0,r.used=!1,"retry"):GT(t)?"stop":"retry"}o(JT,"afterFailure");async function dm(t){let e={url:t.target.sessionUrl,used:!1},r;for(let n=1;n<=t.maxAttempts&&!(t.now()>=t.deadlineAt);n++)try{await ZT(t,e,t.makeSignal());return}catch(s){if(r=s,JT(s,t,e)==="stop"||n>=t.maxAttempts)break;await t.sleep(gs(n,{baseMs:1e3,capMs:16e3,...t.random?{random:t.random}:{}}))}throw r instanceof Error?r:new tt(`resumable upload failed: ${String(r)}`)}o(dm,"uploadResumable");var YT=o(t=>{let e=t;if(e?.name==="TimeoutError")return"timeout";if(e?.name==="AbortError")return"no_progress_abort";let r=e?.cause?.code;if(r==="UND_ERR_CONNECT_TIMEOUT"||r==="UND_ERR_HEADERS_TIMEOUT"||r==="UND_ERR_BODY_TIMEOUT")return"timeout";if(typeof r=="string"&&r.length>0)return`network_error:${r}`;let n=typeof e?.message=="string"?e.message:"";return n.startsWith("Upload failed with status")?"http_error":n.startsWith("get-upload-url")?"signed_url_error":n.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),XT=o(t=>Math.max(1e3,Math.min(1e4,Math.floor(t/4))),"noProgressPollMs"),_s=class{constructor(e,r,n,s,i=!1,a={start:o(u=>{},"start"),complete:o(u=>{},"complete"),error:o((u,d)=>{},"error")},c,l={}){this.apiBaseURL=e;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=s;this.isolationMode=i;this.reporter=a;this.sessionId=c;this.SIGNED_URL_TIMEOUT_MS=3e4;this.tunables=l.tunables??rm,this.fetchImpl=l.fetchImpl??globalThis.fetch,this.now=l.now??Date.now,this.MAX_ATTEMPTS=this.tunables.maxAttempts,this.PUT_NO_PROGRESS_ABORT_MS=this.tunables.noProgressAbortMs,this.ASSET_DEADLINE_MS=this.tunables.assetDeadlineMs,this.MIN_PROGRESS_BYTES=this.tunables.minProgressBytes}static{o(this,"TestAssetUploader")}async uploadAsset(e){if(e.uploadStarted=!0,this.isolationMode){e.lastProgress=Date.now(),e.loadedBytes=0,e.sizeBytes=100,e.response=new Promise(a=>{setTimeout(()=>{e.complete=!0,e.lastProgress=Date.now(),e.loadedBytes=100,a({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=e.info,n=this.now()+this.ASSET_DEADLINE_MS,s=lr("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,fm.basename)(r),test_id:e.info.testId,project:e.info.project}),i=[];try{let c=(0,bs.statSync)(r).size;e.sizeBytes=c,sm(e,this.now()),s.set({size_bytes:c}),this.reporter.start(r);let l;for(let u=1;u<=this.MAX_ATTEMPTS&&!(this.now()>=n);u++){let d={attempt:u};try{let p=this.now();if(await this.getSignedURLForUpload(e),d.signed_url_ms=this.now()-p,!e.uploadURL)throw new Error("No upload URL returned");let _=this.now();d.resumable=e.resumable===!0,e.resumable?await this.putResumable(e,r,c,n):await this.putWithWatchdog(e,r,c),d.put_ms=this.now()-_,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,i.push(d),this.reporter.complete(r),e.complete=!0,s.emit({outcome:"success",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes});return}catch(p){l=p,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,d.failure_reason=YT(p),d.error=et(p);let _=ms(p?.status);d.non_retryable=_,delete e.uploadURL;let g=_?"non_retryable":e.resumable?"resumable_owns_retries":u>=this.MAX_ATTEMPTS?"max_attempts":this.now()>=n?"asset_deadline":void 0;if(d.retry_stop_reason=g,i.push(d),g)break;await this.backoff(u,n)}}this.reporter.error(r,l),e.error=!0,s.emit({outcome:"error",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,deadline_exceeded:this.now()>=n,error:et(l)})}catch(a){this.reporter.error(r,a),e.error=!0,s.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:i.length,attempts:i,error:et(a)})}}async putWithWatchdog(e,r,n){let s=e.uploadURL;if(!s)throw new Error("No upload URL returned");let i=new AbortController,a=this.uploadTimeout??void 0;Ha(e);let c=this.armNoProgressWatchdog(e,()=>i.abort()),l=a!==void 0?setTimeout(()=>i.abort(new DOMException("upload attempt timeout","TimeoutError")),a):void 0,u=(0,bs.createReadStream)(r),d=0,p=this.MIN_PROGRESS_BYTES,_=this.now,g=new TransformStream({transform(w,S){d+=w.byteLength,e.sizeBytes=n,Ga(e,d,p,_()),S.enqueue(w)}}),y=pm.Readable.toWeb(u).pipeThrough(g),E={method:"PUT",headers:{"Content-Type":Da[e.info.type]??""},body:y,duplex:"half",signal:i.signal};try{let w=await this.fetchImpl(s,E);if(!w.ok)throw await ur(w),Object.assign(new Error(`Upload failed with status ${w.status}`),{status:w.status});za(e,n,this.MIN_PROGRESS_BYTES,this.now()),e.response=Promise.resolve(await w.text())}finally{clearInterval(c),clearTimeout(l),u.destroy()}}armNoProgressWatchdog(e,r){let n=-1,s=this.now();return setInterval(()=>{let i=Math.max(e.loadedBytes??0,e.committedBytes??0);i>n?(n=i,s=this.now()):this.now()-s>this.PUT_NO_PROGRESS_ABORT_MS&&r()},XT(this.PUT_NO_PROGRESS_ABORT_MS))}async putResumable(e,r,n,s){let i=e.uploadURL;if(!i)throw new Error("No upload URL returned");Ha(e);let a=this.uploadTimeout??this.tunables.uploadTimeoutMs,c,l,u=o(()=>(clearInterval(l),c=new AbortController,l=this.armNoProgressWatchdog(e,()=>c?.abort()),c.signal),"armAttempt");try{await dm({target:{initUrl:i},filePath:r,size:n,contentType:Da[e.info.type]??"",fetchImpl:this.fetchImpl,makeSignal:o(()=>AbortSignal.any([u(),AbortSignal.timeout(a)]),"makeSignal"),maxAttempts:this.MAX_ATTEMPTS,deadlineAt:s,chunkSizeBytes:this.tunables.resumableChunkBytes,now:this.now,sleep:o(d=>new Promise(p=>setTimeout(p,d)),"sleep"),onSent:o(d=>Ga(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onSent"),onCommitted:o(d=>za(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onCommitted")})}finally{clearInterval(l)}e.response=Promise.resolve("OK")}async backoff(e,r){let n=gs(e,{baseMs:1e3,capMs:16e3}),s=Math.max(0,Math.min(n,r-this.now()));s>0&&await new Promise(i=>setTimeout(i,s))}async getSignedURLForUpload(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let s=JSON.stringify(e.info),i=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(e)}`,a={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},c=await this.fetchImpl(i,{method:"POST",headers:a,body:s,signal:r.signal}),{url:l,resumable:u}=await tm(c,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=l,e.resumable=u===!0}catch(s){throw delete e.uploadURL,s}finally{clearTimeout(n)}}};function Es(t,e,r=Date.now()){let n=t.filter(i=>!i.complete&&!i.error);if(n.length===0)return!1;let s=n.reduce((i,a)=>Math.max(i,a.lastProgress??0),0);return s>0&&r-s>e}o(Es,"isUploadStalled");function ws(t,e,r){return t!==void 0&&r-t>e}o(ws,"hasElapsedSinceTestEnd");function mm(t,e,r){return ws(e.testRunEndTime,e.finalizeBudgetMs,r)?!0:t===void 0?!1:t.complete||t.error?!0:Es([t],e.stallTimeoutMs,r)}o(mm,"shouldStopWaitingForReport");function hm(t){return t.abandonedAssets.length===0}o(hm,"mayCleanUpSources");function QT(t,e,r){if((e.length===0||Es(t.assets,t.stallTimeoutMs,r))&&ws(t.testRunEndTime,t.finalizeBudgetMs,r))return"budget";if(ws(t.testRunEndTime,t.finalizeCeilingMs,r))return"budget-ceiling"}o(QT,"backstopReason");function gm(t,e){let r=t.assets.filter(i=>!i.complete&&!i.error),n=o(i=>({reason:i,abandonedAssets:r}),"decide"),s=QT(t,r,e);if(s!==void 0)return n(s);if(!(t.processingInProgress||!t.doneWaitingForReport)&&!(r.length>0&&!Es(t.assets,t.stallTimeoutMs,e))&&!(t.pendingWatchCount>0&&!ws(t.testRunEndTime,t.watchTimeoutMs,e)))return r.length>0?n("stall"):t.pendingWatchCount>0?n("watch-timeout"):n("complete")}o(gm,"decideFinalize");var ym=require("module");var ev=(0,ym.createRequire)(__filename);function _m(t){let e,r;try{e=ev("undici"),r=new e.Agent({connect:{timeout:t.connectTimeoutMs},headersTimeout:t.headersTimeoutMs,bodyTimeout:t.bodyTimeoutMs,keepAliveTimeout:1e4,keepAliveMaxTimeout:3e4})}catch(s){return Gt("monitor_dispatcher_unavailable",{outcome:"error",error:et(s)}),process.emitWarning("@checksum-ai/runtime: undici dispatcher unavailable; upload timeouts fall back to the platform defaults",{detail:String(s)}),globalThis.fetch}let n=e.fetch;return(s,i)=>{let a={...i,dispatcher:r};return n(s,a)}}o(_m,"createMonitorFetch");var Ka=class{static{o(this,"CLIChannel")}constructor(){}sendToCLI(...e){let r=`{trm}${e.map(n=>n.toString()).join(`,
|
|
68
68
|
`)}{/trm}`;process.stdout.write(`${r}
|
|
69
|
-
`)}event(e,r){return new Promise(n=>{let s=r?`${e}=${r}`:e;setTimeout(()=>{this.sendToCLI(`monitor:${s}`),n(!0)},100)})}trace(e,r){let n=r?`${e}=${JSON.stringify(r)}`:e;setTimeout(()=>{this.sendToCLI(`trace:${n}`)},100)}log(e){return this.event("log",e)}debug(...e){this.sendToCLI(e)}wideEvent(e){let r=Buffer.from(JSON.stringify(e),"utf-8").toString("base64");this.sendToCLI(`wideevent:${r}`)}},Ts=class{constructor(e,r=!1){this.config=e;this.isolationMode=r;this.tunablesResolution=Ba(process.env);this.tunables=this.tunablesResolution.tunables;this.MAX_UPLOADS=this.tunables.maxConcurrentUploads;this.MONITOR_INTERVAL=2500;this.UPLOAD_TIMEOUT=this.tunables.uploadTimeoutMs;this.UPLOAD_STALL_TIMEOUT=this.tunables.stallTimeoutMs;this.WATCH_TIMEOUT=120*1e3;this.FINALIZE_BUDGET=this.tunables.finalizeBudgetMs;this.SHUTDOWN_FLUSH_TIMEOUT=2e3;this.assets=[];this.watchAssets=[];this.processingPaths=new Set;this.doneWaitingForReport=!1;this.processingInProgress=!1;this.pwTestIdToChecksumTestId={};this.checksumTestIdToUsingPlaceholder={};this.progressFlushInFlight=!1;this.stallEventEmitted=!1;this.channel=new Ka,Fa(n=>this.channel.wideEvent(n)),this.testAssetUploader=new bs(e.apiURL,e.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:o(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:o(n=>{if(!this.reportAsset||n!==this.reportAsset.info.path)try{(0,oe.unlinkSync)(n),this.channel.debug(`[TestAssetUploader] Deleted file after successful upload: ${n}`)}catch(s){this.channel.debug(`[TestAssetUploader] Failed to delete file after upload: ${n}`,s)}this.channel.trace("Upload Complete",{filename:n})},"complete"),error:o((n,s)=>this.channel.trace("Upload Failed",{filename:n,error:s}),"error")},e.sessionId,{fetchImpl:hm(this.tunables),tunables:this.tunables}),this.uploadMonitorInterval=setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL);for(let n of this.tunablesResolution.warnings)this.channel.debug(`[upload-tunables] ${n}`),Gt("upload_tunable_coerced",{warning:n});this.listenForMessages(),this.startServer()}static{o(this,"TestRunMonitor")}listenForMessages(){process.stdin.on("data",e=>{(async()=>{let r=e.toString().trim();if(!r.startsWith("cli:"))return;let[n,s]=r.substring(4).split("=");switch(this.channel.debug("Received message from CLI "+n+" "+s),n){case"report":if(this.testRunEndTime=Date.now(),s!=="false")try{let i=Buffer.from(s??"","base64").toString("utf-8"),a=JSON.parse(i);await this.handleReport(a)}catch(i){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(i)),this.stopWaitingForReport("failed")}else this.stopWaitingForReport("not-requested");this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(e){try{let r=await(0,ym.readFile)(e,"utf-8");return JSON.parse(r)}catch(r){return this.channel.trace("Runtime Error",`Error reading checksum metadata file ${e}: ${r.message}`),{}}}async serveReport(e){try{let r=(0,De.dirname)(e);await this.channel.log("Serving report in browser: "+r);let n=cs.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,gm.execSync)(n,{encoding:"utf8",stdio:"pipe"}),await this.channel.log("Success: Report opened in browser")}catch(r){await this.channel.log(`Error serving report in browser: ${r.message}`),r.stderr&&await this.channel.log(r.stderr.toString())}}async handleReport(e){let{reportPath:r,pathToChecksumMetadata:n,didFail:s,openReportCriteria:i,checksumRoot:a,projectRoot:c,isUploadReport:l,dedupeByChecksumTestId:u}=e;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,De.dirname)(r),l);let d=lr("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!l});try{let p=await this.readMetadataFile(n),_=new ps(r,this.config.sessionId,this.pwTestIdToChecksumTestId,p,{hosted:!this.isolationMode,...u?{dedupeByChecksumTestId:u}:{}},this.channel,a,c,this.checksumTestIdToUsingPlaceholder),g=this.initAsset({type:"report",path:""});this.reportAsset=g;try{let w=await _.process();g.info.path=_.getProcessedFilePath(),d.set({processed_path:g.info.path,...w}),this.uploadAsset(g)}catch(w){this.channel.debug("Error processing report, "+w.message),g.error=!0,d.set({error:et(w)})}let y=_.getReportsStats();this.stats=y,Lf(d,g.error?"error":"success",y),this.channel.debug("Checking watch assets");let E=this.watchAssets.filter(w=>!(w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??"")));E.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(E.map(w=>w.path)))),this.watchAssets=this.watchAssets.filter(w=>w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??""))}catch(p){this.channel.debug("Error processing report, "+this.stringify(p)),this.reportAsset&&(this.reportAsset.error=!0),d.emit({outcome:"error",error:et(p)})}finally{if((i==="always"||i==="on-failure"&&s)&&await this.serveReport(r),n&&(0,oe.existsSync)(n))try{(0,oe.unlinkSync)(n)}catch(_){console.error(`Error deleting checksum metadata file ${n}: ${_.message}`)}}}async uploadReportData(e,r){let n=(0,De.join)(e,"data");try{let s=(0,oe.readdirSync)(n),i=r?[".webm"]:[".zip",".webm"],a=s.filter(c=>!i.includes((0,De.extname)(c)));this.channel.debug("Preparing to upload report data files,"+a);for(let c of a)this.channel.debug("Uploading report data file,"+c),this.addAsset({type:"report-data-file",fileName:c,path:`${n}/${c}`})}catch(s){this.channel.debug(`Error reading/adding report data files from dir ${n}`+s.message)}}shutdown(){clearInterval(this.uploadMonitorInterval);try{this.server?.closeAllConnections?.(),this.server?.close?.()}catch{}this.channel.debug("Received shutdown message from CLI"),process.stdout.write("",()=>process.exit(0)),setTimeout(()=>process.exit(0),this.SHUTDOWN_FLUSH_TIMEOUT).unref()}async monitorUploadsCompletion(){let e=Date.now();!this.doneWaitingForReport&&(ws(this.testRunEndTime,this.FINALIZE_BUDGET,e)||this.reportAsset?.complete||this.reportAsset?.error)&&this.settleReport();let r=pm({assets:this.assets,processingInProgress:this.processingInProgress,doneWaitingForReport:this.doneWaitingForReport,pendingWatchCount:this.watchAssets.length,testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,watchTimeoutMs:this.WATCH_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET},e);if(!r){await As(1e3),this.monitorUploadsCompletion();return}this.finalizeRun(r,e)}stopWaitingForReport(e){this.doneWaitingForReport=!0,this.reportOutcome=e}reportAssetOutcome(){return this.reportAsset?.complete?"uploaded":this.reportAsset?.error?"failed":"abandoned"}settleReport(){this.stopWaitingForReport(this.reportAssetOutcome());let e="";try{let r=JSON.stringify(this.stats??{}),n=`checksum-stats-${(0,Vr.randomBytes)(8).toString("hex")}.json`;e=(0,De.join)((0,wm.tmpdir)(),n),(0,oe.writeFileSync)(e,r,"utf-8"),this.channel.debug(`Stats written to temporary file: ${e}`)}catch(r){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${r.message}`)}this.channel.event("report-complete",`${this.reportOutcome==="uploaded"?"true":"false"}:${e}`)}finalizeRun(e,r){e.reason==="stall"&&this.emitStallDetected(e.abandonedAssets,r),e.abandonedAssets.forEach(a=>{a.error=!0});let n=this.assets.some(a=>a.error)?"uploads-complete-with-errors":"uploads-complete",s=this.assets.filter(a=>a.error);Gt("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:s.length>0?"error":"success",decision:n,total_assets:this.assets.length,completed:this.assets.filter(a=>a.complete).length,errored:s.length,stalled:e.abandonedAssets.length>0,stalled_count:e.abandonedAssets.length,finalize_reason:e.reason,finalize_budget_ms:this.FINALIZE_BUDGET,watch_remaining:this.watchAssets.length,report_outcome:this.reportOutcome,upload_finalize_ms:this.testRunEndTime?r-this.testRunEndTime:void 0,errored_assets:s.map(a=>this.assetSnapshot(a,r))});let i=n==="uploads-complete"?{}:{uploadErrors:s.map(a=>{try{return JSON.stringify(a)}catch{return a.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:r};try{this.cleanUp()}catch(a){this.channel.debug("cleanUp failed (ignored): "+a?.message)}this.channel.event(n,JSON.stringify(i))}assetSnapshot(e,r){return{file_name:e.info.fileName??(0,De.basename)(e.info.path),asset_type:e.info.type,test_id:e.info.testId,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,last_progress_age_ms:e.lastProgress?r-e.lastProgress:void 0}}cleanUp(){let e;for(let r of this.assets)if(r.info.type==="rrweb-recording"){e=(0,De.dirname)(r.info.path);break}e&&(0,oe.rmSync)(e,{recursive:!0,force:!0})}emitStallDetected(e,r){this.channel.log("Uploads are stalled"),!this.stallEventEmitted&&(this.stallEventEmitted=!0,Gt("upload_stall_detected",{test_suite_run_id:this.config.sessionId,outcome:"error",timeout_ms:this.UPLOAD_STALL_TIMEOUT,total_assets:this.assets.length,pending_count:e.length,pending_assets:e.map(n=>this.assetSnapshot(n,r))}))}async startServer(){let e=await this.acquirePortNumber();this.channel.event("port",e.toString()),this.server=(0,bm.createServer)((r,n)=>{let s=o(a=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(a)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let i="";r.on("data",a=>{i+=a.toString()}),r.on("end",()=>{let a;try{a=JSON.parse(i)}catch{s("Invalid body");return}let{type:c,payload:l,watch:u}=a;switch(this.channel.debug(`Server received message, ${c}, ${this.stringify(l)}`),c){case"asset":if(!l.path||!l.type){s("Missing arguments");return}u?this.watchAsset(l):this.processAsset(l);break;case"testInfo":if(!l.pwTestId||!l.checksumTestId){s("Missing arguments");return}this.pwTestIdToChecksumTestId[l.pwTestId]=l.checksumTestId,l.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[l.checksumTestId]=l.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let d=l;if(!d.checksumTestId||!l.data){s("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...d}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(l));break;case"runProgress":this.forwardProgress(l);break;default:s("Invalid message type");return}n.writeHead(200,{"Content-Type":"text/plain"}),n.end("OK")})}),this.server.listen(e)}forwardProgress(e){this.latestProgress=e,!this.progressFlushInFlight&&this.flushProgress()}async flushProgress(){this.progressFlushInFlight=!0;try{for(;this.latestProgress;){let e=this.latestProgress;this.latestProgress=void 0,await this.patchProgress(e)}}finally{this.progressFlushInFlight=!1}}async patchProgress(e){if(this.isolationMode)return;let r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{await fetch(`${this.config.apiURL}/client-api/test-runs/${this.config.sessionId}/progress`,{method:"PATCH",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:JSON.stringify({progress:e}),signal:r.signal})}catch(s){this.channel.debug("Failed to send run progress: "+s?.message)}finally{clearTimeout(n)}}stringify(e){try{return JSON.stringify(e)}catch{return"message"in e?e.message:e}}monitorUploads(){let{totalSizeBytes:e,totalUploadedBytes:r}=this.calculateUploadProgress();if(e>0&&!this.isolationMode){let i=(r/e*100).toFixed(2);this.channel.event("upload-progress",i)}let n=this.assets.filter(i=>!i.uploadStarted);if(n.length===0)return;let s=o(()=>this.assets.filter(i=>i.uploadStarted&&!i.complete&&!i.error).length,"getNumOfActiveUploads");if(!(s()>=this.MAX_UPLOADS))for(;n.length>0&&s()<this.MAX_UPLOADS;){let i=n.pop();if(i===void 0)break;this.uploadAsset(i)}}calculateUploadProgress(){let e=this.assets.reduce((n,{sizeBytes:s})=>n+(s??0),0),r=Math.min(e,this.assets.reduce((n,{loadedBytes:s})=>n+(s??0),0));return{totalSizeBytes:e,totalUploadedBytes:r}}getUploadLogMessage(e){switch(e.info.type){case"report":return"Uploading report";case"har":return`Uploading har file for test ${e.info.testId}`;case"trace":return`Uploading trace file for test ${e.info.testId}`;case"esra":return`Uploading metadata file for test ${e.info.testId}`;case"test-files":return`Uploading auto-healed test code for file ${e.info.path}`;default:return}}async uploadAsset(e){try{e.uploadStarted=!0;let r=this.getUploadLogMessage(e);r&&!this.isolationMode&&this.channel.event("log",r),await this.testAssetUploader.uploadAsset(e)}catch(r){e.error=!0,this.channel.debug("Error uploading asset"+this.stringify(r)),this.channel.trace("Upload Failed",{asset:e.info.fileName,error:String(r)})}}async getSignedURLForUpload(e){try{let{apiKey:r,sessionId:n,apiURL:s}=this.config,i=e.info,a=await fetch(`${s}/client-api/test-runs/${n}/get-upload-url`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:r},body:JSON.stringify(i)}),{url:c}=await ms(a,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=c}catch(r){this.channel.debug("Error getting signed URL for artifact"+this.stringify(r))}}watchAsset(e){if(this.watchAssets.some(n=>n.path===e.path)){this.channel.debug(`Already watching file ${e.path}, skipping duplicate`);return}this.channel.debug("Watching file "+e.path),this.watchAssets.push({...e,addedAt:Date.now()});let r=o(async()=>{await this.waitForFileComplete(e.path)&&(this.processAsset(e),this.watchAssets=this.watchAssets.filter(s=>s.path!==e.path))},"waitForCompletion");if((0,oe.existsSync)(e.path))r();else{let n=(0,De.dirname)(e.path),s=(0,De.basename)(e.path),i=!1,a=(0,oe.watch)(n,(c,l)=>{(async()=>{if(!(l!==s||i))try{this.channel.debug("Watched file changed "+e.path),i=!0,await r()}finally{a.close()}})()})}}waitForFileComplete(e,r=1e3,n=6e4,s=1){return new Promise(i=>{let a=Date.now(),c=0,l=s,u=o(()=>{if(!(0,oe.existsSync)(e)){this.channel.debug(`Asset required for upload doesn't exist anymore ${e}`),i(!1);return}let d=(0,oe.statSync)(e).size;if(d===c){if(l>0){this.channel.debug(`File size has not changed, verifying stabilization, ${e}, size: ${d}, equalSizeValidationCountLeft: ${l}`),l--,setTimeout(u,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${e}, size: ${d}`),i(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${e}, previous size: ${c}, current size: ${d}`),Date.now()-a>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${e}`),i(!0);return}c=d,setTimeout(u,r)},"checkFile");u()})}processAsset(e){switch(e.type){case"trace":return this.processTrace(e.path,e.testId);case"har":return this.processHar();case"rrweb-recording":case"esra":case"test-files":return this.addAsset(e);default:return}}async processHar(){}async calculateFileSha1Streaming(e){let r=(0,Vr.createHash)("sha1"),n=(0,oe.createReadStream)(e);return await(0,_m.pipeline)(n,r),r.digest("hex")}async processTrace(e,r){if(this.processingPaths.has(e)){this.channel.debug(`Trace file ${e} already being processed, skipping`);return}this.processingPaths.add(e);let n;try{this.processingInProgress=!0,await As(1e3),n=lr("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let s=e;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),s=e.replace(".zip",".actual.zip"),(0,oe.renameSync)(e,s);let c="checksum-playwright-trace:"+Date.now().toString()+(0,Vr.randomBytes)(1024).toString("hex");(0,oe.writeFileSync)(e,c)}let a=await o(async()=>await this.calculateFileSha1Streaming(e)+(0,De.extname)(e),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${a}, sending for upload...`),this.addAsset({type:"report-data-file",path:s,...r!==void 0?{testId:r}:{},fileName:a}),n?.emit({outcome:"success",file_name:a})}catch(s){let i=String(s);this.channel.debug("Error processing trace file"+i),this.channel.trace("Trace Processing Error",{error:i}),n?.emit({outcome:"error",error:et(s)})}finally{this.processingPaths.delete(e),this.processingInProgress=!1}}addAsset(e){this.channel.debug("Adding file "+e.path);let r=this.initAsset(e);return this.assets.push(r),r}initAsset(e){return{complete:!1,error:!1,info:e,removeAfterUpload:e.type==="rrweb-recording"}}async acquirePortNumber(){return new Promise((e,r)=>{let n=Em.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let s=n.address().port;n.close(()=>{e(s)})})})}},Tm;try{Tm=JSON.parse(process.argv[2]??"")}catch(t){console.error("Error starting test run monitor",t),process.exit(1)}new Ts(Tm,process.argv?.[3]==="isolated");0&&(module.exports={TestRunMonitor});
|
|
69
|
+
`)}event(e,r){return new Promise(n=>{let s=r?`${e}=${r}`:e;setTimeout(()=>{this.sendToCLI(`monitor:${s}`),n(!0)},100)})}trace(e,r){let n=r?`${e}=${JSON.stringify(r)}`:e;setTimeout(()=>{this.sendToCLI(`trace:${n}`)},100)}log(e){return this.event("log",e)}debug(...e){this.sendToCLI(e)}wideEvent(e){let r=Buffer.from(JSON.stringify(e),"utf-8").toString("base64");this.sendToCLI(`wideevent:${r}`)}},Ts=class{constructor(e,r=!1){this.config=e;this.isolationMode=r;this.tunablesResolution=Ba(process.env);this.tunables=this.tunablesResolution.tunables;this.MAX_UPLOADS=this.tunables.maxConcurrentUploads;this.MONITOR_INTERVAL=2500;this.UPLOAD_TIMEOUT=this.tunables.uploadTimeoutMs;this.UPLOAD_STALL_TIMEOUT=this.tunables.stallTimeoutMs;this.WATCH_TIMEOUT=this.tunables.watchTimeoutMs;this.FINALIZE_BUDGET=this.tunables.finalizeBudgetMs;this.FINALIZE_CEILING=this.tunables.finalizeCeilingMs;this.SHUTDOWN_FLUSH_TIMEOUT=2e3;this.assets=[];this.watchAssets=[];this.processingPaths=new Set;this.doneWaitingForReport=!1;this.processingInProgress=!1;this.pwTestIdToChecksumTestId={};this.checksumTestIdToUsingPlaceholder={};this.progressFlushInFlight=!1;this.stallEventEmitted=!1;this.channel=new Ka,Fa(n=>this.channel.wideEvent(n)),this.testAssetUploader=new _s(e.apiURL,e.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:o(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:o(n=>{if(!this.reportAsset||n!==this.reportAsset.info.path)try{(0,oe.unlinkSync)(n),this.channel.debug(`[TestAssetUploader] Deleted file after successful upload: ${n}`)}catch(s){this.channel.debug(`[TestAssetUploader] Failed to delete file after upload: ${n}`,s)}this.channel.trace("Upload Complete",{filename:n})},"complete"),error:o((n,s)=>this.channel.trace("Upload Failed",{filename:n,error:s}),"error")},e.sessionId,{fetchImpl:_m(this.tunables),tunables:this.tunables}),this.uploadMonitorInterval=setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL);for(let n of this.tunablesResolution.warnings)this.channel.debug(`[upload-tunables] ${n}`),Gt("upload_tunable_coerced",{warning:n});this.listenForMessages(),this.startServer()}static{o(this,"TestRunMonitor")}listenForMessages(){process.stdin.on("data",e=>{(async()=>{let r=e.toString().trim();if(!r.startsWith("cli:"))return;let[n,s]=r.substring(4).split("=");switch(this.channel.debug("Received message from CLI "+n+" "+s),n){case"report":if(this.testRunEndTime=Date.now(),s!=="false")try{let i=Buffer.from(s??"","base64").toString("utf-8"),a=JSON.parse(i);await this.handleReport(a)}catch(i){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(i)),this.stopWaitingForReport("failed")}else this.stopWaitingForReport("not-requested");this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(e){try{let r=await(0,Em.readFile)(e,"utf-8");return JSON.parse(r)}catch(r){return this.channel.trace("Runtime Error",`Error reading checksum metadata file ${e}: ${r.message}`),{}}}async serveReport(e){try{let r=(0,De.dirname)(e);await this.channel.log("Serving report in browser: "+r);let n=cs.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,bm.execSync)(n,{encoding:"utf8",stdio:"pipe"}),await this.channel.log("Success: Report opened in browser")}catch(r){await this.channel.log(`Error serving report in browser: ${r.message}`),r.stderr&&await this.channel.log(r.stderr.toString())}}async handleReport(e){let{reportPath:r,pathToChecksumMetadata:n,didFail:s,openReportCriteria:i,checksumRoot:a,projectRoot:c,isUploadReport:l,dedupeByChecksumTestId:u}=e;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,De.dirname)(r),l);let d=lr("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!l});try{let p=await this.readMetadataFile(n),_=new ps(r,this.config.sessionId,this.pwTestIdToChecksumTestId,p,{hosted:!this.isolationMode,...u?{dedupeByChecksumTestId:u}:{}},this.channel,a,c,this.checksumTestIdToUsingPlaceholder),g=this.initAsset({type:"report",path:""});this.reportAsset=g;try{let w=await _.process();g.info.path=_.getProcessedFilePath(),d.set({processed_path:g.info.path,...w}),this.uploadAsset(g)}catch(w){this.channel.debug("Error processing report, "+w.message),g.error=!0,d.set({error:et(w)})}let y=_.getReportsStats();this.stats=y,Lf(d,g.error?"error":"success",y),this.channel.debug("Checking watch assets");let E=this.watchAssets.filter(w=>!(w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??"")));E.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(E.map(w=>w.path)))),this.watchAssets=this.watchAssets.filter(w=>w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??""))}catch(p){this.channel.debug("Error processing report, "+this.stringify(p)),this.reportAsset&&(this.reportAsset.error=!0),d.emit({outcome:"error",error:et(p)})}finally{if((i==="always"||i==="on-failure"&&s)&&await this.serveReport(r),n&&(0,oe.existsSync)(n))try{(0,oe.unlinkSync)(n)}catch(_){console.error(`Error deleting checksum metadata file ${n}: ${_.message}`)}}}async uploadReportData(e,r){let n=(0,De.join)(e,"data");try{let s=(0,oe.readdirSync)(n),i=r?[".webm"]:[".zip",".webm"],a=s.filter(c=>!i.includes((0,De.extname)(c)));this.channel.debug("Preparing to upload report data files,"+a);for(let c of a)this.channel.debug("Uploading report data file,"+c),this.addAsset({type:"report-data-file",fileName:c,path:`${n}/${c}`})}catch(s){this.channel.debug(`Error reading/adding report data files from dir ${n}`+s.message)}}shutdown(){clearInterval(this.uploadMonitorInterval);try{this.server?.closeAllConnections?.(),this.server?.close?.()}catch{}this.channel.debug("Received shutdown message from CLI"),process.stdout.write("",()=>process.exit(0)),setTimeout(()=>process.exit(0),this.SHUTDOWN_FLUSH_TIMEOUT).unref()}async monitorUploadsCompletion(){let e=Date.now();!this.doneWaitingForReport&&mm(this.reportAsset,{testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET},e)&&this.settleReport();let r=gm({assets:this.assets,processingInProgress:this.processingInProgress,doneWaitingForReport:this.doneWaitingForReport,pendingWatchCount:this.watchAssets.length,testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,watchTimeoutMs:this.WATCH_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET,finalizeCeilingMs:this.FINALIZE_CEILING},e);if(!r){await As(1e3),this.monitorUploadsCompletion();return}this.finalizeRun(r,e)}stopWaitingForReport(e){this.doneWaitingForReport=!0,this.reportOutcome=e}reportAssetOutcome(){return this.reportAsset?.complete?"uploaded":this.reportAsset?.error?"failed":"abandoned"}settleReport(){this.stopWaitingForReport(this.reportAssetOutcome());let e="";try{let r=JSON.stringify(this.stats??{}),n=`checksum-stats-${(0,Vr.randomBytes)(8).toString("hex")}.json`;e=(0,De.join)((0,Sm.tmpdir)(),n),(0,oe.writeFileSync)(e,r,"utf-8"),this.channel.debug(`Stats written to temporary file: ${e}`)}catch(r){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${r.message}`)}this.channel.event("report-complete",`${this.reportOutcome==="uploaded"?"true":"false"}:${e}`)}finalizeRun(e,r){e.reason==="stall"&&this.emitStallDetected(e.abandonedAssets,r),e.abandonedAssets.forEach(a=>{a.error=!0});let n=this.assets.some(a=>a.error)?"uploads-complete-with-errors":"uploads-complete",s=this.assets.filter(a=>a.error);Gt("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:s.length>0?"error":"success",decision:n,total_assets:this.assets.length,completed:this.assets.filter(a=>a.complete).length,errored:s.length,stalled:e.abandonedAssets.length>0,stalled_count:e.abandonedAssets.length,finalize_reason:e.reason,finalize_budget_ms:this.FINALIZE_BUDGET,finalize_ceiling_ms:this.FINALIZE_CEILING,watch_remaining:this.watchAssets.length,report_outcome:this.reportOutcome,upload_finalize_ms:this.testRunEndTime?r-this.testRunEndTime:void 0,errored_assets:s.map(a=>this.assetSnapshot(a,r))});let i=n==="uploads-complete"?{}:{uploadErrors:s.map(a=>{try{return JSON.stringify(a)}catch{return a.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:r,finalizeReason:e.reason,abandonedAssets:e.abandonedAssets.map(a=>this.assetSnapshot(a,r))};if(hm(e))try{this.cleanUp()}catch(a){this.channel.debug("cleanUp failed (ignored): "+a?.message)}else this.channel.debug(`skipping cleanUp: ${e.abandonedAssets.length} asset(s) abandoned (${e.reason})`);this.channel.event(n,JSON.stringify(i))}assetSnapshot(e,r){return{file_name:e.info.fileName??(0,De.basename)(e.info.path),asset_type:e.info.type,test_id:e.info.testId,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,last_progress_age_ms:e.lastProgress?r-e.lastProgress:void 0}}cleanUp(){let e;for(let r of this.assets)if(r.info.type==="rrweb-recording"){e=(0,De.dirname)(r.info.path);break}e&&(0,oe.rmSync)(e,{recursive:!0,force:!0})}emitStallDetected(e,r){this.channel.log("Uploads are stalled"),!this.stallEventEmitted&&(this.stallEventEmitted=!0,Gt("upload_stall_detected",{test_suite_run_id:this.config.sessionId,outcome:"error",timeout_ms:this.UPLOAD_STALL_TIMEOUT,total_assets:this.assets.length,pending_count:e.length,pending_assets:e.map(n=>this.assetSnapshot(n,r))}))}async startServer(){let e=await this.acquirePortNumber();this.channel.event("port",e.toString()),this.server=(0,Tm.createServer)((r,n)=>{let s=o(a=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(a)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let i="";r.on("data",a=>{i+=a.toString()}),r.on("end",()=>{let a;try{a=JSON.parse(i)}catch{s("Invalid body");return}let{type:c,payload:l,watch:u}=a;switch(this.channel.debug(`Server received message, ${c}, ${this.stringify(l)}`),c){case"asset":if(!l.path||!l.type){s("Missing arguments");return}u?this.watchAsset(l):this.processAsset(l);break;case"testInfo":if(!l.pwTestId||!l.checksumTestId){s("Missing arguments");return}this.pwTestIdToChecksumTestId[l.pwTestId]=l.checksumTestId,l.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[l.checksumTestId]=l.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let d=l;if(!d.checksumTestId||!l.data){s("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...d}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(l));break;case"runProgress":this.forwardProgress(l);break;default:s("Invalid message type");return}n.writeHead(200,{"Content-Type":"text/plain"}),n.end("OK")})}),this.server.listen(e)}forwardProgress(e){this.latestProgress=e,!this.progressFlushInFlight&&this.flushProgress()}async flushProgress(){this.progressFlushInFlight=!0;try{for(;this.latestProgress;){let e=this.latestProgress;this.latestProgress=void 0,await this.patchProgress(e)}}finally{this.progressFlushInFlight=!1}}async patchProgress(e){if(this.isolationMode)return;let r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{await fetch(`${this.config.apiURL}/client-api/test-runs/${this.config.sessionId}/progress`,{method:"PATCH",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:JSON.stringify({progress:e}),signal:r.signal})}catch(s){this.channel.debug("Failed to send run progress: "+s?.message)}finally{clearTimeout(n)}}stringify(e){try{return JSON.stringify(e)}catch{return"message"in e?e.message:e}}monitorUploads(){let{totalSizeBytes:e,totalUploadedBytes:r}=this.calculateUploadProgress();if(e>0&&!this.isolationMode){let i=(r/e*100).toFixed(2);this.channel.event("upload-progress",i)}let n=this.assets.filter(i=>!i.uploadStarted);if(n.length===0)return;let s=o(()=>this.assets.filter(i=>i.uploadStarted&&!i.complete&&!i.error).length,"getNumOfActiveUploads");if(!(s()>=this.MAX_UPLOADS))for(;n.length>0&&s()<this.MAX_UPLOADS;){let i=n.pop();if(i===void 0)break;this.uploadAsset(i)}}calculateUploadProgress(){let e=this.assets.reduce((n,{sizeBytes:s})=>n+(s??0),0),r=Math.min(e,this.assets.reduce((n,{loadedBytes:s})=>n+(s??0),0));return{totalSizeBytes:e,totalUploadedBytes:r}}getUploadLogMessage(e){switch(e.info.type){case"report":return"Uploading report";case"har":return`Uploading har file for test ${e.info.testId}`;case"trace":return`Uploading trace file for test ${e.info.testId}`;case"esra":return`Uploading metadata file for test ${e.info.testId}`;case"test-files":return`Uploading auto-healed test code for file ${e.info.path}`;default:return}}async uploadAsset(e){try{e.uploadStarted=!0;let r=this.getUploadLogMessage(e);r&&!this.isolationMode&&this.channel.event("log",r),await this.testAssetUploader.uploadAsset(e)}catch(r){e.error=!0,this.channel.debug("Error uploading asset"+this.stringify(r)),this.channel.trace("Upload Failed",{asset:e.info.fileName,error:String(r)})}}watchAsset(e){if(this.watchAssets.some(n=>n.path===e.path)){this.channel.debug(`Already watching file ${e.path}, skipping duplicate`);return}this.channel.debug("Watching file "+e.path),this.watchAssets.push({...e,addedAt:Date.now()});let r=o(async()=>{await this.waitForFileComplete(e.path)&&(this.processAsset(e),this.watchAssets=this.watchAssets.filter(s=>s.path!==e.path))},"waitForCompletion");if((0,oe.existsSync)(e.path))r();else{let n=(0,De.dirname)(e.path),s=(0,De.basename)(e.path),i=!1,a=(0,oe.watch)(n,(c,l)=>{(async()=>{if(!(l!==s||i))try{this.channel.debug("Watched file changed "+e.path),i=!0,await r()}finally{a.close()}})()})}}waitForFileComplete(e,r=1e3,n=6e4,s=1){return new Promise(i=>{let a=Date.now(),c=0,l=s,u=o(()=>{if(!(0,oe.existsSync)(e)){this.channel.debug(`Asset required for upload doesn't exist anymore ${e}`),i(!1);return}let d=(0,oe.statSync)(e).size;if(d===c){if(l>0){this.channel.debug(`File size has not changed, verifying stabilization, ${e}, size: ${d}, equalSizeValidationCountLeft: ${l}`),l--,setTimeout(u,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${e}, size: ${d}`),i(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${e}, previous size: ${c}, current size: ${d}`),Date.now()-a>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${e}`),i(!0);return}c=d,setTimeout(u,r)},"checkFile");u()})}processAsset(e){switch(e.type){case"trace":return this.processTrace(e.path,e.testId);case"har":return this.processHar();case"rrweb-recording":case"esra":case"test-files":return this.addAsset(e);default:return}}async processHar(){}async calculateFileSha1Streaming(e){let r=(0,Vr.createHash)("sha1"),n=(0,oe.createReadStream)(e);return await(0,wm.pipeline)(n,r),r.digest("hex")}async processTrace(e,r){if(this.processingPaths.has(e)){this.channel.debug(`Trace file ${e} already being processed, skipping`);return}this.processingPaths.add(e);let n;try{this.processingInProgress=!0,await As(1e3),n=lr("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let s=e;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),s=e.replace(".zip",".actual.zip"),(0,oe.renameSync)(e,s);let c="checksum-playwright-trace:"+Date.now().toString()+(0,Vr.randomBytes)(1024).toString("hex");(0,oe.writeFileSync)(e,c)}let a=await o(async()=>await this.calculateFileSha1Streaming(e)+(0,De.extname)(e),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${a}, sending for upload...`),this.addAsset({type:"report-data-file",path:s,...r!==void 0?{testId:r}:{},fileName:a}),n?.emit({outcome:"success",file_name:a})}catch(s){let i=String(s);this.channel.debug("Error processing trace file"+i),this.channel.trace("Trace Processing Error",{error:i}),n?.emit({outcome:"error",error:et(s)})}finally{this.processingPaths.delete(e),this.processingInProgress=!1}}addAsset(e){this.channel.debug("Adding file "+e.path);let r=this.initAsset(e);return this.assets.push(r),r}initAsset(e){return{complete:!1,error:!1,info:e,removeAfterUpload:e.type==="rrweb-recording"}}async acquirePortNumber(){return new Promise((e,r)=>{let n=vm.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let s=n.address().port;n.close(()=>{e(s)})})})}},Im;try{Im=JSON.parse(process.argv[2]??"")}catch(t){console.error("Error starting test run monitor",t),process.exit(1)}new Ts(Im,process.argv?.[3]==="isolated");0&&(module.exports={TestRunMonitor});
|
|
70
70
|
/*! Bundled license information:
|
|
71
71
|
|
|
72
72
|
@langchain/core/dist/utils/js-sha256/hash.js:
|