
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Zuplo, Inc. All rights reserved.
 *
 *  This software and associated documentation files (the "Software") is intended to be used
 *  only by Zuplo customers solely to develop and test applications that will be deployed
 *  to Zuplo hosted services. You and others in your organization may use these files on your
 *  Development Devices solely for the above stated purpose.
 *
 *  Outside of uses stated above, no license is granted for any other purpose including
 *  without limitation the rights to use, copy, modify, merge, publish, distribute,
 *  sublicense, host, and/or sell copies of the Software.
 *
 *  The software may include third party components with separate legal notices or governed by
 *  other agreements, as described in licenses either embedded in or accompanying the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 *  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
 *  PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
 *  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
 *  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 *--------------------------------------------------------------------------------------------*/
    
var ot=Object.defineProperty;var n=(t,e)=>ot(t,"name",{value:e,configurable:!0});import{Buffer as nt}from"node:buffer";globalThis.Buffer=nt;import{ExportResultCode as le}from"@opentelemetry/core";import{JsonLogsSerializer as it,JsonTraceSerializer as ct}from"@opentelemetry/otlp-transformer";import{BackgroundDispatcher as de}from"@zuplo/runtime";function st(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}n(st,"isPlainObject");function pe(t){if(t==null)return"";if(Array.isArray(t)){for(let e=0;e<t.length;e+=1)t[e]=pe(t[e]);return t}return st(t)&&F(t),t}n(pe,"sanitizeValue");function F(t){Object.keys(t).forEach(e=>{t[e]=pe(t[e])})}n(F,"sanitizeEmptyAttributes");var J=Symbol("unwrap");function ue(t){return t&&!!t[J]}n(ue,"isWrapped");function at(t){return t!==null&&typeof t=="object"||typeof t=="function"}n(at,"isProxyable");function O(t,e,r=!0){if(ue(t)||!at(t))return t;let o=Object.assign({},e);return o.get=(s,a,i)=>{if(a===J)return t;if(e.get)return e.get(s,a,i);if(a==="bind")return()=>i;if(r)return Y(s,a)},o.apply=(s,a,i)=>{if(e.apply)return e.apply(C(s),C(a),i)},new Proxy(t,o)}n(O,"wrap");function C(t){return t&&ue(t)?t[J]:t}n(C,"unwrap");function Y(t,e,r){let o=C(t);r=C(r)||o;let s=Reflect.get(o,e);return typeof s=="function"?s.constructor.name==="RpcProperty"?(...a)=>o[e](...a):s.bind(r):s}n(Y,"passthroughGet");var me={accept:"application/json","content-type":"application/json"},x=class{static{n(this,"OTLPSpanExporter")}headers;url;constructor(e){this.url=e.url,this.headers=Object.assign({},me,e.headers)}export(e,r){e.forEach(o=>{this.batcher.enqueue(o)}),r({code:le.SUCCESS})}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}dispatchFunction=n(async e=>{if(e.length===0)return;e.forEach(i=>{F(i.attributes)});let r=new TextDecoder,o=ct.serializeRequest(e),s=r.decode(o),a=await C(fetch)(this.url,{method:"POST",body:s,headers:this.headers});if(!a.ok)try{let i=await a.text();throw new Error(`Error exporting traces: ${a.status}:${i}`)}catch(i){throw new Error(`Error exporting traces ${i.message}`)}},"dispatchFunction");batcher=new de(this.dispatchFunction,{msDelay:10})},I=class{static{n(this,"OTLPLogExporter")}headers;url;batcher;constructor(e,r){this.url=e.url,this.headers=Object.assign({},me,e.headers),this.batcher=new de(this.dispatchFunction,{msDelay:r?.scheduledDelayMillis??10})}export(e,r){e.forEach(o=>{this.batcher.enqueue(o)}),r({code:le.SUCCESS})}shutdown(){return Promise.resolve()}dispatchFunction=n(async e=>{if(e.length===0)return;e.forEach(i=>{F(i.attributes)});let r=new TextDecoder,o=it.serializeRequest(e),s=r.decode(o),a=await C(fetch)(this.url,{method:"POST",body:s,headers:this.headers});if(!a.ok)try{let i=await a.text();throw new Error(`Error exporting OTel logs: ${a.status}:${i}`)}catch(i){throw new Error(`Error exporting OTel logs: ${i.message}`)}},"dispatchFunction")};import{TelemetryPlugin as fr,trackFeature as gr}from"@zuplo/runtime";import{context as M,propagation as Le,SpanKind as _e,SpanStatusCode as xt,trace as St}from"@opentelemetry/api";import{context as Pe}from"@opentelemetry/api";import{W3CTraceContextPropagator as mt}from"@opentelemetry/core";var k=class{static{n(this,"DefaultLogProcessor")}exporter;constructor(e){this.exporter=e}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}onEmit(e){this.exporter.export([e],r=>{})}};import{SpanStatusCode as pt,TraceFlags as fe}from"@opentelemetry/api";import{ParentBasedSampler as ge,TraceIdRatioBasedSampler as ut}from"@opentelemetry/sdk-trace-base";import{SemanticAttributes as Q}from"@zuplo/runtime";function he(t){return e=>{let r=e.localRootSpan;return r.attributes[Q.SystemTrace]??r.attributes[Q.RouteSystem]??r.attributes[Q.RouteTrace]===!1?!1:t(e)}}n(he,"internalTailSampler");function Te(t){return e=>t.reduce((r,o)=>r||o(e),!1)}n(Te,"multiTailSampler");var xe=n(t=>(t.localRootSpan.spanContext().traceFlags&fe.SAMPLED)===fe.SAMPLED,"isHeadSampled"),Se=n(t=>t.localRootSpan.status.code===pt.ERROR,"isRootErrorSpan");function Re(t){let e=new ut(t.ratio);return typeof t.acceptRemote=="boolean"&&!t.acceptRemote?new ge({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new ge({root:e})}n(Re,"createSampler");import{ExportResultCode as lt}from"@opentelemetry/core";function dt(){let t=S();return t||console.log("Could not find config for sampling, sending everything by default"),t?t.sampling.tailSampler:()=>!0}n(dt,"getSampler");var ee=class{static{n(this,"TraceState")}unexportedSpans=[];inprogressSpans=new Set;exporter;exportPromises=[];localRootSpan;traceDecision;isFlushed=!1;constructor(e){this.exporter=e}addSpan(e){let r=e;this.localRootSpan=this.localRootSpan||r,this.unexportedSpans.push(r),this.inprogressSpans.add(e.spanContext().spanId)}hasFinished(){return this.inprogressSpans.size===0&&this.isFlushed}async endSpan(e){this.inprogressSpans.delete(e.spanContext().spanId),this.inprogressSpans.size===0&&await this.flush()}sample(){if(this.traceDecision===void 0&&this.unexportedSpans.length>0){let e=dt();this.traceDecision=e({traceId:this.localRootSpan.spanContext().traceId,localRootSpan:this.localRootSpan,spans:this.unexportedSpans})}this.unexportedSpans=this.traceDecision?this.unexportedSpans:[]}async flush(){if(this.unexportedSpans.length>0){let e=this.unexportedSpans.filter(r=>this.isSpanInProgress(r));for(let r of e)console.log(`Span ${r.spanContext().spanId} was not ended properly`),r.end();this.sample(),this.exportPromises.push(this.exportSpans([...this.unexportedSpans])),this.unexportedSpans=[]}this.exportPromises.length>0&&(await Promise.allSettled(this.exportPromises),this.exportPromises=[],this.isFlushed=!0)}isSpanInProgress(e){return this.inprogressSpans.has(e.spanContext().spanId)}async exportSpans(e){let r=S();if(!r){console.log("No config found for exporting spans, skipping export");return}let o=r.postProcessor(e);await scheduler.wait(1),await new Promise((a,i)=>{this.exporter.export(o,c=>{c.code===lt.SUCCESS?a():(console.log(`exporting spans failed! ${c.error}`),i(c.error))})})}},g=class{constructor(e){this.exporter=e}exporter;static{n(this,"BatchTraceSpanProcessor")}traces={};getTraceState(e){let r=this.traces[e]||new ee(this.exporter);return this.traces[e]=r,r}onStart(e,r){let o=e.spanContext().traceId;this.getTraceState(o).addSpan(e)}onEnd(e){let r=e.spanContext().traceId,o=this.getTraceState(r);o.endSpan(e).catch(s=>{console.log(s,"Failed to end span")}).finally(()=>{o.hasFinished()&&delete this.traces[r]})}async forceFlush(e){if(e)await this.getTraceState(e).flush(),delete this.traces[e];else{let r=Object.values(this.traces).map(o=>o.flush);await Promise.allSettled(r),this.traces={}}}async shutdown(){await this.forceFlush()}};function Ce(t){return!!t.spanProcessors}n(Ce,"isSpanProcessorConfig");function be(t){let e=!!t.spanProcessors,r=!!t.logProcessors;return e&&r}n(be,"isProcessorConfig");var ye=Symbol("Otel Tracing Configuration");function Ee(t,e=Pe.active()){return e.setValue(ye,t)}n(Ee,"setConfig");function S(){return Pe.active().getValue(ye)||void 0}n(S,"getActiveConfig");function ft(t){return!!t.shouldSample}n(ft,"isSampler");function gt(t){return!!t.exporter}n(gt,"isTraceConfigExporter");function ht(t){return typeof t.export=="function"}n(ht,"isSpanExporterInstance");function Tt(t){return!!t.logUrl&&!!t.traceUrl&&!!t.headers}n(Tt,"isTraceAndLogConfigExporter");function te(t){let e=[],r=[];if(gt(t)){let a=ht(t.exporter)?t.exporter:new x(t.exporter);e=[new g(a)]}else Tt(t)?(e=[new g(new x({url:t.traceUrl,headers:t.headers}))],r=[new k(new I({url:t.logUrl,headers:t.headers}))]):be(t)?(e=Array.isArray(t.spanProcessors)?t.spanProcessors:[t.spanProcessors],r=Array.isArray(t.logProcessors)?t.logProcessors:[t.logProcessors]):Ce(t)&&(e=Array.isArray(t.spanProcessors)?t.spanProcessors:[t.spanProcessors]);let o=t.sampling?.headSampler||{ratio:1},s=ft(o)?o:Re(o);return{fetch:{includeTraceContext:t.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:t.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:t.postProcessor||(a=>a),sampling:{headSampler:s,tailSampler:he(t.sampling?.tailSampler??Te([xe,Se]))},service:t.service,resourceAttributes:t.resourceAttributes,spanProcessors:e,propagator:t.propagator||new mt,instrumentation:{instrumentGlobalFetch:t.instrumentation?.instrumentGlobalFetch??!0},logProcessors:r}}n(te,"parseConfig");function we(t){let e={},r=t.headers;e["http.request.method"]=t.method.toUpperCase(),e["http.request.body.size"]=r.get("content-length"),e["user_agent.original"]=r.get("user-agent"),e["http.mime_type"]=r.get("content-type"),e["http.accepts"]=r.get("accept");let o=new URL(t.url);return e["url.full"]=`${o.protocol}//${o.host}${o.pathname}${o.search}`,e["server.address"]=o.host,e["url.scheme"]=o.protocol,e["url.path"]=o.pathname,e["url.query"]=o.search,e}n(we,"gatherRequestAttributes");function Ae(t){let e={};return e["http.response.status_code"]=t.status,t.headers.get("content-length")==null&&(e["http.response.body.size"]=t.headers.get("content-length")),e["http.mime_type"]=t.headers.get("content-type"),e}n(Ae,"gatherResponseAttributes");function Rt(t){return Le.extract(M.active(),t,{get(e,r){return e.get(r)||void 0},keys(e){return[...e.keys()]}})}n(Rt,"getParentContextFromHeaders");function Ct(t){let e=S();return e===void 0?M.active():(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(t):e.handlers.fetch.acceptTraceContext??!0)?Rt(t.headers):M.active()}n(Ct,"getParentContextFromRequest");function ve(t,e){let r=t;if(r.attributes["http.route"]){let o=e.method.toUpperCase();t.updateName(`${o} ${r.attributes["http.route"]}`)}}n(ve,"updateSpanNameOnRoute");var Fe={getInitialSpanInfo:n(t=>{let e=Ct(t),r={"faas.trigger":"http","faas.invocation_id":t.headers.get("zp-rid")??void 0,"cf.ray_id":t.headers.get("cf-ray")??void 0};return Object.assign(r,we(t)),{name:`fetchHandler ${t.method.toUpperCase()}`,options:{attributes:r,kind:_e.SERVER},context:e}},"getInitialSpanInfo"),getAttributesFromResult:n(t=>Ae(t),"getAttributesFromResult"),executionSuccess:ve,executionFailed:ve};function bt(t,e,r){return O(t,{apply:n((s,a,i)=>{let c=new Request(i[0],i[1]);if(!c.url.startsWith("http"))return Reflect.apply(s,a,i);let u=S();if(!u)return Reflect.apply(s,a,[c]);let l=e(u),f=St.getTracer("fetcher"),T={kind:_e.CLIENT,attributes:r},d=new URL(c.url).host,L=c.method.toUpperCase(),A=typeof r?.name=="string"?r?.name:`${L}: ${d}`;return f.startActiveSpan(A,T,async p=>{try{((typeof l.includeTraceContext=="function"?l.includeTraceContext(c):l.includeTraceContext)??!0)&&Le.inject(M.active(),c.headers,{set:n((W,K,y)=>W.set(K,typeof y=="string"?y:String(y)),"set")}),p.setAttributes(we(c));let Z=await Reflect.apply(s,a,[c]);return p.setAttributes(Ae(Z)),Z}catch(R){throw p.recordException(R),p.setStatus({code:xt.ERROR}),R}finally{p.end()}})},"apply")},!0)}n(bt,"instrumentClientFetch");function Oe(){globalThis.fetch=bt(globalThis.fetch,t=>t.fetch)}n(Oe,"instrumentGlobalFetch");import{context as Ke,context as Yt,propagation as Qt,SpanStatusCode as er,trace as Xe}from"@opentelemetry/api";import{resourceFromAttributes as ie}from"@opentelemetry/resources";import{ATTR_CLOUD_ACCOUNT_ID as tr,ATTR_CLOUD_PLATFORM as rr,ATTR_CLOUD_PROVIDER as or,ATTR_SERVICE_NAME as nr,ATTR_SERVICE_NAMESPACE as sr,ATTR_SERVICE_VERSION as ar,ATTR_TELEMETRY_SDK_NAME as ir}from"@opentelemetry/semantic-conventions/incubating";import{SemanticAttributes as q}from"@zuplo/runtime";import{AsyncLocalStorage as Pt}from"node:async_hooks";import{EventEmitter as yt}from"node:events";import{ROOT_CONTEXT as Et}from"@opentelemetry/api";var vt=["addListener","on","once","prependListener","prependOnceListener"],re=class{static{n(this,"AbstractAsyncHooksContextManager")}bind(e,r){return r instanceof yt?this._bindEventEmitter(e,r):typeof r=="function"?this._bindFunction(e,r):r}_bindFunction(e,r){let o=this,s=n(function(...a){return o.with(e,()=>r.apply(this,a))},"contextWrapper");return Object.defineProperty(s,"length",{enumerable:!1,configurable:!0,writable:!1,value:r.length}),s}_bindEventEmitter(e,r){return this._getPatchMap(r)!==void 0||(this._createPatchMap(r),vt.forEach(s=>{r[s]!==void 0&&(r[s]=this._patchAddListener(r,r[s],e))}),typeof r.removeListener=="function"&&(r.removeListener=this._patchRemoveListener(r,r.removeListener)),typeof r.off=="function"&&(r.off=this._patchRemoveListener(r,r.off)),typeof r.removeAllListeners=="function"&&(r.removeAllListeners=this._patchRemoveAllListeners(r,r.removeAllListeners))),r}_patchRemoveListener(e,r){let o=this;return function(s,a){let i=o._getPatchMap(e)?.[s];if(i===void 0)return r.call(this,s,a);let c=i.get(a);return r.call(this,s,c||a)}}_patchRemoveAllListeners(e,r){let o=this;return function(s){let a=o._getPatchMap(e);return a!==void 0&&(arguments.length===0?o._createPatchMap(e):a[s]!==void 0&&delete a[s]),r.apply(this,arguments)}}_patchAddListener(e,r,o){let s=this;return function(a,i){if(s._wrapped)return r.call(this,a,i);let c=s._getPatchMap(e);c===void 0&&(c=s._createPatchMap(e));let u=c[a];u===void 0&&(u=new WeakMap,c[a]=u);let l=s.bind(o,i);u.set(i,l),s._wrapped=!0;try{return r.call(this,a,l)}finally{s._wrapped=!1}}}_createPatchMap(e){let r=Object.create(null);return e[this._kOtListeners]=r,r}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},N=class extends re{static{n(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Pt}active(){return this._asyncLocalStorage.getStore()??Et}with(e,r,o,...s){let a=o==null?r:r.bind(o);return this._asyncLocalStorage.run(e,a,...s)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};import{trace as cn}from"@opentelemetry/api";import{context as se,SpanKind as Mt,TraceFlags as He,trace as U}from"@opentelemetry/api";import{sanitizeAttributes as Ue}from"@opentelemetry/core";import{RandomIdGenerator as Nt,SamplingDecision as Ht}from"@opentelemetry/sdk-trace-base";import{SpanKind as Lt,SpanStatusCode as _t}from"@opentelemetry/api";import{hrTimeDuration as wt,isAttributeValue as At,isTimeInput as Ft,sanitizeAttributes as Ie}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as ke,ATTR_EXCEPTION_STACKTRACE as Ot,ATTR_EXCEPTION_TYPE as Me}from"@opentelemetry/semantic-conventions";function It(t){let e={};return typeof t=="string"?e[ke]=t:(t.code?e[Me]=t.code.toString():t.name&&(e[Me]=t.name),t.message&&(e[ke]=t.message),t.stack&&(e[Ot]=t.stack)),e}n(It,"transformExceptionAttributes");function oe(t){return[Math.trunc(t/1e3),t%1e3*1e6]}n(oe,"millisToHr");function ne(t){let e=Date.now();if(t){if(t instanceof Date)return oe(t.getTime());if(typeof t=="number")return oe(t);if(Array.isArray(t))return t}else return oe(e);let r=t;throw new Error(`unreachable value: ${JSON.stringify(r)}`)}n(ne,"getHrTime");function kt(t){return typeof t=="string"&&t.length>0}n(kt,"isAttributeKey");var H=class{static{n(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;parentSpanContext;kind;attributes;status={code:_t.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationScope=Ne;_ended=!1;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.parentSpanContext=e.parentSpanContext,this.kind=e.spanKind||Lt.INTERNAL,this.attributes=Ie(e.attributes),this.startTime=ne(e.startTime),this.links=e.links||[],this.resource=e.resource,this.onEnd=e.onEnd}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}spanContext(){return this._spanContext}setAttribute(e,r){return kt(e)&&At(r)&&(this.attributes[e]=r),this}setAttributes(e){for(let[r,o]of Object.entries(e))this.setAttribute(r,o);return this}addEvent(e,r,o){Ft(r)&&(o=r,r=void 0);let s=Ie(r),a=ne(o);return this.events.push({name:e,attributes:s,time:a}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=ne(e),this._duration=wt(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,r){let o=It(e);this.addEvent("exception",o,r)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}};var ze=new Nt,De;function Ut(t,e){return(t>>e-1&1)*e}n(Ut,"getFlagAt");var b=class{static{n(this,"WorkerTracer")}spanProcessors;resource;constructor(e,r){this.spanProcessors=e,this.resource=r}async forceFlush(e){let r=this.spanProcessors.map(async o=>{await o.forceFlush(e)});await Promise.allSettled(r)}addToResource(e){this.resource.merge(e)}startSpan(e,r={},o=se.active()){r.root&&(o=U.deleteSpan(o));let s=S();if(!s)throw new Error("Config is undefined. This is a bug in the instrumentation logic");let a=U.getSpan(o)?.spanContext(),{traceId:i,randomTraceFlag:c}=Dt(a),u=r.kind||Mt.INTERNAL,l=Ue(r.attributes),T=s.sampling.headSampler.shouldSample(o,i,e,u,l,[]),{decision:d,traceState:L,attributes:A}=T,m=Object.assign({},r.attributes,A,De);De={};let p=ze.generateSpanId(),R=a?.spanId,W=(d===Ht.RECORD_AND_SAMPLED?He.SAMPLED:He.NONE)+c,K={traceId:i,spanId:p,traceFlags:W,traceState:L},y=new H({attributes:Ue(m),name:e,onEnd:n(X=>{this.spanProcessors.forEach(rt=>{rt.onEnd(X)})},"onEnd"),resource:this.resource,spanContext:K,parentSpanContext:a,parentSpanId:R,spanKind:u,startTime:r.startTime});return this.spanProcessors.forEach(X=>{X.onStart(y,o)}),y}startActiveSpan(e,...r){let o=r.length>1?r[0]:void 0,s=r.length>2?r[1]:se.active(),a=r[r.length-1],i=this.startSpan(e,o,s),c=U.setSpan(s,i);return se.with(c,a,void 0,i)}};function Dt(t){if(t&&U.isSpanContextValid(t)){let{traceId:e,traceFlags:r}=t;return{traceId:e,randomTraceFlag:Ut(r,2)}}else return{traceId:ze.generateTraceId(),randomTraceFlag:2}}n(Dt,"getTraceInfo");var ae=class{static{n(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await Bt(this._outstandingPromises)}};function zt(t,e,r){return O(t,{apply(s,a,i){return r.track(i[0]),Reflect.apply(s,e,i)}})}n(zt,"createWaitUntil");function Be(t){let e=new ae;return{event:new Proxy(t,{get(o,s){if(s==="waitUntil"){let a=Reflect.get(o,s);return zt(a,t,e)}else return Y(o,s)}}),tracker:e}}n(Be,"proxyExecutionContext");async function Bt(t){let e;do e=await Promise.allSettled(t);while(e.length!==t.length);return e}n(Bt,"allSettledMutable");import{logs as Xt}from"@opentelemetry/api-logs";import{diag as _}from"@opentelemetry/api";import{NOOP_LOGGER as Vt}from"@opentelemetry/api-logs";import{defaultResource as qt}from"@opentelemetry/resources";import{BindOnceFuture as Zt,merge as Wt}from"@opentelemetry/core";import{context as Gt}from"@opentelemetry/api";import{diag as jt}from"@opentelemetry/api";import*as h from"@opentelemetry/api";import{timeInputToHrTime as je,isAttributeValue as Ge}from"@opentelemetry/core";var D=class{static{n(this,"LogRecord")}hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,r,o){let{timestamp:s,observedTimestamp:a,severityNumber:i,severityText:c,body:u,attributes:l={},context:f}=o,T=Date.now();if(this.hrTime=je(s??T),this.hrTimeObserved=je(a??T),f){let d=h.trace.getSpanContext(f);d&&h.isSpanContextValid(d)&&(this.spanContext=d)}this.severityNumber=i,this.severityText=c,this.body=u,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this.setAttributes(l)}setAttribute(e,r){return this._isLogRecordReadonly()?this:r===null?this:e.length===0?(h.diag.warn(`Invalid attribute key: ${e}`),this):!Ge(r)&&!(typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length>0)?(h.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&h.diag.warn("Dropping extra attributes."),this):(Ge(r)?this.attributes[e]=this._truncateToSize(r):this.attributes[e]=r,this))}setAttributes(e){for(let[r,o]of Object.entries(e))this.setAttribute(r,o);return this}setBody(e){return this.body=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let r=this._logRecordLimits.attributeValueLengthLimit;return r<=0?(h.diag.warn(`Attribute value limit must be positive, got ${r}`),e):typeof e=="string"?this._truncateToLimitUtil(e,r):Array.isArray(e)?e.map(o=>typeof o=="string"?this._truncateToLimitUtil(o,r):o):e}_truncateToLimitUtil(e,r){return e.length<=r?e:e.substring(0,r)}_isLogRecordReadonly(){return this._isReadonly&&jt.warn("Can not execute the operation on emitted log record"),this._isReadonly}};var z=class{static{n(this,"Logger")}instrumentationScope;_sharedState;constructor(e,r){this.instrumentationScope=e,this._sharedState=r}emit(e){let r=e.context||Gt.active(),o=new D(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(o,r),o._makeReadonly()}};import{getNumberFromEnv as E}from"@opentelemetry/core";function $e(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:E("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:E("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??128},includeTraceContext:!0}}n($e,"loadDefaultConfig");function Ve(t){return{attributeCountLimit:t.attributeCountLimit??E("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??E("OTEL_ATTRIBUTE_COUNT_LIMIT")??128,attributeValueLengthLimit:t.attributeValueLengthLimit??E("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??E("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0}}n(Ve,"reconfigureLimits");var B=class{static{n(this,"NoopLogRecordProcessor")}forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}};import{callWithTimeout as $t}from"@opentelemetry/core";var v=class{static{n(this,"MultiLogRecordProcessor")}processors;forceFlushTimeoutMillis;constructor(e,r){this.processors=e,this.forceFlushTimeoutMillis=r}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(r=>$t(r.forceFlush(),e)))}onEmit(e,r){this.processors.forEach(o=>o.onEmit(e,r))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}};var j=class{static{n(this,"LoggerProviderSharedState")}resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,r,o,s){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=o,this.processors=s,s.length>0?(this.registeredLogRecordProcessors=s,this.activeProcessor=new v(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new B}};var Kt="unknown",w=class{static{n(this,"LoggerProvider")}_shutdownOnce;_sharedState;constructor(e={}){let r=Wt({},$e(),e),o=e.resource??qt();this._sharedState=new j(o,r.forceFlushTimeoutMillis,Ve(r.logRecordLimits),e?.processors??[]),this._shutdownOnce=new Zt(this._shutdown,this)}getLogger(e,r,o){if(this._shutdownOnce.isCalled)return _.warn("A shutdown LoggerProvider cannot provide a Logger"),Vt;e||_.warn("Logger requested without instrumentation scope name.");let s=e||Kt,a=`${s}@${r||""}:${o?.schemaUrl||""}`;return this._sharedState.loggers.has(a)||this._sharedState.loggers.set(a,new z({name:s,version:r,schemaUrl:o?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(a)}addLogRecordProcessor(e){this._sharedState.registeredLogRecordProcessors.length===0&&this._sharedState.activeProcessor.shutdown().catch(r=>_.error("Error while trying to shutdown current log record processor",r)),this._sharedState.registeredLogRecordProcessors.push(e),this._sharedState.activeProcessor=new v(this._sharedState.registeredLogRecordProcessors,this._sharedState.forceFlushTimeoutMillis)}forceFlush(){return this._shutdownOnce.isCalled?(_.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(_.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};var G=class{static{n(this,"ZuploOtelLogger")}baseLogger;constructor(e){this.baseLogger=e}emit(e){this.baseLogger.emit(e)}};var $=class extends w{static{n(this,"ZuploLoggerProvider")}getLogger(e,r,o){let s=super.getLogger(e,r,o);return new G(s)}register(){Xt.setGlobalLoggerProvider(this)}};import{trace as Jt}from"@opentelemetry/api";var V=class{static{n(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,r){this.spanProcessors=e,this.resource=r}getTracer(e,r,o){let s=`${e}@${r||""}:${o?.schemaUrl||""}`;return this.tracers[s]||(this.tracers[s]=new b(this.spanProcessors,this.resource)),this.tracers[s]}register(){Jt.setGlobalTracerProvider(this)}};var cr=n((t,e)=>{let r={[or]:"zuplo",[rr]:"zuplo-api",[tr]:t.accountName,"cloud.project.id":t.projectName,"cloud.resource_id":t.deploymentName,"cloud.instance_id":t.instanceId,"deployment.environment.name":t.environmentStage,"zuplo.account_name":t.accountName,"zuplo.project_name":t.projectName,"zuplo.deployment_name":t.deploymentName,[ir]:"@zuplo/otel",[q.ZuploBuildId]:t.buildId,[q.ZuploBuildVersion]:t.zuploVersion,[q.ZuploBuildCompatibilityDate]:t.compatibilityDate,[q.ZuploEnvironmentType]:t.environmentType},o=ie({[nr]:e.service?.name??t.projectName??t.deploymentName??"zuplo",[sr]:e.service?.namespace,[ar]:e.service?.version}),s=ie(r).merge(o);return e.resourceAttributes?s.merge(ie(e.resourceAttributes)):s},"createResource"),qe=!1;function Ze(t,e){if(!qe){e.instrumentation.instrumentGlobalFetch&&Oe(),Qt.setGlobalPropagator(e.propagator);let r=cr(t,e);new V(e.spanProcessors,r).register(),e.logProcessors.length>0&&new $({resource:r,processors:e.logProcessors}).register(),Yt.setGlobalContextManager(new N),qe=!0}}n(Ze,"init");function Je(t,e){return typeof e=="function"?r=>{let o=te(e(r));return Ze(t,o),o}:()=>{let r=te(e);return Ze(t,r),r}}n(Je,"createInitializer");async function pr(t,e){let r=Xe.getTracer("export");r instanceof b?(await scheduler.wait(1),await e?.wait(),await r.forceFlush(t)):console.error("The global tracer is not of type WorkerTracer and can not export spans")}n(pr,"exportSpans");var We=!0;function ur(t){return(e,r)=>{let[o,s]=r,{event:a,tracker:i}=Be(s),c=t.instrumentTrigger?t.instrumentTrigger(o):o,u=Xe.getTracer("handler"),{name:l,options:f,context:T}=t.getInitialSpanInfo(o),d=f.attributes||{};d["faas.coldstart"]=We,f.attributes=d,We=!1;let L=T||Ke.active();return u.startActiveSpan(l,f,L,async m=>{try{let p=await e(c,a);if(t.getAttributesFromResult){let R=t.getAttributesFromResult(p);m.setAttributes(R)}return t.executionSuccess&&t.executionSuccess(m,o,p),p}catch(p){throw m.recordException(p),m.setStatus({code:er.ERROR}),t.executionFailed&&t.executionFailed(m,o,p),p}finally{m.end(),s.waitUntil(pr(m.spanContext().traceId,i))}})}}n(ur,"createHandlerFlowFn");function Ye(t,e,r){return(o,s)=>{let a=e(o),i=Ee(a),c=ur(r);return Ke.with(i,c,o,t,[o,s])}}n(Ye,"createHandlerProxy");var Ne={name:"@zuplo/otel"};import{ConfigurationError as lr}from"@zuplo/runtime";var dr="/otel/v1/traces",Qe;function et(t){Qe=t}n(et,"setManagedTraceEndpoint");function mr(){return new lr("The Zuplo OpenTelemetry exporter (ZuploSpanExporter) is not available because the Zuplo-managed trace ingest is not configured for this deployment. This exporter only works in deployed Zuplo environments. For local development, configure your own `exporter` (or guard the ZuploSpanExporter behind an environment check) instead.")}n(mr,"missingIngestError");var P=class{static{n(this,"ZuploSpanExporter")}delegate;resolveDelegate(){if(this.delegate)return this.delegate;let e=Qe;if(!e||!e.token)throw mr();return this.delegate=new x({url:new URL(dr,e.url).toString(),headers:{authorization:`Bearer ${e.token}`}}),this.delegate}export(e,r){this.resolveDelegate().export(e,r)}shutdown(){return this.delegate?.shutdown()??Promise.resolve()}};function tt(t){return Array.isArray(t)?t.length>0:!!t}n(tt,"hasProcessors");function hr(t){let e=t;return!!e.exporter||tt(e.spanProcessors)||tt(e.logProcessors)||!!(e.logUrl&&e.traceUrl)}n(hr,"hasDestination");function Tr(t){let e=t??{};return hr(e)?e:{...e,spanProcessors:[new g(new P)]}}n(Tr,"withZuploDefaults");function xr(t){let e=t;return e.exporter instanceof P?!0:e.spanProcessors?(Array.isArray(e.spanProcessors)?e.spanProcessors:[e.spanProcessors]).some(o=>o instanceof g&&o.exporter instanceof P):!1}n(xr,"usesZuploExporter");var ce=class extends fr{static{n(this,"OpenTelemetryPlugin")}config;constructor(e){super(),gr("opentelemetry"),this.config=e}instrument(e){et({url:e.__internalOnlyRemoteLogUrl,token:e.__internalOnlyRemoteLogToken});let r=Tr(this.config);if(xr(r)&&!e.__internalOnlyRemoteLogToken)return{requestHandlerProxy:n(a=>a,"requestHandlerProxy")};let o=Je(e,r);return{requestHandlerProxy:n(a=>Ye(a,o,Fe),"requestHandlerProxy")}}};export{x as a,g as b,P as c,ce as d};
//# sourceMappingURL=chunk-T25G5RDX.js.map
