@onelog-sdk/node 0.1.4 → 0.1.6

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/README.md CHANGED
@@ -10,9 +10,18 @@ npm install @onelog/node
10
10
  ## Quickstart
11
11
  ```ts
12
12
  import express from 'express';
13
- import { sdkStartPromise, instrumentApp, createLogger, errorMiddleware, httpCall } from '@onelog/node';
13
+ import {
14
+ sdkStartPromise,
15
+ metricsStartPromise,
16
+ instrumentApp,
17
+ createLogger,
18
+ errorMiddleware,
19
+ httpCall,
20
+ createCounter,
21
+ } from '@onelog/node';
14
22
 
15
23
  const logger = createLogger();
24
+ const requestCounter = createCounter('requests_total', { description: 'Total incoming requests' });
16
25
  const app = express();
17
26
  const PORT = process.env.PORT || 8700;
18
27
 
@@ -23,6 +32,7 @@ app.get('/health', (_req, res) => res.json({ status: 'ok', module: process.env.M
23
32
 
24
33
  app.post('/do', async (req, res, next) => {
25
34
  try {
35
+ requestCounter.add(1, { route: '/do' });
26
36
  const reply = await httpCall(
27
37
  process.env.PEER_URL || 'http://localhost:3001/work',
28
38
  { method: 'POST', body: req.body },
@@ -35,7 +45,7 @@ app.post('/do', async (req, res, next) => {
35
45
 
36
46
  app.use(errorMiddleware(logger));
37
47
 
38
- sdkStartPromise.finally(() => {
48
+ Promise.all([sdkStartPromise, metricsStartPromise]).finally(() => {
39
49
  app.listen(PORT, () => logger.info({ port: PORT }, 'Service started'));
40
50
  });
41
51
  ```
