@zuplo/otel 0.0.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/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) Zuplo, Inc. All rights reserved.
2
+
3
+ This software and associated documentation files (the "Software") is intended to be used
4
+ only by Zuplo customers solely to develop and test applications that will be deployed
5
+ to Zuplo hosted services. You and others in your organization may use these files on your
6
+ Development Devices solely for the above stated purpose.
7
+
8
+ Outside of uses stated above, no license is granted for any other purpose including
9
+ without limitation the rights to use, copy, modify, merge, publish, distribute,
10
+ sublicense, host, and/or sell copies of the Software.
11
+
12
+ The software may include third party components with separate legal notices or governed by
13
+ other agreements, as described in licenses either embedded in or accompanying the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
16
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
17
+ PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
18
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # OpenTelemetry for Zuplo
package/index.min.cjs ADDED
@@ -0,0 +1,26 @@
1
+
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Zuplo, Inc. All rights reserved.
4
+ *
5
+ * This software and associated documentation files (the "Software") is intended to be used
6
+ * only by Zuplo customers solely to develop and test applications that will be deployed
7
+ * to Zuplo hosted services. You and others in your organization may use these files on your
8
+ * Development Devices solely for the above stated purpose.
9
+ *
10
+ * Outside of uses stated above, no license is granted for any other purpose including
11
+ * without limitation the rights to use, copy, modify, merge, publish, distribute,
12
+ * sublicense, host, and/or sell copies of the Software.
13
+ *
14
+ * The software may include third party components with separate legal notices or governed by
15
+ * other agreements, as described in licenses either embedded in or accompanying the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
+ * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
20
+ * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
+ * DEALINGS IN THE SOFTWARE.
23
+ *--------------------------------------------------------------------------------------------*/
24
+
25
+ "use strict";var A=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var a=(r,e)=>A(r,"name",{value:e,configurable:!0});var Oe=(r,e)=>{for(var t in e)A(r,t,{get:e[t],enumerable:!0})},Me=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ke(e))!He.call(r,o)&&o!==t&&A(r,o,{get:()=>e[o],enumerable:!(n=Le(e,o))||n.enumerable});return r};var Ne=r=>Me(A({},"__esModule",{value:!0}),r);var ot={};Oe(ot,{OpenTelemetryPlugin:()=>q});module.exports=Ne(ot);var ee=require("node:buffer");globalThis.Buffer=ee.Buffer;var Ie=require("@zuplo/runtime");var m=require("@opentelemetry/api");var W=require("@opentelemetry/api");var te=Symbol("Otel Tracing Configuration");function re(r,e=W.context.active()){return e.setValue(te,r)}a(re,"setConfig");function S(){return W.context.active().getValue(te)}a(S,"getActiveConfig");var B=Symbol("unwrap");function ne(r){return r&&!!r[B]}a(ne,"isWrapped");function qe(r){return typeof r=="object"||typeof r=="function"}a(qe,"isProxyable");function R(r,e,t=!0){if(ne(r)||!qe(r))return r;let n=Object.assign({},e);return n.get=(o,s,p)=>{if(s===B)return r;if(e.get)return e.get(o,s,p);if(s==="bind")return()=>p;if(t)return U(o,s)},n.apply=(o,s,p)=>{if(e.apply)return e.apply(y(o),y(s),p)},new Proxy(r,n)}a(R,"wrap");function y(r){return r&&ne(r)?r[B]:r}a(y,"unwrap");function U(r,e,t){let n=Reflect.get(y(r),e);return typeof n=="function"?(t=t||y(r),n.bind(t)):n}a(U,"passthroughGet");var ae=require("@opentelemetry/api");var l=require("@opentelemetry/api"),oe=require("@opentelemetry/core"),F=require("@opentelemetry/sdk-trace-base");var I=require("@opentelemetry/api"),f=require("@opentelemetry/core"),b=require("@opentelemetry/semantic-conventions");function ze(r){let e={};return typeof r=="string"?e[b.SemanticAttributes.EXCEPTION_MESSAGE]=r:(r.code?e[b.SemanticAttributes.EXCEPTION_TYPE]=r.code.toString():r.name&&(e[b.SemanticAttributes.EXCEPTION_TYPE]=r.name),r.message&&(e[b.SemanticAttributes.EXCEPTION_MESSAGE]=r.message),r.stack&&(e[b.SemanticAttributes.EXCEPTION_STACKTRACE]=r.stack)),e}a(ze,"transformExceptionAttributes");function G(r){return[Math.trunc(r/1e3),r%1e3*1e6]}a(G,"millisToHr");function $(r){let e=Date.now();if(r){if(r instanceof Date)return G(r.getTime());if(typeof r=="number")return G(r);if(Array.isArray(r))return r}else return G(e);let t=r;throw new Error(`unreachable value: ${JSON.stringify(t)}`)}a($,"getHrTime");var w=class{static{a(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;kind;attributes;status={code:I.SpanStatusCode.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationLibrary={name:"@zuplo/otel"};_ended=!1;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.kind=e.spanKind||I.SpanKind.INTERNAL,this.attributes=(0,f.sanitizeAttributes)(e.attributes),this.startTime=$(e.startTime),this.links=e.links||[],this.resource=e.resource,this.onEnd=e.onEnd}spanContext(){return this._spanContext}setAttribute(e,t){return(0,f.isAttributeKey)(e)&&(0,f.isAttributeValue)(t)&&(this.attributes[e]=t),this}setAttributes(e){for(let[t,n]of Object.entries(e))this.setAttribute(t,n);return this}addEvent(e,t,n){(0,f.isTimeInput)(t)&&(n=t,t=void 0);let o=(0,f.sanitizeAttributes)(t),s=$(n);return this.events.push({name:e,attributes:o,time:s}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=$(e),this._duration=(0,f.hrTimeDuration)(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,t){let n=ze(e);this.addEvent("exception",n,t)}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 P=class{static{a(this,"WorkerTracer")}_spanProcessors;resource;idGenerator=new F.RandomIdGenerator;constructor(e,t){this._spanProcessors=e,this.resource=t}get spanProcessors(){return this._spanProcessors}addToResource(e){this.resource.merge(e)}startSpan(e,t={},n=l.context.active()){t.root&&(n=l.trace.deleteSpan(n));let s=l.trace.getSpan(n)?.spanContext(),p=s&&l.trace.isSpanContextValid(s),i=p?s.traceId:this.idGenerator.generateTraceId(),u=t.kind||l.SpanKind.INTERNAL,c=(0,oe.sanitizeAttributes)(t.attributes),d=S().sampling.headSampler.shouldSample(n,i,e,u,c,[]),{decision:v,traceState:z,attributes:D}=d,J=Object.assign({},c,D),C=this.idGenerator.generateSpanId(),Q=p?s.spanId:void 0,E=v===F.SamplingDecision.RECORD_AND_SAMPLED?l.TraceFlags.SAMPLED:l.TraceFlags.NONE,j={traceId:i,spanId:C,traceFlags:E,traceState:z},_=new w({attributes:J,name:e,onEnd:x=>{this.spanProcessors.forEach(Fe=>{Fe.onEnd(x)})},resource:this.resource,spanContext:j,parentSpanId:Q,spanKind:u,startTime:t.startTime});return this.spanProcessors.forEach(x=>{x.onStart(_,n)}),_}startActiveSpan(e,...t){let n=t.length>1?t[0]:void 0,o=t.length>2?t[1]:l.context.active(),s=t[t.length-1],p=this.startSpan(e,n,o),i=l.trace.setSpan(o,p);return l.context.with(i,s,void 0,p)}};var K=class{static{a(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await je(this._outstandingPromises)}};function De(r,e,t){return R(r,{apply(o,s,p){return t.track(p[0]),Reflect.apply(o,e,p)}})}a(De,"createWaitUntil");function se(r){let e=new K;return{event:new Proxy(r,{get(n,o){if(o==="waitUntil"){let s=Reflect.get(n,o);return De(s,r,e)}else return U(n,o)}}),tracker:e}}a(se,"proxyExecutionContext");async function ie(r){let e=ae.trace.getTracer("export");if(e instanceof P){typeof scheduler<"u"?await scheduler.wait(1):await new Promise(n=>{setTimeout(n,1)}),r&&await r.wait();let t=e.spanProcessors.map(async n=>{await n.forceFlush()});await Promise.allSettled(t)}else console.error("The global tracer is not of type WorkerTracer and can not export spans")}a(ie,"exportSpans");async function je(r){let e;do e=await Promise.allSettled(r);while(e.length!==r.length);return e}a(je,"allSettledMutable");var h=require("@opentelemetry/api");function V(r){let e={},t=r.headers,n=r.cf;e["http.request.method"]=r.method.toUpperCase(),e["network.protocol.name"]="http",e["network.protocol.version"]=n?.httpProtocol;let o=t.get("content-length");o&&(e["http.request.body.size"]=o);let s=t.get("user-agent");s&&(e["user_agent.original"]=s);let p=t.get("content-type");p&&(e["http.mime_type"]=p),e["http.accepts"]=n?.clientAcceptEncoding;let i=new URL(r.url);return e["url.full"]=`${i.protocol}//${i.host}${i.pathname}${i.search}`,e["server.address"]=i.host,e["url.scheme"]=i.protocol,e["url.path"]=i.pathname,e["url.query"]=i.search,e}a(V,"gatherRequestAttributes");function X(r){let e={};e["http.response.status_code"]=r.status;let t=r.headers.get("content-length");t&&(e["http.response.body.size"]=t);let n=r.headers.get("content-type");return n&&(e["http.mime_type"]=n),e}a(X,"gatherResponseAttributes");function pe(r){let e={},t=r.cf;return e["net.colo"]=t?.colo,e["net.country"]=t?.country,e["net.request_priority"]=t?.requestPriority,e["net.tls_cipher"]=t?.tlsCipher,e["net.tls_version"]=t?.tlsVersion,e["net.asn"]=t?.asn,e["net.tcp_rtt"]=t?.clientTcpRtt,e}a(pe,"gatherIncomingCfAttributes");function We(r,e,t){return R(r,{apply:(o,s,p)=>{let i=new Request(p[0],p[1]);if(!i.url.startsWith("http"))return Reflect.apply(o,s,p);let u=S(),c=e(u),g=h.trace.getTracer("fetcher"),d={kind:h.SpanKind.CLIENT,attributes:t},v=new URL(i.url).host,z=i.method.toUpperCase(),D=typeof t?.name=="string"?t?.name:`${z}: ${v}`;return g.startActiveSpan(D,d,async C=>{((typeof c.includeTraceContext=="function"?c.includeTraceContext(i):c.includeTraceContext)??!0)&&h.propagation.inject(h.context.active(),i.headers,{set:(j,_,x)=>j.set(_,typeof x=="string"?x:String(x))}),C.setAttributes(V(i)),i.cf&&C.setAttributes(gatherOutgoingCfAttributes(i.cf));let E=await Reflect.apply(o,s,[i]);return C.setAttributes(X(E)),C.end(),E})}},!0)}a(We,"instrumentClientFetch");function ce(){globalThis.fetch=We(globalThis.fetch,r=>r.fetch)}a(ce,"instrumentGlobalFetch");function Be(r){return m.propagation.extract(m.context.active(),r,{get(e,t){return e.get(t)||void 0},keys(e){return[...e.keys()]}})}a(Be,"getParentContextFromHeaders");function Ue(r){let e=S();return(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(r):e.handlers.fetch.acceptTraceContext??!0)?Be(r.headers):m.context.active()}a(Ue,"getParentContextFromRequest");var le=!0;function Ge(r,[e,t]){let n=Ue(e),o=m.trace.getTracer("pipeline"),s={"faas.trigger":"http","faas.coldstart":le,"faas.invocation_id":e.headers.get("zp-rid")??void 0,"cf.ray_id":e.headers.get("cf-ray")??void 0};le=!1,Object.assign(s,V(e)),Object.assign(s,pe(e));let p={attributes:s,kind:m.SpanKind.SERVER},i=e.method.toUpperCase();return o.startActiveSpan(i,p,n,async c=>{let g=c;try{let d=await r(e,t);return c.setAttributes(X(d)),g.attributes["http.route"]&&c.updateName(`${i} ${g.attributes["http.route"]}`),d}catch(d){throw g.attributes["http.route"]&&c.updateName(`${i} ${g.attributes["http.route"]}`),c.recordException(d),c.setStatus({code:m.SpanStatusCode.ERROR}),d}finally{c.end()}})}a(Ge,"executeRequestHandler");function ue(r,e){return R(r,{apply:async(n,o,s)=>{let[p,i]=s,u=e(p),{event:c,tracker:g}=se(i),d=re(u);try{let v=[p,c];return await m.context.with(d,Ge,void 0,n,v)}finally{i.waitUntil(ie(g))}}})}a(ue,"createHandlerProxy");var Ee=require("@opentelemetry/api"),_e=require("@opentelemetry/core"),Y=require("@opentelemetry/resources"),T=require("@opentelemetry/sdk-trace-base");var de=require("@opentelemetry/core"),me=require("@opentelemetry/otlp-transformer"),fe=require("@zuplo/runtime");var $e={accept:"application/json","content-type":"application/json"},L=class{static{a(this,"OTLPExporter")}headers;url;useHex;useLongBits;constructor(e){this.url=e.url,this.headers=Object.assign({},$e,e.headers),this.useHex=e.useHex,this.useLongBits=e.useLongBits}export(e,t){e.forEach(n=>{this.batcher.enqueue(n)}),t({code:de.ExportResultCode.SUCCESS})}shutdown(){throw new Error("Method not implemented.")}forceFlush(){throw new Error("Method not implemented.")}dispatchFunction=async e=>{if(e.length===0)return;let t=(0,me.createExportTraceServiceRequest)(e,{useLongBits:this.useLongBits,useHex:this.useHex}),n=await y(fetch)(this.url,{method:"POST",body:JSON.stringify(t),headers:this.headers});if(!n.ok)try{let o=await n.text();console.log("Error exporting traces",o)}catch{console.log("Error exporting traces")}};batcher=new fe.BackgroundDispatcher(this.dispatchFunction,{msDelay:10})};var O=require("@opentelemetry/api");var ge=require("@opentelemetry/api"),Se=require("node:async_hooks"),he=require("node:events");var Ke=["addListener","on","once","prependListener","prependOnceListener"],Z=class{static{a(this,"AbstractAsyncHooksContextManager")}bind(e,t){return t instanceof he.EventEmitter?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}_bindFunction(e,t){let n=this,o=a(function(...s){return n.with(e,()=>t.apply(this,s))},"contextWrapper");return Object.defineProperty(o,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),o}_bindEventEmitter(e,t){return this._getPatchMap(t)!==void 0||(this._createPatchMap(t),Ke.forEach(o=>{t[o]!==void 0&&(t[o]=this._patchAddListener(t,t[o],e))}),typeof t.removeListener=="function"&&(t.removeListener=this._patchRemoveListener(t,t.removeListener)),typeof t.off=="function"&&(t.off=this._patchRemoveListener(t,t.off)),typeof t.removeAllListeners=="function"&&(t.removeAllListeners=this._patchRemoveAllListeners(t,t.removeAllListeners))),t}_patchRemoveListener(e,t){let n=this;return function(o,s){let p=n._getPatchMap(e)?.[o];if(p===void 0)return t.call(this,o,s);let i=p.get(s);return t.call(this,o,i||s)}}_patchRemoveAllListeners(e,t){let n=this;return function(o){let s=n._getPatchMap(e);return s!==void 0&&(arguments.length===0?n._createPatchMap(e):s[o]!==void 0&&delete s[o]),t.apply(this,arguments)}}_patchAddListener(e,t,n){let o=this;return function(s,p){if(o._wrapped)return t.call(this,s,p);let i=o._getPatchMap(e);i===void 0&&(i=o._createPatchMap(e));let u=i[s];u===void 0&&(u=new WeakMap,i[s]=u);let c=o.bind(n,p);u.set(p,c),o._wrapped=!0;try{return t.call(this,s,c)}finally{o._wrapped=!1}}}_createPatchMap(e){let t=Object.create(null);return e[this._kOtListeners]=t,t}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},k=class extends Z{static{a(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Se.AsyncLocalStorage}active(){return this._asyncLocalStorage.getStore()??ge.ROOT_CONTEXT}with(e,t,n,...o){let s=n==null?t:t.bind(n);return this._asyncLocalStorage.run(e,s,...o)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};var H=class{static{a(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,t){this.spanProcessors=e,this.resource=t}getTracer(e,t,n){let o=`${e}@${t||""}:${n?.schemaUrl||""}`;return this.tracers[o]||(this.tracers[o]=new P(this.spanProcessors,this.resource)),this.tracers[o]}register(){O.trace.setGlobalTracerProvider(this),O.context.setGlobalContextManager(new k)}};var M=require("@opentelemetry/api");function xe(r){return e=>r.reduce((t,n)=>t||n(e),!1)}a(xe,"multiTailSampler");var Te=a(r=>r.localRootSpan.spanContext().traceFlags===M.TraceFlags.SAMPLED,"isHeadSampled"),Ce=a(r=>r.localRootSpan.status.code===M.SpanStatusCode.ERROR,"isRootErrorSpan");var ye=require("@opentelemetry/api"),Re=require("@opentelemetry/core"),be=require("ts-checked-fsm");function Ve(r,{span:e}){let t=e.spanContext().spanId;return{...r,stateName:"in_progress",traceId:e.spanContext().traceId,localRootSpan:e,completedSpans:[],inProgressSpanIds:new Set([t])}}a(Ve,"newTrace");function Xe(r,{span:e}){let t=e.spanContext().spanId;return r.inProgressSpanIds.add(t),{...r}}a(Xe,"newSpan");function Ze(r,{span:e}){return r.completedSpans.push(e),r.inProgressSpanIds.delete(e.spanContext().spanId),r.inProgressSpanIds.size===0?{stateName:"trace_complete",traceId:r.traceId,localRootSpan:r.localRootSpan,completedSpans:r.completedSpans}:{...r}}a(Ze,"endSpan");function Ye(r,{args:e}){let{exporter:t,tailSampler:n,postProcessor:o}=e,{traceId:s,localRootSpan:p,completedSpans:i}=r;if(n({traceId:s,localRootSpan:p,spans:i})){let c=o(i);return{stateName:"exporting",promise:new Promise(d=>{t.export(c,d)})}}else return{stateName:"done"}}a(Ye,"startExport");var{nextState:Je}=(0,be.stateMachine)().state("not_started").state("in_progress").state("trace_complete").state("exporting").state("done").transition("not_started","in_progress").transition("in_progress","in_progress").transition("in_progress","trace_complete").transition("trace_complete","exporting").transition("trace_complete","done").transition("exporting","done").action("startSpan").action("endSpan").action("startExport").action("exportDone").actionHandler("not_started","startSpan",Ve).actionHandler("in_progress","startSpan",Xe).actionHandler("in_progress","endSpan",Ze).actionHandler("trace_complete","startExport",Ye).actionHandler("exporting","exportDone",(r,e)=>({stateName:"done"})).done(),N=class{constructor(e){this.exporter=e}static{a(this,"BatchTraceSpanProcessor")}traceLookup=new Map;localRootSpanLookup=new Map;inprogressExports=new Map;action(e,t){let n=this.traceLookup.get(e)||{stateName:"not_started"},o=Je(n,t);return o.stateName==="done"?this.traceLookup.delete(e):this.traceLookup.set(e,o),o}export(e){let{sampling:t,postProcessor:n}=S(),o={exporter:this.exporter,tailSampler:t.tailSampler,postProcessor:n},s=this.action(e,{actionName:"startExport",args:o});if(s.stateName==="exporting"){let p=s.promise;this.inprogressExports.set(e,p),p.then(i=>{i.code===Re.ExportResultCode.FAILED&&console.log("Error sending spans to exporter:",i.error),this.action(e,{actionName:"exportDone"}),this.inprogressExports.delete(e)})}}onStart(e,t){let n=e.spanContext().spanId,o=ye.trace.getSpan(t)?.spanContext()?.spanId,p=(o?this.localRootSpanLookup.get(o):void 0)||n;this.localRootSpanLookup.set(n,p),this.action(p,{actionName:"startSpan",span:e})}onEnd(e){let t=e.spanContext().spanId,n=this.localRootSpanLookup.get(t);if(n){let o=this.action(n,{actionName:"endSpan",span:e});o.stateName==="trace_complete"&&(o.completedSpans.forEach(s=>{this.localRootSpanLookup.delete(s.spanContext().spanId)}),this.export(n))}}async forceFlush(){await Promise.allSettled(this.inprogressExports.values())}async shutdown(){}};function Pe(r){return!!r.spanProcessors}a(Pe,"isSpanProcessorConfig");var Qe=a((r,e)=>{let t={"cloud.provider":"zuplo","cloud.platform":"zuplo-api","cloud.account.id":r.accountName,"cloud.project.id":r.projectName,"cloud.resource_id":r.deploymentName,"cloud.instance_id":r.instanceId,"telemetry.sdk.language":"js","telemetry.sdk.name":"@zuplo/otel","zuplo.build.id":r.buildId,"zuplo.build.version":r.zuploVersion,"zuplo.build.compatibility_date":r.compatibilityDate,"zuplo.environment_type":r.environmentType,"zuplo.environment_stage":r.environmentStage},n=new Y.Resource({"service.name":e.service.name,"service.namespace":e.service.namespace,"service.version":e.service.version});return new Y.Resource(t).merge(n)},"createResource");function et(r){return!!r.export}a(et,"isSpanExporter");function tt(r){return!!r.shouldSample}a(tt,"isSampler");function rt(r){let e=new T.TraceIdRatioBasedSampler(r.ratio);return typeof r.acceptRemote=="boolean"&&!r.acceptRemote?new T.ParentBasedSampler({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new T.ParentBasedSampler({root:e})}a(rt,"createSampler");var ve=!1;function nt(r,e){if(!ve){ce(),Ee.propagation.setGlobalPropagator(e.propagator);let t=Qe(r,e);new H(e.spanProcessors,t).register(),ve=!0}}a(nt,"init");function Ae(r,e){if(Pe(e)){let t=e.sampling?.headSampler,n=t?tt(t)?t:rt(t):new T.AlwaysOnSampler,o=Array.isArray(e.spanProcessors)?e.spanProcessors:[e.spanProcessors];return o.length===0&&console.log("Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration."),{fetch:{includeTraceContext:e.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:e.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:e.postProcessor??(s=>s),sampling:{headSampler:n,tailSampler:e.sampling?.tailSampler??xe([Te,Ce])},service:{name:e.service?.name??r.deploymentName,version:e.service?.version,namespace:e.service?.namespace},spanProcessors:o,propagator:e.propagator??new _e.W3CTraceContextPropagator}}else{let t=et(e.exporter)?e.exporter:new L({useHex:!0,useLongBits:!1,...e.exporter}),n=[new N(t)],o=Object.assign(e,{exporter:void 0,spanProcessors:n});return Ae(r,o)}}a(Ae,"parseConfig");function we(r,e){return()=>{let t=Ae(r,e);return nt(r,t),t}}a(we,"createInitializer");var q=class extends Ie.TelemetryPlugin{constructor(t){super();this.config=t}static{a(this,"OpenTelemetryPlugin")}instrument(t){let n=we(t,this.config);return{requestHandlerProxy:a(s=>ue(s,n),"requestHandlerProxy")}}};
26
+ /*! For license information please see index.min.cjs.LEGAL.txt */
File without changes
package/index.min.js ADDED
@@ -0,0 +1,27 @@
1
+ /// <reference types="./no-types.d.ts" />
2
+
3
+ /*---------------------------------------------------------------------------------------------
4
+ * Copyright (c) Zuplo, Inc. All rights reserved.
5
+ *
6
+ * This software and associated documentation files (the "Software") is intended to be used
7
+ * only by Zuplo customers solely to develop and test applications that will be deployed
8
+ * to Zuplo hosted services. You and others in your organization may use these files on your
9
+ * Development Devices solely for the above stated purpose.
10
+ *
11
+ * Outside of uses stated above, no license is granted for any other purpose including
12
+ * without limitation the rights to use, copy, modify, merge, publish, distribute,
13
+ * sublicense, host, and/or sell copies of the Software.
14
+ *
15
+ * The software may include third party components with separate legal notices or governed by
16
+ * other agreements, as described in licenses either embedded in or accompanying the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
19
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
20
+ * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
21
+ * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ * DEALINGS IN THE SOFTWARE.
24
+ *--------------------------------------------------------------------------------------------*/
25
+
26
+ var me=Object.defineProperty;var a=(r,e)=>me(r,"name",{value:e,configurable:!0});import{Buffer as fe}from"node:buffer";globalThis.Buffer=fe;import{TelemetryPlugin as ht}from"@zuplo/runtime";import{SpanKind as Oe,SpanStatusCode as Me,context as D,propagation as Ne,trace as qe}from"@opentelemetry/api";import{context as G}from"@opentelemetry/api";var $=Symbol("Otel Tracing Configuration");function K(r,e=G.active()){return e.setValue($,r)}a(K,"setConfig");function m(){return G.active().getValue($)}a(m,"getActiveConfig");var L=Symbol("unwrap");function V(r){return r&&!!r[L]}a(V,"isWrapped");function ge(r){return typeof r=="object"||typeof r=="function"}a(ge,"isProxyable");function h(r,e,t=!0){if(V(r)||!ge(r))return r;let n=Object.assign({},e);return n.get=(o,s,p)=>{if(s===L)return r;if(e.get)return e.get(o,s,p);if(s==="bind")return()=>p;if(t)return k(o,s)},n.apply=(o,s,p)=>{if(e.apply)return e.apply(S(o),S(s),p)},new Proxy(r,n)}a(h,"wrap");function S(r){return r&&V(r)?r[L]:r}a(S,"unwrap");function k(r,e,t){let n=Reflect.get(S(r),e);return typeof n=="function"?(t=t||S(r),n.bind(t)):n}a(k,"passthroughGet");import{trace as _e}from"@opentelemetry/api";import{SpanKind as be,TraceFlags as Z,context as M,trace as P}from"@opentelemetry/api";import{sanitizeAttributes as Pe}from"@opentelemetry/core";import{RandomIdGenerator as ve,SamplingDecision as Ee}from"@opentelemetry/sdk-trace-base";import{SpanKind as Se,SpanStatusCode as he}from"@opentelemetry/api";import{hrTimeDuration as xe,isAttributeKey as Te,isAttributeValue as Ce,isTimeInput as ye,sanitizeAttributes as X}from"@opentelemetry/core";import{SemanticAttributes as C}from"@opentelemetry/semantic-conventions";function Re(r){let e={};return typeof r=="string"?e[C.EXCEPTION_MESSAGE]=r:(r.code?e[C.EXCEPTION_TYPE]=r.code.toString():r.name&&(e[C.EXCEPTION_TYPE]=r.name),r.message&&(e[C.EXCEPTION_MESSAGE]=r.message),r.stack&&(e[C.EXCEPTION_STACKTRACE]=r.stack)),e}a(Re,"transformExceptionAttributes");function H(r){return[Math.trunc(r/1e3),r%1e3*1e6]}a(H,"millisToHr");function O(r){let e=Date.now();if(r){if(r instanceof Date)return H(r.getTime());if(typeof r=="number")return H(r);if(Array.isArray(r))return r}else return H(e);let t=r;throw new Error(`unreachable value: ${JSON.stringify(t)}`)}a(O,"getHrTime");var b=class{static{a(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;kind;attributes;status={code:he.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationLibrary={name:"@zuplo/otel"};_ended=!1;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.kind=e.spanKind||Se.INTERNAL,this.attributes=X(e.attributes),this.startTime=O(e.startTime),this.links=e.links||[],this.resource=e.resource,this.onEnd=e.onEnd}spanContext(){return this._spanContext}setAttribute(e,t){return Te(e)&&Ce(t)&&(this.attributes[e]=t),this}setAttributes(e){for(let[t,n]of Object.entries(e))this.setAttribute(t,n);return this}addEvent(e,t,n){ye(t)&&(n=t,t=void 0);let o=X(t),s=O(n);return this.events.push({name:e,attributes:o,time:s}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=O(e),this._duration=xe(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,t){let n=Re(e);this.addEvent("exception",n,t)}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 x=class{static{a(this,"WorkerTracer")}_spanProcessors;resource;idGenerator=new ve;constructor(e,t){this._spanProcessors=e,this.resource=t}get spanProcessors(){return this._spanProcessors}addToResource(e){this.resource.merge(e)}startSpan(e,t={},n=M.active()){t.root&&(n=P.deleteSpan(n));let s=P.getSpan(n)?.spanContext(),p=s&&P.isSpanContextValid(s),i=p?s.traceId:this.idGenerator.generateTraceId(),l=t.kind||be.INTERNAL,c=Pe(t.attributes),u=m().sampling.headSampler.shouldSample(n,i,e,l,c,[]),{decision:T,traceState:w,attributes:I}=u,B=Object.assign({},c,I),g=this.idGenerator.generateSpanId(),U=p?s.spanId:void 0,y=T===Ee.RECORD_AND_SAMPLED?Z.SAMPLED:Z.NONE,F={traceId:i,spanId:g,traceFlags:y,traceState:w},R=new b({attributes:B,name:e,onEnd:f=>{this.spanProcessors.forEach(de=>{de.onEnd(f)})},resource:this.resource,spanContext:F,parentSpanId:U,spanKind:l,startTime:t.startTime});return this.spanProcessors.forEach(f=>{f.onStart(R,n)}),R}startActiveSpan(e,...t){let n=t.length>1?t[0]:void 0,o=t.length>2?t[1]:M.active(),s=t[t.length-1],p=this.startSpan(e,n,o),i=P.setSpan(o,p);return M.with(i,s,void 0,p)}};var N=class{static{a(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await we(this._outstandingPromises)}};function Ae(r,e,t){return h(r,{apply(o,s,p){return t.track(p[0]),Reflect.apply(o,e,p)}})}a(Ae,"createWaitUntil");function Y(r){let e=new N;return{event:new Proxy(r,{get(n,o){if(o==="waitUntil"){let s=Reflect.get(n,o);return Ae(s,r,e)}else return k(n,o)}}),tracker:e}}a(Y,"proxyExecutionContext");async function J(r){let e=_e.getTracer("export");if(e instanceof x){typeof scheduler<"u"?await scheduler.wait(1):await new Promise(n=>{setTimeout(n,1)}),r&&await r.wait();let t=e.spanProcessors.map(async n=>{await n.forceFlush()});await Promise.allSettled(t)}else console.error("The global tracer is not of type WorkerTracer and can not export spans")}a(J,"exportSpans");async function we(r){let e;do e=await Promise.allSettled(r);while(e.length!==r.length);return e}a(we,"allSettledMutable");import{SpanKind as Ie,context as Fe,propagation as Le,trace as ke}from"@opentelemetry/api";function q(r){let e={},t=r.headers,n=r.cf;e["http.request.method"]=r.method.toUpperCase(),e["network.protocol.name"]="http",e["network.protocol.version"]=n?.httpProtocol;let o=t.get("content-length");o&&(e["http.request.body.size"]=o);let s=t.get("user-agent");s&&(e["user_agent.original"]=s);let p=t.get("content-type");p&&(e["http.mime_type"]=p),e["http.accepts"]=n?.clientAcceptEncoding;let i=new URL(r.url);return e["url.full"]=`${i.protocol}//${i.host}${i.pathname}${i.search}`,e["server.address"]=i.host,e["url.scheme"]=i.protocol,e["url.path"]=i.pathname,e["url.query"]=i.search,e}a(q,"gatherRequestAttributes");function z(r){let e={};e["http.response.status_code"]=r.status;let t=r.headers.get("content-length");t&&(e["http.response.body.size"]=t);let n=r.headers.get("content-type");return n&&(e["http.mime_type"]=n),e}a(z,"gatherResponseAttributes");function Q(r){let e={},t=r.cf;return e["net.colo"]=t?.colo,e["net.country"]=t?.country,e["net.request_priority"]=t?.requestPriority,e["net.tls_cipher"]=t?.tlsCipher,e["net.tls_version"]=t?.tlsVersion,e["net.asn"]=t?.asn,e["net.tcp_rtt"]=t?.clientTcpRtt,e}a(Q,"gatherIncomingCfAttributes");function He(r,e,t){return h(r,{apply:(o,s,p)=>{let i=new Request(p[0],p[1]);if(!i.url.startsWith("http"))return Reflect.apply(o,s,p);let l=m(),c=e(l),d=ke.getTracer("fetcher"),u={kind:Ie.CLIENT,attributes:t},T=new URL(i.url).host,w=i.method.toUpperCase(),I=typeof t?.name=="string"?t?.name:`${w}: ${T}`;return d.startActiveSpan(I,u,async g=>{((typeof c.includeTraceContext=="function"?c.includeTraceContext(i):c.includeTraceContext)??!0)&&Le.inject(Fe.active(),i.headers,{set:(F,R,f)=>F.set(R,typeof f=="string"?f:String(f))}),g.setAttributes(q(i)),i.cf&&g.setAttributes(gatherOutgoingCfAttributes(i.cf));let y=await Reflect.apply(o,s,[i]);return g.setAttributes(z(y)),g.end(),y})}},!0)}a(He,"instrumentClientFetch");function ee(){globalThis.fetch=He(globalThis.fetch,r=>r.fetch)}a(ee,"instrumentGlobalFetch");function ze(r){return Ne.extract(D.active(),r,{get(e,t){return e.get(t)||void 0},keys(e){return[...e.keys()]}})}a(ze,"getParentContextFromHeaders");function De(r){let e=m();return(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(r):e.handlers.fetch.acceptTraceContext??!0)?ze(r.headers):D.active()}a(De,"getParentContextFromRequest");var te=!0;function je(r,[e,t]){let n=De(e),o=qe.getTracer("pipeline"),s={"faas.trigger":"http","faas.coldstart":te,"faas.invocation_id":e.headers.get("zp-rid")??void 0,"cf.ray_id":e.headers.get("cf-ray")??void 0};te=!1,Object.assign(s,q(e)),Object.assign(s,Q(e));let p={attributes:s,kind:Oe.SERVER},i=e.method.toUpperCase();return o.startActiveSpan(i,p,n,async c=>{let d=c;try{let u=await r(e,t);return c.setAttributes(z(u)),d.attributes["http.route"]&&c.updateName(`${i} ${d.attributes["http.route"]}`),u}catch(u){throw d.attributes["http.route"]&&c.updateName(`${i} ${d.attributes["http.route"]}`),c.recordException(u),c.setStatus({code:Me.ERROR}),u}finally{c.end()}})}a(je,"executeRequestHandler");function re(r,e){return h(r,{apply:async(n,o,s)=>{let[p,i]=s,l=e(p),{event:c,tracker:d}=Y(i),u=K(l);try{let T=[p,c];return await D.with(u,je,void 0,n,T)}finally{i.waitUntil(J(d))}}})}a(re,"createHandlerProxy");import{propagation as pt}from"@opentelemetry/api";import{W3CTraceContextPropagator as ct}from"@opentelemetry/core";import{Resource as ie}from"@opentelemetry/resources";import{AlwaysOnSampler as lt,ParentBasedSampler as pe,TraceIdRatioBasedSampler as ut}from"@opentelemetry/sdk-trace-base";import{ExportResultCode as We}from"@opentelemetry/core";import{createExportTraceServiceRequest as Be}from"@opentelemetry/otlp-transformer";import{BackgroundDispatcher as Ue}from"@zuplo/runtime";var Ge={accept:"application/json","content-type":"application/json"},v=class{static{a(this,"OTLPExporter")}headers;url;useHex;useLongBits;constructor(e){this.url=e.url,this.headers=Object.assign({},Ge,e.headers),this.useHex=e.useHex,this.useLongBits=e.useLongBits}export(e,t){e.forEach(n=>{this.batcher.enqueue(n)}),t({code:We.SUCCESS})}shutdown(){throw new Error("Method not implemented.")}forceFlush(){throw new Error("Method not implemented.")}dispatchFunction=async e=>{if(e.length===0)return;let t=Be(e,{useLongBits:this.useLongBits,useHex:this.useHex}),n=await S(fetch)(this.url,{method:"POST",body:JSON.stringify(t),headers:this.headers});if(!n.ok)try{let o=await n.text();console.log("Error exporting traces",o)}catch{console.log("Error exporting traces")}};batcher=new Ue(this.dispatchFunction,{msDelay:10})};import{context as Ze,trace as Ye}from"@opentelemetry/api";import{ROOT_CONTEXT as $e}from"@opentelemetry/api";import{AsyncLocalStorage as Ke}from"node:async_hooks";import{EventEmitter as Ve}from"node:events";var Xe=["addListener","on","once","prependListener","prependOnceListener"],j=class{static{a(this,"AbstractAsyncHooksContextManager")}bind(e,t){return t instanceof Ve?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}_bindFunction(e,t){let n=this,o=a(function(...s){return n.with(e,()=>t.apply(this,s))},"contextWrapper");return Object.defineProperty(o,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),o}_bindEventEmitter(e,t){return this._getPatchMap(t)!==void 0||(this._createPatchMap(t),Xe.forEach(o=>{t[o]!==void 0&&(t[o]=this._patchAddListener(t,t[o],e))}),typeof t.removeListener=="function"&&(t.removeListener=this._patchRemoveListener(t,t.removeListener)),typeof t.off=="function"&&(t.off=this._patchRemoveListener(t,t.off)),typeof t.removeAllListeners=="function"&&(t.removeAllListeners=this._patchRemoveAllListeners(t,t.removeAllListeners))),t}_patchRemoveListener(e,t){let n=this;return function(o,s){let p=n._getPatchMap(e)?.[o];if(p===void 0)return t.call(this,o,s);let i=p.get(s);return t.call(this,o,i||s)}}_patchRemoveAllListeners(e,t){let n=this;return function(o){let s=n._getPatchMap(e);return s!==void 0&&(arguments.length===0?n._createPatchMap(e):s[o]!==void 0&&delete s[o]),t.apply(this,arguments)}}_patchAddListener(e,t,n){let o=this;return function(s,p){if(o._wrapped)return t.call(this,s,p);let i=o._getPatchMap(e);i===void 0&&(i=o._createPatchMap(e));let l=i[s];l===void 0&&(l=new WeakMap,i[s]=l);let c=o.bind(n,p);l.set(p,c),o._wrapped=!0;try{return t.call(this,s,c)}finally{o._wrapped=!1}}}_createPatchMap(e){let t=Object.create(null);return e[this._kOtListeners]=t,t}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},E=class extends j{static{a(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Ke}active(){return this._asyncLocalStorage.getStore()??$e}with(e,t,n,...o){let s=n==null?t:t.bind(n);return this._asyncLocalStorage.run(e,s,...o)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};var _=class{static{a(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,t){this.spanProcessors=e,this.resource=t}getTracer(e,t,n){let o=`${e}@${t||""}:${n?.schemaUrl||""}`;return this.tracers[o]||(this.tracers[o]=new x(this.spanProcessors,this.resource)),this.tracers[o]}register(){Ye.setGlobalTracerProvider(this),Ze.setGlobalContextManager(new E)}};import{SpanStatusCode as Je,TraceFlags as Qe}from"@opentelemetry/api";function ne(r){return e=>r.reduce((t,n)=>t||n(e),!1)}a(ne,"multiTailSampler");var oe=a(r=>r.localRootSpan.spanContext().traceFlags===Qe.SAMPLED,"isHeadSampled"),ae=a(r=>r.localRootSpan.status.code===Je.ERROR,"isRootErrorSpan");import{trace as et}from"@opentelemetry/api";import{ExportResultCode as tt}from"@opentelemetry/core";import{stateMachine as rt}from"ts-checked-fsm";function nt(r,{span:e}){let t=e.spanContext().spanId;return{...r,stateName:"in_progress",traceId:e.spanContext().traceId,localRootSpan:e,completedSpans:[],inProgressSpanIds:new Set([t])}}a(nt,"newTrace");function ot(r,{span:e}){let t=e.spanContext().spanId;return r.inProgressSpanIds.add(t),{...r}}a(ot,"newSpan");function at(r,{span:e}){return r.completedSpans.push(e),r.inProgressSpanIds.delete(e.spanContext().spanId),r.inProgressSpanIds.size===0?{stateName:"trace_complete",traceId:r.traceId,localRootSpan:r.localRootSpan,completedSpans:r.completedSpans}:{...r}}a(at,"endSpan");function st(r,{args:e}){let{exporter:t,tailSampler:n,postProcessor:o}=e,{traceId:s,localRootSpan:p,completedSpans:i}=r;if(n({traceId:s,localRootSpan:p,spans:i})){let c=o(i);return{stateName:"exporting",promise:new Promise(u=>{t.export(c,u)})}}else return{stateName:"done"}}a(st,"startExport");var{nextState:it}=rt().state("not_started").state("in_progress").state("trace_complete").state("exporting").state("done").transition("not_started","in_progress").transition("in_progress","in_progress").transition("in_progress","trace_complete").transition("trace_complete","exporting").transition("trace_complete","done").transition("exporting","done").action("startSpan").action("endSpan").action("startExport").action("exportDone").actionHandler("not_started","startSpan",nt).actionHandler("in_progress","startSpan",ot).actionHandler("in_progress","endSpan",at).actionHandler("trace_complete","startExport",st).actionHandler("exporting","exportDone",(r,e)=>({stateName:"done"})).done(),A=class{constructor(e){this.exporter=e}static{a(this,"BatchTraceSpanProcessor")}traceLookup=new Map;localRootSpanLookup=new Map;inprogressExports=new Map;action(e,t){let n=this.traceLookup.get(e)||{stateName:"not_started"},o=it(n,t);return o.stateName==="done"?this.traceLookup.delete(e):this.traceLookup.set(e,o),o}export(e){let{sampling:t,postProcessor:n}=m(),o={exporter:this.exporter,tailSampler:t.tailSampler,postProcessor:n},s=this.action(e,{actionName:"startExport",args:o});if(s.stateName==="exporting"){let p=s.promise;this.inprogressExports.set(e,p),p.then(i=>{i.code===tt.FAILED&&console.log("Error sending spans to exporter:",i.error),this.action(e,{actionName:"exportDone"}),this.inprogressExports.delete(e)})}}onStart(e,t){let n=e.spanContext().spanId,o=et.getSpan(t)?.spanContext()?.spanId,p=(o?this.localRootSpanLookup.get(o):void 0)||n;this.localRootSpanLookup.set(n,p),this.action(p,{actionName:"startSpan",span:e})}onEnd(e){let t=e.spanContext().spanId,n=this.localRootSpanLookup.get(t);if(n){let o=this.action(n,{actionName:"endSpan",span:e});o.stateName==="trace_complete"&&(o.completedSpans.forEach(s=>{this.localRootSpanLookup.delete(s.spanContext().spanId)}),this.export(n))}}async forceFlush(){await Promise.allSettled(this.inprogressExports.values())}async shutdown(){}};function se(r){return!!r.spanProcessors}a(se,"isSpanProcessorConfig");var dt=a((r,e)=>{let t={"cloud.provider":"zuplo","cloud.platform":"zuplo-api","cloud.account.id":r.accountName,"cloud.project.id":r.projectName,"cloud.resource_id":r.deploymentName,"cloud.instance_id":r.instanceId,"telemetry.sdk.language":"js","telemetry.sdk.name":"@zuplo/otel","zuplo.build.id":r.buildId,"zuplo.build.version":r.zuploVersion,"zuplo.build.compatibility_date":r.compatibilityDate,"zuplo.environment_type":r.environmentType,"zuplo.environment_stage":r.environmentStage},n=new ie({"service.name":e.service.name,"service.namespace":e.service.namespace,"service.version":e.service.version});return new ie(t).merge(n)},"createResource");function mt(r){return!!r.export}a(mt,"isSpanExporter");function ft(r){return!!r.shouldSample}a(ft,"isSampler");function gt(r){let e=new ut(r.ratio);return typeof r.acceptRemote=="boolean"&&!r.acceptRemote?new pe({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new pe({root:e})}a(gt,"createSampler");var ce=!1;function St(r,e){if(!ce){ee(),pt.setGlobalPropagator(e.propagator);let t=dt(r,e);new _(e.spanProcessors,t).register(),ce=!0}}a(St,"init");function le(r,e){if(se(e)){let t=e.sampling?.headSampler,n=t?ft(t)?t:gt(t):new lt,o=Array.isArray(e.spanProcessors)?e.spanProcessors:[e.spanProcessors];return o.length===0&&console.log("Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration."),{fetch:{includeTraceContext:e.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:e.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:e.postProcessor??(s=>s),sampling:{headSampler:n,tailSampler:e.sampling?.tailSampler??ne([oe,ae])},service:{name:e.service?.name??r.deploymentName,version:e.service?.version,namespace:e.service?.namespace},spanProcessors:o,propagator:e.propagator??new ct}}else{let t=mt(e.exporter)?e.exporter:new v({useHex:!0,useLongBits:!1,...e.exporter}),n=[new A(t)],o=Object.assign(e,{exporter:void 0,spanProcessors:n});return le(r,o)}}a(le,"parseConfig");function ue(r,e){return()=>{let t=le(r,e);return St(r,t),t}}a(ue,"createInitializer");var W=class extends ht{constructor(t){super();this.config=t}static{a(this,"OpenTelemetryPlugin")}instrument(t){let n=ue(t,this.config);return{requestHandlerProxy:a(s=>re(s,n),"requestHandlerProxy")}}};export{W as OpenTelemetryPlugin};
27
+ /*! For license information please see index.min.js.LEGAL.txt */
File without changes
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@zuplo/otel",
3
+ "version": "0.0.0",
4
+ "repository": "https://github.com/zuplo/zuplo",
5
+ "author": "Zuplo, Inc.",
6
+ "exports": {
7
+ ".": {
8
+ "node": "./index.min.cjs",
9
+ "deno": "./index.min.js",
10
+ "worker": "./index.min.js",
11
+ "types": "./types-beta.d.ts"
12
+ }
13
+ },
14
+ "types": "./types-beta.d.ts",
15
+ "license": "SEE LICENSE IN LICENSE.txt",
16
+ "engines": {
17
+ "node": ">=18.0.0"
18
+ },
19
+ "publishConfig": {
20
+ "@zuplo:registry": "https://registry.npmjs.org",
21
+ "registry": "https://registry.npmjs.org"
22
+ },
23
+ "files": [
24
+ "types-beta.d.ts",
25
+ "index.min.cjs",
26
+ "index.min.cjs.LEGAL.txt",
27
+ "index.min.js",
28
+ "index.min.js.LEGAL.txt",
29
+ "README.md",
30
+ "LICENSE.txt"
31
+ ],
32
+ "devDependencies": {
33
+ "@types/node": "^18.11.9",
34
+ "typescript": "^5.0.4"
35
+ },
36
+ "dependencies": {
37
+ "@opentelemetry/api": "1.8.0",
38
+ "@opentelemetry/core": "1.22.0",
39
+ "@opentelemetry/exporter-trace-otlp-http": "0.49.1",
40
+ "@opentelemetry/otlp-exporter-base": "0.49.1",
41
+ "@opentelemetry/otlp-transformer": "0.49.1",
42
+ "@opentelemetry/resources": "1.22.0",
43
+ "@opentelemetry/sdk-trace-base": "1.22.0",
44
+ "@opentelemetry/semantic-conventions": "1.22.0",
45
+ "ts-checked-fsm": "^1.1.0"
46
+ }
47
+ }
@@ -0,0 +1,118 @@
1
+ import { OtlpEncodingOptions } from '@opentelemetry/otlp-transformer';
2
+ import { ReadableSpan } from '@opentelemetry/sdk-trace-base';
3
+ import { Sampler } from '@opentelemetry/sdk-trace-base';
4
+ import { SpanExporter } from '@opentelemetry/sdk-trace-base';
5
+ import { SpanProcessor } from '@opentelemetry/sdk-trace-base';
6
+ import { TextMapPropagator } from '@opentelemetry/api';
7
+
8
+ declare type AcceptTraceContextFn = (request: Request) => boolean;
9
+
10
+ declare type ExporterConfig = OTLPExporterConfig | SpanExporter;
11
+
12
+ declare interface FetcherConfig {
13
+ includeTraceContext?: boolean | IncludeTraceContextFn;
14
+ }
15
+
16
+ declare interface HandlerConfig {
17
+ fetch?: RequestHandlerConfig;
18
+ }
19
+
20
+ declare type HeadSamplerConf = Sampler | ParentRatioSamplingConfig;
21
+
22
+ declare type IncludeTraceContextFn = (request: Request) => boolean;
23
+
24
+ declare interface LocalTrace {
25
+ readonly traceId: string;
26
+ readonly localRootSpan: ReadableSpan;
27
+ readonly spans: ReadableSpan[];
28
+ }
29
+
30
+ declare type LoggingEnvironmentStage = "working-copy" | "preview" | "production" | "local" | "unknown";
31
+
32
+ /**
33
+ * This type exists mostly because we can't break existing loggers,
34
+ * it is probably better to have environment stage and something indicating
35
+ * runtime (which more closely resembles what we actually use internally)
36
+ */
37
+ declare type LoggingEnvironmentType = "edge" | "working-copy" | "local" | "unknown";
38
+
39
+ /**
40
+ * OpenTelemetry plugin for Zuplo
41
+ * @public
42
+ */
43
+ export declare class OpenTelemetryPlugin extends TelemetryPlugin {
44
+ private config;
45
+ constructor(config: TraceConfig);
46
+ instrument(options: TelemetryInitializationOptions): {
47
+ requestHandlerProxy: RequestHandlerProxy;
48
+ };
49
+ }
50
+
51
+ declare interface OTLPExporterConfig extends OtlpEncodingOptions {
52
+ url: string;
53
+ headers?: Record<string, string>;
54
+ }
55
+
56
+ declare interface ParentRatioSamplingConfig {
57
+ acceptRemote?: boolean;
58
+ ratio: number;
59
+ }
60
+
61
+ declare type PostProcessorFn = (spans: ReadableSpan[]) => ReadableSpan[];
62
+
63
+ declare interface RequestHandlerConfig {
64
+ /**
65
+ * Whether to enable context propagation for incoming requests to `fetch`.
66
+ * This enables or disables distributed tracing from W3C Trace Context headers.
67
+ * @default true
68
+ */
69
+ acceptTraceContext?: boolean | AcceptTraceContextFn;
70
+ }
71
+
72
+ /* Excluded from this release type: RequestHandlerFunction */
73
+
74
+ /* Excluded from this release type: RequestHandlerProxy */
75
+
76
+ /* Excluded from this release type: RuntimePlugin */
77
+
78
+ declare interface SamplingConfig<HS extends HeadSamplerConf = HeadSamplerConf> {
79
+ headSampler?: HS;
80
+ tailSampler?: TailSampleFn;
81
+ }
82
+
83
+ declare interface ServiceConfig {
84
+ name?: string;
85
+ namespace?: string;
86
+ version?: string;
87
+ }
88
+
89
+ declare type TailSampleFn = (traceInfo: LocalTrace) => boolean;
90
+
91
+ /* Excluded from this release type: TelemetryInitializationOptions */
92
+
93
+ /* Excluded from this release type: TelemetryPlugin */
94
+
95
+ export declare type TraceConfig = TraceConfigExporter | TraceConfigSpanProcessors;
96
+
97
+ declare interface TraceConfigBase {
98
+ service: ServiceConfig;
99
+ handlers?: HandlerConfig;
100
+ fetch?: FetcherConfig;
101
+ postProcessor?: PostProcessorFn;
102
+ sampling?: SamplingConfig;
103
+ propagator?: TextMapPropagator;
104
+ }
105
+
106
+ declare interface TraceConfigExporter extends TraceConfigBase {
107
+ exporter: ExporterConfig;
108
+ }
109
+
110
+ declare interface TraceConfigSpanProcessors extends TraceConfigBase {
111
+ spanProcessors: SpanProcessor | SpanProcessor[];
112
+ }
113
+
114
+ /* Excluded from this release type: WaitUntilFunc */
115
+
116
+ /* Excluded from this release type: ZuploEventContext */
117
+
118
+ export { }