@glasstrace/sdk 0.2.1 → 0.4.0

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