@@ -70,6 +80,7 @@ await withRequestAttributes({ tenant: 'acme' }, async () => {
70
80
  - **Logging** (`createLogger`) — Pino with dual transports: OTLP-friendly output plus pretty console, pre-tagged with env/app/module.
71
81
  - **Exceptions** (`errorMiddleware`) — records exceptions on the active span, sets span status to ERROR, logs details, and returns JSON.
72
82
  - **HTTP calls** (`httpCall`) — fetch wrapper with consistent logging, JSON handling, and error propagation.
83
+ - **Metrics** (`metricsStartPromise`, `createCounter`, `createHistogram`, `getMeter`) — OTLP metrics pipeline with helpers that auto-attach global/request attributes and the active span context (exemplars) for correlation with traces/logs.
73
84
  - **Runtime attributes** (`setGlobalAttributes`, `setRequestAttributes`) — update attributes on the fly (globally or per request) and they flow into spans, logs, outbound calls, and error responses.
74
85
 
75
86
  ## Environment variables
@@ -84,6 +95,29 @@ await withRequestAttributes({ tenant: 'acme' }, async () => {
84
95
  - `ONELOG_EXPRESS_LAYERS` — set to `true` to include middleware/request_handler spans (defaults to lean mode without them).
85
96
  - `HTTP_PROXY` / `HTTPS_PROXY` (also lowercase variants) — if present, outbound HTTP (including OTLP export) uses the proxy.
86
97
 
98
+ ## Metrics quickstart
99
+ ```ts
100
+ import { createCounter, createHistogram, metricsStartPromise } from '@onelog/node';
101
+
102
+ const requestCounter = createCounter('http.server.requests', { description: 'Total requests' });
103
+ const requestDuration = createHistogram('http.server.duration', { unit: 'ms' });
104
+
105
+ app.use((req, res, next) => {
106
+ const start = Date.now();
107
+ requestCounter.add(1, { method: req.method, route: req.path });
108
+ res.on('finish', () => {
109
+ requestDuration.record(Date.now() - start, {
110
+ method: req.method,
111
+ route: req.path,
112
+ status: res.statusCode,
113
+ });
114
+ });
115
+ next();
116
+ });
117
+
118
+ await metricsStartPromise; // optional: ensure exporter/reader are ready
119
+ ```
120
+
87
121
  ## Build (for contributors)
88
122
  ```bash
89
123
  npm install
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ce=Object.create;var S=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var Re=(e,t)=>{for(var r in t)S(e,r,{get:t[r],enumerable:!0})},F=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Oe(t))!me.call(e,n)&&n!==r&&S(e,n,{get:()=>t[n],enumerable:!(o=le(t,n))||o.enumerable});return e};var Le=(e,t,r)=>(r=e!=null?ce(fe(e)):{},F(t||!e||!e.__esModule?S(r,"default",{value:e,enumerable:!0}):r,e)),de=e=>F(S({},"__esModule",{value:!0}),e);var st={};Re(st,{createLogger:()=>Te,errorMiddleware:()=>pe,getGlobalAttributes:()=>E,getRequestAttributes:()=>_,httpCall:()=>ue,instrumentApp:()=>Ee,mergeGlobalAttributes:()=>$,mergeRequestAttributes:()=>J,runWithRequestContext:()=>A,sdkStartPromise:()=>ie,setGlobalAttributes:()=>Z,setRequestAttributes:()=>m,withRequestAttributes:()=>k});module.exports=de(st);var O=require("@opentelemetry/api"),ee=require("@opentelemetry/sdk-node");var V=require("@opentelemetry/api"),he=(0,V.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function b(e){return e.setValue(he,!0)}var K=require("@opentelemetry/api");function q(){return function(e){K.diag.error(Ae(e))}}function Ae(e){return typeof e=="string"?e:JSON.stringify(Pe(e))}function Pe(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var Se=q();function I(e){try{Se(e)}catch{}}var c=require("@opentelemetry/api");var x;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(x||(x={}));var Ie=",",xe=["OTEL_SDK_DISABLED"];function Ne(e){return xe.indexOf(e)>-1}var ye=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function Ce(e){return ye.indexOf(e)>-1}var ge=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function ve(e){return ge.indexOf(e)>-1}var M=1/0,U=128,be=128,Me=128,B={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:c.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_ATTRIBUTE_COUNT_LIMIT:U,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:U,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:U,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:be,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Me,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:x.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function Ue(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function Be(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function De(e,t,r,o){o===void 0&&(o=Ie);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var we={ALL:c.DiagLogLevel.ALL,VERBOSE:c.DiagLogLevel.VERBOSE,DEBUG:c.DiagLogLevel.DEBUG,INFO:c.DiagLogLevel.INFO,WARN:c.DiagLogLevel.WARN,ERROR:c.DiagLogLevel.ERROR,NONE:c.DiagLogLevel.NONE};function Xe(e,t,r){var o=r[e];if(typeof o=="string"){var n=we[o.toUpperCase()];n!=null&&(t[e]=n)}}function z(e){var t={};for(var r in B){var o=r;switch(o){case"OTEL_LOG_LEVEL":Xe(o,t,e);break;default:if(Ne(o))Ue(o,t,e);else if(Ce(o))Be(o,t,e);else if(ve(o))De(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function R(){var e=z(process.env);return Object.assign({},B,e)}function L(e){e.unref()}var d;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(d||(d={}));var Y=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var qe=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(i){a={error:i}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return s},ze=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},D=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new Y}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,ze([this._that],qe(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();var l=require("@opentelemetry/api");var W=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=R();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new D(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(l.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&l.TraceFlags.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&l.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(l.diag.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),a=0,i=s;a<i;a++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);l.context.with(b(l.context.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var a=function(){return t._exporter.export(s,function(u){var v;clearTimeout(n),u.code===d.SUCCESS?r():o((v=u.error)!==null&&v!==void 0?v:new Error("BatchSpanProcessor: span export failed"))})},i=null,p=0,P=s.length;p<P;p++){var T=s[p];T.resource.asyncAttributesPending&&T.resource.waitForAsyncAttributes&&(i??(i=[]),i.push(T.resource.waitForAsyncAttributes()))}i===null?a():Promise.all(i).then(a,function(u){I(u),o(u)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,I(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),L(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var je=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),h=(function(e){je(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(W);var X=require("@opentelemetry/resources"),te=require("@opentelemetry/exporter-trace-otlp-http"),re=require("@opentelemetry/auto-instrumentations-node"),C=require("undici");var Q=require("async_hooks"),y=new Q.AsyncLocalStorage,N={},f=e=>({...e||{}}),E=()=>f(N),Z=e=>{N=f(e)},$=e=>{N={...N,...f(e)}},_=()=>y.getStore()?.requestAttributes||{},m=(e,t)=>{let r=y.getStore();if(!r)return;let o=t?.append===!1?f(e):{...r.requestAttributes,...f(e)};r.requestAttributes=o},J=e=>m(e),k=(e,t,r)=>y.getStore()?(m(e,r),t()):A(()=>t(),e),A=(e,t)=>y.run({requestAttributes:f(t)},e);O.diag.setLogger(new O.DiagConsoleLogger,O.DiagLogLevel.WARN);var We=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Qe=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Ze=process.env.MAIN_ENV||process.env.NODE_ENV||"development",oe=process.env.MAIN_MODULE||"unknown-module",$e=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Je=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",ne=process.env.MAIN_MODULE||oe,w=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(w)try{(0,C.setGlobalDispatcher)(new C.ProxyAgent(w)),console.log(`[onelog] Proxy enabled for outbound traffic: ${w}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var ke=X.Resource.default().merge(new X.Resource({"service.name":We,"service.namespace":Qe,"deployment.environment":Ze,"module.name":ne})),G=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...E(),..._()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},H=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},et=(0,re.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:Je?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),tt=new te.OTLPTraceExporter({url:`${$e}/v1/traces`}),rt=new H([new G(ne),new h(tt)]),se=new ee.NodeSDK({resource:ke,instrumentations:[et],spanProcessor:rt}),ie=Promise.resolve(se.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),ae=async()=>{try{await se.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",ae);process.on("SIGINT",ae);var Ee=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||oe;e.use((n,s,a)=>{A(()=>{m({"module.name":o,"http.method":n.method,"http.target":n.path});let i=O.trace.getActiveSpan();if(i){i.setAttribute("module.name",o),i.updateName(`[${o}] ${n.method} ${n.path}`);let p={...E(),..._()};for(let[P,T]of Object.entries(p))T!==void 0&&i.setAttribute(P,T)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),a()})})};var _e=Le(require("pino"),1);var ot=["fatal","error","warn","info","debug","trace"],nt=e=>{let t=()=>({...E(),..._()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&ot.includes(o)&&typeof s=="function"?(a,...i)=>{let p=t();return a&&typeof a=="object"&&!Array.isArray(a)?s.call(r,{...p,...a},...i):s.call(r,{...p},a,...i)}:s}})};function Te(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=(0,_e.default)({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":require("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return nt(n)}var g=require("@opentelemetry/api");var pe=e=>(t,r,o,n)=>{let s={...E(),..._()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let a=g.trace.getActiveSpan();if(a&&(a.recordException(t),a.setStatus({code:g.SpanStatusCode.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};async function ue(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let a={...E(),..._(),...o};r&&r.info({...a,url:e,method:s},"HTTP call start");try{let i=await fetch(e,n),T=(i.headers.get("content-type")||"").includes("application/json")?await i.json().catch(()=>null):await i.text().catch(()=>null);if(!i.ok){let u=new Error(`HTTP ${i.status} ${i.statusText||""}`.trim());throw u.status=i.status,u.data=T,r&&r.error({...a,url:e,method:s,status:i.status,data:T},"HTTP call failed"),u}return r&&r.info({...a,url:e,method:s,status:i.status},"HTTP call success"),T}catch(i){throw r&&r.error({...a,url:e,method:s,error:i.message},"HTTP call error"),i}}0&&(module.exports={createLogger,errorMiddleware,getGlobalAttributes,getRequestAttributes,httpCall,instrumentApp,mergeGlobalAttributes,mergeRequestAttributes,runWithRequestContext,sdkStartPromise,setGlobalAttributes,setRequestAttributes,withRequestAttributes});
1
+ "use strict";var Me=Object.create;var b=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var Xe=(e,t)=>{for(var r in t)b(e,r,{get:t[r],enumerable:!0})},ee=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Be(t))!De.call(e,n)&&n!==r&&b(e,n,{get:()=>t[n],enumerable:!(o=Ue(t,n))||o.enumerable});return e};var Ge=(e,t,r)=>(r=e!=null?Me(we(e)):{},ee(t||!e||!e.__esModule?b(r,"default",{value:e,enumerable:!0}):r,e)),He=e=>ee(b({},"__esModule",{value:!0}),e);var bt={};Xe(bt,{createCounter:()=>Ce,createHistogram:()=>be,createLogger:()=>Pe,errorMiddleware:()=>Se,getGlobalAttributes:()=>u,getMeter:()=>H,getRequestAttributes:()=>p,httpCall:()=>ge,instrumentApp:()=>he,mergeGlobalAttributes:()=>Te,mergeRequestAttributes:()=>ue,metricsStartPromise:()=>ve,runWithRequestContext:()=>y,sdkStartPromise:()=>Re,setGlobalAttributes:()=>_e,setRequestAttributes:()=>S,withRequestAttributes:()=>pe});module.exports=He(bt);var c=require("@opentelemetry/api"),ce=require("@opentelemetry/sdk-node");var te=require("@opentelemetry/api"),Fe=(0,te.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function K(e){return e.setValue(Fe,!0)}var re=require("@opentelemetry/api");function oe(){return function(e){re.diag.error(Ve(e))}}function Ve(e){return typeof e=="string"?e:JSON.stringify(Ke(e))}function Ke(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var ze=oe();function M(e){try{ze(e)}catch{}}var f=require("@opentelemetry/api");var U;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(U||(U={}));var qe=",",je=["OTEL_SDK_DISABLED"];function Ye(e){return je.indexOf(e)>-1}var We=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function Qe(e){return We.indexOf(e)>-1}var Je=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function $e(e){return Je.indexOf(e)>-1}var z=1/0,q=128,Ze=128,ke=128,j={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:f.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:z,OTEL_ATTRIBUTE_COUNT_LIMIT:q,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:z,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:q,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:z,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:q,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Ze,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:ke,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:U.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function et(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function tt(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function rt(e,t,r,o){o===void 0&&(o=qe);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var ot={ALL:f.DiagLogLevel.ALL,VERBOSE:f.DiagLogLevel.VERBOSE,DEBUG:f.DiagLogLevel.DEBUG,INFO:f.DiagLogLevel.INFO,WARN:f.DiagLogLevel.WARN,ERROR:f.DiagLogLevel.ERROR,NONE:f.DiagLogLevel.NONE};function nt(e,t,r){var o=r[e];if(typeof o=="string"){var n=ot[o.toUpperCase()];n!=null&&(t[e]=n)}}function ne(e){var t={};for(var r in j){var o=r;switch(o){case"OTEL_LOG_LEVEL":nt(o,t,e);break;default:if(Ye(o))et(o,t,e);else if(Qe(o))tt(o,t,e);else if($e(o))rt(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function I(){var e=ne(process.env);return Object.assign({},j,e)}function x(e){e.unref()}var N;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(N||(N={}));var ie=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var Tt=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],i;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(E){i={error:E}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},ut=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},Y=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new ie}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,ut([this._that],Tt(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();var m=require("@opentelemetry/api");var ae=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=I();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new Y(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(m.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&m.TraceFlags.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&m.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(m.diag.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),i=0,E=s;i<E;i++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);m.context.with(K(m.context.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var i=function(){return t._exporter.export(s,function(O){var R;clearTimeout(n),O.code===N.SUCCESS?r():o((R=O.error)!==null&&R!==void 0?R:new Error("BatchSpanProcessor: span export failed"))})},E=null,_=0,h=s.length;_<h;_++){var d=s[_];d.resource.asyncAttributesPending&&d.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(d.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(O){M(O),o(O)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,M(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),x(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var pt=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),v=(function(e){pt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(ae);var Q=require("@opentelemetry/resources"),le=require("@opentelemetry/exporter-trace-otlp-http"),Oe=require("@opentelemetry/auto-instrumentations-node"),D=require("undici");var Ee=require("async_hooks"),w=new Ee.AsyncLocalStorage,B={},P=e=>({...e||{}}),u=()=>P(B),_e=e=>{B=P(e)},Te=e=>{B={...B,...P(e)}},p=()=>w.getStore()?.requestAttributes||{},S=(e,t)=>{let r=w.getStore();if(!r)return;let o=t?.append===!1?P(e):{...r.requestAttributes,...P(e)};r.requestAttributes=o},ue=e=>S(e),pe=(e,t,r)=>w.getStore()?(S(e,r),t()):y(()=>t(),e),y=(e,t)=>w.run({requestAttributes:P(t)},e);c.diag.setLogger(new c.DiagConsoleLogger,c.DiagLogLevel.WARN);var lt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Ot=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",dt=process.env.MAIN_ENV||process.env.NODE_ENV||"development",de=process.env.MAIN_MODULE||"unknown-module",ft=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),mt=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",fe=process.env.MAIN_MODULE||de,W=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(W)try{(0,D.setGlobalDispatcher)(new D.ProxyAgent(W)),console.log(`[onelog] Proxy enabled for outbound traffic: ${W}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var Rt=Q.Resource.default().merge(new Q.Resource({"service.name":lt,"service.namespace":Ot,"deployment.environment":dt,"module.name":fe})),J=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...u(),...p()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},$=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},Lt=(0,Oe.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:mt?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),ht=new le.OTLPTraceExporter({url:`${ft}/v1/traces`}),At=new $([new J(fe),new v(ht)]),me=new ce.NodeSDK({resource:Rt,instrumentations:[Lt],spanProcessor:At}),Re=Promise.resolve(me.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),Le=async()=>{try{await me.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",Le);process.on("SIGINT",Le);var he=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||de;e.use((n,s,i)=>{y(()=>{let E=c.propagation.getBaggage(c.context.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([l,V])=>[l,V.value])):{},h=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],d=n.headers["session-id"]||_["session-id"],O=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],R=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"],T=n.headers["x-onelog-attr"]||n.headers["x-onelog-attrs"]||_["x-onelog-attr"],F={};if(T)try{let l=typeof T=="string"?JSON.parse(T):T;l&&typeof l=="object"&&(F=l)}catch{}S({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":h,"organization-id":h,"session.id":d,"session-id":d,"execution.id":O,"execution-id":O,"user.id":R,"user-id":R,"request.id":a,"request-id":a,..._,...F});let L=c.trace.getActiveSpan();if(L){L.setAttribute("module.name",o),L.updateName(`[${o}] ${n.method} ${n.path}`);let l={...u(),...p()};for(let[V,k]of Object.entries(l))k!==void 0&&L.setAttribute(V,k)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};var Ae=Ge(require("pino"),1);var Pt=["fatal","error","warn","info","debug","trace"],St=e=>{let t=()=>({...u(),...p()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&Pt.includes(o)&&typeof s=="function"?(i,...E)=>{let _=t();return i&&typeof i=="object"&&!Array.isArray(i)?s.call(r,{..._,...i},...E):s.call(r,{..._},i,...E)}:s}})};function Pe(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=(0,Ae.default)({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":require("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return St(n)}var X=require("@opentelemetry/api");var Se=e=>(t,r,o,n)=>{let s={...u(),...p()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=X.trace.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:X.SpanStatusCode.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};var g=require("@opentelemetry/api");async function ge(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let i={...u(),...p(),...o},E=Object.entries({...n.headers,"organization-id":i["organization-id"]||i["organization.id"],"session-id":i["session-id"]||i["session.id"],"execution-id":i["execution-id"]||i["execution.id"],"user-id":i["user-id"]||i["user.id"],"request-id":i["request-id"]||i["request.id"],"x-onelog-attr":JSON.stringify(i)}).filter(([,a])=>a!=null).map(([a,T])=>[a,String(T)]),h={...Object.fromEntries(E)},d={};for(let[a,T]of Object.entries(i))if(T!=null)try{d[a]={value:typeof T=="string"?T:JSON.stringify(T)}}catch{}let O=g.propagation.createBaggage(d),R=g.propagation.setBaggage(g.context.active(),O);g.propagation.inject(R,h),n.headers=h,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),L=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let l=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw l.status=a.status,l.data=L,r&&r.error({...i,url:e,method:s,status:a.status,data:L},"HTTP call failed"),l}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),L}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}var C=require("@opentelemetry/api"),Z=require("@opentelemetry/resources"),G=require("@opentelemetry/sdk-metrics"),xe=require("@opentelemetry/exporter-metrics-otlp-http");var gt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",It=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",xt=process.env.MAIN_ENV||process.env.NODE_ENV||"development",Nt=process.env.MAIN_MODULE||"unknown-module",vt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),yt=Z.Resource.default().merge(new Z.Resource({"service.name":gt,"service.namespace":It,"deployment.environment":xt,"module.name":Nt})),A,Ie=!1,Ct=()=>{if(Ie)return;Ie=!0;let e=async()=>{if(A)try{await A.shutdown()}catch(t){console.error("[onelog] Error shutting down metrics provider",t.message)}};process.on("SIGTERM",e),process.on("SIGINT",e)},Ne=()=>{if(A)return A;let e=new xe.OTLPMetricExporter({url:`${vt}/v1/metrics`});return A=new G.MeterProvider({resource:yt,readers:[new G.PeriodicExportingMetricReader({exporter:e})]}),C.metrics.setGlobalMeterProvider(A),Ct(),A},ve=Promise.resolve().then(()=>Ne()),H=(e="onelog-metrics")=>Ne().getMeter(e),ye=e=>({...u(),...p(),...e||{}}),Ce=(e,t)=>{let r=H().createCounter(e,t);return{add:(o,n)=>{r.add(o,ye(n),C.context.active())},instrument:r}},be=(e,t)=>{let r=H().createHistogram(e,t);return{record:(o,n)=>{r.record(o,ye(n),C.context.active())},instrument:r}};0&&(module.exports={createCounter,createHistogram,createLogger,errorMiddleware,getGlobalAttributes,getMeter,getRequestAttributes,httpCall,instrumentApp,mergeGlobalAttributes,mergeRequestAttributes,metricsStartPromise,runWithRequestContext,sdkStartPromise,setGlobalAttributes,setRequestAttributes,withRequestAttributes});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["export { sdkStartPromise, instrumentApp } from './tracing.js';\nexport { createLogger } from './logger.js';\nexport { errorMiddleware } from './exceptions.js';\nexport { httpCall } from './http-caller.js';\nexport {\n getGlobalAttributes,\n setGlobalAttributes,\n mergeGlobalAttributes,\n getRequestAttributes,\n setRequestAttributes,\n mergeRequestAttributes,\n withRequestAttributes,\n runWithRequestContext,\n} from './attributes.js';\n","import { diag, DiagConsoleLogger, DiagLogLevel, trace } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"ukBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,GAAA,oBAAAC,GAAA,wBAAAC,EAAA,yBAAAC,EAAA,aAAAC,GAAA,kBAAAC,GAAA,0BAAAC,EAAA,2BAAAC,EAAA,0BAAAC,EAAA,oBAAAC,GAAA,wBAAAC,EAAA,yBAAAC,EAAA,0BAAAC,IAAA,eAAAC,GAAAf,ICAA,IAAAgB,EAA6D,8BAC7DC,GAAwB,mCCexB,IAAAC,EAA0C,8BAEpCC,MAAuB,oBAC3B,gDAAgD,EAG5C,SAAUC,EAAgBC,EAAgB,CAC9C,OAAOA,EAAQ,SAASF,GAAsB,EAAI,CACpD,CCRA,IAAAG,EAAgC,8BAO1B,SAAUC,GAAmB,CACjC,OAAO,SAACC,EAAa,CACnB,OAAK,MAAMC,GAAmBD,CAAE,CAAC,CACnC,CACF,CAMA,SAASC,GAAmBD,EAAsB,CAChD,OAAI,OAAOA,GAAO,SACTA,EAEA,KAAK,UAAUE,GAAiBF,CAAE,CAAC,CAE9C,CAOA,SAASE,GAAiBF,EAAa,CAIrC,QAHMG,EAAS,CAAA,EACXC,EAAUJ,EAEPI,IAAY,MACjB,OAAO,oBAAoBA,CAAO,EAAE,Q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GF,IAAME,EAAiB,CAAE,GAAGC,EAAoB,EAAG,GAAGC,EAAqB,EAAG,GAAGL,CAAW,EAExFD,GACFA,EAAO,KAAK,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,CAAO,EAAG,iBAAiB,EAGnE,GAAI,CACF,IAAMI,EAAM,MAAM,MAAMT,EAAKI,CAAY,EAGnCM,GAFcD,EAAI,QAAQ,IAAI,cAAc,GAAK,IAC5B,SAAS,kBAAkB,EAChC,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAAI,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAE5F,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQ,IAAI,MAAM,QAAQF,EAAI,MAAM,IAAIA,EAAI,YAAc,EAAE,GAAG,KAAK,CAAC,EAC3E,MAACE,EAAc,OAASF,EAAI,OAC3BE,EAAc,KAAOD,EAClBR,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQI,EAAI,OAAQ,KAAAC,CAAK,EAAG,kBAAkB,EAEzFC,CACR,CAEA,OAAIT,GACFA,EAAO,KAAK,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQI,EAAI,MAAO,EAAG,mBAAmB,EAGlFC,CACT,OAASE,EAAU,CACjB,MAAIV,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,MAAOO,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF","names":["index_exports","__export","createLogger","errorMiddleware","getGlobalAttributes","getRequestAttributes","httpCall","instrumentApp","mergeGlobalAttributes","mergeRequestAttributes","runWithRequestContext","sdkStartPromise","setGlobalAttributes","setRequestAttributes","withRequestAttributes","__toCommonJS","import_api","import_sdk_node","import_api","SUPPRESS_TRACING_KEY","suppressTracing","context","import_api","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","import_api","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","import_api","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","_span","_parentContext","span","_this","resolve","reject","promises","count","i","j","timer","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","import_resources","import_exporter_trace_otlp_http","import_auto_instrumentations_node","import_undici","import_node_async_hooks","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","err","resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","exporter","spanProcessor","BatchSpanProcessor","sdk","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","setRequestAttributes","requestAttributes","import_pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","import_api","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","res","data","error","err"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts","../src/metrics.ts"],"sourcesContent":["export { sdkStartPromise, instrumentApp } from './tracing.js';\nexport { createLogger } from './logger.js';\nexport { errorMiddleware } from './exceptions.js';\nexport { httpCall } from './http-caller.js';\nexport { metricsStartPromise, getMeter, createCounter, createHistogram } from './metrics.js';\nexport {\n getGlobalAttributes,\n setGlobalAttributes,\n mergeGlobalAttributes,\n getRequestAttributes,\n setRequestAttributes,\n mergeRequestAttributes,\n withRequestAttributes,\n runWithRequestContext,\n} from './attributes.js';\n","import { diag, DiagConsoleLogger, DiagLogLevel, trace, context as otContext, propagation } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n const baggage = propagation.getBaggage(otContext.active());\n const baggageAttrs = baggage\n ? Object.fromEntries(\n (baggage.getAllEntries?.() || []).map(([key, entry]) => [key, entry.value]),\n )\n : {};\n\n const orgId =\n (req.headers['organization-id'] as string) ||\n (req.headers['activeorgid'] as string) ||\n (req.headers['active-org-id'] as string) ||\n (req.headers['activeOrgID'] as string) ||\n (baggageAttrs['organization-id'] as string);\n const sessionId = (req.headers['session-id'] as string) || (baggageAttrs['session-id'] as string);\n const executionId =\n (req.headers['execution-id'] as string) ||\n (req.headers['executionid'] as string) ||\n (req.headers['execution_id'] as string) ||\n (baggageAttrs['execution-id'] as string);\n const userId = (req.headers['user-id'] as string) || (baggageAttrs['user-id'] as string);\n const requestId = (req.headers['request-id'] as string) || (baggageAttrs['request-id'] as string);\n const rawOnelogAttr =\n (req.headers['x-onelog-attr'] as string) ||\n (req.headers['x-onelog-attrs'] as string) ||\n (baggageAttrs['x-onelog-attr'] as string);\n let parsedOnelogAttrs: Record<string, any> = {};\n if (rawOnelogAttr) {\n try {\n const parsed = typeof rawOnelogAttr === 'string' ? JSON.parse(rawOnelogAttr) : rawOnelogAttr;\n if (parsed && typeof parsed === 'object') parsedOnelogAttrs = parsed;\n } catch {\n // ignore malformed\n }\n }\n\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n 'organization.id': orgId,\n 'organization-id': orgId,\n 'session.id': sessionId,\n 'session-id': sessionId,\n 'execution.id': executionId,\n 'execution-id': executionId,\n 'user.id': userId,\n 'user-id': userId,\n 'request.id': requestId,\n 'request-id': requestId,\n ...baggageAttrs,\n ...parsedOnelogAttrs,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { context, propagation } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n // Inject trace context + baggage, and forward standard IDs as headers for downstream services\n const headerEntries = Object.entries({\n ...(fetchOptions.headers as any),\n 'organization-id':\n (dynamicContext['organization-id'] as string) || (dynamicContext['organization.id'] as string),\n 'session-id': (dynamicContext['session-id'] as string) || (dynamicContext['session.id'] as string),\n 'execution-id':\n (dynamicContext['execution-id'] as string) || (dynamicContext['execution.id'] as string),\n 'user-id': (dynamicContext['user-id'] as string) || (dynamicContext['user.id'] as string),\n 'request-id': (dynamicContext['request-id'] as string) || (dynamicContext['request.id'] as string),\n 'x-onelog-attr': JSON.stringify(dynamicContext),\n })\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]) as [string, string][];\n\n const headers: Record<string, string> = Object.fromEntries(headerEntries);\n\n const carrier: Record<string, any> = { ...headers };\n\n // Build baggage from all attributes to propagate custom keys\n const baggageEntries: Record<string, { value: string }> = {};\n for (const [key, value] of Object.entries(dynamicContext)) {\n if (value === undefined || value === null) continue;\n try {\n baggageEntries[key] = { value: typeof value === 'string' ? value : JSON.stringify(value) };\n } catch {\n // skip values that can't be stringified\n }\n }\n const baggage = propagation.createBaggage(baggageEntries);\n const ctxWithBaggage = propagation.setBaggage(context.active(), baggage);\n propagation.inject(ctxWithBaggage, carrier);\n\n fetchOptions.headers = carrier;\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n","import { context as otContext, metrics as otMetrics, type Attributes, type MetricOptions } from '@opentelemetry/api';\nimport { Resource } from '@opentelemetry/resources';\nimport { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst serviceName = process.env.OTEL_SERVICE_NAME || process.env.MAIN_MODULE || 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE || process.env.OTEL_SERVICE_NAMESPACE || process.env.MAIN_APP || 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleName,\n }),\n);\n\nlet meterProvider: MeterProvider | undefined;\nlet shutdownRegistered = false;\n\nconst registerShutdown = () => {\n if (shutdownRegistered) return;\n shutdownRegistered = true;\n const shutdown = async () => {\n if (!meterProvider) return;\n try {\n await meterProvider.shutdown();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Error shutting down metrics provider', (error as Error).message);\n }\n };\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n};\n\nconst ensureMeterProvider = () => {\n if (meterProvider) return meterProvider;\n\n const exporter = new OTLPMetricExporter({\n url: `${otlpEndpoint}/v1/metrics`,\n });\n\n meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter,\n }),\n ],\n });\n\n otMetrics.setGlobalMeterProvider(meterProvider);\n registerShutdown();\n return meterProvider;\n};\n\nexport const metricsStartPromise = Promise.resolve().then(() => ensureMeterProvider());\n\nexport const getMeter = (name = 'onelog-metrics') => ensureMeterProvider().getMeter(name);\n\nconst buildAttributes = (attrs?: Attributes): Attributes => ({\n ...getGlobalAttributes(),\n ...getRequestAttributes(),\n ...(attrs || {}),\n});\n\nexport const createCounter = (name: string, options?: MetricOptions) => {\n const counter = getMeter().createCounter(name, options);\n return {\n add: (value: number, attributes?: Attributes) => {\n counter.add(value, buildAttributes(attributes), otContext.active());\n },\n instrument: counter,\n };\n};\n\nexport const createHistogram = (name: string, options?: MetricOptions) => {\n const histogram = getMeter().createHistogram(name, options);\n return {\n record: (value: number, attributes?: Attributes) => {\n histogram.record(value, buildAttributes(attributes), otContext.active());\n },\n instrument: histogram,\n };\n};\n"],"mappings":"0kBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,GAAA,oBAAAC,GAAA,iBAAAC,GAAA,oBAAAC,GAAA,wBAAAC,EAAA,aAAAC,EAAA,yBAAAC,EAAA,aAAAC,GAAA,kBAAAC,GAAA,0BAAAC,GAAA,2BAAAC,GAAA,wBAAAC,GAAA,0BAAAC,EAAA,oBAAAC,GAAA,wBAAAC,GAAA,yBAAAC,EAAA,0BAAAC,KAAA,eAAAC,GAAAnB,ICAA,IAAAoB,EAAgG,8BAChGC,GAAwB,mCCexB,IAAAC,GAA0C,8BAEpCC,MAAuB,qBAC3B,gDAAgD,EAG5C,SAAUC,EAAgBC,EAAgB,CAC9C,OAAOA,EAAQ,SAASF,GAAsB,EAAI,CACpD,CCRA,IAAAG,GAAgC,8BAO1B,SAAUC,IAAmB,CACjC,OAAO,SAACC,EAAa,CACnB,QAAK,MAAMC,GAAmBD,CAAE,CAAC,CACnC,CACF,CAMA,SAASC,GAAmBD,EAAsB,CAChD,OAAI,OAAOA,GAAO,SACTA,EAEA,KAAK,UAAUE,GAAiBF,CAAE,CAAC,CAE9C,CAOA,SAASE,GAAiBF,EAAa,CAIrC,QAHMG,EAAS,CAAA,EACXC,EAAUJ,EAEPI,IAAY,MACjB,OAAO,oBAAoBA,CAAO,EAAE,QAAQ,SAAAC,EAAY,CACtD,GAAI,CAAAF,EAAOE,CAAY,EACvB,KAAMC,EAAQF,EAAQC,CAAoC,EACtDC,IACFH,EAAOE,CAAY,EAAI,OAAOC,CAAK,GAEvC,CAAC,EACDF,EAAU,OAAO,eAAeA,CAAO,EAGzC,OAAOD,CACT,CCzCA,IAAII,GAAkBC,GAAmB,EAcnC,SAAUC,EAAmBC,EAAa,CAC9C,GAAI,CACFC,GAAgBD,CAAE,OACZ,CAAA,CACV,CCvBA,IAAAE,EAA6B,8B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AAMH,GAAoB,CAAC,EAExEI,EAAW,CAACC,EAAO,mBAAqBL,GAAoB,EAAE,SAASK,CAAI,EAElFC,GAAmBC,IAAoC,CAC3D,GAAGC,EAAoB,EACvB,GAAGC,EAAqB,EACxB,GAAIF,GAAS,CAAC,CAChB,GAEaG,GAAgB,CAACL,EAAcM,IAA4B,CACtE,IAAMC,EAAUR,EAAS,EAAE,cAAcC,EAAMM,CAAO,EACtD,MAAO,CACL,IAAK,CAACE,EAAeC,IAA4B,CAC/CF,EAAQ,IAAIC,EAAOP,GAAgBQ,CAAU,EAAG,EAAAC,QAAU,OAAO,CAAC,CACpE,EACA,WAAYH,CACd,CACF,EAEaI,GAAkB,CAACX,EAAcM,IAA4B,CACxE,IAAMM,EAAYb,EAAS,EAAE,gBAAgBC,EAAMM,CAAO,EAC1D,MAAO,CACL,OAAQ,CAACE,EAAeC,IAA4B,CAClDG,EAAU,OAAOJ,EAAOP,GAAgBQ,CAAU,EAAG,EAAAC,QAAU,OAAO,CAAC,CACzE,EACA,WAAYE,CACd,CACF","names":["index_exports","__export","createCounter","createHistogram","createLogger","errorMiddleware","getGlobalAttributes","getMeter","getRequestAttributes","httpCall","instrumentApp","mergeGlobalAttributes","mergeRequestAttributes","metricsStartPromise","runWithRequestContext","sdkStartPromise","setGlobalAttributes","setRequestAttributes","withRequestAttributes","__toCommonJS","import_api","import_sdk_node","import_api","SUPPRESS_TRACING_KEY","suppressTracing","context","import_api","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","import_api","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","import_api","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","_span","_parentContext","span","_this","resolve","reject","promises","count","j","timer","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","import_resources","import_exporter_trace_otlp_http","import_auto_instrumentations_node","import_undici","import_node_async_hooks","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","err","resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","exporter","spanProcessor","BatchSpanProcessor","sdk","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","baggage","otContext","baggageAttrs","entry","orgId","sessionId","executionId","userId","requestId","rawOnelogAttr","parsedOnelogAttrs","parsed","setRequestAttributes","requestAttributes","import_pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","import_api","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","import_api","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","ctxWithBaggage","res","data","error","err","import_api","import_resources","import_sdk_metrics","import_exporter_metrics_otlp_http","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","resource","meterProvider","shutdownRegistered","registerShutdown","shutdown","error","ensureMeterProvider","exporter","otMetrics","metricsStartPromise","getMeter","name","buildAttributes","attrs","getGlobalAttributes","getRequestAttributes","createCounter","options","counter","value","attributes","otContext","createHistogram","histogram"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { Application, Request, Response, NextFunction } from 'express';
2
2
  import pino, { Logger } from 'pino';
3
+ import * as _opentelemetry_api from '@opentelemetry/api';
4
+ import { MetricOptions, Attributes } from '@opentelemetry/api';
5
+ import { MeterProvider } from '@opentelemetry/sdk-metrics';
3
6
 
4
7
  declare const sdkStartPromise: Promise<void>;
5
8
  declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
@@ -19,6 +22,17 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
19
22
  error: Function;
20
23
  }, logContext?: HttpCallContext): Promise<any>;
21
24
 
25
+ declare const metricsStartPromise: Promise<MeterProvider>;
26
+ declare const getMeter: (name?: string) => _opentelemetry_api.Meter;
27
+ declare const createCounter: (name: string, options?: MetricOptions) => {
28
+ add: (value: number, attributes?: Attributes) => void;
29
+ instrument: _opentelemetry_api.Counter<Attributes>;
30
+ };
31
+ declare const createHistogram: (name: string, options?: MetricOptions) => {
32
+ record: (value: number, attributes?: Attributes) => void;
33
+ instrument: _opentelemetry_api.Histogram<Attributes>;
34
+ };
35
+
22
36
  type AttributeMap = Record<string, any>;
23
37
  declare const getGlobalAttributes: () => AttributeMap;
24
38
  declare const setGlobalAttributes: (attrs: AttributeMap) => void;
@@ -33,4 +47,4 @@ declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, optio
33
47
  }) => T;
34
48
  declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
35
49
 
36
- export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
50
+ export { createCounter, createHistogram, createLogger, errorMiddleware, getGlobalAttributes, getMeter, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, metricsStartPromise, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { Application, Request, Response, NextFunction } from 'express';
2
2
  import pino, { Logger } from 'pino';
3
+ import * as _opentelemetry_api from '@opentelemetry/api';
4
+ import { MetricOptions, Attributes } from '@opentelemetry/api';
5
+ import { MeterProvider } from '@opentelemetry/sdk-metrics';
3
6
 
4
7
  declare const sdkStartPromise: Promise<void>;
5
8
  declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
@@ -19,6 +22,17 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
19
22
  error: Function;
20
23
  }, logContext?: HttpCallContext): Promise<any>;
21
24
 
25
+ declare const metricsStartPromise: Promise<MeterProvider>;
26
+ declare const getMeter: (name?: string) => _opentelemetry_api.Meter;
27
+ declare const createCounter: (name: string, options?: MetricOptions) => {
28
+ add: (value: number, attributes?: Attributes) => void;
29
+ instrument: _opentelemetry_api.Counter<Attributes>;
30
+ };
31
+ declare const createHistogram: (name: string, options?: MetricOptions) => {
32
+ record: (value: number, attributes?: Attributes) => void;
33
+ instrument: _opentelemetry_api.Histogram<Attributes>;
34
+ };
35
+
22
36
  type AttributeMap = Record<string, any>;
23
37
  declare const getGlobalAttributes: () => AttributeMap;
24
38
  declare const setGlobalAttributes: (attrs: AttributeMap) => void;
@@ -33,4 +47,4 @@ declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, optio
33
47
  }) => T;
34
48
  declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
35
49
 
36
- export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
50
+ export { createCounter, createHistogram, createLogger, errorMiddleware, getGlobalAttributes, getMeter, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, metricsStartPromise, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Y=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{diag as Ce,DiagConsoleLogger as ge,DiagLogLevel as ve,trace as be}from"@opentelemetry/api";import{NodeSDK as Me}from"@opentelemetry/sdk-node";import{createContextKey as W}from"@opentelemetry/api";var Q=W("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function N(e){return e.setValue(Q,!0)}import{diag as Z}from"@opentelemetry/api";function D(){return function(e){Z.error($(e))}}function $(e){return typeof e=="string"?e:JSON.stringify(J(e))}function J(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var k=D();function h(e){try{k(e)}catch{}}import{DiagLogLevel as c}from"@opentelemetry/api";var A;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(A||(A={}));var ee=",",te=["OTEL_SDK_DISABLED"];function re(e){return te.indexOf(e)>-1}var oe=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function ne(e){return oe.indexOf(e)>-1}var se=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function ie(e){return se.indexOf(e)>-1}var y=1/0,C=128,ae=128,Ee=128,g={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:c.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:y,OTEL_ATTRIBUTE_COUNT_LIMIT:C,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:y,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:C,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:y,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:C,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:ae,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Ee,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:A.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function _e(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function Te(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function pe(e,t,r,o){o===void 0&&(o=ee);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var ue={ALL:c.ALL,VERBOSE:c.VERBOSE,DEBUG:c.DEBUG,INFO:c.INFO,WARN:c.WARN,ERROR:c.ERROR,NONE:c.NONE};function ce(e,t,r){var o=r[e];if(typeof o=="string"){var n=ue[o.toUpperCase()];n!=null&&(t[e]=n)}}function w(e){var t={};for(var r in g){var o=r;switch(o){case"OTEL_LOG_LEVEL":ce(o,t,e);break;default:if(re(o))_e(o,t,e);else if(ne(o))Te(o,t,e);else if(ie(o))pe(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function O(){var e=w(process.env);return Object.assign({},g,e)}function f(e){e.unref()}var m;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(m||(m={}));var G=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var Le=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(i){a={error:i}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return s},de=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},v=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new G}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,de([this._that],Le(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();import{context as H,diag as b,TraceFlags as he}from"@opentelemetry/api";var F=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=O();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new v(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(b.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&he.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&b.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(b.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),a=0,i=s;a<i;a++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);H.with(N(H.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var a=function(){return t._exporter.export(s,function(u){var x;clearTimeout(n),u.code===m.SUCCESS?r():o((x=u.error)!==null&&x!==void 0?x:new Error("BatchSpanProcessor: span export failed"))})},i=null,p=0,d=s.length;p<d;p++){var E=s[p];E.resource.asyncAttributesPending&&E.resource.waitForAsyncAttributes&&(i??(i=[]),i.push(E.resource.waitForAsyncAttributes()))}i===null?a():Promise.all(i).then(a,function(u){h(u),o(u)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,h(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),f(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var Ae=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),R=(function(e){Ae(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(F);import{Resource as V}from"@opentelemetry/resources";import{OTLPTraceExporter as Ue}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as Be}from"@opentelemetry/auto-instrumentations-node";import{ProxyAgent as De,setGlobalDispatcher as we}from"undici";import{AsyncLocalStorage as Se}from"async_hooks";var S=new Se,P={},l=e=>({...e||{}}),_=()=>l(P),Ie=e=>{P=l(e)},xe=e=>{P={...P,...l(e)}},T=()=>S.getStore()?.requestAttributes||{},L=(e,t)=>{let r=S.getStore();if(!r)return;let o=t?.append===!1?l(e):{...r.requestAttributes,...l(e)};r.requestAttributes=o},Ne=e=>L(e),ye=(e,t,r)=>S.getStore()?(L(e,r),t()):I(()=>t(),e),I=(e,t)=>S.run({requestAttributes:l(t)},e);Ce.setLogger(new ge,ve.WARN);var Xe=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Ge=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",He=process.env.MAIN_ENV||process.env.NODE_ENV||"development",K=process.env.MAIN_MODULE||"unknown-module",Fe=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Ve=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",q=process.env.MAIN_MODULE||K,M=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(M)try{we(new De(M)),console.log(`[onelog] Proxy enabled for outbound traffic: ${M}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var Ke=V.default().merge(new V({"service.name":Xe,"service.namespace":Ge,"deployment.environment":He,"module.name":q})),U=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={..._(),...T()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},B=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},qe=Be({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:Ve?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),ze=new Ue({url:`${Fe}/v1/traces`}),je=new B([new U(q),new R(ze)]),z=new Me({resource:Ke,instrumentations:[qe],spanProcessor:je}),Ye=Promise.resolve(z.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),j=async()=>{try{await z.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",j);process.on("SIGINT",j);var We=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||K;e.use((n,s,a)=>{I(()=>{L({"module.name":o,"http.method":n.method,"http.target":n.path});let i=be.getActiveSpan();if(i){i.setAttribute("module.name",o),i.updateName(`[${o}] ${n.method} ${n.path}`);let p={..._(),...T()};for(let[d,E]of Object.entries(p))E!==void 0&&i.setAttribute(d,E)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),a()})})};import Qe from"pino";var Ze=["fatal","error","warn","info","debug","trace"],$e=e=>{let t=()=>({..._(),...T()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&Ze.includes(o)&&typeof s=="function"?(a,...i)=>{let p=t();return a&&typeof a=="object"&&!Array.isArray(a)?s.call(r,{...p,...a},...i):s.call(r,{...p},a,...i)}:s}})};function Je(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=Qe({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":Y("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return $e(n)}import{trace as ke,SpanStatusCode as et}from"@opentelemetry/api";var tt=e=>(t,r,o,n)=>{let s={..._(),...T()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let a=ke.getActiveSpan();if(a&&(a.recordException(t),a.setStatus({code:et.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};async function rt(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let a={..._(),...T(),...o};r&&r.info({...a,url:e,method:s},"HTTP call start");try{let i=await fetch(e,n),E=(i.headers.get("content-type")||"").includes("application/json")?await i.json().catch(()=>null):await i.text().catch(()=>null);if(!i.ok){let u=new Error(`HTTP ${i.status} ${i.statusText||""}`.trim());throw u.status=i.status,u.data=E,r&&r.error({...a,url:e,method:s,status:i.status,data:E},"HTTP call failed"),u}return r&&r.info({...a,url:e,method:s,status:i.status},"HTTP call success"),E}catch(i){throw r&&r.error({...a,url:e,method:s,error:i.message},"HTTP call error"),i}}export{Je as createLogger,tt as errorMiddleware,_ as getGlobalAttributes,T as getRequestAttributes,rt as httpCall,We as instrumentApp,xe as mergeGlobalAttributes,Ne as mergeRequestAttributes,I as runWithRequestContext,Ye as sdkStartPromise,Ie as setGlobalAttributes,L as setRequestAttributes,ye as withRequestAttributes};
1
+ var Ee=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{diag as ze,DiagConsoleLogger as qe,DiagLogLevel as je,trace as Ye,context as We,propagation as Qe}from"@opentelemetry/api";import{NodeSDK as Je}from"@opentelemetry/sdk-node";import{createContextKey as _e}from"@opentelemetry/api";var Te=_e("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function U(e){return e.setValue(Te,!0)}import{diag as ue}from"@opentelemetry/api";function j(){return function(e){ue.error(pe(e))}}function pe(e){return typeof e=="string"?e:JSON.stringify(ce(e))}function ce(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var le=j();function x(e){try{le(e)}catch{}}import{DiagLogLevel as m}from"@opentelemetry/api";var N;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(N||(N={}));var Oe=",",de=["OTEL_SDK_DISABLED"];function fe(e){return de.indexOf(e)>-1}var me=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function Re(e){return me.indexOf(e)>-1}var Le=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function he(e){return Le.indexOf(e)>-1}var B=1/0,w=128,Ae=128,Pe=128,D={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:m.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:B,OTEL_ATTRIBUTE_COUNT_LIMIT:w,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:B,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:w,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:B,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:w,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Ae,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Pe,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:N.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function Se(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function ge(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function Ie(e,t,r,o){o===void 0&&(o=Oe);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var xe={ALL:m.ALL,VERBOSE:m.VERBOSE,DEBUG:m.DEBUG,INFO:m.INFO,WARN:m.WARN,ERROR:m.ERROR,NONE:m.NONE};function Ne(e,t,r){var o=r[e];if(typeof o=="string"){var n=xe[o.toUpperCase()];n!=null&&(t[e]=n)}}function Y(e){var t={};for(var r in D){var o=r;switch(o){case"OTEL_LOG_LEVEL":Ne(o,t,e);break;default:if(fe(o))Se(o,t,e);else if(Re(o))ge(o,t,e);else if(he(o))Ie(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function A(){var e=Y(process.env);return Object.assign({},D,e)}function P(e){e.unref()}var S;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(S||(S={}));var Q=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var Ue=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],i;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(E){i={error:E}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},Be=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},X=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new Q}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,Be([this._that],Ue(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();import{context as J,diag as G,TraceFlags as we}from"@opentelemetry/api";var $=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=A();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new X(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(G.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&we.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&G.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(G.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),i=0,E=s;i<E;i++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);J.with(U(J.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var i=function(){return t._exporter.export(s,function(l){var d;clearTimeout(n),l.code===S.SUCCESS?r():o((d=l.error)!==null&&d!==void 0?d:new Error("BatchSpanProcessor: span export failed"))})},E=null,_=0,R=s.length;_<R;_++){var O=s[_];O.resource.asyncAttributesPending&&O.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(O.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(l){x(l),o(l)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,x(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),P(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var De=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),g=(function(e){De(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})($);import{Resource as Z}from"@opentelemetry/resources";import{OTLPTraceExporter as $e}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as Ze}from"@opentelemetry/auto-instrumentations-node";import{ProxyAgent as ke,setGlobalDispatcher as et}from"undici";import{AsyncLocalStorage as Ge}from"async_hooks";var y=new Ge,v={},h=e=>({...e||{}}),u=()=>h(v),He=e=>{v=h(e)},Fe=e=>{v={...v,...h(e)}},p=()=>y.getStore()?.requestAttributes||{},I=(e,t)=>{let r=y.getStore();if(!r)return;let o=t?.append===!1?h(e):{...r.requestAttributes,...h(e)};r.requestAttributes=o},Ve=e=>I(e),Ke=(e,t,r)=>y.getStore()?(I(e,r),t()):C(()=>t(),e),C=(e,t)=>y.run({requestAttributes:h(t)},e);ze.setLogger(new qe,je.WARN);var tt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",rt=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",ot=process.env.MAIN_ENV||process.env.NODE_ENV||"development",k=process.env.MAIN_MODULE||"unknown-module",nt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),st=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",ee=process.env.MAIN_MODULE||k,H=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(H)try{et(new ke(H)),console.log(`[onelog] Proxy enabled for outbound traffic: ${H}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var it=Z.default().merge(new Z({"service.name":tt,"service.namespace":rt,"deployment.environment":ot,"module.name":ee})),F=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...u(),...p()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},V=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},at=Ze({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:st?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),Et=new $e({url:`${nt}/v1/traces`}),_t=new V([new F(ee),new g(Et)]),te=new Je({resource:it,instrumentations:[at],spanProcessor:_t}),Tt=Promise.resolve(te.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),re=async()=>{try{await te.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",re);process.on("SIGINT",re);var ut=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||k;e.use((n,s,i)=>{C(()=>{let E=Qe.getBaggage(We.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([c,M])=>[c,M.value])):{},R=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],O=n.headers["session-id"]||_["session-id"],l=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],d=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"],T=n.headers["x-onelog-attr"]||n.headers["x-onelog-attrs"]||_["x-onelog-attr"],b={};if(T)try{let c=typeof T=="string"?JSON.parse(T):T;c&&typeof c=="object"&&(b=c)}catch{}I({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":R,"organization-id":R,"session.id":O,"session-id":O,"execution.id":l,"execution-id":l,"user.id":d,"user-id":d,"request.id":a,"request-id":a,..._,...b});let f=Ye.getActiveSpan();if(f){f.setAttribute("module.name",o),f.updateName(`[${o}] ${n.method} ${n.path}`);let c={...u(),...p()};for(let[M,q]of Object.entries(c))q!==void 0&&f.setAttribute(M,q)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};import pt from"pino";var ct=["fatal","error","warn","info","debug","trace"],lt=e=>{let t=()=>({...u(),...p()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&ct.includes(o)&&typeof s=="function"?(i,...E)=>{let _=t();return i&&typeof i=="object"&&!Array.isArray(i)?s.call(r,{..._,...i},...E):s.call(r,{..._},i,...E)}:s}})};function Ot(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=pt({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":Ee("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return lt(n)}import{trace as dt,SpanStatusCode as ft}from"@opentelemetry/api";var mt=e=>(t,r,o,n)=>{let s={...u(),...p()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=dt.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:ft.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};import{context as Rt,propagation as K}from"@opentelemetry/api";async function Lt(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let i={...u(),...p(),...o},E=Object.entries({...n.headers,"organization-id":i["organization-id"]||i["organization.id"],"session-id":i["session-id"]||i["session.id"],"execution-id":i["execution-id"]||i["execution.id"],"user-id":i["user-id"]||i["user.id"],"request-id":i["request-id"]||i["request.id"],"x-onelog-attr":JSON.stringify(i)}).filter(([,a])=>a!=null).map(([a,T])=>[a,String(T)]),R={...Object.fromEntries(E)},O={};for(let[a,T]of Object.entries(i))if(T!=null)try{O[a]={value:typeof T=="string"?T:JSON.stringify(T)}}catch{}let l=K.createBaggage(O),d=K.setBaggage(Rt.active(),l);K.inject(d,R),n.headers=R,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),f=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let c=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw c.status=a.status,c.data=f,r&&r.error({...i,url:e,method:s,status:a.status,data:f},"HTTP call failed"),c}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),f}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}import{context as se,metrics as ht}from"@opentelemetry/api";import{Resource as oe}from"@opentelemetry/resources";import{MeterProvider as At,PeriodicExportingMetricReader as Pt}from"@opentelemetry/sdk-metrics";import{OTLPMetricExporter as St}from"@opentelemetry/exporter-metrics-otlp-http";var gt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",It=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",xt=process.env.MAIN_ENV||process.env.NODE_ENV||"development",Nt=process.env.MAIN_MODULE||"unknown-module",vt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),yt=oe.default().merge(new oe({"service.name":gt,"service.namespace":It,"deployment.environment":xt,"module.name":Nt})),L,ne=!1,Ct=()=>{if(ne)return;ne=!0;let e=async()=>{if(L)try{await L.shutdown()}catch(t){console.error("[onelog] Error shutting down metrics provider",t.message)}};process.on("SIGTERM",e),process.on("SIGINT",e)},ie=()=>{if(L)return L;let e=new St({url:`${vt}/v1/metrics`});return L=new At({resource:yt,readers:[new Pt({exporter:e})]}),ht.setGlobalMeterProvider(L),Ct(),L},bt=Promise.resolve().then(()=>ie()),z=(e="onelog-metrics")=>ie().getMeter(e),ae=e=>({...u(),...p(),...e||{}}),Mt=(e,t)=>{let r=z().createCounter(e,t);return{add:(o,n)=>{r.add(o,ae(n),se.active())},instrument:r}},Ut=(e,t)=>{let r=z().createHistogram(e,t);return{record:(o,n)=>{r.record(o,ae(n),se.active())},instrument:r}};export{Mt as createCounter,Ut as createHistogram,Ot as createLogger,mt as errorMiddleware,u as getGlobalAttributes,z as getMeter,p as getRequestAttributes,Lt as httpCall,ut as instrumentApp,Fe as mergeGlobalAttributes,Ve as mergeRequestAttributes,bt as metricsStartPromise,C as runWithRequestContext,Tt as sdkStartPromise,He as setGlobalAttributes,I as setRequestAttributes,Ke as withRequestAttributes};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["import { diag, DiagConsoleLogger, DiagLogLevel, trace } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"yPAAA,OAAS,QAAAA,GAAM,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AC3E,MAACE,EAAc,OAASF,EAAI,OAC3BE,EAAc,KAAOD,EAClBR,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQI,EAAI,OAAQ,KAAAC,CAAK,EAAG,kBAAkB,EAEzFC,CACR,CAEA,OAAIT,GACFA,EAAO,KAAK,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQI,EAAI,MAAO,EAAG,mBAAmB,EAGlFC,CACT,OAASE,EAAU,CACjB,MAAIV,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,MAAOO,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF","names":["diag","DiagConsoleLogger","DiagLogLevel","trace","NodeSDK","createContextKey","SUPPRESS_TRACING_KEY","suppressTracing","context","diag","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","DiagLogLevel","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","DiagLogLevel","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","context","diag","TraceFlags","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","diag","_span","_parentContext","span","TraceFlags","_this","resolve","reject","promises","count","i","j","timer","context","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","ProxyAgent","setGlobalDispatcher","AsyncLocalStorage","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","diag","DiagConsoleLogger","DiagLogLevel","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","setGlobalDispatcher","ProxyAgent","err","resource","Resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","getNodeAutoInstrumentations","exporter","OTLPTraceExporter","spanProcessor","BatchSpanProcessor","sdk","NodeSDK","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","setRequestAttributes","trace","requestAttributes","pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","trace","SpanStatusCode","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","trace","SpanStatusCode","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","res","data","error","err"]}
1
+ {"version":3,"sources":["../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts","../src/metrics.ts"],"sourcesContent":["import { diag, DiagConsoleLogger, DiagLogLevel, trace, context as otContext, propagation } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n const baggage = propagation.getBaggage(otContext.active());\n const baggageAttrs = baggage\n ? Object.fromEntries(\n (baggage.getAllEntries?.() || []).map(([key, entry]) => [key, entry.value]),\n )\n : {};\n\n const orgId =\n (req.headers['organization-id'] as string) ||\n (req.headers['activeorgid'] as string) ||\n (req.headers['active-org-id'] as string) ||\n (req.headers['activeOrgID'] as string) ||\n (baggageAttrs['organization-id'] as string);\n const sessionId = (req.headers['session-id'] as string) || (baggageAttrs['session-id'] as string);\n const executionId =\n (req.headers['execution-id'] as string) ||\n (req.headers['executionid'] as string) ||\n (req.headers['execution_id'] as string) ||\n (baggageAttrs['execution-id'] as string);\n const userId = (req.headers['user-id'] as string) || (baggageAttrs['user-id'] as string);\n const requestId = (req.headers['request-id'] as string) || (baggageAttrs['request-id'] as string);\n const rawOnelogAttr =\n (req.headers['x-onelog-attr'] as string) ||\n (req.headers['x-onelog-attrs'] as string) ||\n (baggageAttrs['x-onelog-attr'] as string);\n let parsedOnelogAttrs: Record<string, any> = {};\n if (rawOnelogAttr) {\n try {\n const parsed = typeof rawOnelogAttr === 'string' ? JSON.parse(rawOnelogAttr) : rawOnelogAttr;\n if (parsed && typeof parsed === 'object') parsedOnelogAttrs = parsed;\n } catch {\n // ignore malformed\n }\n }\n\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n 'organization.id': orgId,\n 'organization-id': orgId,\n 'session.id': sessionId,\n 'session-id': sessionId,\n 'execution.id': executionId,\n 'execution-id': executionId,\n 'user.id': userId,\n 'user-id': userId,\n 'request.id': requestId,\n 'request-id': requestId,\n ...baggageAttrs,\n ...parsedOnelogAttrs,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { context, propagation } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n // Inject trace context + baggage, and forward standard IDs as headers for downstream services\n const headerEntries = Object.entries({\n ...(fetchOptions.headers as any),\n 'organization-id':\n (dynamicContext['organization-id'] as string) || (dynamicContext['organization.id'] as string),\n 'session-id': (dynamicContext['session-id'] as string) || (dynamicContext['session.id'] as string),\n 'execution-id':\n (dynamicContext['execution-id'] as string) || (dynamicContext['execution.id'] as string),\n 'user-id': (dynamicContext['user-id'] as string) || (dynamicContext['user.id'] as string),\n 'request-id': (dynamicContext['request-id'] as string) || (dynamicContext['request.id'] as string),\n 'x-onelog-attr': JSON.stringify(dynamicContext),\n })\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]) as [string, string][];\n\n const headers: Record<string, string> = Object.fromEntries(headerEntries);\n\n const carrier: Record<string, any> = { ...headers };\n\n // Build baggage from all attributes to propagate custom keys\n const baggageEntries: Record<string, { value: string }> = {};\n for (const [key, value] of Object.entries(dynamicContext)) {\n if (value === undefined || value === null) continue;\n try {\n baggageEntries[key] = { value: typeof value === 'string' ? value : JSON.stringify(value) };\n } catch {\n // skip values that can't be stringified\n }\n }\n const baggage = propagation.createBaggage(baggageEntries);\n const ctxWithBaggage = propagation.setBaggage(context.active(), baggage);\n propagation.inject(ctxWithBaggage, carrier);\n\n fetchOptions.headers = carrier;\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n","import { context as otContext, metrics as otMetrics, type Attributes, type MetricOptions } from '@opentelemetry/api';\nimport { Resource } from '@opentelemetry/resources';\nimport { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst serviceName = process.env.OTEL_SERVICE_NAME || process.env.MAIN_MODULE || 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE || process.env.OTEL_SERVICE_NAMESPACE || process.env.MAIN_APP || 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleName,\n }),\n);\n\nlet meterProvider: MeterProvider | undefined;\nlet shutdownRegistered = false;\n\nconst registerShutdown = () => {\n if (shutdownRegistered) return;\n shutdownRegistered = true;\n const shutdown = async () => {\n if (!meterProvider) return;\n try {\n await meterProvider.shutdown();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Error shutting down metrics provider', (error as Error).message);\n }\n };\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n};\n\nconst ensureMeterProvider = () => {\n if (meterProvider) return meterProvider;\n\n const exporter = new OTLPMetricExporter({\n url: `${otlpEndpoint}/v1/metrics`,\n });\n\n meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter,\n }),\n ],\n });\n\n otMetrics.setGlobalMeterProvider(meterProvider);\n registerShutdown();\n return meterProvider;\n};\n\nexport const metricsStartPromise = Promise.resolve().then(() => ensureMeterProvider());\n\nexport const getMeter = (name = 'onelog-metrics') => ensureMeterProvider().getMeter(name);\n\nconst buildAttributes = (attrs?: Attributes): Attributes => ({\n ...getGlobalAttributes(),\n ...getRequestAttributes(),\n ...(attrs || {}),\n});\n\nexport const createCounter = (name: string, options?: MetricOptions) => {\n const counter = getMeter().createCounter(name, options);\n return {\n add: (value: number, attributes?: Attributes) => {\n counter.add(value, buildAttributes(attributes), otContext.active());\n },\n instrument: counter,\n };\n};\n\nexport const createHistogram = (name: string, options?: MetricOptions) => {\n const histogram = getMeter().createHistogram(name, options);\n return {\n record: (value: number, attributes?: Attributes) => {\n histogram.record(value, buildAttributes(attributes), otContext.active());\n },\n instrument: histogram,\n };\n};\n"],"mappings":"0PAAA,OAAS,QAAAA,GAAM,qBAAAC,GAAmB,gBAAAC,GAAc,SAAAC,GAAO,WAAWC,GAAW,eAAAC,OAAmB,qBAChG,OAAS,WAAAC,OAAe,0BCexB,OAAkB,oBAAAC,OAAwB,qBAE1C,IAAMC,GAAuBD,GAC3B,gDAAgD,EAG5C,SAAUE,EAAgBC,EAAgB,CAC9C,OAAOA,EAAQ,SAASF,GAAsB,EAAI,CACpD,CCRA,OAAS,QAAAG,OAAuB,qBAO1B,SAAUC,GAAmB,CACjC,OAAO,SAACC,EAAa,CACnBF,GAAK,MAAMG,GAAmBD,CAAE,CAAC,CACnC,CACF,CAMA,SAASC,GAAmBD,EAAsB,CAChD,OAAI,OAAOA,GAAO,SACTA,EAEA,KAAK,UAAUE,GAAiBF,CAAE,CAAC,CAE9C,CAOA,SAASE,GAAiBF,EAAa,CAIrC,QAHMG,EAAS,CAAA,EACXC,EAAUJ,EAEPI,IAAY,MACjB,OAAO,oBAAoBA,CAAO,EAAE,QAAQ,SAAAC,EAAY,CACtD,GAAI,CAAAF,EAAOE,CAAY,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KEY","suppressTracing","context","diag","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","DiagLogLevel","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","DiagLogLevel","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","context","diag","TraceFlags","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","diag","_span","_parentContext","span","TraceFlags","_this","resolve","reject","promises","count","j","timer","context","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","ProxyAgent","setGlobalDispatcher","AsyncLocalStorage","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","diag","DiagConsoleLogger","DiagLogLevel","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","setGlobalDispatcher","ProxyAgent","err","resource","Resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","getNodeAutoInstrumentations","exporter","OTLPTraceExporter","spanProcessor","BatchSpanProcessor","sdk","NodeSDK","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","baggage","propagation","otContext","baggageAttrs","entry","orgId","sessionId","executionId","userId","requestId","rawOnelogAttr","parsedOnelogAttrs","parsed","setRequestAttributes","trace","requestAttributes","pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","trace","SpanStatusCode","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","trace","SpanStatusCode","context","propagation","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","propagation","ctxWithBaggage","context","res","data","error","err","otContext","otMetrics","Resource","MeterProvider","PeriodicExportingMetricReader","OTLPMetricExporter","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","resource","Resource","meterProvider","shutdownRegistered","registerShutdown","shutdown","error","ensureMeterProvider","exporter","OTLPMetricExporter","MeterProvider","PeriodicExportingMetricReader","otMetrics","metricsStartPromise","getMeter","name","buildAttributes","attrs","getGlobalAttributes","getRequestAttributes","createCounter","options","counter","value","attributes","otContext","createHistogram","histogram"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onelog-sdk/node",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "OneLog Node SDK for unified tracing, logging, and error handling.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -31,9 +31,11 @@
31
31
  "dependencies": {
32
32
  "@opentelemetry/api": "^1.9.0",
33
33
  "@opentelemetry/auto-instrumentations-node": "^0.67.3",
34
+ "@opentelemetry/exporter-metrics-otlp-http": "^0.55.0",
34
35
  "@opentelemetry/exporter-trace-otlp-http": "^0.55.0",
35
36
  "@opentelemetry/resources": "^1.24.1",
36
37
  "@opentelemetry/sdk-node": "^0.55.0",
38
+ "@opentelemetry/sdk-metrics": "^1.24.1",
37
39
  "pino": "^10.1.0",
38
40
  "pino-opentelemetry-transport": "^2.0.0",
39
41
  "pino-pretty": "^13.1.3",