@onelog-sdk/node 0.1.8 → 0.1.9
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 +1 -29
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -15
- package/dist/index.d.ts +1 -15
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -5
package/README.md
CHANGED
|
@@ -12,16 +12,13 @@ npm install @onelog/node
|
|
|
12
12
|
import express from 'express';
|
|
13
13
|
import {
|
|
14
14
|
sdkStartPromise,
|
|
15
|
-
metricsStartPromise,
|
|
16
15
|
instrumentApp,
|
|
17
16
|
createLogger,
|
|
18
17
|
errorMiddleware,
|
|
19
18
|
httpCall,
|
|
20
|
-
createCounter,
|
|
21
19
|
} from '@onelog/node';
|
|
22
20
|
|
|
23
21
|
const logger = createLogger();
|
|
24
|
-
const requestCounter = createCounter('requests_total', { description: 'Total incoming requests' });
|
|
25
22
|
const app = express();
|
|
26
23
|
const PORT = process.env.PORT || 8700;
|
|
27
24
|
|
|
@@ -32,7 +29,6 @@ app.get('/health', (_req, res) => res.json({ status: 'ok', module: process.env.M
|
|
|
32
29
|
|
|
33
30
|
app.post('/do', async (req, res, next) => {
|
|
34
31
|
try {
|
|
35
|
-
requestCounter.add(1, { route: '/do' });
|
|
36
32
|
const reply = await httpCall(
|
|
37
33
|
process.env.PEER_URL || 'http://localhost:3001/work',
|
|
38
34
|
{ method: 'POST', body: req.body },
|
|
@@ -45,7 +41,7 @@ app.post('/do', async (req, res, next) => {
|
|
|
45
41
|
|
|
46
42
|
app.use(errorMiddleware(logger));
|
|
47
43
|
|
|
48
|
-
|
|
44
|
+
sdkStartPromise.finally(() => {
|
|
49
45
|
app.listen(PORT, () => logger.info({ port: PORT }, 'Service started'));
|
|
50
46
|
});
|
|
51
47
|
```
|
|
@@ -80,7 +76,6 @@ await withRequestAttributes({ tenant: 'acme' }, async () => {
|
|
|
80
76
|
- **Logging** (`createLogger`) — Pino with dual transports: OTLP-friendly output plus pretty console, pre-tagged with env/app/module.
|
|
81
77
|
- **Exceptions** (`errorMiddleware`) — records exceptions on the active span, sets span status to ERROR, logs details, and returns JSON.
|
|
82
78
|
- **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.
|
|
84
79
|
- **Runtime attributes** (`setGlobalAttributes`, `setRequestAttributes`) — update attributes on the fly (globally or per request) and they flow into spans, logs, outbound calls, and error responses.
|
|
85
80
|
|
|
86
81
|
## Environment variables
|
|
@@ -95,29 +90,6 @@ await withRequestAttributes({ tenant: 'acme' }, async () => {
|
|
|
95
90
|
- `ONELOG_EXPRESS_LAYERS` — set to `true` to include middleware/request_handler spans (defaults to lean mode without them).
|
|
96
91
|
- `HTTP_PROXY` / `HTTPS_PROXY` (also lowercase variants) — if present, outbound HTTP (including OTLP export) uses the proxy.
|
|
97
92
|
|
|
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
|
-
|
|
121
93
|
## Build (for contributors)
|
|
122
94
|
```bash
|
|
123
95
|
npm install
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Ge=Object.create;var U=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var Ke=(e,t)=>{for(var r in t)U(e,r,{get:t[r],enumerable:!0})},te=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fe(t))!ze.call(e,n)&&n!==r&&U(e,n,{get:()=>t[n],enumerable:!(o=He(t,n))||o.enumerable});return e};var je=(e,t,r)=>(r=e!=null?Ge(Ve(e)):{},te(t||!e||!e.__esModule?U(r,"default",{value:e,enumerable:!0}):r,e)),qe=e=>te(U({},"__esModule",{value:!0}),e);var zt={};Ke(zt,{createCounter:()=>De,createHistogram:()=>Xe,createLogger:()=>ge,errorMiddleware:()=>Ie,getGlobalAttributes:()=>T,getMeter:()=>V,getRequestAttributes:()=>c,httpCall:()=>xe,instrumentApp:()=>Pe,mergeGlobalAttributes:()=>ce,mergeRequestAttributes:()=>pe,metricsStartPromise:()=>Be,runWithRequestContext:()=>M,sdkStartPromise:()=>he,setGlobalAttributes:()=>Te,setRequestAttributes:()=>I,withRequestAttributes:()=>le});module.exports=qe(zt);var S=require("undici"),re=!1,B=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0),Ye=()=>B?new S.ProxyAgent({uri:B,connect:{rejectUnauthorized:!1},requestTls:{rejectUnauthorized:!1},proxyTls:{rejectUnauthorized:!1}}):new S.Agent({connect:{rejectUnauthorized:!1}}),O=()=>{if(!re){re=!0,process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";try{let e=Ye();(0,S.setGlobalDispatcher)(e),(process.env.ONELOG_DEBUG||"").toLowerCase()==="true"&&console.log(`[onelog] Insecure TLS enabled${B?` via proxy ${B}`:""}; certificate validation is disabled.`)}catch(e){console.error("[onelog] Failed to configure insecure TLS dispatcher",e.message)}}};O();var p=require("@opentelemetry/api"),de=require("@opentelemetry/sdk-node");var oe=require("@opentelemetry/api"),We=(0,oe.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function j(e){return e.setValue(We,!0)}var ne=require("@opentelemetry/api");function se(){return function(e){ne.diag.error(Qe(e))}}function Qe(e){return typeof e=="string"?e:JSON.stringify(Je(e))}function Je(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 $e=se();function w(e){try{$e(e)}catch{}}var f=require("@opentelemetry/api");var D;(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"})(D||(D={}));var Ze=",",ke=["OTEL_SDK_DISABLED"];function et(e){return ke.indexOf(e)>-1}var tt=["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 rt(e){return tt.indexOf(e)>-1}var ot=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function nt(e){return ot.indexOf(e)>-1}var q=1/0,Y=128,st=128,it=128,W={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:q,OTEL_ATTRIBUTE_COUNT_LIMIT:Y,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:q,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Y,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:q,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Y,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:st,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:it,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:D.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 at(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function Et(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 _t(e,t,r,o){o===void 0&&(o=Ze);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var ut={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 Tt(e,t,r){var o=r[e];if(typeof o=="string"){var n=ut[o.toUpperCase()];n!=null&&(t[e]=n)}}function ie(e){var t={};for(var r in W){var o=r;switch(o){case"OTEL_LOG_LEVEL":Tt(o,t,e);break;default:if(et(o))at(o,t,e);else if(rt(o))Et(o,t,e);else if(nt(o))_t(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function N(){var e=ie(process.env);return Object.assign({},W,e)}function v(e){e.unref()}var y;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(y||(y={}));var Ee=(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 Ot=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},ft=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))},Q=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new Ee}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,ft([this._that],Ot(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 R=require("@opentelemetry/api");var _e=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=N();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 Q(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(R.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&R.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&&R.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(R.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);R.context.with(j(R.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(d){var h;clearTimeout(n),d.code===y.SUCCESS?r():o((h=d.error)!==null&&h!==void 0?h:new Error("BatchSpanProcessor: span export failed"))})},E=null,_=0,P=s.length;_<P;_++){var m=s[_];m.resource.asyncAttributesPending&&m.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(m.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(d){w(d),o(d)})})})},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,w(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),v(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var Rt=(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)}})(),C=(function(e){Rt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(_e);var J=require("@opentelemetry/resources"),me=require("@opentelemetry/exporter-trace-otlp-http"),Oe=require("@opentelemetry/auto-instrumentations-node");var ue=require("async_hooks"),G=new ue.AsyncLocalStorage,X={},g=e=>({...e||{}}),T=()=>g(X),Te=e=>{X=g(e)},ce=e=>{X={...X,...g(e)}},c=()=>G.getStore()?.requestAttributes||{},I=(e,t)=>{let r=G.getStore();if(!r)return;let o=t?.append===!1?g(e):{...r.requestAttributes,...g(e)};r.requestAttributes=o},pe=e=>I(e),le=(e,t,r)=>G.getStore()?(I(e,r),t()):M(()=>t(),e),M=(e,t)=>G.run({requestAttributes:g(t)},e);p.diag.setLogger(new p.DiagConsoleLogger,p.DiagLogLevel.WARN);var ht=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",At=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Pt=process.env.MAIN_ENV||process.env.NODE_ENV||"development",fe=process.env.MAIN_MODULE||"unknown-module",St=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),gt=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",Re=process.env.MAIN_MODULE||fe;O();var It=J.Resource.default().merge(new J.Resource({"service.name":ht,"service.namespace":At,"deployment.environment":Pt,"module.name":Re})),$=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(),...c()};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()}},Z=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(()=>{})}},xt=(0,Oe.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:gt?[]:["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}}),Nt=new me.OTLPTraceExporter({url:`${St}/v1/traces`}),vt=new Z([new $(Re),new C(Nt)]),Le=new de.NodeSDK({resource:It,instrumentations:[xt],spanProcessor:vt}),he=Promise.resolve(Le.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),Ae=async()=>{try{await Le.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",Ae);process.on("SIGINT",Ae);var Pe=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||fe;e.use((n,s,i)=>{M(()=>{let E=p.propagation.getBaggage(p.context.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([l,K])=>[l,K.value])):{},P=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],m=n.headers["session-id"]||_["session-id"],d=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],h=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"],u=n.headers["x-onelog-attr"]||n.headers["x-onelog-attrs"]||_["x-onelog-attr"],z={};if(u)try{let l=typeof u=="string"?JSON.parse(u):u;l&&typeof l=="object"&&(z=l)}catch{}I({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":P,"organization-id":P,"session.id":m,"session-id":m,"execution.id":d,"execution-id":d,"user.id":h,"user-id":h,"request.id":a,"request-id":a,..._,...z});let A=p.trace.getActiveSpan();if(A){A.setAttribute("module.name",o),A.updateName(`[${o}] ${n.method} ${n.path}`);let l={...T(),...c()};for(let[K,ee]of Object.entries(l))ee!==void 0&&A.setAttribute(K,ee)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};var Se=je(require("pino"),1);var yt=["fatal","error","warn","info","debug","trace"],Ct=e=>{let t=()=>({...T(),...c()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&yt.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 ge(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=(0,Se.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 Ct(n)}var H=require("@opentelemetry/api");var Ie=e=>(t,r,o,n)=>{let s={...T(),...c()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=H.trace.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:H.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 x=require("@opentelemetry/api");async function xe(e,t={},r,o={}){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={...T(),...c(),...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,u])=>[a,String(u)]),P={...Object.fromEntries(E)},m={};for(let[a,u]of Object.entries(i))if(u!=null)try{m[a]={value:typeof u=="string"?u:JSON.stringify(u)}}catch{}let d=x.propagation.createBaggage(m),h=x.propagation.setBaggage(x.context.active(),d);x.propagation.inject(h,P),n.headers=P,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),A=(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=A,r&&r.error({...i,url:e,method:s,status:a.status,data:A},"HTTP call failed"),l}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),A}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}var b=require("@opentelemetry/api"),k=require("@opentelemetry/resources"),F=require("@opentelemetry/sdk-metrics"),Ce=require("@opentelemetry/exporter-metrics-otlp-http"),Me=require("@opentelemetry/host-metrics"),be=require("@opentelemetry/instrumentation-runtime-node");var Mt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",bt=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Ut=process.env.MAIN_ENV||process.env.NODE_ENV||"development",Bt=process.env.MAIN_MODULE||"unknown-module",wt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Dt=(process.env.ONELOG_HOST_METRICS||"true").toLowerCase()==="true",Xt=(process.env.ONELOG_RUNTIME_METRICS||"false").toLowerCase()==="true";O();var Gt=k.Resource.default().merge(new k.Resource({"service.name":Mt,"service.namespace":bt,"deployment.environment":Ut,"module.name":Bt})),L,Ne=!1,ve=!1,ye=!1,Ht=()=>{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)},Ue=()=>{if(L)return L;let e=new Ce.OTLPMetricExporter({url:`${wt}/v1/metrics`});return L=new F.MeterProvider({resource:Gt,readers:[new F.PeriodicExportingMetricReader({exporter:e})]}),b.metrics.setGlobalMeterProvider(L),Ft(L),Vt(L),Ht(),L},Ft=e=>{if(!(!Dt||ve))try{new Me.HostMetrics({meterProvider:e,name:"onelog-host-metrics"}).start(),ve=!0}catch(t){console.error("[onelog] Failed to start host metrics instrumentation",t.message)}},Vt=e=>{if(!(!Xt||ye))try{let t=new be.RuntimeNodeInstrumentation;t.setMeterProvider(e),t.enable(),ye=!0}catch(t){console.error("[onelog] Failed to start runtime metrics instrumentation",t.message)}},Be=Promise.resolve().then(()=>Ue()),V=(e="onelog-metrics")=>Ue().getMeter(e),we=e=>({...T(),...c(),...e||{}}),De=(e,t)=>{let r=V().createCounter(e,t);return{add:(o,n)=>{r.add(o,we(n),b.context.active())},instrument:r}},Xe=(e,t)=>{let r=V().createHistogram(e,t);return{record:(o,n)=>{r.record(o,we(n),b.context.active())},instrument:r}};O();0&&(module.exports={createCounter,createHistogram,createLogger,errorMiddleware,getGlobalAttributes,getMeter,getRequestAttributes,httpCall,instrumentApp,mergeGlobalAttributes,mergeRequestAttributes,metricsStartPromise,runWithRequestContext,sdkStartPromise,setGlobalAttributes,setRequestAttributes,withRequestAttributes});
|
|
1
|
+
"use strict";var Se=Object.create;var b=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var r in t)b(e,r,{get:t[r],enumerable:!0})},J=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ie(t))!xe.call(e,n)&&n!==r&&b(e,n,{get:()=>t[n],enumerable:!(o=Pe(t,n))||o.enumerable});return e};var ye=(e,t,r)=>(r=e!=null?Se(ge(e)):{},J(t||!e||!e.__esModule?b(r,"default",{value:e,enumerable:!0}):r,e)),Ce=e=>J(b({},"__esModule",{value:!0}),e);var ft={};Ne(ft,{createLogger:()=>Le,errorMiddleware:()=>he,getGlobalAttributes:()=>c,getRequestAttributes:()=>l,httpCall:()=>Ae,instrumentApp:()=>me,mergeGlobalAttributes:()=>ae,mergeRequestAttributes:()=>Ee,runWithRequestContext:()=>v,sdkStartPromise:()=>fe,setGlobalAttributes:()=>ie,setRequestAttributes:()=>I,withRequestAttributes:()=>_e});module.exports=Ce(ft);var S=require("undici"),Z=!1,M=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0),ve=()=>M?new S.ProxyAgent({uri:M,connect:{rejectUnauthorized:!1},requestTls:{rejectUnauthorized:!1},proxyTls:{rejectUnauthorized:!1}}):new S.Agent({connect:{rejectUnauthorized:!1}}),A=()=>{if(!Z){Z=!0,process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";try{let e=ve();(0,S.setGlobalDispatcher)(e),(process.env.ONELOG_DEBUG||"").toLowerCase()==="true"&&console.log(`[onelog] Insecure TLS enabled${M?` via proxy ${M}`:""}; certificate validation is disabled.`)}catch(e){console.error("[onelog] Failed to configure insecure TLS dispatcher",e.message)}}};A();var u=require("@opentelemetry/api"),Te=require("@opentelemetry/sdk-node");var $=require("@opentelemetry/api"),be=(0,$.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function F(e){return e.setValue(be,!0)}var k=require("@opentelemetry/api");function ee(){return function(e){k.diag.error(Me(e))}}function Me(e){return typeof e=="string"?e:JSON.stringify(Ue(e))}function Ue(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 Be=ee();function U(e){try{Be(e)}catch{}}var d=require("@opentelemetry/api");var B;(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"})(B||(B={}));var De=",",we=["OTEL_SDK_DISABLED"];function Xe(e){return we.indexOf(e)>-1}var Ge=["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 He(e){return Ge.indexOf(e)>-1}var Fe=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function Ve(e){return Fe.indexOf(e)>-1}var V=1/0,z=128,ze=128,Ke=128,K={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:d.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:V,OTEL_ATTRIBUTE_COUNT_LIMIT:z,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:V,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:z,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:V,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:z,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:B.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 je(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function qe(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 Ye(e,t,r,o){o===void 0&&(o=De);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var We={ALL:d.DiagLogLevel.ALL,VERBOSE:d.DiagLogLevel.VERBOSE,DEBUG:d.DiagLogLevel.DEBUG,INFO:d.DiagLogLevel.INFO,WARN:d.DiagLogLevel.WARN,ERROR:d.DiagLogLevel.ERROR,NONE:d.DiagLogLevel.NONE};function Qe(e,t,r){var o=r[e];if(typeof o=="string"){var n=We[o.toUpperCase()];n!=null&&(t[e]=n)}}function te(e){var t={};for(var r in K){var o=r;switch(o){case"OTEL_LOG_LEVEL":Qe(o,t,e);break;default:if(Xe(o))je(o,t,e);else if(He(o))qe(o,t,e);else if(Ve(o))Ye(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function x(){var e=te(process.env);return Object.assign({},K,e)}function N(e){e.unref()}var y;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(y||(y={}));var oe=(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},rt=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))},j=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new oe}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,rt([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 ne=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=x();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 j(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(F(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===y.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 f=s[_];f.resource.asyncAttributesPending&&f.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(f.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(O){U(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,U(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),N(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var ot=(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)}})(),C=(function(e){ot(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(ne);var q=require("@opentelemetry/resources"),ue=require("@opentelemetry/exporter-trace-otlp-http"),pe=require("@opentelemetry/auto-instrumentations-node");var se=require("async_hooks"),w=new se.AsyncLocalStorage,D={},P=e=>({...e||{}}),c=()=>P(D),ie=e=>{D=P(e)},ae=e=>{D={...D,...P(e)}},l=()=>w.getStore()?.requestAttributes||{},I=(e,t)=>{let r=w.getStore();if(!r)return;let o=t?.append===!1?P(e):{...r.requestAttributes,...P(e)};r.requestAttributes=o},Ee=e=>I(e),_e=(e,t,r)=>w.getStore()?(I(e,r),t()):v(()=>t(),e),v=(e,t)=>w.run({requestAttributes:P(t)},e);u.diag.setLogger(new u.DiagConsoleLogger,u.DiagLogLevel.WARN);var st=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",at=process.env.MAIN_ENV||process.env.NODE_ENV||"development",ce=process.env.MAIN_MODULE||"unknown-module",Et=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),_t=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",le=process.env.MAIN_MODULE||ce;A();var Tt=q.Resource.default().merge(new q.Resource({"service.name":st,"service.namespace":it,"deployment.environment":at,"module.name":le})),Y=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={...c(),...l()};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()}},W=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(()=>{})}},ut=(0,pe.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:_t?[]:["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}}),pt=new ue.OTLPTraceExporter({url:`${Et}/v1/traces`}),ct=new W([new Y(le),new C(pt)]),Oe=new Te.NodeSDK({resource:Tt,instrumentations:[ut],spanProcessor:ct}),fe=Promise.resolve(Oe.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),de=async()=>{try{await Oe.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",de);process.on("SIGINT",de);var me=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||ce;e.use((n,s,i)=>{v(()=>{let E=u.propagation.getBaggage(u.context.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([p,H])=>[p,H.value])):{},h=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],f=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"],G={};if(T)try{let p=typeof T=="string"?JSON.parse(T):T;p&&typeof p=="object"&&(G=p)}catch{}I({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":h,"organization-id":h,"session.id":f,"session-id":f,"execution.id":O,"execution-id":O,"user.id":R,"user-id":R,"request.id":a,"request-id":a,..._,...G});let L=u.trace.getActiveSpan();if(L){L.setAttribute("module.name",o),L.updateName(`[${o}] ${n.method} ${n.path}`);let p={...c(),...l()};for(let[H,Q]of Object.entries(p))Q!==void 0&&L.setAttribute(H,Q)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};var Re=ye(require("pino"),1);var lt=["fatal","error","warn","info","debug","trace"],Ot=e=>{let t=()=>({...c(),...l()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&<.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 Le(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=(0,Re.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 Ot(n)}var X=require("@opentelemetry/api");var he=e=>(t,r,o,n)=>{let s={...c(),...l()};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 Ae(e,t={},r,o={}){A();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={...c(),...l(),...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)},f={};for(let[a,T]of Object.entries(i))if(T!=null)try{f[a]={value:typeof T=="string"?T:JSON.stringify(T)}}catch{}let O=g.propagation.createBaggage(f),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 p=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw p.status=a.status,p.data=L,r&&r.error({...i,url:e,method:s,status:a.status,data:L},"HTTP call failed"),p}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}}A();0&&(module.exports={createLogger,errorMiddleware,getGlobalAttributes,getRequestAttributes,httpCall,instrumentApp,mergeGlobalAttributes,mergeRequestAttributes,runWithRequestContext,sdkStartPromise,setGlobalAttributes,setRequestAttributes,withRequestAttributes});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/network.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":["import { ensureInsecureTls } from './network.js';\n\nensureInsecureTls();\n\nexport { 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 { Agent, ProxyAgent, setGlobalDispatcher } from 'undici';\n\nlet insecureDispatcherConfigured = false;\n\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\nconst buildInsecureDispatcher = () => {\n if (proxyUrl) {\n return new ProxyAgent({\n uri: proxyUrl,\n // Force-disable TLS verification for both the proxy hop and the target\n connect: { rejectUnauthorized: false },\n requestTls: { rejectUnauthorized: false },\n proxyTls: { rejectUnauthorized: false },\n });\n }\n\n return new Agent({\n connect: { rejectUnauthorized: false },\n });\n};\n\nexport const ensureInsecureTls = () => {\n if (insecureDispatcherConfigured) return;\n insecureDispatcherConfigured = true;\n\n // Disable TLS verification for any Node-native HTTPS calls\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n\n try {\n const dispatcher = buildInsecureDispatcher();\n setGlobalDispatcher(dispatcher);\n if ((process.env.ONELOG_DEBUG || '').toLowerCase() === 'true') {\n // eslint-disable-next-line no-console\n console.log(\n `[onelog] Insecure TLS enabled${proxyUrl ? ` via proxy ${proxyUrl}` : ''}; certificate validation is disabled.`,\n );\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure insecure TLS dispatcher', (err as Error).message);\n }\n};\n\n// Apply on import so any consumer automatically opts into insecure TLS handling\nensureInsecureTls();\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 { ensureInsecureTls } from './network.js';\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\nensureInsecureTls();\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';\nimport { ensureInsecureTls } from './network.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 ensureInsecureTls();\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 { HostMetrics } from '@opentelemetry/host-metrics';\nimport { RuntimeNodeInstrumentation } from '@opentelemetry/instrumentation-runtime-node';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport { ensureInsecureTls } from './network.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(/\\/$/, '');\nconst hostMetricsEnabled = (process.env.ONELOG_HOST_METRICS || 'true').toLowerCase() === 'true';\nconst runtimeMetricsEnabled = (process.env.ONELOG_RUNTIME_METRICS || 'false').toLowerCase() === 'true';\n\nensureInsecureTls();\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;\nlet hostMetricsStarted = false;\nlet runtimeMetricsStarted = 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 startHostMetrics(meterProvider);\n startRuntimeMetrics(meterProvider);\n registerShutdown();\n return meterProvider;\n};\n\nconst startHostMetrics = (provider: MeterProvider) => {\n if (!hostMetricsEnabled || hostMetricsStarted) return;\n try {\n const hostMetrics = new HostMetrics({\n meterProvider: provider,\n name: 'onelog-host-metrics',\n });\n hostMetrics.start();\n hostMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start host metrics instrumentation', (error as Error).message);\n }\n};\n\nconst startRuntimeMetrics = (provider: MeterProvider) => {\n if (!runtimeMetricsEnabled || runtimeMetricsStarted) return;\n try {\n const runtimeInstrumentation = new RuntimeNodeInstrumentation();\n runtimeInstrumentation.setMeterProvider(provider);\n runtimeInstrumentation.enable();\n runtimeMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start runtime metrics instrumentation', (error as Error).message);\n }\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,EAAuD,kBAEnDC,GAA+B,GAE7BC,EAAW,CAAC,QAAQ,IAAI,YAAa,QAAQ,IAAI,YAAa,QAAQ,IAAI,WAAY,QAAQ,IAAI,UAAU,EAC/G,KAAMC,GAAMA,GAAKA,EAAE,KAAK,EAAE,OAAS,CAAC,EAEjCC,GAA0B,IAC1BF,EACK,IAAI,aAAW,CACpB,IAAKA,EAEL,QAAS,CAAE,mBAAoB,EAAM,EACrC,WAAY,CAAE,mBAAoB,EAAM,EACxC,SAAU,CAAE,mBAAoB,EAAM,CACxC,CAAC,EAGI,IAAI,QAAM,CACf,QAAS,CAAE,mBAAoB,EAAM,CACvC,CAAC,EAGUG,EAAoB,IAAM,CACrC,GAAI,C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0DA,EAAgB,OAAO,CACjG,CACF,EAEMK,GAAuBC,GAA4B,CACvD,GAAI,GAACf,IAAyBM,IAC9B,GAAI,CACF,IAAMU,EAAyB,IAAI,8BACnCA,EAAuB,iBAAiBD,CAAQ,EAChDC,EAAuB,OAAO,EAC9BV,GAAwB,EAC1B,OAASG,EAAO,CAEd,QAAQ,MAAM,2DAA6DA,EAAgB,OAAO,CACpG,CACF,EAEaQ,GAAsB,QAAQ,QAAQ,EAAE,KAAK,IAAMP,GAAoB,CAAC,EAExEQ,EAAW,CAACC,EAAO,mBAAqBT,GAAoB,EAAE,SAASS,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,EnB/HAC,EAAkB","names":["index_exports","__export","createCounter","createHistogram","createLogger","errorMiddleware","getGlobalAttributes","getMeter","getRequestAttributes","httpCall","instrumentApp","mergeGlobalAttributes","mergeRequestAttributes","metricsStartPromise","runWithRequestContext","sdkStartPromise","setGlobalAttributes","setRequestAttributes","withRequestAttributes","__toCommonJS","import_undici","insecureDispatcherConfigured","proxyUrl","v","buildInsecureDispatcher","ensureInsecureTls","dispatcher","err","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_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","ensureInsecureTls","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","ensureInsecureTls","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","import_host_metrics","import_instrumentation_runtime_node","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","hostMetricsEnabled","runtimeMetricsEnabled","ensureInsecureTls","resource","meterProvider","shutdownRegistered","hostMetricsStarted","runtimeMetricsStarted","registerShutdown","shutdown","error","ensureMeterProvider","exporter","otMetrics","startHostMetrics","startRuntimeMetrics","provider","runtimeInstrumentation","metricsStartPromise","getMeter","name","buildAttributes","attrs","getGlobalAttributes","getRequestAttributes","createCounter","options","counter","value","attributes","otContext","createHistogram","histogram","ensureInsecureTls"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/network.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":["import { ensureInsecureTls } from './network.js';\n\nensureInsecureTls();\n\nexport { 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 { Agent, ProxyAgent, setGlobalDispatcher } from 'undici';\n\nlet insecureDispatcherConfigured = false;\n\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\nconst buildInsecureDispatcher = () => {\n if (proxyUrl) {\n return new ProxyAgent({\n uri: proxyUrl,\n // Force-disable TLS verification for both the proxy hop and the target\n connect: { rejectUnauthorized: false },\n requestTls: { rejectUnauthorized: false },\n proxyTls: { rejectUnauthorized: false },\n });\n }\n\n return new Agent({\n connect: { rejectUnauthorized: false },\n });\n};\n\nexport const ensureInsecureTls = () => {\n if (insecureDispatcherConfigured) return;\n insecureDispatcherConfigured = true;\n\n // Disable TLS verification for any Node-native HTTPS calls\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n\n try {\n const dispatcher = buildInsecureDispatcher();\n setGlobalDispatcher(dispatcher);\n if ((process.env.ONELOG_DEBUG || '').toLowerCase() === 'true') {\n // eslint-disable-next-line no-console\n console.log(\n `[onelog] Insecure TLS enabled${proxyUrl ? ` via proxy ${proxyUrl}` : ''}; certificate validation is disabled.`,\n );\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure insecure TLS dispatcher', (err as Error).message);\n }\n};\n\n// Apply on import so any consumer automatically opts into insecure TLS handling\nensureInsecureTls();\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 { ensureInsecureTls } from './network.js';\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\nensureInsecureTls();\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';\nimport { ensureInsecureTls } from './network.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 ensureInsecureTls();\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"],"mappings":"ukBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,GAAA,oBAAAC,GAAA,wBAAAC,EAAA,yBAAAC,EAAA,aAAAC,GAAA,kBAAAC,GAAA,0BAAAC,GAAA,2BAAAC,GAAA,0BAAAC,EAAA,oBAAAC,GAAA,wBAAAC,GAAA,yBAAAC,EAAA,0BAAAC,KAAA,eAAAC,GAAAf,ICAA,IAAAgB,EAAuD,kBAEnDC,EAA+B,GAE7BC,EAAW,CAAC,QAAQ,IAAI,YAAa,QAAQ,IAAI,YAAa,Q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,IAAAP,EAAK,OAAAM,EAAQ,MAAOgB,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF,ClBtGAC,EAAkB","names":["index_exports","__export","createLogger","errorMiddleware","getGlobalAttributes","getRequestAttributes","httpCall","instrumentApp","mergeGlobalAttributes","mergeRequestAttributes","runWithRequestContext","sdkStartPromise","setGlobalAttributes","setRequestAttributes","withRequestAttributes","__toCommonJS","import_undici","insecureDispatcherConfigured","proxyUrl","v","buildInsecureDispatcher","ensureInsecureTls","dispatcher","err","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_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","ensureInsecureTls","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","ensureInsecureTls","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","ctxWithBaggage","res","data","error","err","ensureInsecureTls"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
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';
|
|
6
3
|
|
|
7
4
|
declare const sdkStartPromise: Promise<void>;
|
|
8
5
|
declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
|
|
@@ -22,17 +19,6 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
|
|
|
22
19
|
error: Function;
|
|
23
20
|
}, logContext?: HttpCallContext): Promise<any>;
|
|
24
21
|
|
|
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
|
-
|
|
36
22
|
type AttributeMap = Record<string, any>;
|
|
37
23
|
declare const getGlobalAttributes: () => AttributeMap;
|
|
38
24
|
declare const setGlobalAttributes: (attrs: AttributeMap) => void;
|
|
@@ -47,4 +33,4 @@ declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, optio
|
|
|
47
33
|
}) => T;
|
|
48
34
|
declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
|
|
49
35
|
|
|
50
|
-
export {
|
|
36
|
+
export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
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';
|
|
6
3
|
|
|
7
4
|
declare const sdkStartPromise: Promise<void>;
|
|
8
5
|
declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
|
|
@@ -22,17 +19,6 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
|
|
|
22
19
|
error: Function;
|
|
23
20
|
}, logContext?: HttpCallContext): Promise<any>;
|
|
24
21
|
|
|
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
|
-
|
|
36
22
|
type AttributeMap = Record<string, any>;
|
|
37
23
|
declare const getGlobalAttributes: () => AttributeMap;
|
|
38
24
|
declare const setGlobalAttributes: (attrs: AttributeMap) => void;
|
|
@@ -47,4 +33,4 @@ declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, optio
|
|
|
47
33
|
}) => T;
|
|
48
34
|
declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
|
|
49
35
|
|
|
50
|
-
export {
|
|
36
|
+
export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var ce=(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{Agent as pe,ProxyAgent as le,setGlobalDispatcher as de}from"undici";var Y=!1,N=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0),me=()=>N?new le({uri:N,connect:{rejectUnauthorized:!1},requestTls:{rejectUnauthorized:!1},proxyTls:{rejectUnauthorized:!1}}):new pe({connect:{rejectUnauthorized:!1}}),m=()=>{if(!Y){Y=!0,process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";try{let e=me();de(e),(process.env.ONELOG_DEBUG||"").toLowerCase()==="true"&&console.log(`[onelog] Insecure TLS enabled${N?` via proxy ${N}`:""}; certificate validation is disabled.`)}catch(e){console.error("[onelog] Failed to configure insecure TLS dispatcher",e.message)}}};m();import{diag as Ze,DiagConsoleLogger as ke,DiagLogLevel as et,trace as tt,context as rt,propagation as ot}from"@opentelemetry/api";import{NodeSDK as nt}from"@opentelemetry/sdk-node";import{createContextKey as Oe}from"@opentelemetry/api";var fe=Oe("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function w(e){return e.setValue(fe,!0)}import{diag as Re}from"@opentelemetry/api";function W(){return function(e){Re.error(Le(e))}}function Le(e){return typeof e=="string"?e:JSON.stringify(he(e))}function he(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 Ae=W();function v(e){try{Ae(e)}catch{}}import{DiagLogLevel as L}from"@opentelemetry/api";var y;(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"})(y||(y={}));var Pe=",",Se=["OTEL_SDK_DISABLED"];function ge(e){return Se.indexOf(e)>-1}var Ie=["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 xe(e){return Ie.indexOf(e)>-1}var Ne=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function ve(e){return Ne.indexOf(e)>-1}var D=1/0,X=128,ye=128,Ce=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:L.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:D,OTEL_ATTRIBUTE_COUNT_LIMIT:X,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:D,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:X,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:D,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:X,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:ye,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Ce,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:y.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 Me(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 Ue(e,t,r,o){o===void 0&&(o=Pe);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var Be={ALL:L.ALL,VERBOSE:L.VERBOSE,DEBUG:L.DEBUG,INFO:L.INFO,WARN:L.WARN,ERROR:L.ERROR,NONE:L.NONE};function we(e,t,r){var o=r[e];if(typeof o=="string"){var n=Be[o.toUpperCase()];n!=null&&(t[e]=n)}}function Q(e){var t={};for(var r in G){var o=r;switch(o){case"OTEL_LOG_LEVEL":we(o,t,e);break;default:if(ge(o))Me(o,t,e);else if(xe(o))be(o,t,e);else if(ve(o))Ue(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function P(){var e=Q(process.env);return Object.assign({},G,e)}function S(e){e.unref()}var g;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(g||(g={}));var $=(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 Ve=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},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))},H=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new $}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],Ve(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 Z,diag as F,TraceFlags as Ke}from"@opentelemetry/api";var k=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=P();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 H(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(F.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&Ke.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&&F.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(F.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);Z.with(w(Z.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 f;clearTimeout(n),l.code===g.SUCCESS?r():o((f=l.error)!==null&&f!==void 0?f: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(l){v(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,v(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),S(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)}})(),I=(function(e){je(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(k);import{Resource as ee}from"@opentelemetry/resources";import{OTLPTraceExporter as st}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as it}from"@opentelemetry/auto-instrumentations-node";import{AsyncLocalStorage as Ye}from"async_hooks";var M=new Ye,C={},A=e=>({...e||{}}),T=()=>A(C),We=e=>{C=A(e)},Qe=e=>{C={...C,...A(e)}},c=()=>M.getStore()?.requestAttributes||{},x=(e,t)=>{let r=M.getStore();if(!r)return;let o=t?.append===!1?A(e):{...r.requestAttributes,...A(e)};r.requestAttributes=o},Je=e=>x(e),$e=(e,t,r)=>M.getStore()?(x(e,r),t()):b(()=>t(),e),b=(e,t)=>M.run({requestAttributes:A(t)},e);Ze.setLogger(new ke,et.WARN);var at=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Et=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",_t=process.env.MAIN_ENV||process.env.NODE_ENV||"development",te=process.env.MAIN_MODULE||"unknown-module",ut=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Tt=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",re=process.env.MAIN_MODULE||te;m();var ct=ee.default().merge(new ee({"service.name":at,"service.namespace":Et,"deployment.environment":_t,"module.name":re})),V=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(),...c()};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()}},z=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(()=>{})}},pt=it({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:Tt?[]:["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}}),lt=new st({url:`${ut}/v1/traces`}),dt=new z([new V(re),new I(lt)]),oe=new nt({resource:ct,instrumentations:[pt],spanProcessor:dt}),mt=Promise.resolve(oe.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),ne=async()=>{try{await oe.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",ne);process.on("SIGINT",ne);var Ot=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||te;e.use((n,s,i)=>{b(()=>{let E=ot.getBaggage(rt.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([p,B])=>[p,B.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"],l=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],f=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"],u=n.headers["x-onelog-attr"]||n.headers["x-onelog-attrs"]||_["x-onelog-attr"],U={};if(u)try{let p=typeof u=="string"?JSON.parse(u):u;p&&typeof p=="object"&&(U=p)}catch{}x({"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":l,"execution-id":l,"user.id":f,"user-id":f,"request.id":a,"request-id":a,..._,...U});let R=tt.getActiveSpan();if(R){R.setAttribute("module.name",o),R.updateName(`[${o}] ${n.method} ${n.path}`);let p={...T(),...c()};for(let[B,q]of Object.entries(p))q!==void 0&&R.setAttribute(B,q)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};import ft from"pino";var Rt=["fatal","error","warn","info","debug","trace"],Lt=e=>{let t=()=>({...T(),...c()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&Rt.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 ht(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=ft({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":ce("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 At,SpanStatusCode as Pt}from"@opentelemetry/api";var St=e=>(t,r,o,n)=>{let s={...T(),...c()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=At.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:Pt.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 gt,propagation as K}from"@opentelemetry/api";async function It(e,t={},r,o={}){m();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={...T(),...c(),...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,u])=>[a,String(u)]),h={...Object.fromEntries(E)},d={};for(let[a,u]of Object.entries(i))if(u!=null)try{d[a]={value:typeof u=="string"?u:JSON.stringify(u)}}catch{}let l=K.createBaggage(d),f=K.setBaggage(gt.active(),l);K.inject(f,h),n.headers=h,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),R=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let p=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw p.status=a.status,p.data=R,r&&r.error({...i,url:e,method:s,status:a.status,data:R},"HTTP call failed"),p}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),R}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}import{context as _e,metrics as xt}from"@opentelemetry/api";import{Resource as se}from"@opentelemetry/resources";import{MeterProvider as Nt,PeriodicExportingMetricReader as vt}from"@opentelemetry/sdk-metrics";import{OTLPMetricExporter as yt}from"@opentelemetry/exporter-metrics-otlp-http";import{HostMetrics as Ct}from"@opentelemetry/host-metrics";import{RuntimeNodeInstrumentation as Mt}from"@opentelemetry/instrumentation-runtime-node";var bt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Ut=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Bt=process.env.MAIN_ENV||process.env.NODE_ENV||"development",wt=process.env.MAIN_MODULE||"unknown-module",Dt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Xt=(process.env.ONELOG_HOST_METRICS||"true").toLowerCase()==="true",Gt=(process.env.ONELOG_RUNTIME_METRICS||"false").toLowerCase()==="true";m();var Ht=se.default().merge(new se({"service.name":bt,"service.namespace":Ut,"deployment.environment":Bt,"module.name":wt})),O,ie=!1,ae=!1,Ee=!1,Ft=()=>{if(ie)return;ie=!0;let e=async()=>{if(O)try{await O.shutdown()}catch(t){console.error("[onelog] Error shutting down metrics provider",t.message)}};process.on("SIGTERM",e),process.on("SIGINT",e)},ue=()=>{if(O)return O;let e=new yt({url:`${Dt}/v1/metrics`});return O=new Nt({resource:Ht,readers:[new vt({exporter:e})]}),xt.setGlobalMeterProvider(O),Vt(O),zt(O),Ft(),O},Vt=e=>{if(!(!Xt||ae))try{new Ct({meterProvider:e,name:"onelog-host-metrics"}).start(),ae=!0}catch(t){console.error("[onelog] Failed to start host metrics instrumentation",t.message)}},zt=e=>{if(!(!Gt||Ee))try{let t=new Mt;t.setMeterProvider(e),t.enable(),Ee=!0}catch(t){console.error("[onelog] Failed to start runtime metrics instrumentation",t.message)}},Kt=Promise.resolve().then(()=>ue()),j=(e="onelog-metrics")=>ue().getMeter(e),Te=e=>({...T(),...c(),...e||{}}),jt=(e,t)=>{let r=j().createCounter(e,t);return{add:(o,n)=>{r.add(o,Te(n),_e.active())},instrument:r}},qt=(e,t)=>{let r=j().createHistogram(e,t);return{record:(o,n)=>{r.record(o,Te(n),_e.active())},instrument:r}};m();export{jt as createCounter,qt as createHistogram,ht as createLogger,St as errorMiddleware,T as getGlobalAttributes,j as getMeter,c as getRequestAttributes,It as httpCall,Ot as instrumentApp,Qe as mergeGlobalAttributes,Je as mergeRequestAttributes,Kt as metricsStartPromise,b as runWithRequestContext,mt as sdkStartPromise,We as setGlobalAttributes,x as setRequestAttributes,$e as withRequestAttributes};
|
|
1
|
+
var oe=(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{Agent as ne,ProxyAgent as se,setGlobalDispatcher as ie}from"undici";var j=!1,x=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0),ae=()=>x?new se({uri:x,connect:{rejectUnauthorized:!1},requestTls:{rejectUnauthorized:!1},proxyTls:{rejectUnauthorized:!1}}):new ne({connect:{rejectUnauthorized:!1}}),L=()=>{if(!j){j=!0,process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";try{let e=ae();ie(e),(process.env.ONELOG_DEBUG||"").toLowerCase()==="true"&&console.log(`[onelog] Insecure TLS enabled${x?` via proxy ${x}`:""}; certificate validation is disabled.`)}catch(e){console.error("[onelog] Failed to configure insecure TLS dispatcher",e.message)}}};L();import{diag as ze,DiagConsoleLogger as Ke,DiagLogLevel as je,trace as qe,context as Ye,propagation as We}from"@opentelemetry/api";import{NodeSDK as Qe}from"@opentelemetry/sdk-node";import{createContextKey as Ee}from"@opentelemetry/api";var _e=Ee("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function B(e){return e.setValue(_e,!0)}import{diag as Te}from"@opentelemetry/api";function q(){return function(e){Te.error(ue(e))}}function ue(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 ce=q();function N(e){try{ce(e)}catch{}}import{DiagLogLevel as m}from"@opentelemetry/api";var y;(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"})(y||(y={}));var le=",",Oe=["OTEL_SDK_DISABLED"];function fe(e){return Oe.indexOf(e)>-1}var de=["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 me(e){return de.indexOf(e)>-1}var Re=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function Le(e){return Re.indexOf(e)>-1}var D=1/0,w=128,he=128,Ae=128,X={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:D,OTEL_ATTRIBUTE_COUNT_LIMIT:w,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:D,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:w,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:D,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:he,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Ae,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:y.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 Pe(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=le);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var ge={ALL:m.ALL,VERBOSE:m.VERBOSE,DEBUG:m.DEBUG,INFO:m.INFO,WARN:m.WARN,ERROR:m.ERROR,NONE:m.NONE};function xe(e,t,r){var o=r[e];if(typeof o=="string"){var n=ge[o.toUpperCase()];n!=null&&(t[e]=n)}}function Y(e){var t={};for(var r in X){var o=r;switch(o){case"OTEL_LOG_LEVEL":xe(o,t,e);break;default:if(fe(o))Se(o,t,e);else if(me(o))Pe(o,t,e);else if(Le(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({},X,e)}function S(e){e.unref()}var P;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(P||(P={}));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 Me=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},Ue=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))},G=(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,Ue([this._that],Me(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 H,TraceFlags as Be}from"@opentelemetry/api";var Z=(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 G(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(H.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&Be.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&&H.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(H.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(B(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(p){var f;clearTimeout(n),p.code===P.SUCCESS?r():o((f=p.error)!==null&&f!==void 0?f: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(p){N(p),o(p)})})})},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,N(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),S(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)}})(),I=(function(e){De(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(Z);import{Resource as $}from"@opentelemetry/resources";import{OTLPTraceExporter as Je}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as Ze}from"@opentelemetry/auto-instrumentations-node";import{AsyncLocalStorage as Xe}from"async_hooks";var v=new Xe,C={},h=e=>({...e||{}}),c=()=>h(C),Ge=e=>{C=h(e)},He=e=>{C={...C,...h(e)}},l=()=>v.getStore()?.requestAttributes||{},g=(e,t)=>{let r=v.getStore();if(!r)return;let o=t?.append===!1?h(e):{...r.requestAttributes,...h(e)};r.requestAttributes=o},Fe=e=>g(e),Ve=(e,t,r)=>v.getStore()?(g(e,r),t()):b(()=>t(),e),b=(e,t)=>v.run({requestAttributes:h(t)},e);ze.setLogger(new Ke,je.WARN);var $e=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",ke=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",et=process.env.MAIN_ENV||process.env.NODE_ENV||"development",k=process.env.MAIN_MODULE||"unknown-module",tt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),rt=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",ee=process.env.MAIN_MODULE||k;L();var ot=$.default().merge(new $({"service.name":$e,"service.namespace":ke,"deployment.environment":et,"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={...c(),...l()};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(()=>{})}},nt=Ze({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:rt?[]:["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}}),st=new Je({url:`${tt}/v1/traces`}),it=new V([new F(ee),new I(st)]),te=new Qe({resource:ot,instrumentations:[nt],spanProcessor:it}),at=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 Et=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||k;e.use((n,s,i)=>{b(()=>{let E=We.getBaggage(Ye.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([u,U])=>[u,U.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"],p=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],f=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"],M={};if(T)try{let u=typeof T=="string"?JSON.parse(T):T;u&&typeof u=="object"&&(M=u)}catch{}g({"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":p,"execution-id":p,"user.id":f,"user-id":f,"request.id":a,"request-id":a,..._,...M});let d=qe.getActiveSpan();if(d){d.setAttribute("module.name",o),d.updateName(`[${o}] ${n.method} ${n.path}`);let u={...c(),...l()};for(let[U,K]of Object.entries(u))K!==void 0&&d.setAttribute(U,K)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};import _t from"pino";var Tt=["fatal","error","warn","info","debug","trace"],ut=e=>{let t=()=>({...c(),...l()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&Tt.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 pt(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=_t({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":oe("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 ut(n)}import{trace as ct,SpanStatusCode as lt}from"@opentelemetry/api";var Ot=e=>(t,r,o,n)=>{let s={...c(),...l()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=ct.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:lt.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 ft,propagation as z}from"@opentelemetry/api";async function dt(e,t={},r,o={}){L();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={...c(),...l(),...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 p=z.createBaggage(O),f=z.setBaggage(ft.active(),p);z.inject(f,R),n.headers=R,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),d=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let u=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw u.status=a.status,u.data=d,r&&r.error({...i,url:e,method:s,status:a.status,data:d},"HTTP call failed"),u}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),d}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}L();export{pt as createLogger,Ot as errorMiddleware,c as getGlobalAttributes,l as getRequestAttributes,dt as httpCall,Et as instrumentApp,He as mergeGlobalAttributes,Fe as mergeRequestAttributes,b as runWithRequestContext,at as sdkStartPromise,Ge as setGlobalAttributes,g as setRequestAttributes,Ve as withRequestAttributes};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/network.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","../src/index.ts"],"sourcesContent":["import { Agent, ProxyAgent, setGlobalDispatcher } from 'undici';\n\nlet insecureDispatcherConfigured = false;\n\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\nconst buildInsecureDispatcher = () => {\n if (proxyUrl) {\n return new ProxyAgent({\n uri: proxyUrl,\n // Force-disable TLS verification for both the proxy hop and the target\n connect: { rejectUnauthorized: false },\n requestTls: { rejectUnauthorized: false },\n proxyTls: { rejectUnauthorized: false },\n });\n }\n\n return new Agent({\n connect: { rejectUnauthorized: false },\n });\n};\n\nexport const ensureInsecureTls = () => {\n if (insecureDispatcherConfigured) return;\n insecureDispatcherConfigured = true;\n\n // Disable TLS verification for any Node-native HTTPS calls\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n\n try {\n const dispatcher = buildInsecureDispatcher();\n setGlobalDispatcher(dispatcher);\n if ((process.env.ONELOG_DEBUG || '').toLowerCase() === 'true') {\n // eslint-disable-next-line no-console\n console.log(\n `[onelog] Insecure TLS enabled${proxyUrl ? ` via proxy ${proxyUrl}` : ''}; certificate validation is disabled.`,\n );\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure insecure TLS dispatcher', (err as Error).message);\n }\n};\n\n// Apply on import so any consumer automatically opts into insecure TLS handling\nensureInsecureTls();\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 { ensureInsecureTls } from './network.js';\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\nensureInsecureTls();\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';\nimport { ensureInsecureTls } from './network.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 ensureInsecureTls();\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 { HostMetrics } from '@opentelemetry/host-metrics';\nimport { RuntimeNodeInstrumentation } from '@opentelemetry/instrumentation-runtime-node';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport { ensureInsecureTls } from './network.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(/\\/$/, '');\nconst hostMetricsEnabled = (process.env.ONELOG_HOST_METRICS || 'true').toLowerCase() === 'true';\nconst runtimeMetricsEnabled = (process.env.ONELOG_RUNTIME_METRICS || 'false').toLowerCase() === 'true';\n\nensureInsecureTls();\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;\nlet hostMetricsStarted = false;\nlet runtimeMetricsStarted = 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 startHostMetrics(meterProvider);\n startRuntimeMetrics(meterProvider);\n registerShutdown();\n return meterProvider;\n};\n\nconst startHostMetrics = (provider: MeterProvider) => {\n if (!hostMetricsEnabled || hostMetricsStarted) return;\n try {\n const hostMetrics = new HostMetrics({\n meterProvider: provider,\n name: 'onelog-host-metrics',\n });\n hostMetrics.start();\n hostMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start host metrics instrumentation', (error as Error).message);\n }\n};\n\nconst startRuntimeMetrics = (provider: MeterProvider) => {\n if (!runtimeMetricsEnabled || runtimeMetricsStarted) return;\n try {\n const runtimeInstrumentation = new RuntimeNodeInstrumentation();\n runtimeInstrumentation.setMeterProvider(provider);\n runtimeInstrumentation.enable();\n runtimeMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start runtime metrics instrumentation', (error as Error).message);\n }\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","import { ensureInsecureTls } from './network.js';\n\nensureInsecureTls();\n\nexport { 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"],"mappings":"0PAAA,OAAS,SAAAA,GAAO,cAAAC,GAAY,uBAAAC,OAA2B,SAEvD,IAAIC,EAA+B,GAE7BC,EAAW,CAAC,QAAQ,IAAI,YAAa,QAAQ,IAAI,YAAa,QAAQ,IAAI,WAAY,QAAQ,IAAI,UAAU,EAC/G,KAAMC,GAAMA,GAAKA,EAAE,KAAK,EAAE,OAAS,CAAC,EAEjCC,GAA0B,IAC1BF,EACK,IAAIH,GAAW,CACpB,IAAKG,EAEL,QAAS,CAAE,mBAAoB,EAAM,EACrC,WAAY,CAAE,mBAAoB,EAAM,EACxC,SAAU,CAAE,mBAAoB,EAAM,CACxC,CAAC,EAGI,IAAIJ,GAAM,CACf,QAAS,CAAE,mBAAoB,EAAM,CACvC,CAAC,EAGUO,EAAoB,IAAM,CACrC,GAAI,CAAAJ,EACJ,CAAAA,EAA+B,GAG/B,QAAQ,IAAI,6BAA+B,IAE3C,GAAI,CACF,IAAMK,EAAaF,GAAwB,EAC3CJ,GAAoBM,CAAU,GACzB,QAAQ,IAAI,cAAgB,IAAI,YAAY,IAAM,QAErD,QAAQ,IACN,gCAAgCJ,EAAW,cAAcA,CAAQ,GAAK,EAAE,uCAC1E,CAEJ,OAASK,EAAK,CAEZ,QAAQ,MAAM,uDAAyDA,EAAc,OAAO,CAC9F,EACF,EAGAF,EAAkB,EC9ClB,OAAS,QAAAG,GAAM,qBAAAC,GAAmB,gBAAAC,GAAc,SAAAC,GAAO,WAAWC,GAAW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ACvD,GAAI,GAACnB,IAAyBO,IAC9B,GAAI,CACF,IAAMc,EAAyB,IAAIC,GACnCD,EAAuB,iBAAiBF,CAAQ,EAChDE,EAAuB,OAAO,EAC9Bd,GAAwB,EAC1B,OAASG,EAAO,CAEd,QAAQ,MAAM,2DAA6DA,EAAgB,OAAO,CACpG,CACF,EAEaa,GAAsB,QAAQ,QAAQ,EAAE,KAAK,IAAMZ,GAAoB,CAAC,EAExEa,EAAW,CAACC,EAAO,mBAAqBd,GAAoB,EAAE,SAASc,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,EAAGC,GAAU,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,EAAGC,GAAU,OAAO,CAAC,CACzE,EACA,WAAYE,CACd,CACF,EC/HAC,EAAkB","names":["Agent","ProxyAgent","setGlobalDispatcher","insecureDispatcherConfigured","proxyUrl","v","buildInsecureDispatcher","ensureInsecureTls","dispatcher","err","diag","DiagConsoleLogger","DiagLogLevel","trace","otContext","propagation","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","j","timer","context","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","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","ensureInsecureTls","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","ensureInsecureTls","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","HostMetrics","RuntimeNodeInstrumentation","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","hostMetricsEnabled","runtimeMetricsEnabled","ensureInsecureTls","resource","Resource","meterProvider","shutdownRegistered","hostMetricsStarted","runtimeMetricsStarted","registerShutdown","shutdown","error","ensureMeterProvider","exporter","OTLPMetricExporter","MeterProvider","PeriodicExportingMetricReader","otMetrics","startHostMetrics","startRuntimeMetrics","provider","HostMetrics","runtimeInstrumentation","RuntimeNodeInstrumentation","metricsStartPromise","getMeter","name","buildAttributes","attrs","getGlobalAttributes","getRequestAttributes","createCounter","options","counter","value","attributes","otContext","createHistogram","histogram","ensureInsecureTls"]}
|
|
1
|
+
{"version":3,"sources":["../src/network.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/index.ts"],"sourcesContent":["import { Agent, ProxyAgent, setGlobalDispatcher } from 'undici';\n\nlet insecureDispatcherConfigured = false;\n\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\nconst buildInsecureDispatcher = () => {\n if (proxyUrl) {\n return new ProxyAgent({\n uri: proxyUrl,\n // Force-disable TLS verification for both the proxy hop and the target\n connect: { rejectUnauthorized: false },\n requestTls: { rejectUnauthorized: false },\n proxyTls: { rejectUnauthorized: false },\n });\n }\n\n return new Agent({\n connect: { rejectUnauthorized: false },\n });\n};\n\nexport const ensureInsecureTls = () => {\n if (insecureDispatcherConfigured) return;\n insecureDispatcherConfigured = true;\n\n // Disable TLS verification for any Node-native HTTPS calls\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n\n try {\n const dispatcher = buildInsecureDispatcher();\n setGlobalDispatcher(dispatcher);\n if ((process.env.ONELOG_DEBUG || '').toLowerCase() === 'true') {\n // eslint-disable-next-line no-console\n console.log(\n `[onelog] Insecure TLS enabled${proxyUrl ? ` via proxy ${proxyUrl}` : ''}; certificate validation is disabled.`,\n );\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure insecure TLS dispatcher', (err as Error).message);\n }\n};\n\n// Apply on import so any consumer automatically opts into insecure TLS handling\nensureInsecureTls();\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 { ensureInsecureTls } from './network.js';\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\nensureInsecureTls();\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';\nimport { ensureInsecureTls } from './network.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 ensureInsecureTls();\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 { ensureInsecureTls } from './network.js';\n\nensureInsecureTls();\n\nexport { 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"],"mappings":"0PAAA,OAAS,SAAAA,GAAO,cAAAC,GAAY,uBAAAC,OAA2B,SAEvD,IAAIC,EAA+B,GAE7BC,EAAW,CAAC,QAAQ,IAAI,YAAa,QAAQ,IAAI,YAAa,QAAQ,IAAI,WAAY,QAAQ,IAAI,UAAU,EAC/G,KAAMC,GAAMA,GAAKA,EAAE,KAAK,EAAE,OAAS,CAAC,EAEjCC,GAA0B,IAC1BF,EACK,IAAIH,GAAW,CACpB,IAAKG,EAEL,QAAS,CA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AG,mBAAmB,EAGlFC,CACT,OAASE,EAAU,CACjB,MAAItB,GACFA,EAAO,MAAM,CAAE,GAAGK,EAAgB,IAAAP,EAAK,OAAAM,EAAQ,MAAOkB,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF,CCtGAC,EAAkB","names":["Agent","ProxyAgent","setGlobalDispatcher","insecureDispatcherConfigured","proxyUrl","v","buildInsecureDispatcher","ensureInsecureTls","dispatcher","err","diag","DiagConsoleLogger","DiagLogLevel","trace","otContext","propagation","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","j","timer","context","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","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","ensureInsecureTls","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","ensureInsecureTls","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","propagation","ctxWithBaggage","context","res","data","error","err","ensureInsecureTls"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onelog-sdk/node",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "OneLog Node SDK for unified tracing, logging, and error handling.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -31,14 +31,10 @@
|
|
|
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",
|
|
35
|
-
"@opentelemetry/host-metrics": "^0.35.0",
|
|
36
34
|
"@opentelemetry/instrumentation": "^0.49.0",
|
|
37
|
-
"@opentelemetry/instrumentation-runtime-node": "^0.22.0",
|
|
38
35
|
"@opentelemetry/exporter-trace-otlp-http": "^0.55.0",
|
|
39
36
|
"@opentelemetry/resources": "^1.24.1",
|
|
40
37
|
"@opentelemetry/sdk-node": "^0.55.0",
|
|
41
|
-
"@opentelemetry/sdk-metrics": "^1.24.1",
|
|
42
38
|
"pino": "^10.1.0",
|
|
43
39
|
"pino-opentelemetry-transport": "^2.0.0",
|
|
44
40
|
"pino-pretty": "^13.1.3",
|