@glasstrace/sdk 0.2.1 → 0.2.3

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/dist/index.js CHANGED
@@ -11,6 +11,21 @@ import {
11
11
  discoverTestFiles,
12
12
  extractImports
13
13
  } from "./chunk-CUFIV225.js";
14
+ import {
15
+ INVALID_SPAN_CONTEXT,
16
+ SamplingDecision,
17
+ SpanKind,
18
+ SpanStatusCode,
19
+ TraceFlags,
20
+ baggageEntryMetadataFromString,
21
+ context,
22
+ createContextKey,
23
+ createNoopMeter,
24
+ diag,
25
+ isSpanContextValid,
26
+ isValidTraceId,
27
+ trace
28
+ } from "./chunk-DQ25VOKK.js";
14
29
  import "./chunk-PZ5AY32C.js";
15
30
 
16
31
  // src/errors.ts
@@ -27,7 +42,7 @@ var SdkError = class extends Error {
27
42
  var DEFAULT_ENDPOINT = "https://api.glasstrace.dev";
28
43
  function readEnvVars() {
29
44
  return {
30
- GLASSTRACE_API_KEY: process.env.GLASSTRACE_API_KEY,
45
+ GLASSTRACE_API_KEY: process.env.GLASSTRACE_API_KEY?.trim() || void 0,
31
46
  GLASSTRACE_FORCE_ENABLE: process.env.GLASSTRACE_FORCE_ENABLE,
32
47
  GLASSTRACE_ENV: process.env.GLASSTRACE_ENV,
33
48
  GLASSTRACE_COVERAGE_MAP: process.env.GLASSTRACE_COVERAGE_MAP,
@@ -265,7 +280,7 @@ async function saveCachedConfig(response, projectRoot) {
265
280
  }
266
281
  }
267
282
  async function sendInitRequest(config, anonKey, sdkVersion, importGraph, healthReport, diagnostics, signal) {
268
- const effectiveKey = config.apiKey ?? anonKey;
283
+ const effectiveKey = config.apiKey || anonKey;
269
284
  if (!effectiveKey) {
270
285
  throw new Error("No API key available for init request");
271
286
  }
@@ -316,7 +331,7 @@ async function performInit(config, anonKey, sdkVersion) {
316
331
  return;
317
332
  }
318
333
  try {
319
- const effectiveKey = config.apiKey ?? anonKey;
334
+ const effectiveKey = config.apiKey || anonKey;
320
335
  if (!effectiveKey) {
321
336
  console.warn("[glasstrace] No API key available for init request.");
322
337
  return;
@@ -412,7 +427,6 @@ var GlasstraceSpanProcessor = class {
412
427
  };
413
428
 
414
429
  // src/enriching-exporter.ts
415
- import { SpanKind } from "@opentelemetry/api";
416
430
  var ATTR = GLASSTRACE_ATTRIBUTE_NAMES;
417
431
  var API_KEY_PENDING = "pending";
418
432
  var MAX_PENDING_SPANS = 1024;
@@ -762,251 +776,2744 @@ function createDiscoveryHandler(getAnonKey, getSessionId) {
762
776
  };
763
777
  }
764
778
 
765
- // src/otel-config.ts
766
- var _resolvedApiKey = API_KEY_PENDING;
767
- var _activeExporter = null;
768
- var _shutdownHandler = null;
769
- function setResolvedApiKey(key) {
770
- _resolvedApiKey = key;
771
- }
772
- function getResolvedApiKey() {
773
- return _resolvedApiKey;
774
- }
775
- function notifyApiKeyResolved() {
776
- _activeExporter?.notifyKeyResolved();
777
- }
778
- async function tryImport(moduleId) {
779
- try {
780
- return await Function("id", "return import(id)")(moduleId);
781
- } catch {
782
- return null;
779
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js
780
+ var OTLPExporterBase = class {
781
+ _delegate;
782
+ constructor(delegate) {
783
+ this._delegate = delegate;
783
784
  }
784
- }
785
- function registerShutdownHooks(provider) {
786
- if (typeof process === "undefined" || typeof process.once !== "function") {
787
- return;
785
+ /**
786
+ * Export items.
787
+ * @param items
788
+ * @param resultCallback
789
+ */
790
+ export(items, resultCallback) {
791
+ this._delegate.export(items, resultCallback);
788
792
  }
789
- if (_shutdownHandler) {
790
- process.removeListener("SIGTERM", _shutdownHandler);
791
- process.removeListener("SIGINT", _shutdownHandler);
793
+ forceFlush() {
794
+ return this._delegate.forceFlush();
792
795
  }
793
- let shutdownCalled = false;
794
- const shutdown = (signal) => {
795
- if (shutdownCalled) return;
796
- shutdownCalled = true;
797
- void provider.shutdown().catch((err) => {
798
- console.warn(
799
- `[glasstrace] Error during OTel shutdown: ${err instanceof Error ? err.message : String(err)}`
800
- );
801
- }).finally(() => {
802
- process.removeListener("SIGTERM", _shutdownHandler);
803
- process.removeListener("SIGINT", _shutdownHandler);
804
- process.kill(process.pid, signal);
805
- });
796
+ shutdown() {
797
+ return this._delegate.shutdown();
798
+ }
799
+ };
800
+
801
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js
802
+ var OTLPExporterError = class extends Error {
803
+ code;
804
+ name = "OTLPExporterError";
805
+ data;
806
+ constructor(message, code, data) {
807
+ super(message);
808
+ this.data = data;
809
+ this.code = code;
810
+ }
811
+ };
812
+
813
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-configuration.js
814
+ function validateTimeoutMillis(timeoutMillis) {
815
+ if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {
816
+ return timeoutMillis;
817
+ }
818
+ throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`);
819
+ }
820
+ function wrapStaticHeadersInFunction(headers) {
821
+ if (headers == null) {
822
+ return void 0;
823
+ }
824
+ return async () => headers;
825
+ }
826
+ function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
827
+ return {
828
+ timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? fallbackConfiguration.timeoutMillis ?? defaultConfiguration.timeoutMillis),
829
+ concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? fallbackConfiguration.concurrencyLimit ?? defaultConfiguration.concurrencyLimit,
830
+ compression: userProvidedConfiguration.compression ?? fallbackConfiguration.compression ?? defaultConfiguration.compression
806
831
  };
807
- const handler = (signal) => shutdown(signal);
808
- _shutdownHandler = handler;
809
- process.once("SIGTERM", handler);
810
- process.once("SIGINT", handler);
811
832
  }
812
- async function configureOtel(config, sessionManager) {
813
- const exporterUrl = `${config.endpoint}/v1/traces`;
814
- let createOtlpExporter = null;
815
- const otlpModule = await tryImport("@opentelemetry/exporter-trace-otlp-http");
816
- if (otlpModule && typeof otlpModule.OTLPTraceExporter === "function") {
817
- const OTLPTraceExporter = otlpModule.OTLPTraceExporter;
818
- createOtlpExporter = (url, headers) => new OTLPTraceExporter({ url, headers });
833
+ function getSharedConfigurationDefaults() {
834
+ return {
835
+ timeoutMillis: 1e4,
836
+ concurrencyLimit: 30,
837
+ compression: "none"
838
+ };
839
+ }
840
+
841
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js
842
+ var BoundedQueueExportPromiseHandler = class {
843
+ _concurrencyLimit;
844
+ _sendingPromises = [];
845
+ /**
846
+ * @param concurrencyLimit maximum promises allowed in a queue at the same time.
847
+ */
848
+ constructor(concurrencyLimit) {
849
+ this._concurrencyLimit = concurrencyLimit;
819
850
  }
820
- const glasstraceExporter = new GlasstraceExporter({
821
- getApiKey: getResolvedApiKey,
822
- sessionManager,
823
- getConfig: () => getActiveConfig(),
824
- environment: config.environment,
825
- endpointUrl: exporterUrl,
826
- createDelegate: createOtlpExporter
827
- });
828
- _activeExporter = glasstraceExporter;
829
- const vercelOtel = await tryImport("@vercel/otel");
830
- if (vercelOtel && typeof vercelOtel.registerOTel === "function") {
831
- if (!createOtlpExporter) {
832
- console.warn(
833
- "[glasstrace] @opentelemetry/exporter-trace-otlp-http not found for @vercel/otel path. Trace export disabled."
834
- );
851
+ pushPromise(promise) {
852
+ if (this.hasReachedLimit()) {
853
+ throw new Error("Concurrency Limit reached");
835
854
  }
836
- const otelConfig = {
837
- serviceName: "glasstrace-sdk",
838
- traceExporter: glasstraceExporter
855
+ this._sendingPromises.push(promise);
856
+ const popPromise = () => {
857
+ const index = this._sendingPromises.indexOf(promise);
858
+ void this._sendingPromises.splice(index, 1);
839
859
  };
840
- const prismaModule = await tryImport("@prisma/instrumentation");
841
- if (prismaModule) {
842
- const PrismaInstrumentation = prismaModule.PrismaInstrumentation;
843
- if (PrismaInstrumentation) {
844
- otelConfig.instrumentations = [new PrismaInstrumentation()];
845
- }
846
- }
847
- vercelOtel.registerOTel(otelConfig);
848
- return;
860
+ promise.then(popPromise, popPromise);
849
861
  }
850
- try {
851
- const otelSdk = await import("@opentelemetry/sdk-trace-base");
852
- const otelApi3 = await import("@opentelemetry/api");
853
- const existingProvider = otelApi3.trace.getTracerProvider();
854
- const probeTracer = existingProvider.getTracer("glasstrace-probe");
855
- if (probeTracer.constructor.name !== "ProxyTracer") {
856
- console.warn(
857
- "[glasstrace] An existing OpenTelemetry TracerProvider is already registered. Glasstrace will not overwrite it. To use Glasstrace alongside another tracing tool, add GlasstraceExporter as an additional span processor on your existing provider."
858
- );
859
- _activeExporter = null;
860
- return;
861
- }
862
- if (!createOtlpExporter) {
863
- const consoleExporter = new otelSdk.ConsoleSpanExporter();
864
- const consoleGlasstraceExporter = new GlasstraceExporter({
865
- getApiKey: getResolvedApiKey,
866
- sessionManager,
867
- getConfig: () => getActiveConfig(),
868
- environment: config.environment,
869
- endpointUrl: exporterUrl,
870
- createDelegate: () => consoleExporter
871
- });
872
- _activeExporter = consoleGlasstraceExporter;
873
- console.warn(
874
- "[glasstrace] @opentelemetry/exporter-trace-otlp-http not found. Using ConsoleSpanExporter."
875
- );
876
- const processor2 = new otelSdk.SimpleSpanProcessor(consoleGlasstraceExporter);
877
- const provider2 = new otelSdk.BasicTracerProvider({
878
- spanProcessors: [processor2]
879
- });
880
- otelApi3.trace.setGlobalTracerProvider(provider2);
881
- registerShutdownHooks(provider2);
882
- return;
883
- }
884
- const processor = new otelSdk.BatchSpanProcessor(glasstraceExporter);
885
- const provider = new otelSdk.BasicTracerProvider({
886
- spanProcessors: [processor]
887
- });
888
- otelApi3.trace.setGlobalTracerProvider(provider);
889
- registerShutdownHooks(provider);
890
- } catch {
891
- console.warn(
892
- "[glasstrace] Neither @vercel/otel nor @opentelemetry/sdk-trace-base available. Tracing disabled."
893
- );
862
+ hasReachedLimit() {
863
+ return this._sendingPromises.length >= this._concurrencyLimit;
864
+ }
865
+ async awaitAll() {
866
+ await Promise.all(this._sendingPromises);
894
867
  }
868
+ };
869
+ function createBoundedQueueExportPromiseHandler(options) {
870
+ return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);
895
871
  }
896
872
 
897
- // src/console-capture.ts
898
- var isGlasstraceLog = false;
899
- var originalError = null;
900
- var originalWarn = null;
901
- var installed = false;
902
- var otelApi = null;
903
- function formatArgs(args) {
904
- return args.map((arg) => {
905
- if (typeof arg === "string") return arg;
906
- if (arg instanceof Error) return arg.stack ?? arg.message;
907
- try {
908
- return JSON.stringify(arg);
909
- } catch {
910
- return String(arg);
911
- }
912
- }).join(" ");
873
+ // ../../node_modules/@opentelemetry/core/build/esm/trace/suppress-tracing.js
874
+ var SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
875
+ function suppressTracing(context2) {
876
+ return context2.setValue(SUPPRESS_TRACING_KEY, true);
913
877
  }
914
- function isSdkMessage(args) {
915
- return typeof args[0] === "string" && args[0].startsWith("[glasstrace]");
878
+ function isTracingSuppressed(context2) {
879
+ return context2.getValue(SUPPRESS_TRACING_KEY) === true;
916
880
  }
917
- async function installConsoleCapture() {
918
- if (installed) return;
881
+
882
+ // ../../node_modules/@opentelemetry/core/build/esm/baggage/constants.js
883
+ var BAGGAGE_KEY_PAIR_SEPARATOR = "=";
884
+ var BAGGAGE_PROPERTIES_SEPARATOR = ";";
885
+ var BAGGAGE_ITEMS_SEPARATOR = ",";
886
+
887
+ // ../../node_modules/@opentelemetry/core/build/esm/baggage/utils.js
888
+ function parsePairKeyValue(entry) {
889
+ if (!entry)
890
+ return;
891
+ const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);
892
+ const keyPairPart = metadataSeparatorIndex === -1 ? entry : entry.substring(0, metadataSeparatorIndex);
893
+ const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);
894
+ if (separatorIndex <= 0)
895
+ return;
896
+ const rawKey = keyPairPart.substring(0, separatorIndex).trim();
897
+ const rawValue = keyPairPart.substring(separatorIndex + 1).trim();
898
+ if (!rawKey || !rawValue)
899
+ return;
900
+ let key;
901
+ let value;
919
902
  try {
920
- otelApi = await import("@opentelemetry/api");
903
+ key = decodeURIComponent(rawKey);
904
+ value = decodeURIComponent(rawValue);
921
905
  } catch {
922
- otelApi = null;
906
+ return;
923
907
  }
924
- originalError = console.error;
925
- originalWarn = console.warn;
926
- installed = true;
927
- console.error = (...args) => {
928
- originalError.apply(console, args);
929
- if (isGlasstraceLog || isSdkMessage(args)) return;
930
- if (otelApi) {
931
- const span = otelApi.trace.getSpan(otelApi.context.active());
932
- if (span) {
933
- span.addEvent("console.error", {
934
- "console.message": formatArgs(args)
935
- });
908
+ let metadata;
909
+ if (metadataSeparatorIndex !== -1 && metadataSeparatorIndex < entry.length - 1) {
910
+ const metadataString = entry.substring(metadataSeparatorIndex + 1);
911
+ metadata = baggageEntryMetadataFromString(metadataString);
912
+ }
913
+ return { key, value, metadata };
914
+ }
915
+ function parseKeyPairsIntoRecord(value) {
916
+ const result = {};
917
+ if (typeof value === "string" && value.length > 0) {
918
+ value.split(BAGGAGE_ITEMS_SEPARATOR).forEach((entry) => {
919
+ const keyPair = parsePairKeyValue(entry);
920
+ if (keyPair !== void 0 && keyPair.value.length > 0) {
921
+ result[keyPair.key] = keyPair.value;
936
922
  }
923
+ });
924
+ }
925
+ return result;
926
+ }
927
+
928
+ // ../../node_modules/@opentelemetry/core/build/esm/common/attributes.js
929
+ function sanitizeAttributes(attributes) {
930
+ const out = {};
931
+ if (typeof attributes !== "object" || attributes == null) {
932
+ return out;
933
+ }
934
+ for (const key in attributes) {
935
+ if (!Object.prototype.hasOwnProperty.call(attributes, key)) {
936
+ continue;
937
937
  }
938
- };
939
- console.warn = (...args) => {
940
- originalWarn.apply(console, args);
941
- if (isGlasstraceLog || isSdkMessage(args)) return;
942
- if (otelApi) {
943
- const span = otelApi.trace.getSpan(otelApi.context.active());
944
- if (span) {
945
- span.addEvent("console.warn", {
946
- "console.message": formatArgs(args)
947
- });
938
+ if (!isAttributeKey(key)) {
939
+ diag.warn(`Invalid attribute key: ${key}`);
940
+ continue;
941
+ }
942
+ const val = attributes[key];
943
+ if (!isAttributeValue(val)) {
944
+ diag.warn(`Invalid attribute value set for key: ${key}`);
945
+ continue;
946
+ }
947
+ if (Array.isArray(val)) {
948
+ out[key] = val.slice();
949
+ } else {
950
+ out[key] = val;
951
+ }
952
+ }
953
+ return out;
954
+ }
955
+ function isAttributeKey(key) {
956
+ return typeof key === "string" && key !== "";
957
+ }
958
+ function isAttributeValue(val) {
959
+ if (val == null) {
960
+ return true;
961
+ }
962
+ if (Array.isArray(val)) {
963
+ return isHomogeneousAttributeValueArray(val);
964
+ }
965
+ return isValidPrimitiveAttributeValueType(typeof val);
966
+ }
967
+ function isHomogeneousAttributeValueArray(arr) {
968
+ let type;
969
+ for (const element of arr) {
970
+ if (element == null)
971
+ continue;
972
+ const elementType = typeof element;
973
+ if (elementType === type) {
974
+ continue;
975
+ }
976
+ if (!type) {
977
+ if (isValidPrimitiveAttributeValueType(elementType)) {
978
+ type = elementType;
979
+ continue;
948
980
  }
981
+ return false;
949
982
  }
983
+ return false;
984
+ }
985
+ return true;
986
+ }
987
+ function isValidPrimitiveAttributeValueType(valType) {
988
+ switch (valType) {
989
+ case "number":
990
+ case "boolean":
991
+ case "string":
992
+ return true;
993
+ }
994
+ return false;
995
+ }
996
+
997
+ // ../../node_modules/@opentelemetry/core/build/esm/common/logging-error-handler.js
998
+ function loggingErrorHandler() {
999
+ return (ex) => {
1000
+ diag.error(stringifyException(ex));
950
1001
  };
951
1002
  }
1003
+ function stringifyException(ex) {
1004
+ if (typeof ex === "string") {
1005
+ return ex;
1006
+ } else {
1007
+ return JSON.stringify(flattenException(ex));
1008
+ }
1009
+ }
1010
+ function flattenException(ex) {
1011
+ const result = {};
1012
+ let current = ex;
1013
+ while (current !== null) {
1014
+ Object.getOwnPropertyNames(current).forEach((propertyName) => {
1015
+ if (result[propertyName])
1016
+ return;
1017
+ const value = current[propertyName];
1018
+ if (value) {
1019
+ result[propertyName] = String(value);
1020
+ }
1021
+ });
1022
+ current = Object.getPrototypeOf(current);
1023
+ }
1024
+ return result;
1025
+ }
952
1026
 
953
- // src/capture-error.ts
954
- var otelApi2 = null;
955
- var otelLoadAttempted = false;
956
- var otelLoadPromise = null;
957
- async function _preloadOtelApi() {
958
- if (otelLoadAttempted) return;
959
- otelLoadAttempted = true;
1027
+ // ../../node_modules/@opentelemetry/core/build/esm/common/global-error-handler.js
1028
+ var delegateHandler = loggingErrorHandler();
1029
+ function globalErrorHandler(ex) {
960
1030
  try {
961
- otelApi2 = await import("@opentelemetry/api");
1031
+ delegateHandler(ex);
962
1032
  } catch {
963
- otelApi2 = null;
964
1033
  }
965
1034
  }
966
- function captureError(error) {
967
- if (otelApi2) {
968
- recordError(otelApi2, error);
969
- return;
1035
+
1036
+ // ../../node_modules/@opentelemetry/core/build/esm/platform/node/environment.js
1037
+ import { inspect } from "util";
1038
+ function getNumberFromEnv(key) {
1039
+ const raw = process.env[key];
1040
+ if (raw == null || raw.trim() === "") {
1041
+ return void 0;
1042
+ }
1043
+ const value = Number(raw);
1044
+ if (isNaN(value)) {
1045
+ diag.warn(`Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`);
1046
+ return void 0;
1047
+ }
1048
+ return value;
1049
+ }
1050
+ function getStringFromEnv(key) {
1051
+ const raw = process.env[key];
1052
+ if (raw == null || raw.trim() === "") {
1053
+ return void 0;
1054
+ }
1055
+ return raw;
1056
+ }
1057
+
1058
+ // ../../node_modules/@opentelemetry/core/build/esm/version.js
1059
+ var VERSION = "2.6.1";
1060
+
1061
+ // ../../node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js
1062
+ var ATTR_EXCEPTION_MESSAGE = "exception.message";
1063
+ var ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace";
1064
+ var ATTR_EXCEPTION_TYPE = "exception.type";
1065
+ var ATTR_SERVICE_NAME = "service.name";
1066
+ var ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language";
1067
+ var TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs";
1068
+ var ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name";
1069
+ var ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version";
1070
+
1071
+ // ../../node_modules/@opentelemetry/core/build/esm/semconv.js
1072
+ var ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
1073
+
1074
+ // ../../node_modules/@opentelemetry/core/build/esm/platform/node/sdk-info.js
1075
+ var SDK_INFO = {
1076
+ [ATTR_TELEMETRY_SDK_NAME]: "opentelemetry",
1077
+ [ATTR_PROCESS_RUNTIME_NAME]: "node",
1078
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
1079
+ [ATTR_TELEMETRY_SDK_VERSION]: VERSION
1080
+ };
1081
+
1082
+ // ../../node_modules/@opentelemetry/core/build/esm/platform/node/index.js
1083
+ var otperformance = performance;
1084
+
1085
+ // ../../node_modules/@opentelemetry/core/build/esm/common/time.js
1086
+ var NANOSECOND_DIGITS = 9;
1087
+ var NANOSECOND_DIGITS_IN_MILLIS = 6;
1088
+ var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
1089
+ var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
1090
+ function millisToHrTime(epochMillis) {
1091
+ const epochSeconds = epochMillis / 1e3;
1092
+ const seconds = Math.trunc(epochSeconds);
1093
+ const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
1094
+ return [seconds, nanos];
1095
+ }
1096
+ function hrTime(performanceNow) {
1097
+ const timeOrigin = millisToHrTime(otperformance.timeOrigin);
1098
+ const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : otperformance.now());
1099
+ return addHrTimes(timeOrigin, now);
1100
+ }
1101
+ function hrTimeDuration(startTime, endTime) {
1102
+ let seconds = endTime[0] - startTime[0];
1103
+ let nanos = endTime[1] - startTime[1];
1104
+ if (nanos < 0) {
1105
+ seconds -= 1;
1106
+ nanos += SECOND_TO_NANOSECONDS;
1107
+ }
1108
+ return [seconds, nanos];
1109
+ }
1110
+ function hrTimeToNanoseconds(time) {
1111
+ return time[0] * SECOND_TO_NANOSECONDS + time[1];
1112
+ }
1113
+ function isTimeInputHrTime(value) {
1114
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number";
1115
+ }
1116
+ function isTimeInput(value) {
1117
+ return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date;
1118
+ }
1119
+ function addHrTimes(time1, time2) {
1120
+ const out = [time1[0] + time2[0], time1[1] + time2[1]];
1121
+ if (out[1] >= SECOND_TO_NANOSECONDS) {
1122
+ out[1] -= SECOND_TO_NANOSECONDS;
1123
+ out[0] += 1;
970
1124
  }
971
- if (!otelLoadAttempted) {
972
- otelLoadPromise ??= _preloadOtelApi();
1125
+ return out;
1126
+ }
1127
+
1128
+ // ../../node_modules/@opentelemetry/core/build/esm/ExportResult.js
1129
+ var ExportResultCode;
1130
+ (function(ExportResultCode2) {
1131
+ ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
1132
+ ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
1133
+ })(ExportResultCode || (ExportResultCode = {}));
1134
+
1135
+ // ../../node_modules/@opentelemetry/core/build/esm/utils/lodash.merge.js
1136
+ var objectTag = "[object Object]";
1137
+ var nullTag = "[object Null]";
1138
+ var undefinedTag = "[object Undefined]";
1139
+ var funcProto = Function.prototype;
1140
+ var funcToString = funcProto.toString;
1141
+ var objectCtorString = funcToString.call(Object);
1142
+ var getPrototypeOf = Object.getPrototypeOf;
1143
+ var objectProto = Object.prototype;
1144
+ var hasOwnProperty = objectProto.hasOwnProperty;
1145
+ var symToStringTag = Symbol ? Symbol.toStringTag : void 0;
1146
+ var nativeObjectToString = objectProto.toString;
1147
+ function isPlainObject(value) {
1148
+ if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {
1149
+ return false;
973
1150
  }
974
- if (otelLoadPromise) {
975
- void otelLoadPromise.then(() => {
976
- if (otelApi2) {
977
- recordError(otelApi2, error);
978
- }
979
- });
1151
+ const proto = getPrototypeOf(value);
1152
+ if (proto === null) {
1153
+ return true;
1154
+ }
1155
+ const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
1156
+ return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString;
1157
+ }
1158
+ function isObjectLike(value) {
1159
+ return value != null && typeof value == "object";
1160
+ }
1161
+ function baseGetTag(value) {
1162
+ if (value == null) {
1163
+ return value === void 0 ? undefinedTag : nullTag;
980
1164
  }
1165
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
981
1166
  }
982
- function recordError(api, error) {
1167
+ function getRawTag(value) {
1168
+ const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
1169
+ let unmasked = false;
983
1170
  try {
984
- const span = api.trace.getSpan(api.context.active());
985
- if (!span) return;
986
- const attributes = {
987
- "error.message": String(error)
988
- };
989
- if (error instanceof Error) {
990
- attributes["error.type"] = error.constructor.name;
991
- }
992
- span.addEvent("glasstrace.error", attributes);
1171
+ value[symToStringTag] = void 0;
1172
+ unmasked = true;
993
1173
  } catch {
994
1174
  }
1175
+ const result = nativeObjectToString.call(value);
1176
+ if (unmasked) {
1177
+ if (isOwn) {
1178
+ value[symToStringTag] = tag;
1179
+ } else {
1180
+ delete value[symToStringTag];
1181
+ }
1182
+ }
1183
+ return result;
1184
+ }
1185
+ function objectToString(value) {
1186
+ return nativeObjectToString.call(value);
995
1187
  }
996
1188
 
997
- // src/register.ts
998
- var consoleCaptureInstalled = false;
999
- var discoveryHandler = null;
1000
- var isRegistered = false;
1001
- var registrationGeneration = 0;
1002
- function registerGlasstrace(options) {
1003
- try {
1004
- if (isRegistered) {
1005
- return;
1189
+ // ../../node_modules/@opentelemetry/core/build/esm/utils/merge.js
1190
+ var MAX_LEVEL = 20;
1191
+ function merge(...args) {
1192
+ let result = args.shift();
1193
+ const objects = /* @__PURE__ */ new WeakMap();
1194
+ while (args.length > 0) {
1195
+ result = mergeTwoObjects(result, args.shift(), 0, objects);
1196
+ }
1197
+ return result;
1198
+ }
1199
+ function takeValue(value) {
1200
+ if (isArray(value)) {
1201
+ return value.slice();
1202
+ }
1203
+ return value;
1204
+ }
1205
+ function mergeTwoObjects(one, two, level = 0, objects) {
1206
+ let result;
1207
+ if (level > MAX_LEVEL) {
1208
+ return void 0;
1209
+ }
1210
+ level++;
1211
+ if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {
1212
+ result = takeValue(two);
1213
+ } else if (isArray(one)) {
1214
+ result = one.slice();
1215
+ if (isArray(two)) {
1216
+ for (let i = 0, j = two.length; i < j; i++) {
1217
+ result.push(takeValue(two[i]));
1218
+ }
1219
+ } else if (isObject(two)) {
1220
+ const keys = Object.keys(two);
1221
+ for (let i = 0, j = keys.length; i < j; i++) {
1222
+ const key = keys[i];
1223
+ result[key] = takeValue(two[key]);
1224
+ }
1006
1225
  }
1007
- const config = resolveConfig(options);
1008
- if (config.verbose) {
1009
- console.info("[glasstrace] Config resolved.");
1226
+ } else if (isObject(one)) {
1227
+ if (isObject(two)) {
1228
+ if (!shouldMerge(one, two)) {
1229
+ return two;
1230
+ }
1231
+ result = Object.assign({}, one);
1232
+ const keys = Object.keys(two);
1233
+ for (let i = 0, j = keys.length; i < j; i++) {
1234
+ const key = keys[i];
1235
+ const twoValue = two[key];
1236
+ if (isPrimitive(twoValue)) {
1237
+ if (typeof twoValue === "undefined") {
1238
+ delete result[key];
1239
+ } else {
1240
+ result[key] = twoValue;
1241
+ }
1242
+ } else {
1243
+ const obj1 = result[key];
1244
+ const obj2 = twoValue;
1245
+ if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) {
1246
+ delete result[key];
1247
+ } else {
1248
+ if (isObject(obj1) && isObject(obj2)) {
1249
+ const arr1 = objects.get(obj1) || [];
1250
+ const arr2 = objects.get(obj2) || [];
1251
+ arr1.push({ obj: one, key });
1252
+ arr2.push({ obj: two, key });
1253
+ objects.set(obj1, arr1);
1254
+ objects.set(obj2, arr2);
1255
+ }
1256
+ result[key] = mergeTwoObjects(result[key], twoValue, level, objects);
1257
+ }
1258
+ }
1259
+ }
1260
+ } else {
1261
+ result = two;
1262
+ }
1263
+ }
1264
+ return result;
1265
+ }
1266
+ function wasObjectReferenced(obj, key, objects) {
1267
+ const arr = objects.get(obj[key]) || [];
1268
+ for (let i = 0, j = arr.length; i < j; i++) {
1269
+ const info = arr[i];
1270
+ if (info.key === key && info.obj === obj) {
1271
+ return true;
1272
+ }
1273
+ }
1274
+ return false;
1275
+ }
1276
+ function isArray(value) {
1277
+ return Array.isArray(value);
1278
+ }
1279
+ function isFunction(value) {
1280
+ return typeof value === "function";
1281
+ }
1282
+ function isObject(value) {
1283
+ return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object";
1284
+ }
1285
+ function isPrimitive(value) {
1286
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
1287
+ }
1288
+ function shouldMerge(one, two) {
1289
+ if (!isPlainObject(one) || !isPlainObject(two)) {
1290
+ return false;
1291
+ }
1292
+ return true;
1293
+ }
1294
+
1295
+ // ../../node_modules/@opentelemetry/core/build/esm/utils/promise.js
1296
+ var Deferred = class {
1297
+ _promise;
1298
+ _resolve;
1299
+ _reject;
1300
+ constructor() {
1301
+ this._promise = new Promise((resolve2, reject) => {
1302
+ this._resolve = resolve2;
1303
+ this._reject = reject;
1304
+ });
1305
+ }
1306
+ get promise() {
1307
+ return this._promise;
1308
+ }
1309
+ resolve(val) {
1310
+ this._resolve(val);
1311
+ }
1312
+ reject(err) {
1313
+ this._reject(err);
1314
+ }
1315
+ };
1316
+
1317
+ // ../../node_modules/@opentelemetry/core/build/esm/utils/callback.js
1318
+ var BindOnceFuture = class {
1319
+ _isCalled = false;
1320
+ _deferred = new Deferred();
1321
+ _callback;
1322
+ _that;
1323
+ constructor(callback, that) {
1324
+ this._callback = callback;
1325
+ this._that = that;
1326
+ }
1327
+ get isCalled() {
1328
+ return this._isCalled;
1329
+ }
1330
+ get promise() {
1331
+ return this._deferred.promise;
1332
+ }
1333
+ call(...args) {
1334
+ if (!this._isCalled) {
1335
+ this._isCalled = true;
1336
+ try {
1337
+ Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err));
1338
+ } catch (err) {
1339
+ this._deferred.reject(err);
1340
+ }
1341
+ }
1342
+ return this._deferred.promise;
1343
+ }
1344
+ };
1345
+
1346
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js
1347
+ function isPartialSuccessResponse(response) {
1348
+ return Object.prototype.hasOwnProperty.call(response, "partialSuccess");
1349
+ }
1350
+ function createLoggingPartialSuccessResponseHandler() {
1351
+ return {
1352
+ handleResponse(response) {
1353
+ if (response == null || !isPartialSuccessResponse(response) || response.partialSuccess == null || Object.keys(response.partialSuccess).length === 0) {
1354
+ return;
1355
+ }
1356
+ diag.warn("Received Partial Success response:", JSON.stringify(response.partialSuccess));
1357
+ }
1358
+ };
1359
+ }
1360
+
1361
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js
1362
+ var OTLPExportDelegate = class {
1363
+ _diagLogger;
1364
+ _transport;
1365
+ _serializer;
1366
+ _responseHandler;
1367
+ _promiseQueue;
1368
+ _timeout;
1369
+ constructor(transport, serializer, responseHandler, promiseQueue, timeout) {
1370
+ this._transport = transport;
1371
+ this._serializer = serializer;
1372
+ this._responseHandler = responseHandler;
1373
+ this._promiseQueue = promiseQueue;
1374
+ this._timeout = timeout;
1375
+ this._diagLogger = diag.createComponentLogger({
1376
+ namespace: "OTLPExportDelegate"
1377
+ });
1378
+ }
1379
+ export(internalRepresentation, resultCallback) {
1380
+ this._diagLogger.debug("items to be sent", internalRepresentation);
1381
+ if (this._promiseQueue.hasReachedLimit()) {
1382
+ resultCallback({
1383
+ code: ExportResultCode.FAILED,
1384
+ error: new Error("Concurrent export limit reached")
1385
+ });
1386
+ return;
1387
+ }
1388
+ const serializedRequest = this._serializer.serializeRequest(internalRepresentation);
1389
+ if (serializedRequest == null) {
1390
+ resultCallback({
1391
+ code: ExportResultCode.FAILED,
1392
+ error: new Error("Nothing to send")
1393
+ });
1394
+ return;
1395
+ }
1396
+ this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then((response) => {
1397
+ if (response.status === "success") {
1398
+ if (response.data != null) {
1399
+ try {
1400
+ this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data));
1401
+ } catch (e) {
1402
+ this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?", e, response.data);
1403
+ }
1404
+ }
1405
+ resultCallback({
1406
+ code: ExportResultCode.SUCCESS
1407
+ });
1408
+ return;
1409
+ } else if (response.status === "failure" && response.error) {
1410
+ resultCallback({
1411
+ code: ExportResultCode.FAILED,
1412
+ error: response.error
1413
+ });
1414
+ return;
1415
+ } else if (response.status === "retryable") {
1416
+ resultCallback({
1417
+ code: ExportResultCode.FAILED,
1418
+ error: response.error ?? new OTLPExporterError("Export failed with retryable status")
1419
+ });
1420
+ } else {
1421
+ resultCallback({
1422
+ code: ExportResultCode.FAILED,
1423
+ error: new OTLPExporterError("Export failed with unknown error")
1424
+ });
1425
+ }
1426
+ }, (reason) => resultCallback({
1427
+ code: ExportResultCode.FAILED,
1428
+ error: reason
1429
+ })));
1430
+ }
1431
+ forceFlush() {
1432
+ return this._promiseQueue.awaitAll();
1433
+ }
1434
+ async shutdown() {
1435
+ this._diagLogger.debug("shutdown started");
1436
+ await this.forceFlush();
1437
+ this._transport.shutdown();
1438
+ }
1439
+ };
1440
+ function createOtlpExportDelegate(components, settings) {
1441
+ return new OTLPExportDelegate(components.transport, components.serializer, createLoggingPartialSuccessResponseHandler(), components.promiseHandler, settings.timeout);
1442
+ }
1443
+
1444
+ // ../../node_modules/@opentelemetry/otlp-transformer/build/esm/common/internal.js
1445
+ function createResource(resource, encoder) {
1446
+ const result = {
1447
+ attributes: toAttributes(resource.attributes, encoder),
1448
+ droppedAttributesCount: 0
1449
+ };
1450
+ const schemaUrl = resource.schemaUrl;
1451
+ if (schemaUrl && schemaUrl !== "")
1452
+ result.schemaUrl = schemaUrl;
1453
+ return result;
1454
+ }
1455
+ function createInstrumentationScope(scope) {
1456
+ return {
1457
+ name: scope.name,
1458
+ version: scope.version
1459
+ };
1460
+ }
1461
+ function toAttributes(attributes, encoder) {
1462
+ return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key], encoder));
1463
+ }
1464
+ function toKeyValue(key, value, encoder) {
1465
+ return {
1466
+ key,
1467
+ value: toAnyValue(value, encoder)
1468
+ };
1469
+ }
1470
+ function toAnyValue(value, encoder) {
1471
+ const t = typeof value;
1472
+ if (t === "string")
1473
+ return { stringValue: value };
1474
+ if (t === "number") {
1475
+ if (!Number.isInteger(value))
1476
+ return { doubleValue: value };
1477
+ return { intValue: value };
1478
+ }
1479
+ if (t === "boolean")
1480
+ return { boolValue: value };
1481
+ if (value instanceof Uint8Array)
1482
+ return { bytesValue: encoder.encodeUint8Array(value) };
1483
+ if (Array.isArray(value)) {
1484
+ const values = new Array(value.length);
1485
+ for (let i = 0; i < value.length; i++) {
1486
+ values[i] = toAnyValue(value[i], encoder);
1487
+ }
1488
+ return { arrayValue: { values } };
1489
+ }
1490
+ if (t === "object" && value != null) {
1491
+ const keys = Object.keys(value);
1492
+ const values = new Array(keys.length);
1493
+ for (let i = 0; i < keys.length; i++) {
1494
+ values[i] = {
1495
+ key: keys[i],
1496
+ value: toAnyValue(value[keys[i]], encoder)
1497
+ };
1498
+ }
1499
+ return { kvlistValue: { values } };
1500
+ }
1501
+ return {};
1502
+ }
1503
+
1504
+ // ../../node_modules/@opentelemetry/otlp-transformer/build/esm/common/utils.js
1505
+ function hrTimeToNanos(hrTime2) {
1506
+ const NANOSECONDS = BigInt(1e9);
1507
+ return BigInt(Math.trunc(hrTime2[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime2[1]));
1508
+ }
1509
+ function encodeAsString(hrTime2) {
1510
+ const nanos = hrTimeToNanos(hrTime2);
1511
+ return nanos.toString();
1512
+ }
1513
+ var encodeTimestamp = typeof BigInt !== "undefined" ? encodeAsString : hrTimeToNanoseconds;
1514
+ function identity(value) {
1515
+ return value;
1516
+ }
1517
+ var JSON_ENCODER = {
1518
+ encodeHrTime: encodeTimestamp,
1519
+ encodeSpanContext: identity,
1520
+ encodeOptionalSpanContext: identity,
1521
+ encodeUint8Array: (bytes) => {
1522
+ if (typeof Buffer !== "undefined") {
1523
+ return Buffer.from(bytes).toString("base64");
1524
+ }
1525
+ const chars = new Array(bytes.length);
1526
+ for (let i = 0; i < bytes.length; i++) {
1527
+ chars[i] = String.fromCharCode(bytes[i]);
1528
+ }
1529
+ return btoa(chars.join(""));
1530
+ }
1531
+ };
1532
+
1533
+ // ../../node_modules/@opentelemetry/resources/build/esm/default-service-name.js
1534
+ var serviceName;
1535
+ function defaultServiceName() {
1536
+ if (serviceName === void 0) {
1537
+ try {
1538
+ const argv0 = globalThis.process.argv0;
1539
+ serviceName = argv0 ? `unknown_service:${argv0}` : "unknown_service";
1540
+ } catch {
1541
+ serviceName = "unknown_service";
1542
+ }
1543
+ }
1544
+ return serviceName;
1545
+ }
1546
+
1547
+ // ../../node_modules/@opentelemetry/resources/build/esm/utils.js
1548
+ var isPromiseLike = (val) => {
1549
+ return val !== null && typeof val === "object" && typeof val.then === "function";
1550
+ };
1551
+
1552
+ // ../../node_modules/@opentelemetry/resources/build/esm/ResourceImpl.js
1553
+ var ResourceImpl = class _ResourceImpl {
1554
+ _rawAttributes;
1555
+ _asyncAttributesPending = false;
1556
+ _schemaUrl;
1557
+ _memoizedAttributes;
1558
+ static FromAttributeList(attributes, options) {
1559
+ const res = new _ResourceImpl({}, options);
1560
+ res._rawAttributes = guardedRawAttributes(attributes);
1561
+ res._asyncAttributesPending = attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;
1562
+ return res;
1563
+ }
1564
+ constructor(resource, options) {
1565
+ const attributes = resource.attributes ?? {};
1566
+ this._rawAttributes = Object.entries(attributes).map(([k, v]) => {
1567
+ if (isPromiseLike(v)) {
1568
+ this._asyncAttributesPending = true;
1569
+ }
1570
+ return [k, v];
1571
+ });
1572
+ this._rawAttributes = guardedRawAttributes(this._rawAttributes);
1573
+ this._schemaUrl = validateSchemaUrl(options?.schemaUrl);
1574
+ }
1575
+ get asyncAttributesPending() {
1576
+ return this._asyncAttributesPending;
1577
+ }
1578
+ async waitForAsyncAttributes() {
1579
+ if (!this.asyncAttributesPending) {
1580
+ return;
1581
+ }
1582
+ for (let i = 0; i < this._rawAttributes.length; i++) {
1583
+ const [k, v] = this._rawAttributes[i];
1584
+ this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];
1585
+ }
1586
+ this._asyncAttributesPending = false;
1587
+ }
1588
+ get attributes() {
1589
+ if (this.asyncAttributesPending) {
1590
+ diag.error("Accessing resource attributes before async attributes settled");
1591
+ }
1592
+ if (this._memoizedAttributes) {
1593
+ return this._memoizedAttributes;
1594
+ }
1595
+ const attrs = {};
1596
+ for (const [k, v] of this._rawAttributes) {
1597
+ if (isPromiseLike(v)) {
1598
+ diag.debug(`Unsettled resource attribute ${k} skipped`);
1599
+ continue;
1600
+ }
1601
+ if (v != null) {
1602
+ attrs[k] ??= v;
1603
+ }
1604
+ }
1605
+ if (!this._asyncAttributesPending) {
1606
+ this._memoizedAttributes = attrs;
1607
+ }
1608
+ return attrs;
1609
+ }
1610
+ getRawAttributes() {
1611
+ return this._rawAttributes;
1612
+ }
1613
+ get schemaUrl() {
1614
+ return this._schemaUrl;
1615
+ }
1616
+ merge(resource) {
1617
+ if (resource == null)
1618
+ return this;
1619
+ const mergedSchemaUrl = mergeSchemaUrl(this, resource);
1620
+ const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : void 0;
1621
+ return _ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions);
1622
+ }
1623
+ };
1624
+ function resourceFromAttributes(attributes, options) {
1625
+ return ResourceImpl.FromAttributeList(Object.entries(attributes), options);
1626
+ }
1627
+ function defaultResource() {
1628
+ return resourceFromAttributes({
1629
+ [ATTR_SERVICE_NAME]: defaultServiceName(),
1630
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],
1631
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],
1632
+ [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION]
1633
+ });
1634
+ }
1635
+ function guardedRawAttributes(attributes) {
1636
+ return attributes.map(([k, v]) => {
1637
+ if (isPromiseLike(v)) {
1638
+ return [
1639
+ k,
1640
+ v.catch((err) => {
1641
+ diag.debug("promise rejection for resource attribute: %s - %s", k, err);
1642
+ return void 0;
1643
+ })
1644
+ ];
1645
+ }
1646
+ return [k, v];
1647
+ });
1648
+ }
1649
+ function validateSchemaUrl(schemaUrl) {
1650
+ if (typeof schemaUrl === "string" || schemaUrl === void 0) {
1651
+ return schemaUrl;
1652
+ }
1653
+ diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl);
1654
+ return void 0;
1655
+ }
1656
+ function mergeSchemaUrl(old, updating) {
1657
+ const oldSchemaUrl = old?.schemaUrl;
1658
+ const updatingSchemaUrl = updating?.schemaUrl;
1659
+ const isOldEmpty = oldSchemaUrl === void 0 || oldSchemaUrl === "";
1660
+ const isUpdatingEmpty = updatingSchemaUrl === void 0 || updatingSchemaUrl === "";
1661
+ if (isOldEmpty) {
1662
+ return updatingSchemaUrl;
1663
+ }
1664
+ if (isUpdatingEmpty) {
1665
+ return oldSchemaUrl;
1666
+ }
1667
+ if (oldSchemaUrl === updatingSchemaUrl) {
1668
+ return oldSchemaUrl;
1669
+ }
1670
+ diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl);
1671
+ return void 0;
1672
+ }
1673
+
1674
+ // ../../node_modules/@opentelemetry/otlp-transformer/build/esm/trace/internal.js
1675
+ var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256;
1676
+ var SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512;
1677
+ function buildSpanFlagsFrom(traceFlags, isRemote) {
1678
+ let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;
1679
+ if (isRemote) {
1680
+ flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;
1681
+ }
1682
+ return flags;
1683
+ }
1684
+ function sdkSpanToOtlpSpan(span, encoder) {
1685
+ const ctx = span.spanContext();
1686
+ const status = span.status;
1687
+ const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : void 0;
1688
+ return {
1689
+ traceId: encoder.encodeSpanContext(ctx.traceId),
1690
+ spanId: encoder.encodeSpanContext(ctx.spanId),
1691
+ parentSpanId,
1692
+ traceState: ctx.traceState?.serialize(),
1693
+ name: span.name,
1694
+ // Span kind is offset by 1 because the API does not define a value for unset
1695
+ kind: span.kind == null ? 0 : span.kind + 1,
1696
+ startTimeUnixNano: encoder.encodeHrTime(span.startTime),
1697
+ endTimeUnixNano: encoder.encodeHrTime(span.endTime),
1698
+ attributes: toAttributes(span.attributes, encoder),
1699
+ droppedAttributesCount: span.droppedAttributesCount,
1700
+ events: span.events.map((event) => toOtlpSpanEvent(event, encoder)),
1701
+ droppedEventsCount: span.droppedEventsCount,
1702
+ status: {
1703
+ // API and proto enums share the same values
1704
+ code: status.code,
1705
+ message: status.message
1706
+ },
1707
+ links: span.links.map((link) => toOtlpLink(link, encoder)),
1708
+ droppedLinksCount: span.droppedLinksCount,
1709
+ flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote)
1710
+ };
1711
+ }
1712
+ function toOtlpLink(link, encoder) {
1713
+ return {
1714
+ attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],
1715
+ spanId: encoder.encodeSpanContext(link.context.spanId),
1716
+ traceId: encoder.encodeSpanContext(link.context.traceId),
1717
+ traceState: link.context.traceState?.serialize(),
1718
+ droppedAttributesCount: link.droppedAttributesCount || 0,
1719
+ flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote)
1720
+ };
1721
+ }
1722
+ function toOtlpSpanEvent(timedEvent, encoder) {
1723
+ return {
1724
+ attributes: timedEvent.attributes ? toAttributes(timedEvent.attributes, encoder) : [],
1725
+ name: timedEvent.name,
1726
+ timeUnixNano: encoder.encodeHrTime(timedEvent.time),
1727
+ droppedAttributesCount: timedEvent.droppedAttributesCount || 0
1728
+ };
1729
+ }
1730
+ function createExportTraceServiceRequest(spans, encoder) {
1731
+ return {
1732
+ resourceSpans: spanRecordsToResourceSpans(spans, encoder)
1733
+ };
1734
+ }
1735
+ function createResourceMap(readableSpans) {
1736
+ const resourceMap = /* @__PURE__ */ new Map();
1737
+ for (const record of readableSpans) {
1738
+ let ilsMap = resourceMap.get(record.resource);
1739
+ if (!ilsMap) {
1740
+ ilsMap = /* @__PURE__ */ new Map();
1741
+ resourceMap.set(record.resource, ilsMap);
1742
+ }
1743
+ const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ""}:${record.instrumentationScope.schemaUrl || ""}`;
1744
+ let records = ilsMap.get(instrumentationScopeKey);
1745
+ if (!records) {
1746
+ records = [];
1747
+ ilsMap.set(instrumentationScopeKey, records);
1748
+ }
1749
+ records.push(record);
1750
+ }
1751
+ return resourceMap;
1752
+ }
1753
+ function spanRecordsToResourceSpans(readableSpans, encoder) {
1754
+ const resourceMap = createResourceMap(readableSpans);
1755
+ const out = [];
1756
+ const entryIterator = resourceMap.entries();
1757
+ let entry = entryIterator.next();
1758
+ while (!entry.done) {
1759
+ const [resource, ilmMap] = entry.value;
1760
+ const scopeResourceSpans = [];
1761
+ const ilmIterator = ilmMap.values();
1762
+ let ilmEntry = ilmIterator.next();
1763
+ while (!ilmEntry.done) {
1764
+ const scopeSpans = ilmEntry.value;
1765
+ if (scopeSpans.length > 0) {
1766
+ const spans = scopeSpans.map((readableSpan) => sdkSpanToOtlpSpan(readableSpan, encoder));
1767
+ scopeResourceSpans.push({
1768
+ scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),
1769
+ spans,
1770
+ schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl
1771
+ });
1772
+ }
1773
+ ilmEntry = ilmIterator.next();
1774
+ }
1775
+ const processedResource = createResource(resource, encoder);
1776
+ const transformedSpans = {
1777
+ resource: processedResource,
1778
+ scopeSpans: scopeResourceSpans,
1779
+ schemaUrl: processedResource.schemaUrl
1780
+ };
1781
+ out.push(transformedSpans);
1782
+ entry = entryIterator.next();
1783
+ }
1784
+ return out;
1785
+ }
1786
+
1787
+ // ../../node_modules/@opentelemetry/otlp-transformer/build/esm/trace/json/trace.js
1788
+ var JsonTraceSerializer = {
1789
+ serializeRequest: (arg) => {
1790
+ const request = createExportTraceServiceRequest(arg, JSON_ENCODER);
1791
+ const encoder = new TextEncoder();
1792
+ return encoder.encode(JSON.stringify(request));
1793
+ },
1794
+ deserializeResponse: (arg) => {
1795
+ if (arg.length === 0) {
1796
+ return {};
1797
+ }
1798
+ const decoder = new TextDecoder();
1799
+ return JSON.parse(decoder.decode(arg));
1800
+ }
1801
+ };
1802
+
1803
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/util.js
1804
+ function validateAndNormalizeHeaders(partialHeaders) {
1805
+ const headers = {};
1806
+ Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {
1807
+ if (typeof value !== "undefined") {
1808
+ headers[key] = String(value);
1809
+ } else {
1810
+ diag.warn(`Header "${key}" has invalid value (${value}) and will be ignored`);
1811
+ }
1812
+ });
1813
+ return headers;
1814
+ }
1815
+
1816
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-configuration.js
1817
+ function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) {
1818
+ return async () => {
1819
+ const requiredHeaders = {
1820
+ ...await defaultHeaders()
1821
+ };
1822
+ const headers = {};
1823
+ if (fallbackHeaders != null) {
1824
+ Object.assign(headers, await fallbackHeaders());
1825
+ }
1826
+ if (userProvidedHeaders != null) {
1827
+ Object.assign(headers, validateAndNormalizeHeaders(await userProvidedHeaders()));
1828
+ }
1829
+ return Object.assign(headers, requiredHeaders);
1830
+ };
1831
+ }
1832
+ function validateUserProvidedUrl(url) {
1833
+ if (url == null) {
1834
+ return void 0;
1835
+ }
1836
+ try {
1837
+ const base = globalThis.location?.href;
1838
+ return new URL(url, base).href;
1839
+ } catch {
1840
+ throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`);
1841
+ }
1842
+ }
1843
+ function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
1844
+ return {
1845
+ ...mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
1846
+ headers: mergeHeaders(userProvidedConfiguration.headers, fallbackConfiguration.headers, defaultConfiguration.headers),
1847
+ url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? fallbackConfiguration.url ?? defaultConfiguration.url
1848
+ };
1849
+ }
1850
+ function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {
1851
+ return {
1852
+ ...getSharedConfigurationDefaults(),
1853
+ headers: async () => requiredHeaders,
1854
+ url: "http://localhost:4318/" + signalResourcePath
1855
+ };
1856
+ }
1857
+
1858
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-node-http-configuration.js
1859
+ function httpAgentFactoryFromOptions(options) {
1860
+ return async (protocol) => {
1861
+ const isInsecure = protocol === "http:";
1862
+ const module = isInsecure ? import("http") : import("https");
1863
+ const { Agent } = await module;
1864
+ if (isInsecure) {
1865
+ const { ca, cert, key, ...insecureOptions } = options;
1866
+ return new Agent(insecureOptions);
1867
+ }
1868
+ return new Agent(options);
1869
+ };
1870
+ }
1871
+ function mergeOtlpNodeHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
1872
+ return {
1873
+ ...mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
1874
+ agentFactory: userProvidedConfiguration.agentFactory ?? fallbackConfiguration.agentFactory ?? defaultConfiguration.agentFactory,
1875
+ userAgent: userProvidedConfiguration.userAgent
1876
+ };
1877
+ }
1878
+ function getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {
1879
+ return {
1880
+ ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),
1881
+ agentFactory: httpAgentFactoryFromOptions({ keepAlive: true })
1882
+ };
1883
+ }
1884
+
1885
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js
1886
+ import * as zlib from "zlib";
1887
+ import { Readable } from "stream";
1888
+
1889
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js
1890
+ function isExportHTTPErrorRetryable(statusCode) {
1891
+ return statusCode === 429 || statusCode === 502 || statusCode === 503 || statusCode === 504;
1892
+ }
1893
+ function parseRetryAfterToMills(retryAfter) {
1894
+ if (retryAfter == null) {
1895
+ return void 0;
1896
+ }
1897
+ const seconds = Number.parseInt(retryAfter, 10);
1898
+ if (Number.isInteger(seconds)) {
1899
+ return seconds > 0 ? seconds * 1e3 : -1;
1900
+ }
1901
+ const delay = new Date(retryAfter).getTime() - Date.now();
1902
+ if (delay >= 0) {
1903
+ return delay;
1904
+ }
1905
+ return 0;
1906
+ }
1907
+
1908
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/version.js
1909
+ var VERSION2 = "0.214.0";
1910
+
1911
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js
1912
+ var DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION2}`;
1913
+ function sendWithHttp(request, url, headers, compression, userAgent, agent, data, timeoutMillis) {
1914
+ return new Promise((resolve2) => {
1915
+ const parsedUrl = new URL(url);
1916
+ if (userAgent) {
1917
+ headers["User-Agent"] = `${userAgent} ${DEFAULT_USER_AGENT}`;
1918
+ } else {
1919
+ headers["User-Agent"] = DEFAULT_USER_AGENT;
1920
+ }
1921
+ const options = {
1922
+ hostname: parsedUrl.hostname,
1923
+ port: parsedUrl.port,
1924
+ path: parsedUrl.pathname,
1925
+ method: "POST",
1926
+ headers,
1927
+ agent
1928
+ };
1929
+ const req = request(options, (res) => {
1930
+ const responseData = [];
1931
+ res.on("data", (chunk) => responseData.push(chunk));
1932
+ res.on("end", () => {
1933
+ if (res.statusCode && res.statusCode <= 299) {
1934
+ resolve2({
1935
+ status: "success",
1936
+ data: Buffer.concat(responseData)
1937
+ });
1938
+ } else if (res.statusCode && isExportHTTPErrorRetryable(res.statusCode)) {
1939
+ resolve2({
1940
+ status: "retryable",
1941
+ retryInMillis: parseRetryAfterToMills(res.headers["retry-after"])
1942
+ });
1943
+ } else {
1944
+ const error = new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString());
1945
+ resolve2({
1946
+ status: "failure",
1947
+ error
1948
+ });
1949
+ }
1950
+ });
1951
+ res.on("error", (error) => {
1952
+ if (res.statusCode && res.statusCode <= 299) {
1953
+ resolve2({
1954
+ status: "success"
1955
+ });
1956
+ } else if (res.statusCode && isExportHTTPErrorRetryable(res.statusCode)) {
1957
+ resolve2({
1958
+ status: "retryable",
1959
+ error,
1960
+ retryInMillis: parseRetryAfterToMills(res.headers["retry-after"])
1961
+ });
1962
+ } else {
1963
+ resolve2({
1964
+ status: "failure",
1965
+ error
1966
+ });
1967
+ }
1968
+ });
1969
+ });
1970
+ req.setTimeout(timeoutMillis, () => {
1971
+ req.destroy();
1972
+ resolve2({
1973
+ status: "retryable",
1974
+ error: new Error("Request timed out")
1975
+ });
1976
+ });
1977
+ req.on("error", (error) => {
1978
+ if (isHttpTransportNetworkErrorRetryable(error)) {
1979
+ resolve2({
1980
+ status: "retryable",
1981
+ error
1982
+ });
1983
+ } else {
1984
+ resolve2({
1985
+ status: "failure",
1986
+ error
1987
+ });
1988
+ }
1989
+ });
1990
+ compressAndSend(req, compression, data, (error) => {
1991
+ resolve2({
1992
+ status: "failure",
1993
+ error
1994
+ });
1995
+ });
1996
+ });
1997
+ }
1998
+ function compressAndSend(req, compression, data, onError) {
1999
+ let dataStream = readableFromUint8Array(data);
2000
+ if (compression === "gzip") {
2001
+ req.setHeader("Content-Encoding", "gzip");
2002
+ dataStream = dataStream.on("error", onError).pipe(zlib.createGzip()).on("error", onError);
2003
+ }
2004
+ dataStream.pipe(req).on("error", onError);
2005
+ }
2006
+ function readableFromUint8Array(buff) {
2007
+ const readable = new Readable();
2008
+ readable.push(buff);
2009
+ readable.push(null);
2010
+ return readable;
2011
+ }
2012
+ function isHttpTransportNetworkErrorRetryable(error) {
2013
+ const RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
2014
+ "ECONNRESET",
2015
+ "ECONNREFUSED",
2016
+ "EPIPE",
2017
+ "ETIMEDOUT",
2018
+ "EAI_AGAIN",
2019
+ "ENOTFOUND",
2020
+ "ENETUNREACH",
2021
+ "EHOSTUNREACH"
2022
+ ]);
2023
+ if ("code" in error && typeof error.code === "string") {
2024
+ return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);
2025
+ }
2026
+ return false;
2027
+ }
2028
+
2029
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js
2030
+ var HttpExporterTransport = class {
2031
+ _utils = null;
2032
+ _parameters;
2033
+ constructor(parameters) {
2034
+ this._parameters = parameters;
2035
+ }
2036
+ async send(data, timeoutMillis) {
2037
+ const { agent, request } = await this._loadUtils();
2038
+ const headers = await this._parameters.headers();
2039
+ return sendWithHttp(request, this._parameters.url, headers, this._parameters.compression, this._parameters.userAgent, agent, data, timeoutMillis);
2040
+ }
2041
+ shutdown() {
2042
+ }
2043
+ async _loadUtils() {
2044
+ let utils = this._utils;
2045
+ if (utils === null) {
2046
+ const protocol = new URL(this._parameters.url).protocol;
2047
+ const [agent, request] = await Promise.all([
2048
+ this._parameters.agentFactory(protocol),
2049
+ requestFunctionFactory(protocol)
2050
+ ]);
2051
+ utils = this._utils = { agent, request };
2052
+ }
2053
+ return utils;
2054
+ }
2055
+ };
2056
+ async function requestFunctionFactory(protocol) {
2057
+ const module = protocol === "http:" ? import("http") : import("https");
2058
+ const { request } = await module;
2059
+ return request;
2060
+ }
2061
+ function createHttpExporterTransport(parameters) {
2062
+ return new HttpExporterTransport(parameters);
2063
+ }
2064
+
2065
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js
2066
+ var MAX_ATTEMPTS = 5;
2067
+ var INITIAL_BACKOFF = 1e3;
2068
+ var MAX_BACKOFF = 5e3;
2069
+ var BACKOFF_MULTIPLIER = 1.5;
2070
+ var JITTER = 0.2;
2071
+ function getJitter() {
2072
+ return Math.random() * (2 * JITTER) - JITTER;
2073
+ }
2074
+ var RetryingTransport = class {
2075
+ _transport;
2076
+ constructor(transport) {
2077
+ this._transport = transport;
2078
+ }
2079
+ retry(data, timeoutMillis, inMillis) {
2080
+ return new Promise((resolve2, reject) => {
2081
+ setTimeout(() => {
2082
+ this._transport.send(data, timeoutMillis).then(resolve2, reject);
2083
+ }, inMillis);
2084
+ });
2085
+ }
2086
+ async send(data, timeoutMillis) {
2087
+ let attempts = MAX_ATTEMPTS;
2088
+ let nextBackoff = INITIAL_BACKOFF;
2089
+ const deadline = Date.now() + timeoutMillis;
2090
+ let result = await this._transport.send(data, timeoutMillis);
2091
+ while (result.status === "retryable" && attempts > 0) {
2092
+ attempts--;
2093
+ const backoff = Math.max(Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF), 0);
2094
+ nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;
2095
+ const retryInMillis = result.retryInMillis ?? backoff;
2096
+ const remainingTimeoutMillis = deadline - Date.now();
2097
+ if (retryInMillis > remainingTimeoutMillis) {
2098
+ diag.info(`Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(remainingTimeoutMillis)}ms, not retrying further.`);
2099
+ return result;
2100
+ }
2101
+ diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);
2102
+ result = await this.retry(data, remainingTimeoutMillis, retryInMillis);
2103
+ }
2104
+ if (result.status === "success") {
2105
+ diag.verbose(`Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`);
2106
+ } else if (result.status === "retryable") {
2107
+ diag.info(`Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`);
2108
+ } else {
2109
+ diag.info(`Export failed with non-retryable error: ${result.error}`);
2110
+ }
2111
+ return result;
2112
+ }
2113
+ shutdown() {
2114
+ return this._transport.shutdown();
2115
+ }
2116
+ };
2117
+ function createRetryingTransport(options) {
2118
+ return new RetryingTransport(options.transport);
2119
+ }
2120
+
2121
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js
2122
+ function createOtlpHttpExportDelegate(options, serializer) {
2123
+ return createOtlpExportDelegate({
2124
+ transport: createRetryingTransport({
2125
+ transport: createHttpExporterTransport(options)
2126
+ }),
2127
+ serializer,
2128
+ promiseHandler: createBoundedQueueExportPromiseHandler(options)
2129
+ }, { timeout: options.timeoutMillis });
2130
+ }
2131
+
2132
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-env-configuration.js
2133
+ function parseAndValidateTimeoutFromEnv(timeoutEnvVar) {
2134
+ const envTimeout = getNumberFromEnv(timeoutEnvVar);
2135
+ if (envTimeout != null) {
2136
+ if (Number.isFinite(envTimeout) && envTimeout > 0) {
2137
+ return envTimeout;
2138
+ }
2139
+ diag.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`);
2140
+ }
2141
+ return void 0;
2142
+ }
2143
+ function getTimeoutFromEnv(signalIdentifier) {
2144
+ const specificTimeout = parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`);
2145
+ const nonSpecificTimeout = parseAndValidateTimeoutFromEnv("OTEL_EXPORTER_OTLP_TIMEOUT");
2146
+ return specificTimeout ?? nonSpecificTimeout;
2147
+ }
2148
+ function parseAndValidateCompressionFromEnv(compressionEnvVar) {
2149
+ const compression = getStringFromEnv(compressionEnvVar)?.trim();
2150
+ if (compression == null || compression === "none" || compression === "gzip") {
2151
+ return compression;
2152
+ }
2153
+ diag.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`);
2154
+ return void 0;
2155
+ }
2156
+ function getCompressionFromEnv(signalIdentifier) {
2157
+ const specificCompression = parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`);
2158
+ const nonSpecificCompression = parseAndValidateCompressionFromEnv("OTEL_EXPORTER_OTLP_COMPRESSION");
2159
+ return specificCompression ?? nonSpecificCompression;
2160
+ }
2161
+ function getSharedConfigurationFromEnvironment(signalIdentifier) {
2162
+ return {
2163
+ timeoutMillis: getTimeoutFromEnv(signalIdentifier),
2164
+ compression: getCompressionFromEnv(signalIdentifier)
2165
+ };
2166
+ }
2167
+
2168
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-node-http-env-configuration.js
2169
+ import * as fs from "fs";
2170
+ import * as path from "path";
2171
+ function getStaticHeadersFromEnv(signalIdentifier) {
2172
+ const signalSpecificRawHeaders = getStringFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`);
2173
+ const nonSignalSpecificRawHeaders = getStringFromEnv("OTEL_EXPORTER_OTLP_HEADERS");
2174
+ const signalSpecificHeaders = parseKeyPairsIntoRecord(signalSpecificRawHeaders);
2175
+ const nonSignalSpecificHeaders = parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders);
2176
+ if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) {
2177
+ return void 0;
2178
+ }
2179
+ return Object.assign({}, parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders), parseKeyPairsIntoRecord(signalSpecificRawHeaders));
2180
+ }
2181
+ function appendRootPathToUrlIfNeeded(url) {
2182
+ try {
2183
+ const parsedUrl = new URL(url);
2184
+ return parsedUrl.toString();
2185
+ } catch {
2186
+ diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`);
2187
+ return void 0;
2188
+ }
2189
+ }
2190
+ function appendResourcePathToUrl(url, path3) {
2191
+ try {
2192
+ new URL(url);
2193
+ } catch {
2194
+ diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`);
2195
+ return void 0;
2196
+ }
2197
+ if (!url.endsWith("/")) {
2198
+ url = url + "/";
2199
+ }
2200
+ url += path3;
2201
+ try {
2202
+ new URL(url);
2203
+ } catch {
2204
+ diag.warn(`Configuration: Provided URL appended with '${path3}' is not a valid URL, using 'undefined' instead of '${url}'`);
2205
+ return void 0;
2206
+ }
2207
+ return url;
2208
+ }
2209
+ function getNonSpecificUrlFromEnv(signalResourcePath) {
2210
+ const envUrl = getStringFromEnv("OTEL_EXPORTER_OTLP_ENDPOINT");
2211
+ if (envUrl === void 0) {
2212
+ return void 0;
2213
+ }
2214
+ return appendResourcePathToUrl(envUrl, signalResourcePath);
2215
+ }
2216
+ function getSpecificUrlFromEnv(signalIdentifier) {
2217
+ const envUrl = getStringFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`);
2218
+ if (envUrl === void 0) {
2219
+ return void 0;
2220
+ }
2221
+ return appendRootPathToUrlIfNeeded(envUrl);
2222
+ }
2223
+ function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) {
2224
+ const signalSpecificPath = getStringFromEnv(signalSpecificEnvVar);
2225
+ const nonSignalSpecificPath = getStringFromEnv(nonSignalSpecificEnvVar);
2226
+ const filePath = signalSpecificPath ?? nonSignalSpecificPath;
2227
+ if (filePath != null) {
2228
+ try {
2229
+ return fs.readFileSync(path.resolve(process.cwd(), filePath));
2230
+ } catch {
2231
+ diag.warn(warningMessage);
2232
+ return void 0;
2233
+ }
2234
+ } else {
2235
+ return void 0;
2236
+ }
2237
+ }
2238
+ function getClientCertificateFromEnv(signalIdentifier) {
2239
+ return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file");
2240
+ }
2241
+ function getClientKeyFromEnv(signalIdentifier) {
2242
+ return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file");
2243
+ }
2244
+ function getRootCertificateFromEnv(signalIdentifier) {
2245
+ return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file");
2246
+ }
2247
+ function getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) {
2248
+ return {
2249
+ ...getSharedConfigurationFromEnvironment(signalIdentifier),
2250
+ url: getSpecificUrlFromEnv(signalIdentifier) ?? getNonSpecificUrlFromEnv(signalResourcePath),
2251
+ headers: wrapStaticHeadersInFunction(getStaticHeadersFromEnv(signalIdentifier)),
2252
+ agentFactory: httpAgentFactoryFromOptions({
2253
+ keepAlive: true,
2254
+ ca: getRootCertificateFromEnv(signalIdentifier),
2255
+ cert: getClientCertificateFromEnv(signalIdentifier),
2256
+ key: getClientKeyFromEnv(signalIdentifier)
2257
+ })
2258
+ };
2259
+ }
2260
+
2261
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-http-options.js
2262
+ function convertLegacyHeaders(config) {
2263
+ if (typeof config.headers === "function") {
2264
+ return config.headers;
2265
+ }
2266
+ return wrapStaticHeadersInFunction(config.headers);
2267
+ }
2268
+
2269
+ // ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-node-http-options.js
2270
+ function convertLegacyAgentOptions(config) {
2271
+ if (typeof config.httpAgentOptions === "function") {
2272
+ return config.httpAgentOptions;
2273
+ }
2274
+ let legacy = config.httpAgentOptions;
2275
+ if (config.keepAlive != null) {
2276
+ legacy = { keepAlive: config.keepAlive, ...legacy };
2277
+ }
2278
+ if (legacy != null) {
2279
+ return httpAgentFactoryFromOptions(legacy);
2280
+ } else {
2281
+ return void 0;
2282
+ }
2283
+ }
2284
+ function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) {
2285
+ if (config.metadata) {
2286
+ diag.warn("Metadata cannot be set when using http");
2287
+ }
2288
+ return mergeOtlpNodeHttpConfigurationWithDefaults({
2289
+ url: config.url,
2290
+ headers: convertLegacyHeaders(config),
2291
+ concurrencyLimit: config.concurrencyLimit,
2292
+ timeoutMillis: config.timeoutMillis,
2293
+ compression: config.compression,
2294
+ agentFactory: convertLegacyAgentOptions(config),
2295
+ userAgent: config.userAgent
2296
+ }, getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath), getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath));
2297
+ }
2298
+
2299
+ // ../../node_modules/@opentelemetry/exporter-trace-otlp-http/build/esm/platform/node/OTLPTraceExporter.js
2300
+ var OTLPTraceExporter = class extends OTLPExporterBase {
2301
+ constructor(config = {}) {
2302
+ super(createOtlpHttpExportDelegate(convertLegacyHttpOptions(config, "TRACES", "v1/traces", {
2303
+ "Content-Type": "application/json"
2304
+ }), JsonTraceSerializer));
2305
+ }
2306
+ };
2307
+
2308
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/enums.js
2309
+ var ExceptionEventName = "exception";
2310
+
2311
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Span.js
2312
+ var SpanImpl = class {
2313
+ // Below properties are included to implement ReadableSpan for export
2314
+ // purposes but are not intended to be written-to directly.
2315
+ _spanContext;
2316
+ kind;
2317
+ parentSpanContext;
2318
+ attributes = {};
2319
+ links = [];
2320
+ events = [];
2321
+ startTime;
2322
+ resource;
2323
+ instrumentationScope;
2324
+ _droppedAttributesCount = 0;
2325
+ _droppedEventsCount = 0;
2326
+ _droppedLinksCount = 0;
2327
+ _attributesCount = 0;
2328
+ name;
2329
+ status = {
2330
+ code: SpanStatusCode.UNSET
2331
+ };
2332
+ endTime = [0, 0];
2333
+ _ended = false;
2334
+ _duration = [-1, -1];
2335
+ _spanProcessor;
2336
+ _spanLimits;
2337
+ _attributeValueLengthLimit;
2338
+ _recordEndMetrics;
2339
+ _performanceStartTime;
2340
+ _performanceOffset;
2341
+ _startTimeProvided;
2342
+ /**
2343
+ * Constructs a new SpanImpl instance.
2344
+ */
2345
+ constructor(opts) {
2346
+ const now = Date.now();
2347
+ this._spanContext = opts.spanContext;
2348
+ this._performanceStartTime = otperformance.now();
2349
+ this._performanceOffset = now - (this._performanceStartTime + otperformance.timeOrigin);
2350
+ this._startTimeProvided = opts.startTime != null;
2351
+ this._spanLimits = opts.spanLimits;
2352
+ this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit ?? 0;
2353
+ this._spanProcessor = opts.spanProcessor;
2354
+ this.name = opts.name;
2355
+ this.parentSpanContext = opts.parentSpanContext;
2356
+ this.kind = opts.kind;
2357
+ if (opts.links) {
2358
+ for (const link of opts.links) {
2359
+ this.addLink(link);
2360
+ }
2361
+ }
2362
+ this.startTime = this._getTime(opts.startTime ?? now);
2363
+ this.resource = opts.resource;
2364
+ this.instrumentationScope = opts.scope;
2365
+ this._recordEndMetrics = opts.recordEndMetrics;
2366
+ if (opts.attributes != null) {
2367
+ this.setAttributes(opts.attributes);
2368
+ }
2369
+ this._spanProcessor.onStart(this, opts.context);
2370
+ }
2371
+ spanContext() {
2372
+ return this._spanContext;
2373
+ }
2374
+ setAttribute(key, value) {
2375
+ if (value == null || this._isSpanEnded())
2376
+ return this;
2377
+ if (key.length === 0) {
2378
+ diag.warn(`Invalid attribute key: ${key}`);
2379
+ return this;
2380
+ }
2381
+ if (!isAttributeValue(value)) {
2382
+ diag.warn(`Invalid attribute value set for key: ${key}`);
2383
+ return this;
2384
+ }
2385
+ const { attributeCountLimit } = this._spanLimits;
2386
+ const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
2387
+ if (attributeCountLimit !== void 0 && this._attributesCount >= attributeCountLimit && isNewKey) {
2388
+ this._droppedAttributesCount++;
2389
+ return this;
2390
+ }
2391
+ this.attributes[key] = this._truncateToSize(value);
2392
+ if (isNewKey) {
2393
+ this._attributesCount++;
2394
+ }
2395
+ return this;
2396
+ }
2397
+ setAttributes(attributes) {
2398
+ for (const key in attributes) {
2399
+ if (Object.prototype.hasOwnProperty.call(attributes, key)) {
2400
+ this.setAttribute(key, attributes[key]);
2401
+ }
2402
+ }
2403
+ return this;
2404
+ }
2405
+ /**
2406
+ *
2407
+ * @param name Span Name
2408
+ * @param [attributesOrStartTime] Span attributes or start time
2409
+ * if type is {@type TimeInput} and 3rd param is undefined
2410
+ * @param [timeStamp] Specified time stamp for the event
2411
+ */
2412
+ addEvent(name, attributesOrStartTime, timeStamp) {
2413
+ if (this._isSpanEnded())
2414
+ return this;
2415
+ const { eventCountLimit } = this._spanLimits;
2416
+ if (eventCountLimit === 0) {
2417
+ diag.warn("No events allowed.");
2418
+ this._droppedEventsCount++;
2419
+ return this;
2420
+ }
2421
+ if (eventCountLimit !== void 0 && this.events.length >= eventCountLimit) {
2422
+ if (this._droppedEventsCount === 0) {
2423
+ diag.debug("Dropping extra events.");
2424
+ }
2425
+ this.events.shift();
2426
+ this._droppedEventsCount++;
2427
+ }
2428
+ if (isTimeInput(attributesOrStartTime)) {
2429
+ if (!isTimeInput(timeStamp)) {
2430
+ timeStamp = attributesOrStartTime;
2431
+ }
2432
+ attributesOrStartTime = void 0;
2433
+ }
2434
+ const sanitized = sanitizeAttributes(attributesOrStartTime);
2435
+ const { attributePerEventCountLimit } = this._spanLimits;
2436
+ const attributes = {};
2437
+ let droppedAttributesCount = 0;
2438
+ let eventAttributesCount = 0;
2439
+ for (const attr in sanitized) {
2440
+ if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
2441
+ continue;
2442
+ }
2443
+ const attrVal = sanitized[attr];
2444
+ if (attributePerEventCountLimit !== void 0 && eventAttributesCount >= attributePerEventCountLimit) {
2445
+ droppedAttributesCount++;
2446
+ continue;
2447
+ }
2448
+ attributes[attr] = this._truncateToSize(attrVal);
2449
+ eventAttributesCount++;
2450
+ }
2451
+ this.events.push({
2452
+ name,
2453
+ attributes,
2454
+ time: this._getTime(timeStamp),
2455
+ droppedAttributesCount
2456
+ });
2457
+ return this;
2458
+ }
2459
+ addLink(link) {
2460
+ if (this._isSpanEnded())
2461
+ return this;
2462
+ const { linkCountLimit } = this._spanLimits;
2463
+ if (linkCountLimit === 0) {
2464
+ this._droppedLinksCount++;
2465
+ return this;
2466
+ }
2467
+ if (linkCountLimit !== void 0 && this.links.length >= linkCountLimit) {
2468
+ if (this._droppedLinksCount === 0) {
2469
+ diag.debug("Dropping extra links.");
2470
+ }
2471
+ this.links.shift();
2472
+ this._droppedLinksCount++;
2473
+ }
2474
+ const { attributePerLinkCountLimit } = this._spanLimits;
2475
+ const sanitized = sanitizeAttributes(link.attributes);
2476
+ const attributes = {};
2477
+ let droppedAttributesCount = 0;
2478
+ let linkAttributesCount = 0;
2479
+ for (const attr in sanitized) {
2480
+ if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
2481
+ continue;
2482
+ }
2483
+ const attrVal = sanitized[attr];
2484
+ if (attributePerLinkCountLimit !== void 0 && linkAttributesCount >= attributePerLinkCountLimit) {
2485
+ droppedAttributesCount++;
2486
+ continue;
2487
+ }
2488
+ attributes[attr] = this._truncateToSize(attrVal);
2489
+ linkAttributesCount++;
2490
+ }
2491
+ const processedLink = { context: link.context };
2492
+ if (linkAttributesCount > 0) {
2493
+ processedLink.attributes = attributes;
2494
+ }
2495
+ if (droppedAttributesCount > 0) {
2496
+ processedLink.droppedAttributesCount = droppedAttributesCount;
2497
+ }
2498
+ this.links.push(processedLink);
2499
+ return this;
2500
+ }
2501
+ addLinks(links) {
2502
+ for (const link of links) {
2503
+ this.addLink(link);
2504
+ }
2505
+ return this;
2506
+ }
2507
+ setStatus(status) {
2508
+ if (this._isSpanEnded())
2509
+ return this;
2510
+ if (status.code === SpanStatusCode.UNSET)
2511
+ return this;
2512
+ if (this.status.code === SpanStatusCode.OK)
2513
+ return this;
2514
+ const newStatus = { code: status.code };
2515
+ if (status.code === SpanStatusCode.ERROR) {
2516
+ if (typeof status.message === "string") {
2517
+ newStatus.message = status.message;
2518
+ } else if (status.message != null) {
2519
+ diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
2520
+ }
2521
+ }
2522
+ this.status = newStatus;
2523
+ return this;
2524
+ }
2525
+ updateName(name) {
2526
+ if (this._isSpanEnded())
2527
+ return this;
2528
+ this.name = name;
2529
+ return this;
2530
+ }
2531
+ end(endTime) {
2532
+ if (this._isSpanEnded()) {
2533
+ diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
2534
+ return;
2535
+ }
2536
+ this.endTime = this._getTime(endTime);
2537
+ this._duration = hrTimeDuration(this.startTime, this.endTime);
2538
+ if (this._duration[0] < 0) {
2539
+ diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime);
2540
+ this.endTime = this.startTime.slice();
2541
+ this._duration = [0, 0];
2542
+ }
2543
+ if (this._droppedEventsCount > 0) {
2544
+ diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
2545
+ }
2546
+ if (this._droppedLinksCount > 0) {
2547
+ diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
2548
+ }
2549
+ if (this._spanProcessor.onEnding) {
2550
+ this._spanProcessor.onEnding(this);
2551
+ }
2552
+ this._recordEndMetrics?.();
2553
+ this._ended = true;
2554
+ this._spanProcessor.onEnd(this);
2555
+ }
2556
+ _getTime(inp) {
2557
+ if (typeof inp === "number" && inp <= otperformance.now()) {
2558
+ return hrTime(inp + this._performanceOffset);
2559
+ }
2560
+ if (typeof inp === "number") {
2561
+ return millisToHrTime(inp);
2562
+ }
2563
+ if (inp instanceof Date) {
2564
+ return millisToHrTime(inp.getTime());
2565
+ }
2566
+ if (isTimeInputHrTime(inp)) {
2567
+ return inp;
2568
+ }
2569
+ if (this._startTimeProvided) {
2570
+ return millisToHrTime(Date.now());
2571
+ }
2572
+ const msDuration = otperformance.now() - this._performanceStartTime;
2573
+ return addHrTimes(this.startTime, millisToHrTime(msDuration));
2574
+ }
2575
+ isRecording() {
2576
+ return this._ended === false;
2577
+ }
2578
+ recordException(exception, time) {
2579
+ const attributes = {};
2580
+ if (typeof exception === "string") {
2581
+ attributes[ATTR_EXCEPTION_MESSAGE] = exception;
2582
+ } else if (exception) {
2583
+ if (exception.code) {
2584
+ attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
2585
+ } else if (exception.name) {
2586
+ attributes[ATTR_EXCEPTION_TYPE] = exception.name;
2587
+ }
2588
+ if (exception.message) {
2589
+ attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
2590
+ }
2591
+ if (exception.stack) {
2592
+ attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
2593
+ }
2594
+ }
2595
+ if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {
2596
+ this.addEvent(ExceptionEventName, attributes, time);
2597
+ } else {
2598
+ diag.warn(`Failed to record an exception ${exception}`);
2599
+ }
2600
+ }
2601
+ get duration() {
2602
+ return this._duration;
2603
+ }
2604
+ get ended() {
2605
+ return this._ended;
2606
+ }
2607
+ get droppedAttributesCount() {
2608
+ return this._droppedAttributesCount;
2609
+ }
2610
+ get droppedEventsCount() {
2611
+ return this._droppedEventsCount;
2612
+ }
2613
+ get droppedLinksCount() {
2614
+ return this._droppedLinksCount;
2615
+ }
2616
+ _isSpanEnded() {
2617
+ if (this._ended) {
2618
+ const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
2619
+ diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
2620
+ }
2621
+ return this._ended;
2622
+ }
2623
+ // Utility function to truncate given value within size
2624
+ // for value type of string, will truncate to given limit
2625
+ // for type of non-string, will return same value
2626
+ _truncateToLimitUtil(value, limit) {
2627
+ if (value.length <= limit) {
2628
+ return value;
2629
+ }
2630
+ return value.substring(0, limit);
2631
+ }
2632
+ /**
2633
+ * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
2634
+ * return string with truncated to {@code attributeValueLengthLimit} characters
2635
+ *
2636
+ * If the given attribute value is array of strings then
2637
+ * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
2638
+ *
2639
+ * Otherwise return same Attribute {@code value}
2640
+ *
2641
+ * @param value Attribute value
2642
+ * @returns truncated attribute value if required, otherwise same value
2643
+ */
2644
+ _truncateToSize(value) {
2645
+ const limit = this._attributeValueLengthLimit;
2646
+ if (limit <= 0) {
2647
+ diag.warn(`Attribute value limit must be positive, got ${limit}`);
2648
+ return value;
2649
+ }
2650
+ if (typeof value === "string") {
2651
+ return this._truncateToLimitUtil(value, limit);
2652
+ }
2653
+ if (Array.isArray(value)) {
2654
+ return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val);
2655
+ }
2656
+ return value;
2657
+ }
2658
+ };
2659
+
2660
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Sampler.js
2661
+ var SamplingDecision2;
2662
+ (function(SamplingDecision3) {
2663
+ SamplingDecision3[SamplingDecision3["NOT_RECORD"] = 0] = "NOT_RECORD";
2664
+ SamplingDecision3[SamplingDecision3["RECORD"] = 1] = "RECORD";
2665
+ SamplingDecision3[SamplingDecision3["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
2666
+ })(SamplingDecision2 || (SamplingDecision2 = {}));
2667
+
2668
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOffSampler.js
2669
+ var AlwaysOffSampler = class {
2670
+ shouldSample() {
2671
+ return {
2672
+ decision: SamplingDecision2.NOT_RECORD
2673
+ };
2674
+ }
2675
+ toString() {
2676
+ return "AlwaysOffSampler";
2677
+ }
2678
+ };
2679
+
2680
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOnSampler.js
2681
+ var AlwaysOnSampler = class {
2682
+ shouldSample() {
2683
+ return {
2684
+ decision: SamplingDecision2.RECORD_AND_SAMPLED
2685
+ };
2686
+ }
2687
+ toString() {
2688
+ return "AlwaysOnSampler";
2689
+ }
2690
+ };
2691
+
2692
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/ParentBasedSampler.js
2693
+ var ParentBasedSampler = class {
2694
+ _root;
2695
+ _remoteParentSampled;
2696
+ _remoteParentNotSampled;
2697
+ _localParentSampled;
2698
+ _localParentNotSampled;
2699
+ constructor(config) {
2700
+ this._root = config.root;
2701
+ if (!this._root) {
2702
+ globalErrorHandler(new Error("ParentBasedSampler must have a root sampler configured"));
2703
+ this._root = new AlwaysOnSampler();
2704
+ }
2705
+ this._remoteParentSampled = config.remoteParentSampled ?? new AlwaysOnSampler();
2706
+ this._remoteParentNotSampled = config.remoteParentNotSampled ?? new AlwaysOffSampler();
2707
+ this._localParentSampled = config.localParentSampled ?? new AlwaysOnSampler();
2708
+ this._localParentNotSampled = config.localParentNotSampled ?? new AlwaysOffSampler();
2709
+ }
2710
+ shouldSample(context2, traceId, spanName, spanKind, attributes, links) {
2711
+ const parentContext = trace.getSpanContext(context2);
2712
+ if (!parentContext || !isSpanContextValid(parentContext)) {
2713
+ return this._root.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
2714
+ }
2715
+ if (parentContext.isRemote) {
2716
+ if (parentContext.traceFlags & TraceFlags.SAMPLED) {
2717
+ return this._remoteParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
2718
+ }
2719
+ return this._remoteParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
2720
+ }
2721
+ if (parentContext.traceFlags & TraceFlags.SAMPLED) {
2722
+ return this._localParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
2723
+ }
2724
+ return this._localParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
2725
+ }
2726
+ toString() {
2727
+ return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
2728
+ }
2729
+ };
2730
+
2731
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/TraceIdRatioBasedSampler.js
2732
+ var TraceIdRatioBasedSampler = class {
2733
+ _ratio;
2734
+ _upperBound;
2735
+ constructor(ratio = 0) {
2736
+ this._ratio = this._normalize(ratio);
2737
+ this._upperBound = Math.floor(this._ratio * 4294967295);
2738
+ }
2739
+ shouldSample(context2, traceId) {
2740
+ return {
2741
+ decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound ? SamplingDecision2.RECORD_AND_SAMPLED : SamplingDecision2.NOT_RECORD
2742
+ };
2743
+ }
2744
+ toString() {
2745
+ return `TraceIdRatioBased{${this._ratio}}`;
2746
+ }
2747
+ _normalize(ratio) {
2748
+ if (typeof ratio !== "number" || isNaN(ratio))
2749
+ return 0;
2750
+ return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
2751
+ }
2752
+ _accumulate(traceId) {
2753
+ let accumulation = 0;
2754
+ for (let i = 0; i < traceId.length / 8; i++) {
2755
+ const pos = i * 8;
2756
+ const part = parseInt(traceId.slice(pos, pos + 8), 16);
2757
+ accumulation = (accumulation ^ part) >>> 0;
2758
+ }
2759
+ return accumulation;
2760
+ }
2761
+ };
2762
+
2763
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/config.js
2764
+ var TracesSamplerValues;
2765
+ (function(TracesSamplerValues2) {
2766
+ TracesSamplerValues2["AlwaysOff"] = "always_off";
2767
+ TracesSamplerValues2["AlwaysOn"] = "always_on";
2768
+ TracesSamplerValues2["ParentBasedAlwaysOff"] = "parentbased_always_off";
2769
+ TracesSamplerValues2["ParentBasedAlwaysOn"] = "parentbased_always_on";
2770
+ TracesSamplerValues2["ParentBasedTraceIdRatio"] = "parentbased_traceidratio";
2771
+ TracesSamplerValues2["TraceIdRatio"] = "traceidratio";
2772
+ })(TracesSamplerValues || (TracesSamplerValues = {}));
2773
+ var DEFAULT_RATIO = 1;
2774
+ function loadDefaultConfig() {
2775
+ return {
2776
+ sampler: buildSamplerFromEnv(),
2777
+ forceFlushTimeoutMillis: 3e4,
2778
+ generalLimits: {
2779
+ attributeValueLengthLimit: getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
2780
+ attributeCountLimit: getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128
2781
+ },
2782
+ spanLimits: {
2783
+ attributeValueLengthLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
2784
+ attributeCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128,
2785
+ linkCountLimit: getNumberFromEnv("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128,
2786
+ eventCountLimit: getNumberFromEnv("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128,
2787
+ attributePerEventCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128,
2788
+ attributePerLinkCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128
2789
+ }
2790
+ };
2791
+ }
2792
+ function buildSamplerFromEnv() {
2793
+ const sampler = getStringFromEnv("OTEL_TRACES_SAMPLER") ?? TracesSamplerValues.ParentBasedAlwaysOn;
2794
+ switch (sampler) {
2795
+ case TracesSamplerValues.AlwaysOn:
2796
+ return new AlwaysOnSampler();
2797
+ case TracesSamplerValues.AlwaysOff:
2798
+ return new AlwaysOffSampler();
2799
+ case TracesSamplerValues.ParentBasedAlwaysOn:
2800
+ return new ParentBasedSampler({
2801
+ root: new AlwaysOnSampler()
2802
+ });
2803
+ case TracesSamplerValues.ParentBasedAlwaysOff:
2804
+ return new ParentBasedSampler({
2805
+ root: new AlwaysOffSampler()
2806
+ });
2807
+ case TracesSamplerValues.TraceIdRatio:
2808
+ return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
2809
+ case TracesSamplerValues.ParentBasedTraceIdRatio:
2810
+ return new ParentBasedSampler({
2811
+ root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())
2812
+ });
2813
+ default:
2814
+ diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`);
2815
+ return new ParentBasedSampler({
2816
+ root: new AlwaysOnSampler()
2817
+ });
2818
+ }
2819
+ }
2820
+ function getSamplerProbabilityFromEnv() {
2821
+ const probability = getNumberFromEnv("OTEL_TRACES_SAMPLER_ARG");
2822
+ if (probability == null) {
2823
+ diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);
2824
+ return DEFAULT_RATIO;
2825
+ }
2826
+ if (probability < 0 || probability > 1) {
2827
+ diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);
2828
+ return DEFAULT_RATIO;
2829
+ }
2830
+ return probability;
2831
+ }
2832
+
2833
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/utility.js
2834
+ var DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
2835
+ var DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;
2836
+ function mergeConfig(userConfig) {
2837
+ const perInstanceDefaults = {
2838
+ sampler: buildSamplerFromEnv()
2839
+ };
2840
+ const DEFAULT_CONFIG = loadDefaultConfig();
2841
+ const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
2842
+ target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
2843
+ target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
2844
+ return target;
2845
+ }
2846
+ function reconfigureLimits(userConfig) {
2847
+ const spanLimits = Object.assign({}, userConfig.spanLimits);
2848
+ spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? DEFAULT_ATTRIBUTE_COUNT_LIMIT;
2849
+ spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;
2850
+ return Object.assign({}, userConfig, { spanLimits });
2851
+ }
2852
+
2853
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/export/BatchSpanProcessorBase.js
2854
+ var BatchSpanProcessorBase = class {
2855
+ _maxExportBatchSize;
2856
+ _maxQueueSize;
2857
+ _scheduledDelayMillis;
2858
+ _exportTimeoutMillis;
2859
+ _exporter;
2860
+ _isExporting = false;
2861
+ _finishedSpans = [];
2862
+ _timer;
2863
+ _shutdownOnce;
2864
+ _droppedSpansCount = 0;
2865
+ constructor(exporter, config) {
2866
+ this._exporter = exporter;
2867
+ this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : getNumberFromEnv("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512;
2868
+ this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : getNumberFromEnv("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048;
2869
+ this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : getNumberFromEnv("OTEL_BSP_SCHEDULE_DELAY") ?? 5e3;
2870
+ this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : getNumberFromEnv("OTEL_BSP_EXPORT_TIMEOUT") ?? 3e4;
2871
+ this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
2872
+ if (this._maxExportBatchSize > this._maxQueueSize) {
2873
+ diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
2874
+ this._maxExportBatchSize = this._maxQueueSize;
2875
+ }
2876
+ }
2877
+ forceFlush() {
2878
+ if (this._shutdownOnce.isCalled) {
2879
+ return this._shutdownOnce.promise;
2880
+ }
2881
+ return this._flushAll();
2882
+ }
2883
+ // does nothing.
2884
+ onStart(_span, _parentContext) {
2885
+ }
2886
+ onEnd(span) {
2887
+ if (this._shutdownOnce.isCalled) {
2888
+ return;
2889
+ }
2890
+ if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
2891
+ return;
2892
+ }
2893
+ this._addToBuffer(span);
2894
+ }
2895
+ shutdown() {
2896
+ return this._shutdownOnce.call();
2897
+ }
2898
+ _shutdown() {
2899
+ return Promise.resolve().then(() => {
2900
+ return this.onShutdown();
2901
+ }).then(() => {
2902
+ return this._flushAll();
2903
+ }).then(() => {
2904
+ return this._exporter.shutdown();
2905
+ });
2906
+ }
2907
+ /** Add a span in the buffer. */
2908
+ _addToBuffer(span) {
2909
+ if (this._finishedSpans.length >= this._maxQueueSize) {
2910
+ if (this._droppedSpansCount === 0) {
2911
+ diag.debug("maxQueueSize reached, dropping spans");
2912
+ }
2913
+ this._droppedSpansCount++;
2914
+ return;
2915
+ }
2916
+ if (this._droppedSpansCount > 0) {
2917
+ diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
2918
+ this._droppedSpansCount = 0;
2919
+ }
2920
+ this._finishedSpans.push(span);
2921
+ this._maybeStartTimer();
2922
+ }
2923
+ /**
2924
+ * Send all spans to the exporter respecting the batch size limit
2925
+ * This function is used only on forceFlush or shutdown,
2926
+ * for all other cases _flush should be used
2927
+ * */
2928
+ _flushAll() {
2929
+ return new Promise((resolve2, reject) => {
2930
+ const promises = [];
2931
+ const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
2932
+ for (let i = 0, j = count; i < j; i++) {
2933
+ promises.push(this._flushOneBatch());
2934
+ }
2935
+ Promise.all(promises).then(() => {
2936
+ resolve2();
2937
+ }).catch(reject);
2938
+ });
2939
+ }
2940
+ _flushOneBatch() {
2941
+ this._clearTimer();
2942
+ if (this._finishedSpans.length === 0) {
2943
+ return Promise.resolve();
2944
+ }
2945
+ return new Promise((resolve2, reject) => {
2946
+ const timer = setTimeout(() => {
2947
+ reject(new Error("Timeout"));
2948
+ }, this._exportTimeoutMillis);
2949
+ context.with(suppressTracing(context.active()), () => {
2950
+ let spans;
2951
+ if (this._finishedSpans.length <= this._maxExportBatchSize) {
2952
+ spans = this._finishedSpans;
2953
+ this._finishedSpans = [];
2954
+ } else {
2955
+ spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
2956
+ }
2957
+ const doExport = () => this._exporter.export(spans, (result) => {
2958
+ clearTimeout(timer);
2959
+ if (result.code === ExportResultCode.SUCCESS) {
2960
+ resolve2();
2961
+ } else {
2962
+ reject(result.error ?? new Error("BatchSpanProcessor: span export failed"));
2963
+ }
2964
+ });
2965
+ let pendingResources = null;
2966
+ for (let i = 0, len = spans.length; i < len; i++) {
2967
+ const span = spans[i];
2968
+ if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) {
2969
+ pendingResources ??= [];
2970
+ pendingResources.push(span.resource.waitForAsyncAttributes());
2971
+ }
2972
+ }
2973
+ if (pendingResources === null) {
2974
+ doExport();
2975
+ } else {
2976
+ Promise.all(pendingResources).then(doExport, (err) => {
2977
+ globalErrorHandler(err);
2978
+ reject(err);
2979
+ });
2980
+ }
2981
+ });
2982
+ });
2983
+ }
2984
+ _maybeStartTimer() {
2985
+ if (this._isExporting)
2986
+ return;
2987
+ const flush = () => {
2988
+ this._isExporting = true;
2989
+ this._flushOneBatch().finally(() => {
2990
+ this._isExporting = false;
2991
+ if (this._finishedSpans.length > 0) {
2992
+ this._clearTimer();
2993
+ this._maybeStartTimer();
2994
+ }
2995
+ }).catch((e) => {
2996
+ this._isExporting = false;
2997
+ globalErrorHandler(e);
2998
+ });
2999
+ };
3000
+ if (this._finishedSpans.length >= this._maxExportBatchSize) {
3001
+ return flush();
3002
+ }
3003
+ if (this._timer !== void 0)
3004
+ return;
3005
+ this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
3006
+ if (typeof this._timer !== "number") {
3007
+ this._timer.unref();
3008
+ }
3009
+ }
3010
+ _clearTimer() {
3011
+ if (this._timer !== void 0) {
3012
+ clearTimeout(this._timer);
3013
+ this._timer = void 0;
3014
+ }
3015
+ }
3016
+ };
3017
+
3018
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/node/export/BatchSpanProcessor.js
3019
+ var BatchSpanProcessor = class extends BatchSpanProcessorBase {
3020
+ onShutdown() {
3021
+ }
3022
+ };
3023
+
3024
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/node/RandomIdGenerator.js
3025
+ var SPAN_ID_BYTES = 8;
3026
+ var TRACE_ID_BYTES = 16;
3027
+ var RandomIdGenerator = class {
3028
+ /**
3029
+ * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
3030
+ * characters corresponding to 128 bits.
3031
+ */
3032
+ generateTraceId = getIdGenerator(TRACE_ID_BYTES);
3033
+ /**
3034
+ * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
3035
+ * characters corresponding to 64 bits.
3036
+ */
3037
+ generateSpanId = getIdGenerator(SPAN_ID_BYTES);
3038
+ };
3039
+ var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
3040
+ function getIdGenerator(bytes) {
3041
+ return function generateId() {
3042
+ for (let i = 0; i < bytes / 4; i++) {
3043
+ SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i * 4);
3044
+ }
3045
+ for (let i = 0; i < bytes; i++) {
3046
+ if (SHARED_BUFFER[i] > 0) {
3047
+ break;
3048
+ } else if (i === bytes - 1) {
3049
+ SHARED_BUFFER[bytes - 1] = 1;
3050
+ }
3051
+ }
3052
+ return SHARED_BUFFER.toString("hex", 0, bytes);
3053
+ };
3054
+ }
3055
+
3056
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/semconv.js
3057
+ var ATTR_OTEL_SPAN_PARENT_ORIGIN = "otel.span.parent.origin";
3058
+ var ATTR_OTEL_SPAN_SAMPLING_RESULT = "otel.span.sampling_result";
3059
+ var METRIC_OTEL_SDK_SPAN_LIVE = "otel.sdk.span.live";
3060
+ var METRIC_OTEL_SDK_SPAN_STARTED = "otel.sdk.span.started";
3061
+
3062
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/TracerMetrics.js
3063
+ var TracerMetrics = class {
3064
+ startedSpans;
3065
+ liveSpans;
3066
+ constructor(meter) {
3067
+ this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {
3068
+ unit: "{span}",
3069
+ description: "The number of created spans."
3070
+ });
3071
+ this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {
3072
+ unit: "{span}",
3073
+ description: "The number of currently live spans."
3074
+ });
3075
+ }
3076
+ startSpan(parentSpanCtx, samplingDecision) {
3077
+ const samplingDecisionStr = samplingDecisionToString(samplingDecision);
3078
+ this.startedSpans.add(1, {
3079
+ [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
3080
+ [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr
3081
+ });
3082
+ if (samplingDecision === SamplingDecision2.NOT_RECORD) {
3083
+ return () => {
3084
+ };
3085
+ }
3086
+ const liveSpanAttributes = {
3087
+ [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr
3088
+ };
3089
+ this.liveSpans.add(1, liveSpanAttributes);
3090
+ return () => {
3091
+ this.liveSpans.add(-1, liveSpanAttributes);
3092
+ };
3093
+ }
3094
+ };
3095
+ function parentOrigin(parentSpanContext) {
3096
+ if (!parentSpanContext) {
3097
+ return "none";
3098
+ }
3099
+ if (parentSpanContext.isRemote) {
3100
+ return "remote";
3101
+ }
3102
+ return "local";
3103
+ }
3104
+ function samplingDecisionToString(decision) {
3105
+ switch (decision) {
3106
+ case SamplingDecision2.RECORD_AND_SAMPLED:
3107
+ return "RECORD_AND_SAMPLE";
3108
+ case SamplingDecision2.RECORD:
3109
+ return "RECORD_ONLY";
3110
+ case SamplingDecision2.NOT_RECORD:
3111
+ return "DROP";
3112
+ }
3113
+ }
3114
+
3115
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js
3116
+ var VERSION3 = "2.6.1";
3117
+
3118
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Tracer.js
3119
+ var Tracer = class {
3120
+ _sampler;
3121
+ _generalLimits;
3122
+ _spanLimits;
3123
+ _idGenerator;
3124
+ instrumentationScope;
3125
+ _resource;
3126
+ _spanProcessor;
3127
+ _tracerMetrics;
3128
+ /**
3129
+ * Constructs a new Tracer instance.
3130
+ */
3131
+ constructor(instrumentationScope, config, resource, spanProcessor) {
3132
+ const localConfig = mergeConfig(config);
3133
+ this._sampler = localConfig.sampler;
3134
+ this._generalLimits = localConfig.generalLimits;
3135
+ this._spanLimits = localConfig.spanLimits;
3136
+ this._idGenerator = config.idGenerator || new RandomIdGenerator();
3137
+ this._resource = resource;
3138
+ this._spanProcessor = spanProcessor;
3139
+ this.instrumentationScope = instrumentationScope;
3140
+ const meter = localConfig.meterProvider ? localConfig.meterProvider.getMeter("@opentelemetry/sdk-trace", VERSION3) : createNoopMeter();
3141
+ this._tracerMetrics = new TracerMetrics(meter);
3142
+ }
3143
+ /**
3144
+ * Starts a new Span or returns the default NoopSpan based on the sampling
3145
+ * decision.
3146
+ */
3147
+ startSpan(name, options = {}, context2 = context.active()) {
3148
+ if (options.root) {
3149
+ context2 = trace.deleteSpan(context2);
3150
+ }
3151
+ const parentSpan = trace.getSpan(context2);
3152
+ if (isTracingSuppressed(context2)) {
3153
+ diag.debug("Instrumentation suppressed, returning Noop Span");
3154
+ const nonRecordingSpan = trace.wrapSpanContext(INVALID_SPAN_CONTEXT);
3155
+ return nonRecordingSpan;
3156
+ }
3157
+ const parentSpanContext = parentSpan?.spanContext();
3158
+ const spanId = this._idGenerator.generateSpanId();
3159
+ let validParentSpanContext;
3160
+ let traceId;
3161
+ let traceState;
3162
+ if (!parentSpanContext || !trace.isSpanContextValid(parentSpanContext)) {
3163
+ traceId = this._idGenerator.generateTraceId();
3164
+ } else {
3165
+ traceId = parentSpanContext.traceId;
3166
+ traceState = parentSpanContext.traceState;
3167
+ validParentSpanContext = parentSpanContext;
3168
+ }
3169
+ const spanKind = options.kind ?? SpanKind.INTERNAL;
3170
+ const links = (options.links ?? []).map((link) => {
3171
+ return {
3172
+ context: link.context,
3173
+ attributes: sanitizeAttributes(link.attributes)
3174
+ };
3175
+ });
3176
+ const attributes = sanitizeAttributes(options.attributes);
3177
+ const samplingResult = this._sampler.shouldSample(context2, traceId, name, spanKind, attributes, links);
3178
+ const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);
3179
+ traceState = samplingResult.traceState ?? traceState;
3180
+ const traceFlags = samplingResult.decision === SamplingDecision.RECORD_AND_SAMPLED ? TraceFlags.SAMPLED : TraceFlags.NONE;
3181
+ const spanContext = { traceId, spanId, traceFlags, traceState };
3182
+ if (samplingResult.decision === SamplingDecision.NOT_RECORD) {
3183
+ diag.debug("Recording is off, propagating context in a non-recording span");
3184
+ const nonRecordingSpan = trace.wrapSpanContext(spanContext);
3185
+ return nonRecordingSpan;
3186
+ }
3187
+ const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes));
3188
+ const span = new SpanImpl({
3189
+ resource: this._resource,
3190
+ scope: this.instrumentationScope,
3191
+ context: context2,
3192
+ spanContext,
3193
+ name,
3194
+ kind: spanKind,
3195
+ links,
3196
+ parentSpanContext: validParentSpanContext,
3197
+ attributes: initAttributes,
3198
+ startTime: options.startTime,
3199
+ spanProcessor: this._spanProcessor,
3200
+ spanLimits: this._spanLimits,
3201
+ recordEndMetrics
3202
+ });
3203
+ return span;
3204
+ }
3205
+ startActiveSpan(name, arg2, arg3, arg4) {
3206
+ let opts;
3207
+ let ctx;
3208
+ let fn;
3209
+ if (arguments.length < 2) {
3210
+ return;
3211
+ } else if (arguments.length === 2) {
3212
+ fn = arg2;
3213
+ } else if (arguments.length === 3) {
3214
+ opts = arg2;
3215
+ fn = arg3;
3216
+ } else {
3217
+ opts = arg2;
3218
+ ctx = arg3;
3219
+ fn = arg4;
3220
+ }
3221
+ const parentContext = ctx ?? context.active();
3222
+ const span = this.startSpan(name, opts, parentContext);
3223
+ const contextWithSpanSet = trace.setSpan(parentContext, span);
3224
+ return context.with(contextWithSpanSet, fn, void 0, span);
3225
+ }
3226
+ /** Returns the active {@link GeneralLimits}. */
3227
+ getGeneralLimits() {
3228
+ return this._generalLimits;
3229
+ }
3230
+ /** Returns the active {@link SpanLimits}. */
3231
+ getSpanLimits() {
3232
+ return this._spanLimits;
3233
+ }
3234
+ };
3235
+
3236
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/MultiSpanProcessor.js
3237
+ var MultiSpanProcessor = class {
3238
+ _spanProcessors;
3239
+ constructor(spanProcessors) {
3240
+ this._spanProcessors = spanProcessors;
3241
+ }
3242
+ forceFlush() {
3243
+ const promises = [];
3244
+ for (const spanProcessor of this._spanProcessors) {
3245
+ promises.push(spanProcessor.forceFlush());
3246
+ }
3247
+ return new Promise((resolve2) => {
3248
+ Promise.all(promises).then(() => {
3249
+ resolve2();
3250
+ }).catch((error) => {
3251
+ globalErrorHandler(error || new Error("MultiSpanProcessor: forceFlush failed"));
3252
+ resolve2();
3253
+ });
3254
+ });
3255
+ }
3256
+ onStart(span, context2) {
3257
+ for (const spanProcessor of this._spanProcessors) {
3258
+ spanProcessor.onStart(span, context2);
3259
+ }
3260
+ }
3261
+ onEnding(span) {
3262
+ for (const spanProcessor of this._spanProcessors) {
3263
+ if (spanProcessor.onEnding) {
3264
+ spanProcessor.onEnding(span);
3265
+ }
3266
+ }
3267
+ }
3268
+ onEnd(span) {
3269
+ for (const spanProcessor of this._spanProcessors) {
3270
+ spanProcessor.onEnd(span);
3271
+ }
3272
+ }
3273
+ shutdown() {
3274
+ const promises = [];
3275
+ for (const spanProcessor of this._spanProcessors) {
3276
+ promises.push(spanProcessor.shutdown());
3277
+ }
3278
+ return new Promise((resolve2, reject) => {
3279
+ Promise.all(promises).then(() => {
3280
+ resolve2();
3281
+ }, reject);
3282
+ });
3283
+ }
3284
+ };
3285
+
3286
+ // ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/BasicTracerProvider.js
3287
+ var ForceFlushState;
3288
+ (function(ForceFlushState2) {
3289
+ ForceFlushState2[ForceFlushState2["resolved"] = 0] = "resolved";
3290
+ ForceFlushState2[ForceFlushState2["timeout"] = 1] = "timeout";
3291
+ ForceFlushState2[ForceFlushState2["error"] = 2] = "error";
3292
+ ForceFlushState2[ForceFlushState2["unresolved"] = 3] = "unresolved";
3293
+ })(ForceFlushState || (ForceFlushState = {}));
3294
+ var BasicTracerProvider = class {
3295
+ _config;
3296
+ _tracers = /* @__PURE__ */ new Map();
3297
+ _resource;
3298
+ _activeSpanProcessor;
3299
+ constructor(config = {}) {
3300
+ const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
3301
+ this._resource = mergedConfig.resource ?? defaultResource();
3302
+ this._config = Object.assign({}, mergedConfig, {
3303
+ resource: this._resource
3304
+ });
3305
+ const spanProcessors = [];
3306
+ if (config.spanProcessors?.length) {
3307
+ spanProcessors.push(...config.spanProcessors);
3308
+ }
3309
+ this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);
3310
+ }
3311
+ getTracer(name, version, options) {
3312
+ const key = `${name}@${version || ""}:${options?.schemaUrl || ""}`;
3313
+ if (!this._tracers.has(key)) {
3314
+ this._tracers.set(key, new Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
3315
+ }
3316
+ return this._tracers.get(key);
3317
+ }
3318
+ forceFlush() {
3319
+ const timeout = this._config.forceFlushTimeoutMillis;
3320
+ const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
3321
+ return new Promise((resolve2) => {
3322
+ let state;
3323
+ const timeoutInterval = setTimeout(() => {
3324
+ resolve2(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
3325
+ state = ForceFlushState.timeout;
3326
+ }, timeout);
3327
+ spanProcessor.forceFlush().then(() => {
3328
+ clearTimeout(timeoutInterval);
3329
+ if (state !== ForceFlushState.timeout) {
3330
+ state = ForceFlushState.resolved;
3331
+ resolve2(state);
3332
+ }
3333
+ }).catch((error) => {
3334
+ clearTimeout(timeoutInterval);
3335
+ state = ForceFlushState.error;
3336
+ resolve2(error);
3337
+ });
3338
+ });
3339
+ });
3340
+ return new Promise((resolve2, reject) => {
3341
+ Promise.all(promises).then((results) => {
3342
+ const errors = results.filter((result) => result !== ForceFlushState.resolved);
3343
+ if (errors.length > 0) {
3344
+ reject(errors);
3345
+ } else {
3346
+ resolve2();
3347
+ }
3348
+ }).catch((error) => reject([error]));
3349
+ });
3350
+ }
3351
+ shutdown() {
3352
+ return this._activeSpanProcessor.shutdown();
3353
+ }
3354
+ };
3355
+
3356
+ // src/otel-config.ts
3357
+ var _resolvedApiKey = API_KEY_PENDING;
3358
+ var _activeExporter = null;
3359
+ var _shutdownHandler = null;
3360
+ function setResolvedApiKey(key) {
3361
+ _resolvedApiKey = key;
3362
+ }
3363
+ function getResolvedApiKey() {
3364
+ return _resolvedApiKey;
3365
+ }
3366
+ function notifyApiKeyResolved() {
3367
+ _activeExporter?.notifyKeyResolved();
3368
+ }
3369
+ async function tryImport(moduleId) {
3370
+ try {
3371
+ return await Function("id", "return import(id)")(moduleId);
3372
+ } catch {
3373
+ return null;
3374
+ }
3375
+ }
3376
+ function registerShutdownHooks(provider) {
3377
+ if (typeof process === "undefined" || typeof process.once !== "function") {
3378
+ return;
3379
+ }
3380
+ if (_shutdownHandler) {
3381
+ process.removeListener("SIGTERM", _shutdownHandler);
3382
+ process.removeListener("SIGINT", _shutdownHandler);
3383
+ }
3384
+ let shutdownCalled = false;
3385
+ const shutdown = (signal) => {
3386
+ if (shutdownCalled) return;
3387
+ shutdownCalled = true;
3388
+ void provider.shutdown().catch((err) => {
3389
+ console.warn(
3390
+ `[glasstrace] Error during OTel shutdown: ${err instanceof Error ? err.message : String(err)}`
3391
+ );
3392
+ }).finally(() => {
3393
+ process.removeListener("SIGTERM", _shutdownHandler);
3394
+ process.removeListener("SIGINT", _shutdownHandler);
3395
+ process.kill(process.pid, signal);
3396
+ });
3397
+ };
3398
+ const handler = (signal) => shutdown(signal);
3399
+ _shutdownHandler = handler;
3400
+ process.once("SIGTERM", handler);
3401
+ process.once("SIGINT", handler);
3402
+ }
3403
+ async function configureOtel(config, sessionManager) {
3404
+ const exporterUrl = `${config.endpoint}/v1/traces`;
3405
+ const createOtlpExporter = (url, headers) => new OTLPTraceExporter({ url, headers });
3406
+ const glasstraceExporter = new GlasstraceExporter({
3407
+ getApiKey: getResolvedApiKey,
3408
+ sessionManager,
3409
+ getConfig: () => getActiveConfig(),
3410
+ environment: config.environment,
3411
+ endpointUrl: exporterUrl,
3412
+ createDelegate: createOtlpExporter
3413
+ });
3414
+ _activeExporter = glasstraceExporter;
3415
+ const vercelOtel = await tryImport("@vercel/otel");
3416
+ if (vercelOtel && typeof vercelOtel.registerOTel === "function") {
3417
+ const otelConfig = {
3418
+ serviceName: "glasstrace-sdk",
3419
+ traceExporter: glasstraceExporter
3420
+ };
3421
+ const prismaModule = await tryImport("@prisma/instrumentation");
3422
+ if (prismaModule) {
3423
+ const PrismaInstrumentation = prismaModule.PrismaInstrumentation;
3424
+ if (PrismaInstrumentation) {
3425
+ otelConfig.instrumentations = [new PrismaInstrumentation()];
3426
+ }
3427
+ }
3428
+ vercelOtel.registerOTel(otelConfig);
3429
+ return;
3430
+ }
3431
+ const existingProvider = trace.getTracerProvider();
3432
+ const probeTracer = existingProvider.getTracer("glasstrace-probe");
3433
+ if (probeTracer.constructor.name !== "ProxyTracer") {
3434
+ console.warn(
3435
+ "[glasstrace] An existing OpenTelemetry TracerProvider is already registered. Glasstrace will not overwrite it. To use Glasstrace alongside another tracing tool, add GlasstraceExporter as an additional span processor on your existing provider."
3436
+ );
3437
+ _activeExporter = null;
3438
+ return;
3439
+ }
3440
+ const processor = new BatchSpanProcessor(glasstraceExporter);
3441
+ const provider = new BasicTracerProvider({
3442
+ spanProcessors: [processor]
3443
+ });
3444
+ trace.setGlobalTracerProvider(provider);
3445
+ registerShutdownHooks(provider);
3446
+ }
3447
+
3448
+ // src/console-capture.ts
3449
+ var isGlasstraceLog = false;
3450
+ var originalError = null;
3451
+ var originalWarn = null;
3452
+ var installed = false;
3453
+ var otelApi = null;
3454
+ function formatArgs(args) {
3455
+ return args.map((arg) => {
3456
+ if (typeof arg === "string") return arg;
3457
+ if (arg instanceof Error) return arg.stack ?? arg.message;
3458
+ try {
3459
+ return JSON.stringify(arg);
3460
+ } catch {
3461
+ return String(arg);
3462
+ }
3463
+ }).join(" ");
3464
+ }
3465
+ function isSdkMessage(args) {
3466
+ return typeof args[0] === "string" && args[0].startsWith("[glasstrace]");
3467
+ }
3468
+ async function installConsoleCapture() {
3469
+ if (installed) return;
3470
+ try {
3471
+ otelApi = await import("./esm-POMEQPKL.js");
3472
+ } catch {
3473
+ otelApi = null;
3474
+ }
3475
+ originalError = console.error;
3476
+ originalWarn = console.warn;
3477
+ installed = true;
3478
+ console.error = (...args) => {
3479
+ originalError.apply(console, args);
3480
+ if (isGlasstraceLog || isSdkMessage(args)) return;
3481
+ if (otelApi) {
3482
+ const span = otelApi.trace.getSpan(otelApi.context.active());
3483
+ if (span) {
3484
+ span.addEvent("console.error", {
3485
+ "console.message": formatArgs(args)
3486
+ });
3487
+ }
3488
+ }
3489
+ };
3490
+ console.warn = (...args) => {
3491
+ originalWarn.apply(console, args);
3492
+ if (isGlasstraceLog || isSdkMessage(args)) return;
3493
+ if (otelApi) {
3494
+ const span = otelApi.trace.getSpan(otelApi.context.active());
3495
+ if (span) {
3496
+ span.addEvent("console.warn", {
3497
+ "console.message": formatArgs(args)
3498
+ });
3499
+ }
3500
+ }
3501
+ };
3502
+ }
3503
+
3504
+ // src/register.ts
3505
+ var consoleCaptureInstalled = false;
3506
+ var discoveryHandler = null;
3507
+ var isRegistered = false;
3508
+ var registrationGeneration = 0;
3509
+ function registerGlasstrace(options) {
3510
+ try {
3511
+ if (isRegistered) {
3512
+ return;
3513
+ }
3514
+ const config = resolveConfig(options);
3515
+ if (config.verbose) {
3516
+ console.info("[glasstrace] Config resolved.");
1010
3517
  }
1011
3518
  if (isProductionDisabled(config)) {
1012
3519
  console.warn(
@@ -1044,7 +3551,6 @@ function registerGlasstrace(options) {
1044
3551
  const currentGeneration = registrationGeneration;
1045
3552
  void configureOtel(config, sessionManager).then(
1046
3553
  () => {
1047
- void _preloadOtelApi();
1048
3554
  maybeInstallConsoleCapture();
1049
3555
  if (config.verbose) {
1050
3556
  console.info("[glasstrace] OTel configured.");
@@ -1083,7 +3589,7 @@ function registerGlasstrace(options) {
1083
3589
  if (config.verbose) {
1084
3590
  console.info("[glasstrace] Background init firing.");
1085
3591
  }
1086
- await performInit(config, anonKey, "0.2.1");
3592
+ await performInit(config, anonKey, "0.2.3");
1087
3593
  maybeInstallConsoleCapture();
1088
3594
  } catch (err) {
1089
3595
  console.warn(
@@ -1103,7 +3609,7 @@ function registerGlasstrace(options) {
1103
3609
  if (config.verbose) {
1104
3610
  console.info("[glasstrace] Background init firing.");
1105
3611
  }
1106
- await performInit(config, anonKey, "0.2.1");
3612
+ await performInit(config, anonKey, "0.2.3");
1107
3613
  maybeInstallConsoleCapture();
1108
3614
  } catch (err) {
1109
3615
  console.warn(
@@ -1125,7 +3631,7 @@ function registerGlasstrace(options) {
1125
3631
  if (config.verbose) {
1126
3632
  console.info("[glasstrace] Background init firing.");
1127
3633
  }
1128
- await performInit(config, anonKeyForInit, "0.2.1");
3634
+ await performInit(config, anonKeyForInit, "0.2.3");
1129
3635
  maybeInstallConsoleCapture();
1130
3636
  } catch (err) {
1131
3637
  console.warn(
@@ -1163,8 +3669,8 @@ function isDiscoveryEnabled(config) {
1163
3669
  }
1164
3670
 
1165
3671
  // src/source-map-uploader.ts
1166
- import * as fs from "fs/promises";
1167
- import * as path from "path";
3672
+ import * as fs2 from "fs/promises";
3673
+ import * as path2 from "path";
1168
3674
  import * as crypto from "crypto";
1169
3675
  import { execSync } from "child_process";
1170
3676
  async function collectSourceMaps(buildDir) {
@@ -1179,18 +3685,18 @@ async function collectSourceMaps(buildDir) {
1179
3685
  async function walkDir(baseDir, currentDir, results) {
1180
3686
  let entries;
1181
3687
  try {
1182
- entries = await fs.readdir(currentDir, { withFileTypes: true });
3688
+ entries = await fs2.readdir(currentDir, { withFileTypes: true });
1183
3689
  } catch {
1184
3690
  return;
1185
3691
  }
1186
3692
  for (const entry of entries) {
1187
- const fullPath = path.join(currentDir, entry.name);
3693
+ const fullPath = path2.join(currentDir, entry.name);
1188
3694
  if (entry.isDirectory()) {
1189
3695
  await walkDir(baseDir, fullPath, results);
1190
3696
  } else if (entry.isFile() && entry.name.endsWith(".map")) {
1191
3697
  try {
1192
- const content = await fs.readFile(fullPath, "utf-8");
1193
- const relativePath = path.relative(baseDir, fullPath).replace(/\\/g, "/");
3698
+ const content = await fs2.readFile(fullPath, "utf-8");
3699
+ const relativePath = path2.relative(baseDir, fullPath).replace(/\\/g, "/");
1194
3700
  const compiledPath = relativePath.replace(/\.map$/, "");
1195
3701
  results.push({ filePath: compiledPath, content });
1196
3702
  } catch {
@@ -1253,12 +3759,12 @@ function withGlasstraceConfig(nextConfig) {
1253
3759
  config.experimental = { ...existingExperimental, serverSourceMaps: true };
1254
3760
  const distDir = typeof config.distDir === "string" ? config.distDir : ".next";
1255
3761
  const existingWebpack = config.webpack;
1256
- config.webpack = (webpackConfig, context) => {
3762
+ config.webpack = (webpackConfig, context2) => {
1257
3763
  let result = webpackConfig;
1258
3764
  if (typeof existingWebpack === "function") {
1259
- result = existingWebpack(webpackConfig, context);
3765
+ result = existingWebpack(webpackConfig, context2);
1260
3766
  }
1261
- const webpackContext = context;
3767
+ const webpackContext = context2;
1262
3768
  if (!webpackContext.isServer && webpackContext.dev === false) {
1263
3769
  const plugins = result.plugins ?? [];
1264
3770
  plugins.push({
@@ -1307,6 +3813,22 @@ async function handleSourceMapUpload(distDir) {
1307
3813
  );
1308
3814
  }
1309
3815
  }
3816
+
3817
+ // src/capture-error.ts
3818
+ function captureError(error) {
3819
+ try {
3820
+ const span = trace.getSpan(context.active());
3821
+ if (!span) return;
3822
+ const attributes = {
3823
+ "error.message": String(error)
3824
+ };
3825
+ if (error instanceof Error) {
3826
+ attributes["error.type"] = error.constructor.name;
3827
+ }
3828
+ span.addEvent("glasstrace.error", attributes);
3829
+ } catch {
3830
+ }
3831
+ }
1310
3832
  export {
1311
3833
  GlasstraceExporter,
1312
3834
  GlasstraceSpanProcessor,