// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
import{a as n}from"./chunk-V4WSBIXB.js";var o=class r{static{n(this,"SpanImpl")}id;traceId;parentId;name;data;startedAt;_endedAt;_error;_children=[];now;nextSpanId;onChildCreated;onSpanEnd;_ended=!1;constructor(e){this.id=e.id,this.traceId=e.traceId,this.parentId=e.parentId,this.name=e.name,this.data=e.data,this.now=e.now??(()=>Date.now()),this.startedAt=e.startedAt??this.now(),this.nextSpanId=e.nextSpanId??I,this.onChildCreated=e.onChildCreated,this.onSpanEnd=e.onSpanEnd}get endedAt(){return this._endedAt}get error(){return this._error}get children(){return this._children}addChild(e,a){let t=new r({id:this.nextSpanId(),traceId:this.traceId,parentId:this.id,name:e,data:a,now:this.now,nextSpanId:this.nextSpanId,onChildCreated:this.onChildCreated,onSpanEnd:this.onSpanEnd});return this._children.push(t),this.onChildCreated&&this.onChildCreated(t),t}setError(e){e instanceof Error?this._error={message:e.message,stack:e.stack}:this._error=e}end(){this._ended||(this._ended=!0,this._endedAt=this.now(),this.onSpanEnd&&this.onSpanEnd(this))}},f=0;function I(){f+=1;let r=Math.random().toString(36).slice(2,8);return`span-${Date.now()}-${f}-${r}`}n(I,"defaultNextSpanId");var g=0;function w(){g+=1;let r=Math.random().toString(36).slice(2,8);return`trace-${Date.now()}-${g}-${r}`}n(w,"defaultNextTraceId");function s(r={}){let e=r.now??(()=>Date.now()),a=r.id??(r.nextTraceId??w)(),t=e(),u=r.name??"trace",T=r.metadata??new Map,x=r.rootSpanData??{kind:"agent",agentName:u},m=!1,h,v,d=new o({id:`${a}-root`,traceId:a,name:u,data:x,startedAt:t,now:e,nextSpanId:r.nextSpanId,onChildCreated:r.onSpanStart,onSpanEnd:r.onSpanEnd});r.onSpanStart&&r.onSpanStart(d);let y={id:a,startedAt:t,rootSpan:d,metadata:T,get endedAt(){return h},get error(){return v??d.error},end(){m||(m=!0,h=e(),d.end(),r.onTraceEnd&&r.onTraceEnd(y))}};return y}n(s,"createTrace");var p=[];function c(r){for(let e of p)try{e.onSpanStart(r)}catch{}}n(c,"_emitSpanStart");function l(r){for(let e of p)try{e.onSpanEnd(r)}catch{}}n(l,"_emitSpanEnd");function S(r){for(let e of p)try{e.onTraceEnd(r)}catch{}}n(S,"_emitTraceEnd");var i=class{static{n(this,"Tracer")}options;constructor(e={}){this.options=e}startTrace(e={}){return s({id:e.id,name:e.name,rootSpanData:e.rootSpanData,metadata:e.metadata,now:this.options.now,nextSpanId:this.options.nextSpanId,nextTraceId:this.options.nextTraceId,onSpanStart:c,onSpanEnd:l,onTraceEnd:S})}},E=new i;export{E as a};
