@spatius/avatarkit 1.3.1-beta.7 → 1.3.1

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 (22) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/{AvatarDownloader-B1tJTnIb.js → AvatarDownloader-DyhenPKd.js} +98 -43
  3. package/dist/{AvatarSDK-CTprrfJk.js → AvatarSDK-DgPvHU4L.js} +162 -2560
  4. package/dist/{OpusCodec-PWv7ynPp.js → OpusCodec-CXU7ysrU.js} +43 -9
  5. package/dist/{OpusDecoderProxy-m0fVN_M2.js → OpusDecoderProxy-Cq8Z_MZY.js} +19 -6
  6. package/dist/{OpusEncoderProxy-DiW21sBK.js → OpusEncoderProxy-CzY-VckE.js} +42 -7
  7. package/dist/{StreamingAudioPlayer-C6hgkvbK.js → StreamingAudioPlayer-CIJmBp3z.js} +2 -2
  8. package/dist/assets/{AvatarDownloader-LO9uuYvm.js → AvatarDownloader-G5FO1bVl.js} +96 -41
  9. package/dist/assets/{AvatarSDK-CPEeTeLT.js → AvatarSDK-C_Anluwp.js} +149 -12
  10. package/dist/assets/{OpusDecoderWorker.worker-CSSWn75M.js → OpusDecoderWorker.worker-C2T0afkj.js} +21 -5
  11. package/dist/assets/{OpusEncoderWorker.worker-q4TdCVDZ.js → OpusEncoderWorker.worker-DLYO9vPK.js} +53 -11
  12. package/dist/assets/{logger-DCzHWd4N.js → logger-YPooEAbA.js} +319 -126
  13. package/dist/core/AvatarController.d.ts +10 -0
  14. package/dist/{error-utils-BCZDCrc6.js → error-utils-BogEllAd.js} +1 -1
  15. package/dist/index.js +274 -43
  16. package/dist/internal-telemetry.d.ts +45 -20
  17. package/dist/internal-telemetry.js +27 -2
  18. package/dist/{logger-DdmfSEn-.js → logger-BOpQ7u0w.js} +336 -126
  19. package/dist/otel-trace-Ct4T48nC.js +2565 -0
  20. package/dist/{pwa-cache-manager-BMKyJWXI.js → pwa-cache-manager-C7NbU52Q.js} +1 -1
  21. package/dist/types/index.d.ts +30 -4
  22. package/package.json +1 -1
@@ -0,0 +1,2565 @@
1
+ import { $ as isSpanContextValid, A as defaultResource, B as otperformance, D as createResource, E as createInstrumentationScope, F as hrTime, G as getNumberFromEnv, H as ATTR_EXCEPTION_STACKTRACE, I as hrTimeDuration, J as isTracingSuppressed, K as getStringFromEnv, L as isTimeInput, M as BindOnceFuture, N as ExportResultCode, O as toAttributes, P as addHrTimes, Q as context, R as isTimeInputHrTime, T as JSON_ENCODER, U as ATTR_EXCEPTION_TYPE, V as ATTR_EXCEPTION_MESSAGE, W as ATTR_SERVICE_NAME, X as trace, Y as suppressTracing, Z as diag$1, a as clientContextFields, at as ROOT_CONTEXT, ct as getGlobal, et as isValidTraceId, ft as OTEL_PASSWORD, gt as OTEL_USERNAME, ht as OTEL_TRACES_STREAM_NAME, it as createNoopMeter, j as resourceFromAttributes, k as OTLPExporterBase, lt as registerGlobal, mt as OTEL_TRACES_ENDPOINT, nt as TraceFlags, ot as createContextKey, q as globalErrorHandler, rt as ContextAPI, st as DiagAPI, t as logger, tt as INVALID_SPAN_CONTEXT, ut as unregisterGlobal, vt as idManager, w as createLegacyOtlpBrowserExportDelegate, y as observeExporter, z as millisToHrTime } from "./logger-BOpQ7u0w.js";
2
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js
3
+ var BaggageImpl = class BaggageImpl {
4
+ constructor(entries) {
5
+ this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map();
6
+ }
7
+ getEntry(key) {
8
+ const entry = this._entries.get(key);
9
+ if (!entry) return;
10
+ return Object.assign({}, entry);
11
+ }
12
+ getAllEntries() {
13
+ return Array.from(this._entries.entries());
14
+ }
15
+ setEntry(key, entry) {
16
+ const newBaggage = new BaggageImpl(this._entries);
17
+ newBaggage._entries.set(key, entry);
18
+ return newBaggage;
19
+ }
20
+ removeEntry(key) {
21
+ const newBaggage = new BaggageImpl(this._entries);
22
+ newBaggage._entries.delete(key);
23
+ return newBaggage;
24
+ }
25
+ removeEntries(...keys) {
26
+ const newBaggage = new BaggageImpl(this._entries);
27
+ for (const key of keys) newBaggage._entries.delete(key);
28
+ return newBaggage;
29
+ }
30
+ clear() {
31
+ return new BaggageImpl();
32
+ }
33
+ };
34
+ //#endregion
35
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js
36
+ /**
37
+ * Symbol used to make BaggageEntryMetadata an opaque type
38
+ */
39
+ var baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata");
40
+ //#endregion
41
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/utils.js
42
+ var diag = DiagAPI.instance();
43
+ /**
44
+ * Create a new Baggage with optional entries
45
+ *
46
+ * @param entries An array of baggage entries the new baggage should contain
47
+ */
48
+ function createBaggage(entries = {}) {
49
+ return new BaggageImpl(new Map(Object.entries(entries)));
50
+ }
51
+ /**
52
+ * Create a serializable BaggageEntryMetadata object from a string.
53
+ *
54
+ * @param str string metadata. Format is currently not defined by the spec and has no special meaning.
55
+ *
56
+ * @since 1.0.0
57
+ */
58
+ function baggageEntryMetadataFromString(str) {
59
+ if (typeof str !== "string") {
60
+ diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
61
+ str = "";
62
+ }
63
+ return {
64
+ __TYPE__: baggageEntryMetadataSymbol,
65
+ toString() {
66
+ return str;
67
+ }
68
+ };
69
+ }
70
+ //#endregion
71
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js
72
+ /**
73
+ * @since 1.0.0
74
+ */
75
+ var defaultTextMapGetter = {
76
+ get(carrier, key) {
77
+ if (carrier == null) return;
78
+ return carrier[key];
79
+ },
80
+ keys(carrier) {
81
+ if (carrier == null) return [];
82
+ return Object.keys(carrier);
83
+ }
84
+ };
85
+ /**
86
+ * @since 1.0.0
87
+ */
88
+ var defaultTextMapSetter = { set(carrier, key, value) {
89
+ if (carrier == null) return;
90
+ carrier[key] = value;
91
+ } };
92
+ //#endregion
93
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js
94
+ /**
95
+ * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.
96
+ * A sampling decision that determines how a {@link Span} will be recorded
97
+ * and collected.
98
+ *
99
+ * @since 1.0.0
100
+ */
101
+ var SamplingDecision$1;
102
+ (function(SamplingDecision) {
103
+ /**
104
+ * `Span.isRecording() === false`, span will not be recorded and all events
105
+ * and attributes will be dropped.
106
+ */
107
+ SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
108
+ /**
109
+ * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
110
+ * MUST NOT be set.
111
+ */
112
+ SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
113
+ /**
114
+ * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
115
+ * MUST be set.
116
+ */
117
+ SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
118
+ })(SamplingDecision$1 || (SamplingDecision$1 = {}));
119
+ //#endregion
120
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js
121
+ /**
122
+ * @since 1.0.0
123
+ */
124
+ var SpanKind;
125
+ (function(SpanKind) {
126
+ /** Default value. Indicates that the span is used internally. */
127
+ SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL";
128
+ /**
129
+ * Indicates that the span covers server-side handling of an RPC or other
130
+ * remote request.
131
+ */
132
+ SpanKind[SpanKind["SERVER"] = 1] = "SERVER";
133
+ /**
134
+ * Indicates that the span covers the client-side wrapper around an RPC or
135
+ * other remote request.
136
+ */
137
+ SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT";
138
+ /**
139
+ * Indicates that the span describes producer sending a message to a
140
+ * broker. Unlike client and server, there is no direct critical path latency
141
+ * relationship between producer and consumer spans.
142
+ */
143
+ SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER";
144
+ /**
145
+ * Indicates that the span describes consumer receiving a message from a
146
+ * broker. Unlike client and server, there is no direct critical path latency
147
+ * relationship between producer and consumer spans.
148
+ */
149
+ SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER";
150
+ })(SpanKind || (SpanKind = {}));
151
+ //#endregion
152
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/status.js
153
+ /**
154
+ * An enumeration of status codes.
155
+ *
156
+ * @since 1.0.0
157
+ */
158
+ var SpanStatusCode;
159
+ (function(SpanStatusCode) {
160
+ /**
161
+ * The default status.
162
+ */
163
+ SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET";
164
+ /**
165
+ * The operation has been validated by an Application developer or
166
+ * Operator to have completed successfully.
167
+ */
168
+ SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK";
169
+ /**
170
+ * The operation contains an error.
171
+ */
172
+ SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
173
+ })(SpanStatusCode || (SpanStatusCode = {}));
174
+ //#endregion
175
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js
176
+ /**
177
+ * No-op implementations of {@link TextMapPropagator}.
178
+ */
179
+ var NoopTextMapPropagator = class {
180
+ /** Noop inject function does nothing */
181
+ inject(_context, _carrier) {}
182
+ /** Noop extract function does nothing and returns the input context */
183
+ extract(context, _carrier) {
184
+ return context;
185
+ }
186
+ fields() {
187
+ return [];
188
+ }
189
+ };
190
+ //#endregion
191
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js
192
+ /**
193
+ * Baggage key
194
+ */
195
+ var BAGGAGE_KEY = createContextKey("OpenTelemetry Baggage Key");
196
+ /**
197
+ * Retrieve the current baggage from the given context
198
+ *
199
+ * @param {Context} Context that manage all context values
200
+ * @returns {Baggage} Extracted baggage from the context
201
+ */
202
+ function getBaggage(context) {
203
+ return context.getValue(BAGGAGE_KEY) || void 0;
204
+ }
205
+ /**
206
+ * Retrieve the current baggage from the active/current context
207
+ *
208
+ * @returns {Baggage} Extracted baggage from the context
209
+ */
210
+ function getActiveBaggage() {
211
+ return getBaggage(ContextAPI.getInstance().active());
212
+ }
213
+ /**
214
+ * Store a baggage in the given context
215
+ *
216
+ * @param {Context} Context that manage all context values
217
+ * @param {Baggage} baggage that will be set in the actual context
218
+ */
219
+ function setBaggage(context, baggage) {
220
+ return context.setValue(BAGGAGE_KEY, baggage);
221
+ }
222
+ /**
223
+ * Delete the baggage stored in the given context
224
+ *
225
+ * @param {Context} Context that manage all context values
226
+ */
227
+ function deleteBaggage(context) {
228
+ return context.deleteValue(BAGGAGE_KEY);
229
+ }
230
+ //#endregion
231
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/propagation.js
232
+ var API_NAME = "propagation";
233
+ var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();
234
+ //#endregion
235
+ //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation-api.js
236
+ /**
237
+ * Entrypoint for propagation API
238
+ *
239
+ * @since 1.0.0
240
+ */
241
+ var propagation = class PropagationAPI {
242
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
243
+ constructor() {
244
+ this.createBaggage = createBaggage;
245
+ this.getBaggage = getBaggage;
246
+ this.getActiveBaggage = getActiveBaggage;
247
+ this.setBaggage = setBaggage;
248
+ this.deleteBaggage = deleteBaggage;
249
+ }
250
+ /** Get the singleton instance of the Propagator API */
251
+ static getInstance() {
252
+ if (!this._instance) this._instance = new PropagationAPI();
253
+ return this._instance;
254
+ }
255
+ /**
256
+ * Set the current propagator.
257
+ *
258
+ * @returns true if the propagator was successfully registered, else false
259
+ */
260
+ setGlobalPropagator(propagator) {
261
+ return registerGlobal(API_NAME, propagator, DiagAPI.instance());
262
+ }
263
+ /**
264
+ * Inject context into a carrier to be propagated inter-process
265
+ *
266
+ * @param context Context carrying tracing data to inject
267
+ * @param carrier carrier to inject context into
268
+ * @param setter Function used to set values on the carrier
269
+ */
270
+ inject(context, carrier, setter = defaultTextMapSetter) {
271
+ return this._getGlobalPropagator().inject(context, carrier, setter);
272
+ }
273
+ /**
274
+ * Extract context from a carrier
275
+ *
276
+ * @param context Context which the newly created context will inherit from
277
+ * @param carrier Carrier to extract context from
278
+ * @param getter Function used to extract keys from a carrier
279
+ */
280
+ extract(context, carrier, getter = defaultTextMapGetter) {
281
+ return this._getGlobalPropagator().extract(context, carrier, getter);
282
+ }
283
+ /**
284
+ * Return a list of all fields which may be used by the propagator.
285
+ */
286
+ fields() {
287
+ return this._getGlobalPropagator().fields();
288
+ }
289
+ /** Remove the global propagator */
290
+ disable() {
291
+ unregisterGlobal(API_NAME, DiagAPI.instance());
292
+ }
293
+ _getGlobalPropagator() {
294
+ return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
295
+ }
296
+ }.getInstance();
297
+ //#endregion
298
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/baggage/constants.js
299
+ var BAGGAGE_HEADER = "baggage";
300
+ var BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;
301
+ //#endregion
302
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/baggage/utils.js
303
+ function serializeKeyPairs(keyPairs) {
304
+ return keyPairs.reduce((hValue, current) => {
305
+ const value = `${hValue}${hValue !== "" ? "," : ""}${current}`;
306
+ return value.length > 8192 ? hValue : value;
307
+ }, "");
308
+ }
309
+ function getKeyPairs(baggage) {
310
+ return baggage.getAllEntries().map(([key, value]) => {
311
+ let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;
312
+ if (value.metadata !== void 0) entry += ";" + value.metadata.toString();
313
+ return entry;
314
+ });
315
+ }
316
+ function parsePairKeyValue(entry) {
317
+ if (!entry) return;
318
+ const metadataSeparatorIndex = entry.indexOf(";");
319
+ const keyPairPart = metadataSeparatorIndex === -1 ? entry : entry.substring(0, metadataSeparatorIndex);
320
+ const separatorIndex = keyPairPart.indexOf("=");
321
+ if (separatorIndex <= 0) return;
322
+ const rawKey = keyPairPart.substring(0, separatorIndex).trim();
323
+ const rawValue = keyPairPart.substring(separatorIndex + 1).trim();
324
+ if (!rawKey || !rawValue) return;
325
+ let key;
326
+ let value;
327
+ try {
328
+ key = decodeURIComponent(rawKey);
329
+ value = decodeURIComponent(rawValue);
330
+ } catch {
331
+ return;
332
+ }
333
+ let metadata;
334
+ if (metadataSeparatorIndex !== -1 && metadataSeparatorIndex < entry.length - 1) metadata = baggageEntryMetadataFromString(entry.substring(metadataSeparatorIndex + 1));
335
+ return {
336
+ key,
337
+ value,
338
+ metadata
339
+ };
340
+ }
341
+ //#endregion
342
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/baggage/propagation/W3CBaggagePropagator.js
343
+ /**
344
+ * Propagates {@link Baggage} through Context format propagation.
345
+ *
346
+ * Based on the Baggage specification:
347
+ * https://w3c.github.io/baggage/
348
+ */
349
+ var W3CBaggagePropagator = class {
350
+ inject(context, carrier, setter) {
351
+ const baggage = propagation.getBaggage(context);
352
+ if (!baggage || isTracingSuppressed(context)) return;
353
+ const headerValue = serializeKeyPairs(getKeyPairs(baggage).filter((pair) => {
354
+ return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;
355
+ }).slice(0, 180));
356
+ if (headerValue.length > 0) setter.set(carrier, BAGGAGE_HEADER, headerValue);
357
+ }
358
+ extract(context, carrier, getter) {
359
+ const headerValue = getter.get(carrier, BAGGAGE_HEADER);
360
+ const baggageString = Array.isArray(headerValue) ? headerValue.join(",") : headerValue;
361
+ if (!baggageString) return context;
362
+ const baggage = {};
363
+ if (baggageString.length === 0) return context;
364
+ baggageString.split(",").forEach((entry) => {
365
+ const keyPair = parsePairKeyValue(entry);
366
+ if (keyPair) {
367
+ const baggageEntry = { value: keyPair.value };
368
+ if (keyPair.metadata) baggageEntry.metadata = keyPair.metadata;
369
+ baggage[keyPair.key] = baggageEntry;
370
+ }
371
+ });
372
+ if (Object.entries(baggage).length === 0) return context;
373
+ return propagation.setBaggage(context, propagation.createBaggage(baggage));
374
+ }
375
+ fields() {
376
+ return [BAGGAGE_HEADER];
377
+ }
378
+ };
379
+ //#endregion
380
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/common/attributes.js
381
+ function sanitizeAttributes(attributes) {
382
+ const out = {};
383
+ if (typeof attributes !== "object" || attributes == null) return out;
384
+ for (const key in attributes) {
385
+ if (!Object.prototype.hasOwnProperty.call(attributes, key)) continue;
386
+ if (!isAttributeKey(key)) {
387
+ diag$1.warn(`Invalid attribute key: ${key}`);
388
+ continue;
389
+ }
390
+ const val = attributes[key];
391
+ if (!isAttributeValue(val)) {
392
+ diag$1.warn(`Invalid attribute value set for key: ${key}`);
393
+ continue;
394
+ }
395
+ if (Array.isArray(val)) out[key] = val.slice();
396
+ else out[key] = val;
397
+ }
398
+ return out;
399
+ }
400
+ function isAttributeKey(key) {
401
+ return typeof key === "string" && key !== "";
402
+ }
403
+ function isAttributeValue(val) {
404
+ if (val == null) return true;
405
+ if (Array.isArray(val)) return isHomogeneousAttributeValueArray(val);
406
+ return isValidPrimitiveAttributeValueType(typeof val);
407
+ }
408
+ function isHomogeneousAttributeValueArray(arr) {
409
+ let type;
410
+ for (const element of arr) {
411
+ if (element == null) continue;
412
+ const elementType = typeof element;
413
+ if (elementType === type) continue;
414
+ if (!type) {
415
+ if (isValidPrimitiveAttributeValueType(elementType)) {
416
+ type = elementType;
417
+ continue;
418
+ }
419
+ return false;
420
+ }
421
+ return false;
422
+ }
423
+ return true;
424
+ }
425
+ function isValidPrimitiveAttributeValueType(valType) {
426
+ switch (valType) {
427
+ case "number":
428
+ case "boolean":
429
+ case "string": return true;
430
+ }
431
+ return false;
432
+ }
433
+ //#endregion
434
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/propagation/composite.js
435
+ /** Combines multiple propagators into a single propagator. */
436
+ var CompositePropagator = class {
437
+ _propagators;
438
+ _fields;
439
+ /**
440
+ * Construct a composite propagator from a list of propagators.
441
+ *
442
+ * @param [config] Configuration object for composite propagator
443
+ */
444
+ constructor(config = {}) {
445
+ this._propagators = config.propagators ?? [];
446
+ const fields = /* @__PURE__ */ new Set();
447
+ for (const propagator of this._propagators) {
448
+ const propagatorFields = typeof propagator.fields === "function" ? propagator.fields() : [];
449
+ for (const field of propagatorFields) fields.add(field);
450
+ }
451
+ this._fields = Array.from(fields);
452
+ }
453
+ /**
454
+ * Run each of the configured propagators with the given context and carrier.
455
+ * Propagators are run in the order they are configured, so if multiple
456
+ * propagators write the same carrier key, the propagator later in the list
457
+ * will "win".
458
+ *
459
+ * @param context Context to inject
460
+ * @param carrier Carrier into which context will be injected
461
+ */
462
+ inject(context, carrier, setter) {
463
+ for (const propagator of this._propagators) try {
464
+ propagator.inject(context, carrier, setter);
465
+ } catch (err) {
466
+ diag$1.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`);
467
+ }
468
+ }
469
+ /**
470
+ * Run each of the configured propagators with the given context and carrier.
471
+ * Propagators are run in the order they are configured, so if multiple
472
+ * propagators write the same context key, the propagator later in the list
473
+ * will "win".
474
+ *
475
+ * @param context Context to add values to
476
+ * @param carrier Carrier from which to extract context
477
+ */
478
+ extract(context, carrier, getter) {
479
+ return this._propagators.reduce((ctx, propagator) => {
480
+ try {
481
+ return propagator.extract(ctx, carrier, getter);
482
+ } catch (err) {
483
+ diag$1.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`);
484
+ }
485
+ return ctx;
486
+ }, context);
487
+ }
488
+ fields() {
489
+ return this._fields.slice();
490
+ }
491
+ };
492
+ //#endregion
493
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/internal/validators.js
494
+ var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
495
+ var VALID_KEY_REGEX = new RegExp(`^(?:${`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`}|${`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`})$`);
496
+ var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
497
+ var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
498
+ /**
499
+ * Key is opaque string up to 256 characters printable. It MUST begin with a
500
+ * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,
501
+ * underscores _, dashes -, asterisks *, and forward slashes /.
502
+ * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the
503
+ * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.
504
+ * see https://www.w3.org/TR/trace-context/#key
505
+ */
506
+ function validateKey(key) {
507
+ return VALID_KEY_REGEX.test(key);
508
+ }
509
+ /**
510
+ * Value is opaque string up to 256 characters printable ASCII RFC0020
511
+ * characters (i.e., the range 0x20 to 0x7E) except comma , and =.
512
+ */
513
+ function validateValue(value) {
514
+ return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
515
+ }
516
+ //#endregion
517
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/trace/TraceState.js
518
+ var MAX_TRACE_STATE_ITEMS = 32;
519
+ var MAX_TRACE_STATE_LEN = 512;
520
+ var LIST_MEMBERS_SEPARATOR = ",";
521
+ var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
522
+ /**
523
+ * TraceState must be a class and not a simple object type because of the spec
524
+ * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).
525
+ *
526
+ * Here is the list of allowed mutations:
527
+ * - New key-value pair should be added into the beginning of the list
528
+ * - The value of any key can be updated. Modified keys MUST be moved to the
529
+ * beginning of the list.
530
+ */
531
+ var TraceState = class TraceState {
532
+ _length;
533
+ _rawTraceState;
534
+ _internalState;
535
+ constructor(rawTraceState) {
536
+ this._rawTraceState = typeof rawTraceState === "string" ? rawTraceState : "";
537
+ this._length = this._rawTraceState.length;
538
+ }
539
+ set(key, value) {
540
+ if (!validateKey(key) || !validateValue(value)) return this;
541
+ const currState = this._getState();
542
+ const currValue = currState.get(key);
543
+ let newLength = this._length;
544
+ if (typeof currValue === "string") newLength += value.length - currValue.length;
545
+ else newLength += key.length + value.length + (currState.size > 0 ? 2 : 1);
546
+ if (newLength > MAX_TRACE_STATE_LEN) return this;
547
+ const newState = new Map(currState);
548
+ newState.delete(key);
549
+ newState.set(key, value);
550
+ return this._fromState(newState, newLength);
551
+ }
552
+ unset(key) {
553
+ const currState = this._getState();
554
+ const currValue = currState.get(key);
555
+ if (typeof currValue !== "string") return this;
556
+ let newLength = this._length - (key.length + currValue.length + 1);
557
+ if (currState.size > 1) newLength = newLength - 1;
558
+ const newState = new Map(currState);
559
+ newState.delete(key);
560
+ return this._fromState(newState, newLength);
561
+ }
562
+ get(key) {
563
+ return this._getState().get(key);
564
+ }
565
+ serialize() {
566
+ let serialized = "";
567
+ let index = 0;
568
+ for (const entry of this._getState()) {
569
+ if (index > 0) serialized = LIST_MEMBERS_SEPARATOR + serialized;
570
+ serialized = `${entry[0]}${LIST_MEMBER_KEY_VALUE_SPLITTER}${entry[1]}` + serialized;
571
+ index++;
572
+ }
573
+ return serialized;
574
+ }
575
+ _getState() {
576
+ if (this._internalState) return this._internalState;
577
+ const vendorMembers = this._rawTraceState.split(LIST_MEMBERS_SEPARATOR);
578
+ const vendorEntries = /* @__PURE__ */ new Map();
579
+ let currentLength = 0;
580
+ for (const member of vendorMembers) {
581
+ const m = member.trim();
582
+ const idx = m.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
583
+ if (idx === -1) continue;
584
+ const key = m.slice(0, idx);
585
+ const value = m.slice(idx + 1);
586
+ if (!validateKey(key) || !validateValue(value)) continue;
587
+ const futureLength = currentLength + m.length + (vendorEntries.size > 0 ? 1 : 0);
588
+ if (futureLength > MAX_TRACE_STATE_LEN) continue;
589
+ vendorEntries.set(key, value);
590
+ currentLength = futureLength;
591
+ if (vendorEntries.size >= MAX_TRACE_STATE_ITEMS) break;
592
+ }
593
+ this._length = currentLength;
594
+ this._internalState = new Map(Array.from(vendorEntries.entries()).reverse());
595
+ return this._internalState;
596
+ }
597
+ _fromState(state, length) {
598
+ const traceState = Object.create(TraceState.prototype);
599
+ traceState._internalState = state;
600
+ traceState._length = length;
601
+ return traceState;
602
+ }
603
+ };
604
+ //#endregion
605
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/trace/W3CTraceContextPropagator.js
606
+ var TRACE_PARENT_HEADER = "traceparent";
607
+ var TRACE_STATE_HEADER = "tracestate";
608
+ var VERSION$1 = "00";
609
+ var TRACE_PARENT_REGEX = new RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);
610
+ /**
611
+ * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}
612
+ * @param traceParent - A meta property that comes from server.
613
+ * It should be dynamically generated server side to have the server's request trace Id,
614
+ * a parent span Id that was set on the server's request span,
615
+ * and the trace flags to indicate the server's sampling decision
616
+ * (01 = sampled, 00 = not sampled).
617
+ * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'
618
+ * For more information see {@link https://www.w3.org/TR/trace-context/}
619
+ */
620
+ function parseTraceParent(traceParent) {
621
+ const match = TRACE_PARENT_REGEX.exec(traceParent);
622
+ if (!match) return null;
623
+ if (match[1] === "00" && match[5]) return null;
624
+ return {
625
+ traceId: match[2],
626
+ spanId: match[3],
627
+ traceFlags: parseInt(match[4], 16)
628
+ };
629
+ }
630
+ /**
631
+ * Propagates {@link SpanContext} through Trace Context format propagation.
632
+ *
633
+ * Based on the Trace Context specification:
634
+ * https://www.w3.org/TR/trace-context/
635
+ */
636
+ var W3CTraceContextPropagator = class {
637
+ inject(context, carrier, setter) {
638
+ const spanContext = trace.getSpanContext(context);
639
+ if (!spanContext || isTracingSuppressed(context) || !isSpanContextValid(spanContext)) return;
640
+ const traceParent = `${VERSION$1}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;
641
+ setter.set(carrier, TRACE_PARENT_HEADER, traceParent);
642
+ if (spanContext.traceState) setter.set(carrier, TRACE_STATE_HEADER, spanContext.traceState.serialize());
643
+ }
644
+ extract(context, carrier, getter) {
645
+ const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);
646
+ if (!traceParentHeader) return context;
647
+ const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader;
648
+ if (typeof traceParent !== "string") return context;
649
+ const spanContext = parseTraceParent(traceParent);
650
+ if (!spanContext) return context;
651
+ spanContext.isRemote = true;
652
+ const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);
653
+ if (traceStateHeader) {
654
+ const state = Array.isArray(traceStateHeader) ? traceStateHeader.join(",") : traceStateHeader;
655
+ spanContext.traceState = new TraceState(typeof state === "string" ? state : void 0);
656
+ }
657
+ return trace.setSpanContext(context, spanContext);
658
+ }
659
+ fields() {
660
+ return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];
661
+ }
662
+ };
663
+ //#endregion
664
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/utils/lodash.merge.js
665
+ /**
666
+ * based on lodash in order to support esm builds without esModuleInterop.
667
+ * lodash is using MIT License.
668
+ **/
669
+ var objectTag = "[object Object]";
670
+ var nullTag = "[object Null]";
671
+ var undefinedTag = "[object Undefined]";
672
+ var funcToString = Function.prototype.toString;
673
+ var objectCtorString = funcToString.call(Object);
674
+ var getPrototypeOf = Object.getPrototypeOf;
675
+ var objectProto = Object.prototype;
676
+ var hasOwnProperty = objectProto.hasOwnProperty;
677
+ var symToStringTag = Symbol ? Symbol.toStringTag : void 0;
678
+ var nativeObjectToString = objectProto.toString;
679
+ /**
680
+ * Checks if `value` is a plain object, that is, an object created by the
681
+ * `Object` constructor or one with a `[[Prototype]]` of `null`.
682
+ *
683
+ * @static
684
+ * @memberOf _
685
+ * @since 0.8.0
686
+ * @category Lang
687
+ * @param {*} value The value to check.
688
+ * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
689
+ * @example
690
+ *
691
+ * function Foo() {
692
+ * this.a = 1;
693
+ * }
694
+ *
695
+ * _.isPlainObject(new Foo);
696
+ * // => false
697
+ *
698
+ * _.isPlainObject([1, 2, 3]);
699
+ * // => false
700
+ *
701
+ * _.isPlainObject({ 'x': 0, 'y': 0 });
702
+ * // => true
703
+ *
704
+ * _.isPlainObject(Object.create(null));
705
+ * // => true
706
+ */
707
+ function isPlainObject(value) {
708
+ if (!isObjectLike(value) || baseGetTag(value) !== objectTag) return false;
709
+ const proto = getPrototypeOf(value);
710
+ if (proto === null) return true;
711
+ const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
712
+ return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString;
713
+ }
714
+ /**
715
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
716
+ * and has a `typeof` result of "object".
717
+ *
718
+ * @static
719
+ * @memberOf _
720
+ * @since 4.0.0
721
+ * @category Lang
722
+ * @param {*} value The value to check.
723
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
724
+ * @example
725
+ *
726
+ * _.isObjectLike({});
727
+ * // => true
728
+ *
729
+ * _.isObjectLike([1, 2, 3]);
730
+ * // => true
731
+ *
732
+ * _.isObjectLike(_.noop);
733
+ * // => false
734
+ *
735
+ * _.isObjectLike(null);
736
+ * // => false
737
+ */
738
+ function isObjectLike(value) {
739
+ return value != null && typeof value == "object";
740
+ }
741
+ /**
742
+ * The base implementation of `getTag` without fallbacks for buggy environments.
743
+ *
744
+ * @private
745
+ * @param {*} value The value to query.
746
+ * @returns {string} Returns the `toStringTag`.
747
+ */
748
+ function baseGetTag(value) {
749
+ if (value == null) return value === void 0 ? undefinedTag : nullTag;
750
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
751
+ }
752
+ /**
753
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
754
+ *
755
+ * @private
756
+ * @param {*} value The value to query.
757
+ * @returns {string} Returns the raw `toStringTag`.
758
+ */
759
+ function getRawTag(value) {
760
+ const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
761
+ let unmasked = false;
762
+ try {
763
+ value[symToStringTag] = void 0;
764
+ unmasked = true;
765
+ } catch {}
766
+ const result = nativeObjectToString.call(value);
767
+ if (unmasked) if (isOwn) value[symToStringTag] = tag;
768
+ else delete value[symToStringTag];
769
+ return result;
770
+ }
771
+ /**
772
+ * Converts `value` to a string using `Object.prototype.toString`.
773
+ *
774
+ * @private
775
+ * @param {*} value The value to convert.
776
+ * @returns {string} Returns the converted string.
777
+ */
778
+ function objectToString(value) {
779
+ return nativeObjectToString.call(value);
780
+ }
781
+ //#endregion
782
+ //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/utils/merge.js
783
+ var MAX_LEVEL = 20;
784
+ /**
785
+ * Merges objects together
786
+ * @param args - objects / values to be merged
787
+ */
788
+ function merge(...args) {
789
+ let result = args.shift();
790
+ const objects = /* @__PURE__ */ new WeakMap();
791
+ while (args.length > 0) result = mergeTwoObjects(result, args.shift(), 0, objects);
792
+ return result;
793
+ }
794
+ function takeValue(value) {
795
+ if (isArray(value)) return value.slice();
796
+ return value;
797
+ }
798
+ /**
799
+ * Merges two objects
800
+ * @param one - first object
801
+ * @param two - second object
802
+ * @param level - current deep level
803
+ * @param objects - objects holder that has been already referenced - to prevent
804
+ * cyclic dependency
805
+ */
806
+ function mergeTwoObjects(one, two, level = 0, objects) {
807
+ let result;
808
+ if (level > MAX_LEVEL) return;
809
+ level++;
810
+ if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) result = takeValue(two);
811
+ else if (isArray(one)) {
812
+ result = one.slice();
813
+ if (isArray(two)) for (let i = 0, j = two.length; i < j; i++) result.push(takeValue(two[i]));
814
+ else if (isObject(two)) {
815
+ const keys = Object.keys(two);
816
+ for (let i = 0, j = keys.length; i < j; i++) {
817
+ const key = keys[i];
818
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
819
+ result[key] = takeValue(two[key]);
820
+ }
821
+ }
822
+ } else if (isObject(one)) if (isObject(two)) {
823
+ if (!shouldMerge(one, two)) return two;
824
+ result = Object.assign({}, one);
825
+ const keys = Object.keys(two);
826
+ for (let i = 0, j = keys.length; i < j; i++) {
827
+ const key = keys[i];
828
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
829
+ const twoValue = two[key];
830
+ if (isPrimitive(twoValue)) if (typeof twoValue === "undefined") delete result[key];
831
+ else result[key] = twoValue;
832
+ else {
833
+ const obj1 = result[key];
834
+ const obj2 = twoValue;
835
+ if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) delete result[key];
836
+ else {
837
+ if (isObject(obj1) && isObject(obj2)) {
838
+ const arr1 = objects.get(obj1) || [];
839
+ const arr2 = objects.get(obj2) || [];
840
+ arr1.push({
841
+ obj: one,
842
+ key
843
+ });
844
+ arr2.push({
845
+ obj: two,
846
+ key
847
+ });
848
+ objects.set(obj1, arr1);
849
+ objects.set(obj2, arr2);
850
+ }
851
+ result[key] = mergeTwoObjects(result[key], twoValue, level, objects);
852
+ }
853
+ }
854
+ }
855
+ } else result = two;
856
+ return result;
857
+ }
858
+ /**
859
+ * Function to check if object has been already reference
860
+ * @param obj
861
+ * @param key
862
+ * @param objects
863
+ */
864
+ function wasObjectReferenced(obj, key, objects) {
865
+ const arr = objects.get(obj[key]) || [];
866
+ for (let i = 0, j = arr.length; i < j; i++) {
867
+ const info = arr[i];
868
+ if (info.key === key && info.obj === obj) return true;
869
+ }
870
+ return false;
871
+ }
872
+ function isArray(value) {
873
+ return Array.isArray(value);
874
+ }
875
+ function isFunction(value) {
876
+ return typeof value === "function";
877
+ }
878
+ function isObject(value) {
879
+ return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object";
880
+ }
881
+ function isPrimitive(value) {
882
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
883
+ }
884
+ function shouldMerge(one, two) {
885
+ if (!isPlainObject(one) || !isPlainObject(two)) return false;
886
+ return true;
887
+ }
888
+ //#endregion
889
+ //#region node_modules/.pnpm/@opentelemetry+otlp-transformer@0.218.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/esm/trace/internal.js
890
+ var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256;
891
+ var SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512;
892
+ /**
893
+ * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags
894
+ * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.
895
+ */
896
+ function buildSpanFlagsFrom(traceFlags, isRemote) {
897
+ let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;
898
+ if (isRemote) flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;
899
+ return flags;
900
+ }
901
+ function sdkSpanToOtlpSpan(span, encoder) {
902
+ const ctx = span.spanContext();
903
+ const status = span.status;
904
+ const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : void 0;
905
+ return {
906
+ traceId: encoder.encodeSpanContext(ctx.traceId),
907
+ spanId: encoder.encodeSpanContext(ctx.spanId),
908
+ parentSpanId,
909
+ traceState: ctx.traceState?.serialize(),
910
+ name: span.name,
911
+ kind: span.kind == null ? 0 : span.kind + 1,
912
+ startTimeUnixNano: encoder.encodeHrTime(span.startTime),
913
+ endTimeUnixNano: encoder.encodeHrTime(span.endTime),
914
+ attributes: toAttributes(span.attributes, encoder),
915
+ droppedAttributesCount: span.droppedAttributesCount,
916
+ events: span.events.map((event) => toOtlpSpanEvent(event, encoder)),
917
+ droppedEventsCount: span.droppedEventsCount,
918
+ status: {
919
+ code: status.code,
920
+ message: status.message
921
+ },
922
+ links: span.links.map((link) => toOtlpLink(link, encoder)),
923
+ droppedLinksCount: span.droppedLinksCount,
924
+ flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote)
925
+ };
926
+ }
927
+ function toOtlpLink(link, encoder) {
928
+ return {
929
+ attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],
930
+ spanId: encoder.encodeSpanContext(link.context.spanId),
931
+ traceId: encoder.encodeSpanContext(link.context.traceId),
932
+ traceState: link.context.traceState?.serialize(),
933
+ droppedAttributesCount: link.droppedAttributesCount || 0,
934
+ flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote)
935
+ };
936
+ }
937
+ function toOtlpSpanEvent(timedEvent, encoder) {
938
+ return {
939
+ attributes: timedEvent.attributes ? toAttributes(timedEvent.attributes, encoder) : [],
940
+ name: timedEvent.name,
941
+ timeUnixNano: encoder.encodeHrTime(timedEvent.time),
942
+ droppedAttributesCount: timedEvent.droppedAttributesCount || 0
943
+ };
944
+ }
945
+ function createExportTraceServiceRequest(spans, encoder) {
946
+ return { resourceSpans: spanRecordsToResourceSpans(spans, encoder) };
947
+ }
948
+ function createResourceMap(readableSpans) {
949
+ const resourceMap = /* @__PURE__ */ new Map();
950
+ for (const record of readableSpans) {
951
+ let ilsMap = resourceMap.get(record.resource);
952
+ if (!ilsMap) {
953
+ ilsMap = /* @__PURE__ */ new Map();
954
+ resourceMap.set(record.resource, ilsMap);
955
+ }
956
+ const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ""}:${record.instrumentationScope.schemaUrl || ""}`;
957
+ let records = ilsMap.get(instrumentationScopeKey);
958
+ if (!records) {
959
+ records = [];
960
+ ilsMap.set(instrumentationScopeKey, records);
961
+ }
962
+ records.push(record);
963
+ }
964
+ return resourceMap;
965
+ }
966
+ function spanRecordsToResourceSpans(readableSpans, encoder) {
967
+ const resourceMap = createResourceMap(readableSpans);
968
+ const out = [];
969
+ const entryIterator = resourceMap.entries();
970
+ let entry = entryIterator.next();
971
+ while (!entry.done) {
972
+ const [resource, ilmMap] = entry.value;
973
+ const scopeResourceSpans = [];
974
+ const ilmIterator = ilmMap.values();
975
+ let ilmEntry = ilmIterator.next();
976
+ while (!ilmEntry.done) {
977
+ const scopeSpans = ilmEntry.value;
978
+ if (scopeSpans.length > 0) {
979
+ const spans = scopeSpans.map((readableSpan) => sdkSpanToOtlpSpan(readableSpan, encoder));
980
+ scopeResourceSpans.push({
981
+ scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),
982
+ spans,
983
+ schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl
984
+ });
985
+ }
986
+ ilmEntry = ilmIterator.next();
987
+ }
988
+ const processedResource = createResource(resource, encoder);
989
+ out.push({
990
+ resource: processedResource,
991
+ scopeSpans: scopeResourceSpans,
992
+ schemaUrl: processedResource.schemaUrl
993
+ });
994
+ entry = entryIterator.next();
995
+ }
996
+ return out;
997
+ }
998
+ //#endregion
999
+ //#region node_modules/.pnpm/@opentelemetry+otlp-transformer@0.218.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/esm/trace/json/trace.js
1000
+ var JsonTraceSerializer = {
1001
+ serializeRequest: (arg) => {
1002
+ const request = createExportTraceServiceRequest(arg, JSON_ENCODER);
1003
+ return new TextEncoder().encode(JSON.stringify(request));
1004
+ },
1005
+ deserializeResponse: (arg) => {
1006
+ if (arg.length === 0) return {};
1007
+ const decoder = new TextDecoder();
1008
+ try {
1009
+ return JSON.parse(decoder.decode(arg));
1010
+ } catch (err) {
1011
+ diag$1.warn(`Failed to parse trace export response: ${err.message}. Returning empty response`);
1012
+ return {};
1013
+ }
1014
+ }
1015
+ };
1016
+ //#endregion
1017
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/enums.js
1018
+ var ExceptionEventName = "exception";
1019
+ //#endregion
1020
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/Span.js
1021
+ /**
1022
+ * This class represents a span.
1023
+ */
1024
+ var SpanImpl = class {
1025
+ _spanContext;
1026
+ kind;
1027
+ parentSpanContext;
1028
+ attributes = {};
1029
+ links = [];
1030
+ events = [];
1031
+ startTime;
1032
+ resource;
1033
+ instrumentationScope;
1034
+ _droppedAttributesCount = 0;
1035
+ _droppedEventsCount = 0;
1036
+ _droppedLinksCount = 0;
1037
+ _attributesCount = 0;
1038
+ name;
1039
+ status = { code: SpanStatusCode.UNSET };
1040
+ endTime = [0, 0];
1041
+ _ended = false;
1042
+ _duration = [-1, -1];
1043
+ _spanProcessor;
1044
+ _spanLimits;
1045
+ _attributeValueLengthLimit;
1046
+ _recordEndMetrics;
1047
+ _performanceStartTime;
1048
+ _performanceOffset;
1049
+ _startTimeProvided;
1050
+ /**
1051
+ * Constructs a new SpanImpl instance.
1052
+ */
1053
+ constructor(opts) {
1054
+ const now = Date.now();
1055
+ this._spanContext = opts.spanContext;
1056
+ this._performanceStartTime = otperformance.now();
1057
+ this._performanceOffset = now - (this._performanceStartTime + otperformance.timeOrigin);
1058
+ this._startTimeProvided = opts.startTime != null;
1059
+ this._spanLimits = opts.spanLimits;
1060
+ this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit ?? 0;
1061
+ this._spanProcessor = opts.spanProcessor;
1062
+ this.name = opts.name;
1063
+ this.parentSpanContext = opts.parentSpanContext;
1064
+ this.kind = opts.kind;
1065
+ if (opts.links) for (const link of opts.links) this.addLink(link);
1066
+ this.startTime = this._getTime(opts.startTime ?? now);
1067
+ this.resource = opts.resource;
1068
+ this.instrumentationScope = opts.scope;
1069
+ this._recordEndMetrics = opts.recordEndMetrics;
1070
+ if (opts.attributes != null) this.setAttributes(opts.attributes);
1071
+ this._spanProcessor.onStart(this, opts.context);
1072
+ }
1073
+ spanContext() {
1074
+ return this._spanContext;
1075
+ }
1076
+ setAttribute(key, value) {
1077
+ if (value == null || this._isSpanEnded()) return this;
1078
+ if (key.length === 0) {
1079
+ diag$1.warn(`Invalid attribute key: ${key}`);
1080
+ return this;
1081
+ }
1082
+ if (!isAttributeValue(value)) {
1083
+ diag$1.warn(`Invalid attribute value set for key: ${key}`);
1084
+ return this;
1085
+ }
1086
+ const { attributeCountLimit } = this._spanLimits;
1087
+ const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
1088
+ if (attributeCountLimit !== void 0 && this._attributesCount >= attributeCountLimit && isNewKey) {
1089
+ this._droppedAttributesCount++;
1090
+ return this;
1091
+ }
1092
+ this.attributes[key] = this._truncateToSize(value);
1093
+ if (isNewKey) this._attributesCount++;
1094
+ return this;
1095
+ }
1096
+ setAttributes(attributes) {
1097
+ for (const key in attributes) if (Object.prototype.hasOwnProperty.call(attributes, key)) this.setAttribute(key, attributes[key]);
1098
+ return this;
1099
+ }
1100
+ /**
1101
+ *
1102
+ * @param name Span Name
1103
+ * @param [attributesOrStartTime] Span attributes or start time
1104
+ * if type is {@type TimeInput} and 3rd param is undefined
1105
+ * @param [timeStamp] Specified time stamp for the event
1106
+ */
1107
+ addEvent(name, attributesOrStartTime, timeStamp) {
1108
+ if (this._isSpanEnded()) return this;
1109
+ const { eventCountLimit } = this._spanLimits;
1110
+ if (eventCountLimit === 0) {
1111
+ diag$1.warn("No events allowed.");
1112
+ this._droppedEventsCount++;
1113
+ return this;
1114
+ }
1115
+ if (eventCountLimit !== void 0 && this.events.length >= eventCountLimit) {
1116
+ if (this._droppedEventsCount === 0) diag$1.debug("Dropping extra events.");
1117
+ this.events.shift();
1118
+ this._droppedEventsCount++;
1119
+ }
1120
+ if (isTimeInput(attributesOrStartTime)) {
1121
+ if (!isTimeInput(timeStamp)) timeStamp = attributesOrStartTime;
1122
+ attributesOrStartTime = void 0;
1123
+ }
1124
+ const sanitized = sanitizeAttributes(attributesOrStartTime);
1125
+ const { attributePerEventCountLimit } = this._spanLimits;
1126
+ const attributes = {};
1127
+ let droppedAttributesCount = 0;
1128
+ let eventAttributesCount = 0;
1129
+ for (const attr in sanitized) {
1130
+ if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) continue;
1131
+ const attrVal = sanitized[attr];
1132
+ if (attributePerEventCountLimit !== void 0 && eventAttributesCount >= attributePerEventCountLimit) {
1133
+ droppedAttributesCount++;
1134
+ continue;
1135
+ }
1136
+ attributes[attr] = this._truncateToSize(attrVal);
1137
+ eventAttributesCount++;
1138
+ }
1139
+ this.events.push({
1140
+ name,
1141
+ attributes,
1142
+ time: this._getTime(timeStamp),
1143
+ droppedAttributesCount
1144
+ });
1145
+ return this;
1146
+ }
1147
+ addLink(link) {
1148
+ if (this._isSpanEnded()) return this;
1149
+ const { linkCountLimit } = this._spanLimits;
1150
+ if (linkCountLimit === 0) {
1151
+ this._droppedLinksCount++;
1152
+ return this;
1153
+ }
1154
+ if (linkCountLimit !== void 0 && this.links.length >= linkCountLimit) {
1155
+ if (this._droppedLinksCount === 0) diag$1.debug("Dropping extra links.");
1156
+ this.links.shift();
1157
+ this._droppedLinksCount++;
1158
+ }
1159
+ const { attributePerLinkCountLimit } = this._spanLimits;
1160
+ const sanitized = sanitizeAttributes(link.attributes);
1161
+ const attributes = {};
1162
+ let droppedAttributesCount = 0;
1163
+ let linkAttributesCount = 0;
1164
+ for (const attr in sanitized) {
1165
+ if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) continue;
1166
+ const attrVal = sanitized[attr];
1167
+ if (attributePerLinkCountLimit !== void 0 && linkAttributesCount >= attributePerLinkCountLimit) {
1168
+ droppedAttributesCount++;
1169
+ continue;
1170
+ }
1171
+ attributes[attr] = this._truncateToSize(attrVal);
1172
+ linkAttributesCount++;
1173
+ }
1174
+ const processedLink = { context: link.context };
1175
+ if (linkAttributesCount > 0) processedLink.attributes = attributes;
1176
+ if (droppedAttributesCount > 0) processedLink.droppedAttributesCount = droppedAttributesCount;
1177
+ this.links.push(processedLink);
1178
+ return this;
1179
+ }
1180
+ addLinks(links) {
1181
+ for (const link of links) this.addLink(link);
1182
+ return this;
1183
+ }
1184
+ setStatus(status) {
1185
+ if (this._isSpanEnded()) return this;
1186
+ if (status.code === SpanStatusCode.UNSET) return this;
1187
+ if (this.status.code === SpanStatusCode.OK) return this;
1188
+ const newStatus = { code: status.code };
1189
+ if (status.code === SpanStatusCode.ERROR) {
1190
+ if (typeof status.message === "string") newStatus.message = status.message;
1191
+ else if (status.message != null) diag$1.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
1192
+ }
1193
+ this.status = newStatus;
1194
+ return this;
1195
+ }
1196
+ updateName(name) {
1197
+ if (this._isSpanEnded()) return this;
1198
+ this.name = name;
1199
+ return this;
1200
+ }
1201
+ end(endTime) {
1202
+ if (this._isSpanEnded()) {
1203
+ diag$1.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
1204
+ return;
1205
+ }
1206
+ this.endTime = this._getTime(endTime);
1207
+ this._duration = hrTimeDuration(this.startTime, this.endTime);
1208
+ if (this._duration[0] < 0) {
1209
+ diag$1.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime);
1210
+ this.endTime = this.startTime.slice();
1211
+ this._duration = [0, 0];
1212
+ }
1213
+ if (this._droppedEventsCount > 0) diag$1.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
1214
+ if (this._droppedLinksCount > 0) diag$1.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
1215
+ if (this._spanProcessor.onEnding) this._spanProcessor.onEnding(this);
1216
+ this._recordEndMetrics?.();
1217
+ this._ended = true;
1218
+ this._spanProcessor.onEnd(this);
1219
+ }
1220
+ _getTime(inp) {
1221
+ if (typeof inp === "number" && inp <= otperformance.now()) return hrTime(inp + this._performanceOffset);
1222
+ if (typeof inp === "number") return millisToHrTime(inp);
1223
+ if (inp instanceof Date) return millisToHrTime(inp.getTime());
1224
+ if (isTimeInputHrTime(inp)) return inp;
1225
+ if (this._startTimeProvided) return millisToHrTime(Date.now());
1226
+ const msDuration = otperformance.now() - this._performanceStartTime;
1227
+ return addHrTimes(this.startTime, millisToHrTime(msDuration));
1228
+ }
1229
+ isRecording() {
1230
+ return this._ended === false;
1231
+ }
1232
+ recordException(exception, time) {
1233
+ const attributes = {};
1234
+ if (typeof exception === "string") attributes[ATTR_EXCEPTION_MESSAGE] = exception;
1235
+ else if (exception) {
1236
+ if (exception.code) attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
1237
+ else if (exception.name) attributes[ATTR_EXCEPTION_TYPE] = exception.name;
1238
+ if (exception.message) attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
1239
+ if (exception.stack) attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
1240
+ }
1241
+ if (attributes["exception.type"] || attributes["exception.message"]) this.addEvent(ExceptionEventName, attributes, time);
1242
+ else diag$1.warn(`Failed to record an exception ${exception}`);
1243
+ }
1244
+ get duration() {
1245
+ return this._duration;
1246
+ }
1247
+ get ended() {
1248
+ return this._ended;
1249
+ }
1250
+ get droppedAttributesCount() {
1251
+ return this._droppedAttributesCount;
1252
+ }
1253
+ get droppedEventsCount() {
1254
+ return this._droppedEventsCount;
1255
+ }
1256
+ get droppedLinksCount() {
1257
+ return this._droppedLinksCount;
1258
+ }
1259
+ _isSpanEnded() {
1260
+ if (this._ended) {
1261
+ const error = /* @__PURE__ */ new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
1262
+ diag$1.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
1263
+ }
1264
+ return this._ended;
1265
+ }
1266
+ _truncateToLimitUtil(value, limit) {
1267
+ if (value.length <= limit) return value;
1268
+ return value.substring(0, limit);
1269
+ }
1270
+ /**
1271
+ * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
1272
+ * return string with truncated to {@code attributeValueLengthLimit} characters
1273
+ *
1274
+ * If the given attribute value is array of strings then
1275
+ * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
1276
+ *
1277
+ * Otherwise return same Attribute {@code value}
1278
+ *
1279
+ * @param value Attribute value
1280
+ * @returns truncated attribute value if required, otherwise same value
1281
+ */
1282
+ _truncateToSize(value) {
1283
+ const limit = this._attributeValueLengthLimit;
1284
+ if (limit <= 0) {
1285
+ diag$1.warn(`Attribute value limit must be positive, got ${limit}`);
1286
+ return value;
1287
+ }
1288
+ if (typeof value === "string") return this._truncateToLimitUtil(value, limit);
1289
+ if (Array.isArray(value)) return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val);
1290
+ return value;
1291
+ }
1292
+ };
1293
+ //#endregion
1294
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/Sampler.js
1295
+ /**
1296
+ * A sampling decision that determines how a {@link Span} will be recorded
1297
+ * and collected.
1298
+ */
1299
+ var SamplingDecision;
1300
+ (function(SamplingDecision) {
1301
+ /**
1302
+ * `Span.isRecording() === false`, span will not be recorded and all events
1303
+ * and attributes will be dropped.
1304
+ */
1305
+ SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
1306
+ /**
1307
+ * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
1308
+ * MUST NOT be set.
1309
+ */
1310
+ SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
1311
+ /**
1312
+ * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
1313
+ * MUST be set.
1314
+ */
1315
+ SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
1316
+ })(SamplingDecision || (SamplingDecision = {}));
1317
+ //#endregion
1318
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOffSampler.js
1319
+ /** Sampler that samples no traces. */
1320
+ var AlwaysOffSampler = class {
1321
+ shouldSample() {
1322
+ return { decision: SamplingDecision.NOT_RECORD };
1323
+ }
1324
+ toString() {
1325
+ return "AlwaysOffSampler";
1326
+ }
1327
+ };
1328
+ //#endregion
1329
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOnSampler.js
1330
+ /** Sampler that samples all traces. */
1331
+ var AlwaysOnSampler = class {
1332
+ shouldSample() {
1333
+ return { decision: SamplingDecision.RECORD_AND_SAMPLED };
1334
+ }
1335
+ toString() {
1336
+ return "AlwaysOnSampler";
1337
+ }
1338
+ };
1339
+ //#endregion
1340
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/ParentBasedSampler.js
1341
+ /**
1342
+ * A composite sampler that either respects the parent span's sampling decision
1343
+ * or delegates to `delegateSampler` for root spans.
1344
+ */
1345
+ var ParentBasedSampler = class {
1346
+ _root;
1347
+ _remoteParentSampled;
1348
+ _remoteParentNotSampled;
1349
+ _localParentSampled;
1350
+ _localParentNotSampled;
1351
+ constructor(config) {
1352
+ this._root = config.root;
1353
+ if (!this._root) {
1354
+ globalErrorHandler(/* @__PURE__ */ new Error("ParentBasedSampler must have a root sampler configured"));
1355
+ this._root = new AlwaysOnSampler();
1356
+ }
1357
+ this._remoteParentSampled = config.remoteParentSampled ?? new AlwaysOnSampler();
1358
+ this._remoteParentNotSampled = config.remoteParentNotSampled ?? new AlwaysOffSampler();
1359
+ this._localParentSampled = config.localParentSampled ?? new AlwaysOnSampler();
1360
+ this._localParentNotSampled = config.localParentNotSampled ?? new AlwaysOffSampler();
1361
+ }
1362
+ shouldSample(context, traceId, spanName, spanKind, attributes, links) {
1363
+ const parentContext = trace.getSpanContext(context);
1364
+ if (!parentContext || !isSpanContextValid(parentContext)) return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);
1365
+ if (parentContext.isRemote) {
1366
+ if (parentContext.traceFlags & TraceFlags.SAMPLED) return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
1367
+ return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
1368
+ }
1369
+ if (parentContext.traceFlags & TraceFlags.SAMPLED) return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
1370
+ return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
1371
+ }
1372
+ toString() {
1373
+ return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
1374
+ }
1375
+ };
1376
+ //#endregion
1377
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/TraceIdRatioBasedSampler.js
1378
+ /** Sampler that samples a given fraction of traces based of trace id deterministically. */
1379
+ var TraceIdRatioBasedSampler = class {
1380
+ _ratio;
1381
+ _upperBound;
1382
+ constructor(ratio = 0) {
1383
+ this._ratio = this._normalize(ratio);
1384
+ this._upperBound = Math.floor(this._ratio * 4294967295);
1385
+ }
1386
+ shouldSample(context, traceId) {
1387
+ return { decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD };
1388
+ }
1389
+ toString() {
1390
+ return `TraceIdRatioBased{${this._ratio}}`;
1391
+ }
1392
+ _normalize(ratio) {
1393
+ if (typeof ratio !== "number" || isNaN(ratio)) return 0;
1394
+ return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
1395
+ }
1396
+ _accumulate(traceId) {
1397
+ let accumulation = 0;
1398
+ for (let i = 0; i < 32; i += 8) {
1399
+ let part = 0;
1400
+ for (let j = 0; j < 8; j++) {
1401
+ const c = traceId.charCodeAt(i + j);
1402
+ const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;
1403
+ part = part << 4 | v;
1404
+ }
1405
+ accumulation = (accumulation ^ part) >>> 0;
1406
+ }
1407
+ return accumulation;
1408
+ }
1409
+ };
1410
+ //#endregion
1411
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/config.js
1412
+ var TracesSamplerValues;
1413
+ (function(TracesSamplerValues) {
1414
+ TracesSamplerValues["AlwaysOff"] = "always_off";
1415
+ TracesSamplerValues["AlwaysOn"] = "always_on";
1416
+ TracesSamplerValues["ParentBasedAlwaysOff"] = "parentbased_always_off";
1417
+ TracesSamplerValues["ParentBasedAlwaysOn"] = "parentbased_always_on";
1418
+ TracesSamplerValues["ParentBasedTraceIdRatio"] = "parentbased_traceidratio";
1419
+ TracesSamplerValues["TraceIdRatio"] = "traceidratio";
1420
+ })(TracesSamplerValues || (TracesSamplerValues = {}));
1421
+ var DEFAULT_RATIO = 1;
1422
+ /**
1423
+ * Load default configuration. For fields with primitive values, any user-provided
1424
+ * value will override the corresponding default value. For fields with
1425
+ * non-primitive values (like `spanLimits`), the user-provided value will be
1426
+ * used to extend the default value.
1427
+ */
1428
+ function loadDefaultConfig() {
1429
+ return {
1430
+ sampler: buildSamplerFromEnv(),
1431
+ forceFlushTimeoutMillis: 3e4,
1432
+ generalLimits: {
1433
+ attributeValueLengthLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
1434
+ attributeCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128
1435
+ },
1436
+ spanLimits: {
1437
+ attributeValueLengthLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
1438
+ attributeCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128,
1439
+ linkCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128,
1440
+ eventCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128,
1441
+ attributePerEventCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128,
1442
+ attributePerLinkCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128
1443
+ }
1444
+ };
1445
+ }
1446
+ /**
1447
+ * Based on environment, builds a sampler, complies with specification.
1448
+ */
1449
+ function buildSamplerFromEnv() {
1450
+ const sampler = /* @__PURE__ */ getStringFromEnv("OTEL_TRACES_SAMPLER") ?? TracesSamplerValues.ParentBasedAlwaysOn;
1451
+ switch (sampler) {
1452
+ case TracesSamplerValues.AlwaysOn: return new AlwaysOnSampler();
1453
+ case TracesSamplerValues.AlwaysOff: return new AlwaysOffSampler();
1454
+ case TracesSamplerValues.ParentBasedAlwaysOn: return new ParentBasedSampler({ root: new AlwaysOnSampler() });
1455
+ case TracesSamplerValues.ParentBasedAlwaysOff: return new ParentBasedSampler({ root: new AlwaysOffSampler() });
1456
+ case TracesSamplerValues.TraceIdRatio: return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
1457
+ case TracesSamplerValues.ParentBasedTraceIdRatio: return new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()) });
1458
+ default:
1459
+ diag$1.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`);
1460
+ return new ParentBasedSampler({ root: new AlwaysOnSampler() });
1461
+ }
1462
+ }
1463
+ function getSamplerProbabilityFromEnv() {
1464
+ const probability = /* @__PURE__ */ getNumberFromEnv("OTEL_TRACES_SAMPLER_ARG");
1465
+ if (probability == null) {
1466
+ diag$1.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);
1467
+ return DEFAULT_RATIO;
1468
+ }
1469
+ if (probability < 0 || probability > 1) {
1470
+ diag$1.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);
1471
+ return DEFAULT_RATIO;
1472
+ }
1473
+ return probability;
1474
+ }
1475
+ /**
1476
+ * Function to merge Default configuration (as specified in './config') with
1477
+ * user provided configurations.
1478
+ */
1479
+ function mergeConfig(userConfig) {
1480
+ const perInstanceDefaults = { sampler: buildSamplerFromEnv() };
1481
+ const DEFAULT_CONFIG = loadDefaultConfig();
1482
+ const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
1483
+ target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
1484
+ target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
1485
+ return target;
1486
+ }
1487
+ /**
1488
+ * When general limits are provided and model specific limits are not,
1489
+ * configures the model specific limits by using the values from the general ones.
1490
+ * @param userConfig User provided tracer configuration
1491
+ */
1492
+ function reconfigureLimits(userConfig) {
1493
+ const spanLimits = Object.assign({}, userConfig.spanLimits);
1494
+ /**
1495
+ * Reassign span attribute count limit to use first non null value defined by user or use default value
1496
+ */
1497
+ spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128;
1498
+ /**
1499
+ * Reassign span attribute value length limit to use first non null value defined by user or use default value
1500
+ */
1501
+ spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity;
1502
+ return Object.assign({}, userConfig, { spanLimits });
1503
+ }
1504
+ //#endregion
1505
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/export/BatchSpanProcessorBase.js
1506
+ /**
1507
+ * Implementation of the {@link SpanProcessor} that batches spans exported by
1508
+ * the SDK then pushes them to the exporter pipeline.
1509
+ */
1510
+ var BatchSpanProcessorBase = class {
1511
+ _maxExportBatchSize;
1512
+ _maxQueueSize;
1513
+ _scheduledDelayMillis;
1514
+ _exportTimeoutMillis;
1515
+ _exporter;
1516
+ _isExporting = false;
1517
+ _finishedSpans = [];
1518
+ _timer;
1519
+ _shutdownOnce;
1520
+ _droppedSpansCount = 0;
1521
+ constructor(exporter, config) {
1522
+ this._exporter = exporter;
1523
+ this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512;
1524
+ this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048;
1525
+ this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_SCHEDULE_DELAY") ?? 5e3;
1526
+ this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_EXPORT_TIMEOUT") ?? 3e4;
1527
+ this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
1528
+ if (this._maxExportBatchSize > this._maxQueueSize) {
1529
+ diag$1.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
1530
+ this._maxExportBatchSize = this._maxQueueSize;
1531
+ }
1532
+ }
1533
+ forceFlush() {
1534
+ if (this._shutdownOnce.isCalled) return this._shutdownOnce.promise;
1535
+ return this._flushAll();
1536
+ }
1537
+ onStart(_span, _parentContext) {}
1538
+ onEnd(span) {
1539
+ if (this._shutdownOnce.isCalled) return;
1540
+ if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) return;
1541
+ this._addToBuffer(span);
1542
+ }
1543
+ shutdown() {
1544
+ return this._shutdownOnce.call();
1545
+ }
1546
+ _shutdown() {
1547
+ return Promise.resolve().then(() => {
1548
+ return this.onShutdown();
1549
+ }).then(() => {
1550
+ return this._flushAll();
1551
+ }).then(() => {
1552
+ return this._exporter.shutdown();
1553
+ });
1554
+ }
1555
+ /** Add a span in the buffer. */
1556
+ _addToBuffer(span) {
1557
+ if (this._finishedSpans.length >= this._maxQueueSize) {
1558
+ if (this._droppedSpansCount === 0) diag$1.debug("maxQueueSize reached, dropping spans");
1559
+ this._droppedSpansCount++;
1560
+ return;
1561
+ }
1562
+ if (this._droppedSpansCount > 0) {
1563
+ diag$1.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
1564
+ this._droppedSpansCount = 0;
1565
+ }
1566
+ this._finishedSpans.push(span);
1567
+ this._maybeStartTimer();
1568
+ }
1569
+ /**
1570
+ * Send all spans to the exporter respecting the batch size limit
1571
+ * This function is used only on forceFlush or shutdown,
1572
+ * for all other cases _flush should be used
1573
+ * */
1574
+ _flushAll() {
1575
+ return new Promise((resolve, reject) => {
1576
+ const promises = [];
1577
+ const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
1578
+ for (let i = 0, j = count; i < j; i++) promises.push(this._flushOneBatch());
1579
+ Promise.all(promises).then(() => {
1580
+ resolve();
1581
+ }).catch(reject);
1582
+ });
1583
+ }
1584
+ _flushOneBatch() {
1585
+ this._clearTimer();
1586
+ if (this._finishedSpans.length === 0) return Promise.resolve();
1587
+ return new Promise((resolve, reject) => {
1588
+ const timer = setTimeout(() => {
1589
+ reject(/* @__PURE__ */ new Error("Timeout"));
1590
+ }, this._exportTimeoutMillis);
1591
+ context.with(suppressTracing(context.active()), () => {
1592
+ let spans;
1593
+ if (this._finishedSpans.length <= this._maxExportBatchSize) {
1594
+ spans = this._finishedSpans;
1595
+ this._finishedSpans = [];
1596
+ } else spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
1597
+ const doExport = () => this._exporter.export(spans, (result) => {
1598
+ clearTimeout(timer);
1599
+ if (result.code === ExportResultCode.SUCCESS) resolve();
1600
+ else reject(result.error ?? /* @__PURE__ */ new Error("BatchSpanProcessor: span export failed"));
1601
+ });
1602
+ let pendingResources = null;
1603
+ for (let i = 0, len = spans.length; i < len; i++) {
1604
+ const span = spans[i];
1605
+ if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) {
1606
+ pendingResources ??= [];
1607
+ pendingResources.push(span.resource.waitForAsyncAttributes());
1608
+ }
1609
+ }
1610
+ if (pendingResources === null) doExport();
1611
+ else Promise.all(pendingResources).then(doExport, (err) => {
1612
+ globalErrorHandler(err);
1613
+ reject(err);
1614
+ });
1615
+ });
1616
+ });
1617
+ }
1618
+ _maybeStartTimer() {
1619
+ if (this._isExporting) return;
1620
+ const flush = () => {
1621
+ this._isExporting = true;
1622
+ this._flushOneBatch().finally(() => {
1623
+ this._isExporting = false;
1624
+ if (this._finishedSpans.length > 0) {
1625
+ this._clearTimer();
1626
+ this._maybeStartTimer();
1627
+ }
1628
+ }).catch((e) => {
1629
+ this._isExporting = false;
1630
+ globalErrorHandler(e);
1631
+ });
1632
+ };
1633
+ if (this._finishedSpans.length >= this._maxExportBatchSize) return flush();
1634
+ if (this._timer !== void 0) return;
1635
+ this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
1636
+ if (typeof this._timer !== "number") this._timer.unref();
1637
+ }
1638
+ _clearTimer() {
1639
+ if (this._timer !== void 0) {
1640
+ clearTimeout(this._timer);
1641
+ this._timer = void 0;
1642
+ }
1643
+ }
1644
+ };
1645
+ //#endregion
1646
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/browser/export/BatchSpanProcessor.js
1647
+ var BatchSpanProcessor = class extends BatchSpanProcessorBase {
1648
+ _visibilityChangeListener;
1649
+ _pageHideListener;
1650
+ constructor(_exporter, config) {
1651
+ super(_exporter, config);
1652
+ this.onInit(config);
1653
+ }
1654
+ onInit(config) {
1655
+ if (config?.disableAutoFlushOnDocumentHide !== true && typeof document !== "undefined") {
1656
+ this._visibilityChangeListener = () => {
1657
+ if (document.visibilityState === "hidden") this.forceFlush().catch((error) => {
1658
+ globalErrorHandler(error);
1659
+ });
1660
+ };
1661
+ this._pageHideListener = () => {
1662
+ this.forceFlush().catch((error) => {
1663
+ globalErrorHandler(error);
1664
+ });
1665
+ };
1666
+ document.addEventListener("visibilitychange", this._visibilityChangeListener);
1667
+ document.addEventListener("pagehide", this._pageHideListener);
1668
+ }
1669
+ }
1670
+ onShutdown() {
1671
+ if (typeof document !== "undefined") {
1672
+ if (this._visibilityChangeListener) document.removeEventListener("visibilitychange", this._visibilityChangeListener);
1673
+ if (this._pageHideListener) document.removeEventListener("pagehide", this._pageHideListener);
1674
+ }
1675
+ }
1676
+ };
1677
+ //#endregion
1678
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/browser/RandomIdGenerator.js
1679
+ var TRACE_ID_BYTES = 16;
1680
+ var SPAN_ID_BYTES = 8;
1681
+ var TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);
1682
+ var SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);
1683
+ var HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
1684
+ /**
1685
+ * Fills buffer with random bytes, ensuring at least one is non-zero
1686
+ * per W3C Trace Context spec.
1687
+ */
1688
+ function randomFill(buf) {
1689
+ for (let i = 0; i < buf.length; i++) buf[i] = Math.random() * 256 >>> 0;
1690
+ for (let i = 0; i < buf.length; i++) if (buf[i] > 0) return;
1691
+ buf[buf.length - 1] = 1;
1692
+ }
1693
+ function toHex(buf) {
1694
+ let hex = "";
1695
+ for (let i = 0; i < buf.length; i++) hex += HEX[buf[i]];
1696
+ return hex;
1697
+ }
1698
+ var RandomIdGenerator = class {
1699
+ /**
1700
+ * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
1701
+ * characters corresponding to 128 bits.
1702
+ */
1703
+ generateTraceId() {
1704
+ randomFill(TRACE_BUFFER);
1705
+ return toHex(TRACE_BUFFER);
1706
+ }
1707
+ /**
1708
+ * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
1709
+ * characters corresponding to 64 bits.
1710
+ */
1711
+ generateSpanId() {
1712
+ randomFill(SPAN_BUFFER);
1713
+ return toHex(SPAN_BUFFER);
1714
+ }
1715
+ };
1716
+ //#endregion
1717
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/semconv.js
1718
+ /**
1719
+ * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
1720
+ *
1721
+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
1722
+ */
1723
+ var ATTR_OTEL_SPAN_PARENT_ORIGIN = "otel.span.parent.origin";
1724
+ /**
1725
+ * The result value of the sampler for this span
1726
+ *
1727
+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
1728
+ */
1729
+ var ATTR_OTEL_SPAN_SAMPLING_RESULT = "otel.span.sampling_result";
1730
+ /**
1731
+ * The number of created spans with `recording=true` for which the end operation has not been called yet.
1732
+ *
1733
+ * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
1734
+ */
1735
+ var METRIC_OTEL_SDK_SPAN_LIVE = "otel.sdk.span.live";
1736
+ /**
1737
+ * The number of created spans.
1738
+ *
1739
+ * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
1740
+ *
1741
+ * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
1742
+ */
1743
+ var METRIC_OTEL_SDK_SPAN_STARTED = "otel.sdk.span.started";
1744
+ //#endregion
1745
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/TracerMetrics.js
1746
+ /**
1747
+ * Generates `otel.sdk.span.*` metrics.
1748
+ * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
1749
+ */
1750
+ var TracerMetrics = class {
1751
+ startedSpans;
1752
+ liveSpans;
1753
+ constructor(meter) {
1754
+ this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {
1755
+ unit: "{span}",
1756
+ description: "The number of created spans."
1757
+ });
1758
+ this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {
1759
+ unit: "{span}",
1760
+ description: "The number of currently live spans."
1761
+ });
1762
+ }
1763
+ startSpan(parentSpanCtx, samplingDecision) {
1764
+ const samplingDecisionStr = samplingDecisionToString(samplingDecision);
1765
+ this.startedSpans.add(1, {
1766
+ [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
1767
+ [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr
1768
+ });
1769
+ if (samplingDecision === SamplingDecision.NOT_RECORD) return () => {};
1770
+ const liveSpanAttributes = { [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr };
1771
+ this.liveSpans.add(1, liveSpanAttributes);
1772
+ return () => {
1773
+ this.liveSpans.add(-1, liveSpanAttributes);
1774
+ };
1775
+ }
1776
+ };
1777
+ function parentOrigin(parentSpanContext) {
1778
+ if (!parentSpanContext) return "none";
1779
+ if (parentSpanContext.isRemote) return "remote";
1780
+ return "local";
1781
+ }
1782
+ function samplingDecisionToString(decision) {
1783
+ switch (decision) {
1784
+ case SamplingDecision.RECORD_AND_SAMPLED: return "RECORD_AND_SAMPLE";
1785
+ case SamplingDecision.RECORD: return "RECORD_ONLY";
1786
+ case SamplingDecision.NOT_RECORD: return "DROP";
1787
+ }
1788
+ }
1789
+ //#endregion
1790
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js
1791
+ var VERSION = "2.7.1";
1792
+ //#endregion
1793
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/Tracer.js
1794
+ /**
1795
+ * This class represents a basic tracer.
1796
+ */
1797
+ var Tracer = class {
1798
+ _sampler;
1799
+ _generalLimits;
1800
+ _spanLimits;
1801
+ _idGenerator;
1802
+ instrumentationScope;
1803
+ _resource;
1804
+ _spanProcessor;
1805
+ _tracerMetrics;
1806
+ /**
1807
+ * Constructs a new Tracer instance.
1808
+ */
1809
+ constructor(instrumentationScope, config, resource, spanProcessor) {
1810
+ const localConfig = mergeConfig(config);
1811
+ this._sampler = localConfig.sampler;
1812
+ this._generalLimits = localConfig.generalLimits;
1813
+ this._spanLimits = localConfig.spanLimits;
1814
+ this._idGenerator = config.idGenerator || new RandomIdGenerator();
1815
+ this._resource = resource;
1816
+ this._spanProcessor = spanProcessor;
1817
+ this.instrumentationScope = instrumentationScope;
1818
+ const meter = localConfig.meterProvider ? localConfig.meterProvider.getMeter("@opentelemetry/sdk-trace", VERSION) : createNoopMeter();
1819
+ this._tracerMetrics = new TracerMetrics(meter);
1820
+ }
1821
+ /**
1822
+ * Starts a new Span or returns the default NoopSpan based on the sampling
1823
+ * decision.
1824
+ */
1825
+ startSpan(name, options = {}, context$1 = context.active()) {
1826
+ if (options.root) context$1 = trace.deleteSpan(context$1);
1827
+ const parentSpan = trace.getSpan(context$1);
1828
+ if (isTracingSuppressed(context$1)) {
1829
+ diag$1.debug("Instrumentation suppressed, returning Noop Span");
1830
+ return trace.wrapSpanContext(INVALID_SPAN_CONTEXT);
1831
+ }
1832
+ const parentSpanContext = parentSpan?.spanContext();
1833
+ const spanId = this._idGenerator.generateSpanId();
1834
+ let validParentSpanContext;
1835
+ let traceId;
1836
+ let traceState;
1837
+ if (!parentSpanContext || !trace.isSpanContextValid(parentSpanContext)) traceId = this._idGenerator.generateTraceId();
1838
+ else {
1839
+ traceId = parentSpanContext.traceId;
1840
+ traceState = parentSpanContext.traceState;
1841
+ validParentSpanContext = parentSpanContext;
1842
+ }
1843
+ const spanKind = options.kind ?? SpanKind.INTERNAL;
1844
+ const links = (options.links ?? []).map((link) => {
1845
+ return {
1846
+ context: link.context,
1847
+ attributes: sanitizeAttributes(link.attributes)
1848
+ };
1849
+ });
1850
+ const attributes = sanitizeAttributes(options.attributes);
1851
+ const samplingResult = this._sampler.shouldSample(context$1, traceId, name, spanKind, attributes, links);
1852
+ const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);
1853
+ traceState = samplingResult.traceState ?? traceState;
1854
+ const spanContext = {
1855
+ traceId,
1856
+ spanId,
1857
+ traceFlags: samplingResult.decision === SamplingDecision$1.RECORD_AND_SAMPLED ? TraceFlags.SAMPLED : TraceFlags.NONE,
1858
+ traceState
1859
+ };
1860
+ if (samplingResult.decision === SamplingDecision$1.NOT_RECORD) {
1861
+ diag$1.debug("Recording is off, propagating context in a non-recording span");
1862
+ return trace.wrapSpanContext(spanContext);
1863
+ }
1864
+ const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes));
1865
+ return new SpanImpl({
1866
+ resource: this._resource,
1867
+ scope: this.instrumentationScope,
1868
+ context: context$1,
1869
+ spanContext,
1870
+ name,
1871
+ kind: spanKind,
1872
+ links,
1873
+ parentSpanContext: validParentSpanContext,
1874
+ attributes: initAttributes,
1875
+ startTime: options.startTime,
1876
+ spanProcessor: this._spanProcessor,
1877
+ spanLimits: this._spanLimits,
1878
+ recordEndMetrics
1879
+ });
1880
+ }
1881
+ startActiveSpan(name, arg2, arg3, arg4) {
1882
+ let opts;
1883
+ let ctx;
1884
+ let fn;
1885
+ if (arguments.length < 2) return;
1886
+ else if (arguments.length === 2) fn = arg2;
1887
+ else if (arguments.length === 3) {
1888
+ opts = arg2;
1889
+ fn = arg3;
1890
+ } else {
1891
+ opts = arg2;
1892
+ ctx = arg3;
1893
+ fn = arg4;
1894
+ }
1895
+ const parentContext = ctx ?? context.active();
1896
+ const span = this.startSpan(name, opts, parentContext);
1897
+ const contextWithSpanSet = trace.setSpan(parentContext, span);
1898
+ return context.with(contextWithSpanSet, fn, void 0, span);
1899
+ }
1900
+ /** Returns the active {@link GeneralLimits}. */
1901
+ getGeneralLimits() {
1902
+ return this._generalLimits;
1903
+ }
1904
+ /** Returns the active {@link SpanLimits}. */
1905
+ getSpanLimits() {
1906
+ return this._spanLimits;
1907
+ }
1908
+ };
1909
+ //#endregion
1910
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/MultiSpanProcessor.js
1911
+ /**
1912
+ * Implementation of the {@link SpanProcessor} that simply forwards all
1913
+ * received events to a list of {@link SpanProcessor}s.
1914
+ */
1915
+ var MultiSpanProcessor = class {
1916
+ _spanProcessors;
1917
+ constructor(spanProcessors) {
1918
+ this._spanProcessors = spanProcessors;
1919
+ }
1920
+ forceFlush() {
1921
+ const promises = [];
1922
+ for (const spanProcessor of this._spanProcessors) promises.push(spanProcessor.forceFlush());
1923
+ return new Promise((resolve) => {
1924
+ Promise.all(promises).then(() => {
1925
+ resolve();
1926
+ }).catch((error) => {
1927
+ globalErrorHandler(error || /* @__PURE__ */ new Error("MultiSpanProcessor: forceFlush failed"));
1928
+ resolve();
1929
+ });
1930
+ });
1931
+ }
1932
+ onStart(span, context) {
1933
+ for (const spanProcessor of this._spanProcessors) spanProcessor.onStart(span, context);
1934
+ }
1935
+ onEnding(span) {
1936
+ for (const spanProcessor of this._spanProcessors) if (spanProcessor.onEnding) spanProcessor.onEnding(span);
1937
+ }
1938
+ onEnd(span) {
1939
+ for (const spanProcessor of this._spanProcessors) spanProcessor.onEnd(span);
1940
+ }
1941
+ shutdown() {
1942
+ const promises = [];
1943
+ for (const spanProcessor of this._spanProcessors) promises.push(spanProcessor.shutdown());
1944
+ return new Promise((resolve, reject) => {
1945
+ Promise.all(promises).then(() => {
1946
+ resolve();
1947
+ }, reject);
1948
+ });
1949
+ }
1950
+ };
1951
+ //#endregion
1952
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/BasicTracerProvider.js
1953
+ var ForceFlushState;
1954
+ (function(ForceFlushState) {
1955
+ ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
1956
+ ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
1957
+ ForceFlushState[ForceFlushState["error"] = 2] = "error";
1958
+ ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
1959
+ })(ForceFlushState || (ForceFlushState = {}));
1960
+ /**
1961
+ * This class represents a basic tracer provider which platform libraries can extend
1962
+ */
1963
+ var BasicTracerProvider = class {
1964
+ _config;
1965
+ _tracers = /* @__PURE__ */ new Map();
1966
+ _resource;
1967
+ _activeSpanProcessor;
1968
+ constructor(config = {}) {
1969
+ const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
1970
+ this._resource = mergedConfig.resource ?? defaultResource();
1971
+ this._config = Object.assign({}, mergedConfig, { resource: this._resource });
1972
+ const spanProcessors = [];
1973
+ if (config.spanProcessors?.length) spanProcessors.push(...config.spanProcessors);
1974
+ this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);
1975
+ }
1976
+ getTracer(name, version, options) {
1977
+ const key = `${name}@${version || ""}:${options?.schemaUrl || ""}`;
1978
+ if (!this._tracers.has(key)) this._tracers.set(key, new Tracer({
1979
+ name,
1980
+ version,
1981
+ schemaUrl: options?.schemaUrl
1982
+ }, this._config, this._resource, this._activeSpanProcessor));
1983
+ return this._tracers.get(key);
1984
+ }
1985
+ forceFlush() {
1986
+ const timeout = this._config.forceFlushTimeoutMillis;
1987
+ const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
1988
+ return new Promise((resolve) => {
1989
+ let state;
1990
+ const timeoutInterval = setTimeout(() => {
1991
+ resolve(/* @__PURE__ */ new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
1992
+ state = ForceFlushState.timeout;
1993
+ }, timeout);
1994
+ spanProcessor.forceFlush().then(() => {
1995
+ clearTimeout(timeoutInterval);
1996
+ if (state !== ForceFlushState.timeout) {
1997
+ state = ForceFlushState.resolved;
1998
+ resolve(state);
1999
+ }
2000
+ }).catch((error) => {
2001
+ clearTimeout(timeoutInterval);
2002
+ state = ForceFlushState.error;
2003
+ resolve(error);
2004
+ });
2005
+ });
2006
+ });
2007
+ return new Promise((resolve, reject) => {
2008
+ Promise.all(promises).then((results) => {
2009
+ const errors = results.filter((result) => result !== ForceFlushState.resolved);
2010
+ if (errors.length > 0) reject(errors);
2011
+ else resolve();
2012
+ }).catch((error) => reject([error]));
2013
+ });
2014
+ }
2015
+ shutdown() {
2016
+ return this._activeSpanProcessor.shutdown();
2017
+ }
2018
+ };
2019
+ //#endregion
2020
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-web@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-web/build/esm/StackContextManager.js
2021
+ /**
2022
+ * Stack Context Manager for managing the state in web
2023
+ * it doesn't fully support the async calls though
2024
+ */
2025
+ var StackContextManager = class {
2026
+ /**
2027
+ * whether the context manager is enabled or not
2028
+ */
2029
+ _enabled = false;
2030
+ /**
2031
+ * Keeps the reference to current context
2032
+ */
2033
+ _currentContext = ROOT_CONTEXT;
2034
+ /**
2035
+ *
2036
+ * @param context
2037
+ * @param target Function to be executed within the context
2038
+ */
2039
+ _bindFunction(context = ROOT_CONTEXT, target) {
2040
+ const manager = this;
2041
+ const contextWrapper = function(...args) {
2042
+ return manager.with(context, () => target.apply(this, args));
2043
+ };
2044
+ Object.defineProperty(contextWrapper, "length", {
2045
+ enumerable: false,
2046
+ configurable: true,
2047
+ writable: false,
2048
+ value: target.length
2049
+ });
2050
+ return contextWrapper;
2051
+ }
2052
+ /**
2053
+ * Returns the active context
2054
+ */
2055
+ active() {
2056
+ return this._currentContext;
2057
+ }
2058
+ /**
2059
+ * Binds a the certain context or the active one to the target function and then returns the target
2060
+ * @param context A context (span) to be bind to target
2061
+ * @param target a function or event emitter. When target or one of its callbacks is called,
2062
+ * the provided context will be used as the active context for the duration of the call.
2063
+ */
2064
+ bind(context, target) {
2065
+ if (context === void 0) context = this.active();
2066
+ if (typeof target === "function") return this._bindFunction(context, target);
2067
+ return target;
2068
+ }
2069
+ /**
2070
+ * Disable the context manager (clears the current context)
2071
+ */
2072
+ disable() {
2073
+ this._currentContext = ROOT_CONTEXT;
2074
+ this._enabled = false;
2075
+ return this;
2076
+ }
2077
+ /**
2078
+ * Enables the context manager and creates a default(root) context
2079
+ */
2080
+ enable() {
2081
+ if (this._enabled) return this;
2082
+ this._enabled = true;
2083
+ this._currentContext = ROOT_CONTEXT;
2084
+ return this;
2085
+ }
2086
+ /**
2087
+ * Calls the callback function [fn] with the provided [context]. If [context] is undefined then it will use the window.
2088
+ * The context will be set as active
2089
+ * @param context
2090
+ * @param fn Callback function
2091
+ * @param thisArg optional receiver to be used for calling fn
2092
+ * @param args optional arguments forwarded to fn
2093
+ */
2094
+ with(context, fn, thisArg, ...args) {
2095
+ const previousContext = this._currentContext;
2096
+ this._currentContext = context || ROOT_CONTEXT;
2097
+ try {
2098
+ return fn.call(thisArg, ...args);
2099
+ } finally {
2100
+ this._currentContext = previousContext;
2101
+ }
2102
+ }
2103
+ };
2104
+ //#endregion
2105
+ //#region node_modules/.pnpm/@opentelemetry+sdk-trace-web@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-web/build/esm/WebTracerProvider.js
2106
+ function setupContextManager(contextManager) {
2107
+ if (contextManager === null) return;
2108
+ if (contextManager === void 0) {
2109
+ const defaultContextManager = new StackContextManager();
2110
+ defaultContextManager.enable();
2111
+ context.setGlobalContextManager(defaultContextManager);
2112
+ return;
2113
+ }
2114
+ contextManager.enable();
2115
+ context.setGlobalContextManager(contextManager);
2116
+ }
2117
+ function setupPropagator(propagator) {
2118
+ if (propagator === null) return;
2119
+ if (propagator === void 0) {
2120
+ propagation.setGlobalPropagator(new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }));
2121
+ return;
2122
+ }
2123
+ propagation.setGlobalPropagator(propagator);
2124
+ }
2125
+ /**
2126
+ * This class represents a web tracer with {@link StackContextManager}
2127
+ */
2128
+ var WebTracerProvider = class extends BasicTracerProvider {
2129
+ /**
2130
+ * Constructs a new Tracer instance.
2131
+ * @param config Web Tracer config
2132
+ */
2133
+ constructor(config = {}) {
2134
+ super(config);
2135
+ }
2136
+ /**
2137
+ * Register this TracerProvider for use with the OpenTelemetry API.
2138
+ * Undefined values may be replaced with defaults, and
2139
+ * null values will be skipped.
2140
+ *
2141
+ * @param config Configuration object for SDK registration
2142
+ */
2143
+ register(config = {}) {
2144
+ trace.setGlobalTracerProvider(this);
2145
+ setupPropagator(config.propagator);
2146
+ setupContextManager(config.contextManager);
2147
+ }
2148
+ };
2149
+ //#endregion
2150
+ //#region node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.218.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/exporter-trace-otlp-http/build/esm/platform/browser/OTLPTraceExporter.js
2151
+ /**
2152
+ * Collector Trace Exporter for Web
2153
+ */
2154
+ var OTLPTraceExporter = class extends OTLPExporterBase {
2155
+ constructor(config = {}) {
2156
+ super(createLegacyOtlpBrowserExportDelegate(config, JsonTraceSerializer, "v1/traces", { "Content-Type": "application/json" }));
2157
+ }
2158
+ };
2159
+ //#endregion
2160
+ //#region utils/trace-id.ts
2161
+ /**
2162
+ * W3C trace-id / traceparent derivation for the driving-service upstream.
2163
+ *
2164
+ * Kept apart from `otel-trace.ts` so it pulls in no `@opentelemetry` packages:
2165
+ * the WebSocket client stamps a traceparent on every first audio chunk, and it
2166
+ * should not drag the tracer SDK into that path (nor into the unit tests, where
2167
+ * the otel-api ESM build does not resolve cleanly).
2168
+ *
2169
+ * @internal
2170
+ */
2171
+ /**
2172
+ * 把 conversation_id 确定性映射成合法的 W3C trace_id(16 字节 / 32 位十六进制)。
2173
+ *
2174
+ * W3C/OTel 规定 trace_id 必须是 32 hex,而 conversation_id(形如
2175
+ * `20260718110509_4xz9iyH8F3Gi`)不是合法格式,不能直接用。这里用 FNV-1a 以 4 个不同
2176
+ * 初始种子各算一个 32bit 哈希,拼成 128bit —— 同步、确定性(同一 conversation_id 永远
2177
+ * 得同一 trace_id)、无外部依赖,后端可用同一算法复现以串成同一条 trace。
2178
+ * @internal
2179
+ */
2180
+ /** FNV-1a 32-bit with a variable seed, so one string yields several independent hashes. */
2181
+ function fnv1a(str, seed) {
2182
+ let h = seed >>> 0;
2183
+ for (let i = 0; i < str.length; i++) {
2184
+ h ^= str.charCodeAt(i);
2185
+ h = Math.imul(h, 16777619) >>> 0;
2186
+ }
2187
+ return h >>> 0;
2188
+ }
2189
+ function conversationIdToTraceId(conversationId) {
2190
+ const seeds = [
2191
+ 2166136261,
2192
+ 16777619,
2193
+ 3735928559,
2194
+ 2654435769
2195
+ ];
2196
+ let hex = "";
2197
+ for (const s of seeds) hex += fnv1a(conversationId, s).toString(16).padStart(8, "0");
2198
+ return /^0+$/.test(hex) ? "0".repeat(31) + "1" : hex;
2199
+ }
2200
+ /**
2201
+ * Derive the driven.request span_id (8 bytes / 16 hex) deterministically from
2202
+ * the conversation_id.
2203
+ *
2204
+ * The server needs traceparent's parent span_id on the FIRST ClientAudioInput —
2205
+ * before the SDK has built the driven.request span, which only happens when
2206
+ * playback ends and the timeline is known. Deriving it means both moments can
2207
+ * compute the same span_id independently, so the traceparent the server sees and
2208
+ * the span the SDK later reports carry the identical id, with no state threaded
2209
+ * between "audio sent" and "playback ended". Uses seeds distinct from the
2210
+ * trace_id ones so the span_id is not a slice of the trace_id.
2211
+ * @internal
2212
+ */
2213
+ function conversationIdToDrivenSpanId(conversationId) {
2214
+ const hex = fnv1a(conversationId, 3421674724).toString(16).padStart(8, "0") + fnv1a(conversationId, 4294967297).toString(16).padStart(8, "0");
2215
+ return /^0+$/.test(hex) ? "0".repeat(15) + "1" : hex;
2216
+ }
2217
+ /**
2218
+ * Monotonic counter mixed into every generated id. performance.now() barely moves
2219
+ * between spans built in the same millisecond, so on its own it produced COLLIDING
2220
+ * span ids (several recv spans shared one id, breaking the trace tree). The counter
2221
+ * guarantees a distinct seed per call and per hex chunk.
2222
+ */
2223
+ var idCounter = 0;
2224
+ /** A random lowercase-hex string of `len` chars, non-zero. Not for ids that must be reproducible. */
2225
+ function randomHex(len) {
2226
+ let out = "";
2227
+ while (out.length < len) {
2228
+ idCounter = idCounter + 1 >>> 0;
2229
+ const seed = ((performance.now() * 1e6 | 0) ^ Math.imul(idCounter, 2654435769)) >>> 0;
2230
+ const n = Math.imul(seed, 2246822507) >>> 0;
2231
+ out += n.toString(16).padStart(8, "0");
2232
+ }
2233
+ const hex = out.slice(0, len);
2234
+ return /^0+$/.test(hex) ? "0".repeat(len - 1) + "1" : hex;
2235
+ }
2236
+ /**
2237
+ * OTel IdGenerator that lets one span be given a specific id — the officially
2238
+ * supported way to control a span_id, versus reaching into span internals.
2239
+ *
2240
+ * driven.request must carry the exact span_id already placed in the first
2241
+ * ClientAudioInput's traceparent, so the server's audio.process (parent = that
2242
+ * id) hangs under the SDK's real span. Set `nextSpanId` right before startSpan;
2243
+ * the generator hands it out once, then falls back to random for every other
2244
+ * span (whose ids need not be predictable).
2245
+ *
2246
+ * Deliberately dependency-free (no `implements IdGenerator`) so this module pulls
2247
+ * in no @opentelemetry package; it duck-types the two-method interface.
2248
+ * @internal
2249
+ */
2250
+ var PinnableIdGenerator = class {
2251
+ nextSpanId = null;
2252
+ generateTraceId() {
2253
+ return randomHex(32);
2254
+ }
2255
+ generateSpanId() {
2256
+ if (this.nextSpanId) {
2257
+ const id = this.nextSpanId;
2258
+ this.nextSpanId = null;
2259
+ return id;
2260
+ }
2261
+ return randomHex(16);
2262
+ }
2263
+ };
2264
+ /**
2265
+ * Build the W3C `traceparent` for a conversation's upstream audio, to hand the
2266
+ * driving service on the first ClientAudioInput of each req_id so its trace
2267
+ * continues this SDK's rather than starting a fresh root.
2268
+ *
2269
+ * Both ids are DERIVED from the conversation_id, matching what the playback
2270
+ * trace builds when it ends: the trace_id so the server's trace and the SDK's
2271
+ * spans share one trace, and the span_id so it equals the driven.request span's
2272
+ * id — which the server hangs audio.process under. Deriving both means the
2273
+ * traceparent sent now and the span reported later carry the identical ids with
2274
+ * no state threaded between them.
2275
+ *
2276
+ * Returns null when tracing is disabled or filtered, so callers simply omit the
2277
+ * field — matching the proto's "absent → server starts a new root" contract.
2278
+ *
2279
+ * @internal
2280
+ */
2281
+ function buildTraceparent(conversationId) {
2282
+ if (!conversationId) return null;
2283
+ return `00-${conversationIdToTraceId(conversationId)}-${conversationIdToDrivenSpanId(conversationId)}-01`;
2284
+ }
2285
+ //#endregion
2286
+ //#region utils/otel-trace.ts
2287
+ /**
2288
+ * OpenTelemetry Trace Tracker (Browser Version)
2289
+ *
2290
+ * 独立于 logs / metrics 的第三条 OTel 通道——**Trace 信号**(OTLP `/v1/traces`),
2291
+ * 目标后端 OpenObserve。与另两条通道分离:各自 provider、各自 exporter、各自清理。
2292
+ *
2293
+ * 用途:一轮播放 = 一条 trace。root span 覆盖整轮,子 span 标记关键时刻
2294
+ * (首包音频到达 / 首组动画到达 / 播放结束)。trace_id 由 conversation_id 确定性
2295
+ * 派生(见 conversationIdToTraceId),使 SDK 与后端能以同一 conversation_id 关联/串联。
2296
+ * @internal
2297
+ */
2298
+ var OTEL_TRACER_NAME = "spatius-avatarkit";
2299
+ var sdkVersion = "1.0.0";
2300
+ var isInitialized = false;
2301
+ var tracerProvider = null;
2302
+ var tracer = null;
2303
+ var idGenerator = new PinnableIdGenerator();
2304
+ function buildBasicAuthHeader() {
2305
+ const credentials = `${OTEL_USERNAME}:${OTEL_PASSWORD}`;
2306
+ return `Basic ${btoa(credentials)}`;
2307
+ }
2308
+ /**
2309
+ * Initialize OTel TracerProvider.
2310
+ * 与 logs / metrics 平行:同一份 resource 语义、同一套门禁与鉴权。
2311
+ * @internal
2312
+ */
2313
+ function initializeOtelTrace(version, resourceAttrs) {
2314
+ if (isInitialized) {
2315
+ logger.log("[OTel-Trace] Already initialized, skipping");
2316
+ return;
2317
+ }
2318
+ if ("wangruizhen@spatialwalk.net".startsWith("<TODO"), "spatialwalk".startsWith("<TODO"));
2319
+ sdkVersion = version;
2320
+ try {
2321
+ tracerProvider = new WebTracerProvider({
2322
+ resource: resourceFromAttributes({
2323
+ [ATTR_SERVICE_NAME]: "avatarkit",
2324
+ "sdk.version": sdkVersion,
2325
+ "sdk.platform": "web",
2326
+ "sdk.package": "spatius-web-sdk",
2327
+ "app_id": resourceAttrs.appId || "",
2328
+ "region": resourceAttrs.region,
2329
+ "dsm": resourceAttrs.dsm,
2330
+ ...clientContextFields()
2331
+ }),
2332
+ spanProcessors: [new BatchSpanProcessor(observeExporter(new OTLPTraceExporter({
2333
+ url: OTEL_TRACES_ENDPOINT,
2334
+ headers: {
2335
+ "Authorization": buildBasicAuthHeader(),
2336
+ "stream-name": OTEL_TRACES_STREAM_NAME
2337
+ }
2338
+ }), "/v1/traces", OTEL_TRACES_ENDPOINT))],
2339
+ idGenerator
2340
+ });
2341
+ trace.setGlobalTracerProvider(tracerProvider);
2342
+ tracer = trace.getTracer(OTEL_TRACER_NAME, sdkVersion);
2343
+ isInitialized = true;
2344
+ logger.log(`[OTel-Trace] Initialized - endpoint: ${OTEL_TRACES_ENDPOINT}, stream: ${OTEL_TRACES_STREAM_NAME}`);
2345
+ } catch (error) {
2346
+ logger.warn("[OTel-Trace] Failed to initialize:", error instanceof Error ? error.message : String(error));
2347
+ }
2348
+ }
2349
+ /** 空实现:未初始化 / 被门禁拦截时返回,调用方无需判空。 */
2350
+ var NOOP_GROUP = {
2351
+ span: () => {},
2352
+ end: () => {}
2353
+ };
2354
+ var NOOP_TRACE = {
2355
+ span: () => {},
2356
+ group: () => NOOP_GROUP,
2357
+ end: () => {}
2358
+ };
2359
+ /**
2360
+ * 开一条**加载角色**的 trace。root span 名 `load_avatar`,覆盖 `AvatarManager` 加载
2361
+ * 全过程,内部按四段切子 span(见调用处)。
2362
+ *
2363
+ * 与播放 trace 的两点不同:
2364
+ * - **trace_id 随机**,不从业务 id 派生。加载链路上后端只参与元数据接口一处,串联需求
2365
+ * 弱;而按 avatar_id 派生会让同一角色的多次加载撞进同一条 trace,在 viewer 里叠成
2366
+ * 一条、时间轴错乱。avatar_id 作 span 属性照样能筛。
2367
+ * - **无 anchor / 不钉 span_id**:那两样是为了匹配已在线上的 traceparent,加载没有这个约束。
2368
+ *
2369
+ * 量级上远小于播放 trace:一次会话通常只加载一次角色,而对话是几十轮。
2370
+ * @internal
2371
+ */
2372
+ /**
2373
+ * 开一条 **SDK 初始化** 的 trace。root span 名 `sdk_init`。
2374
+ *
2375
+ * 与 load / playback 是三条**独立** trace:它们本就是独立流程(初始化一次、加载可多次、
2376
+ * 对话更多次),硬串成一条会得到横跨整个 app 生命周期的怪 waterfall。三者靠 `session_id`
2377
+ * 关联——后台按它一查就能还原「这次启动做了什么」。
2378
+ *
2379
+ * 注意调用时机:trace 通道本身要到 `initializeOtelTrace` 之后才就绪,所以初始化早期
2380
+ * 阶段(region 解析等)只能先记时刻、等通道起来再用历史时间戳补发 span。
2381
+ * @internal
2382
+ */
2383
+ function startInitTrace(sessionId, startTimeMs, attrs = {}) {
2384
+ if (!tracer || !tracerProvider) return NOOP_TRACE;
2385
+ try {
2386
+ const root = tracer.startSpan("sdk_init", {
2387
+ startTime: startTimeMs,
2388
+ attributes: {
2389
+ session_id: sessionId,
2390
+ ...attrs
2391
+ }
2392
+ }, ROOT_CONTEXT);
2393
+ const rootCtx = trace.setSpan(ROOT_CONTEXT, root);
2394
+ return {
2395
+ span(name, startMs, endMs, spanAttrs = {}, isError = false) {
2396
+ try {
2397
+ const sp = tracer.startSpan(name, {
2398
+ startTime: startMs,
2399
+ attributes: spanAttrs
2400
+ }, rootCtx);
2401
+ if (isError) sp.setStatus({ code: SpanStatusCode.ERROR });
2402
+ sp.end(endMs);
2403
+ } catch {}
2404
+ },
2405
+ group: () => NOOP_GROUP,
2406
+ end(ok = true, endTimeMs, endAttrs = {}) {
2407
+ try {
2408
+ for (const [k, v] of Object.entries(endAttrs)) root.setAttribute(k, v);
2409
+ root.setStatus({ code: ok ? SpanStatusCode.OK : SpanStatusCode.ERROR });
2410
+ root.end(endTimeMs);
2411
+ } catch {}
2412
+ }
2413
+ };
2414
+ } catch (error) {
2415
+ logger.warn("[OTel-Trace] Failed to start init trace:", error instanceof Error ? error.message : String(error));
2416
+ return NOOP_TRACE;
2417
+ }
2418
+ }
2419
+ function startLoadTrace(avatarId, startTimeMs, attrs = {}) {
2420
+ if (!tracer || !tracerProvider) return NOOP_TRACE;
2421
+ try {
2422
+ const root = tracer.startSpan("load_avatar", {
2423
+ startTime: startTimeMs,
2424
+ attributes: {
2425
+ avatar_id: avatarId,
2426
+ session_id: idManager.getSessionId(),
2427
+ ...attrs
2428
+ }
2429
+ }, ROOT_CONTEXT);
2430
+ const rootCtx = trace.setSpan(ROOT_CONTEXT, root);
2431
+ return {
2432
+ span(name, startMs, endMs, spanAttrs = {}, isError = false) {
2433
+ try {
2434
+ const s = tracer.startSpan(name, {
2435
+ startTime: startMs,
2436
+ attributes: spanAttrs
2437
+ }, rootCtx);
2438
+ if (isError) s.setStatus({ code: SpanStatusCode.ERROR });
2439
+ s.end(endMs);
2440
+ } catch {}
2441
+ },
2442
+ group: () => NOOP_GROUP,
2443
+ end(ok = true, endTimeMs, endAttrs = {}) {
2444
+ try {
2445
+ for (const [k, v] of Object.entries(endAttrs)) root.setAttribute(k, v);
2446
+ root.setStatus({ code: ok ? SpanStatusCode.OK : SpanStatusCode.ERROR });
2447
+ root.end(endTimeMs);
2448
+ } catch {}
2449
+ }
2450
+ };
2451
+ } catch (error) {
2452
+ logger.warn("[OTel-Trace] Failed to start load trace:", error instanceof Error ? error.message : String(error));
2453
+ return NOOP_TRACE;
2454
+ }
2455
+ }
2456
+ /**
2457
+ * 开一条播放 trace。root span 名 `playback`,trace_id 由 conversation_id 确定性派生,
2458
+ * conversation_id 同时作为 span 属性(无论是否与后端串成一条 trace,都能按它关联查询)。
2459
+ * @param startTimeMs root span 起点(首包音频 tap_0 的真实时刻,epoch ms);省略则用当前时刻。
2460
+ * @internal
2461
+ */
2462
+ function startPlaybackTrace(conversationId, startTimeMs, attrs = {}) {
2463
+ if (!tracer || !tracerProvider) return NOOP_TRACE;
2464
+ if (!conversationId) return NOOP_TRACE;
2465
+ try {
2466
+ const traceId = conversationIdToTraceId(conversationId);
2467
+ const drivenSpanId = conversationIdToDrivenSpanId(conversationId);
2468
+ const traceRootCtx = trace.setSpanContext(ROOT_CONTEXT, {
2469
+ traceId,
2470
+ spanId: randomHex(16),
2471
+ traceFlags: 1,
2472
+ isRemote: true
2473
+ });
2474
+ idGenerator.nextSpanId = drivenSpanId;
2475
+ const drivenRequest = tracer.startSpan("driven.request", {
2476
+ attributes: {
2477
+ conversation_id: conversationId,
2478
+ session_id: idManager.getSessionId(),
2479
+ ...attrs
2480
+ },
2481
+ ...typeof startTimeMs === "number" ? { startTime: startTimeMs } : {}
2482
+ }, traceRootCtx);
2483
+ const drivenCtx = trace.setSpan(traceRootCtx, drivenRequest);
2484
+ const root = tracer.startSpan("playback", {
2485
+ attributes: {
2486
+ conversation_id: conversationId,
2487
+ session_id: idManager.getSessionId(),
2488
+ ...attrs
2489
+ },
2490
+ ...typeof startTimeMs === "number" ? { startTime: startTimeMs } : {}
2491
+ }, drivenCtx);
2492
+ const rootCtx = trace.setSpan(drivenCtx, root);
2493
+ const emitSpan = (ctx, name, startMs, endMs, attrs, isError = false) => {
2494
+ try {
2495
+ const s = tracer.startSpan(name, {
2496
+ attributes: attrs,
2497
+ startTime: startMs
2498
+ }, ctx);
2499
+ if (isError) s.setStatus({ code: SpanStatusCode.ERROR });
2500
+ s.end(endMs);
2501
+ } catch {}
2502
+ };
2503
+ return {
2504
+ span(name, startMs, endMs, spanAttrs = {}, isError = false) {
2505
+ emitSpan(rootCtx, name, startMs, endMs, spanAttrs, isError);
2506
+ },
2507
+ group(name, startMs, groupAttrs = {}) {
2508
+ try {
2509
+ const container = tracer.startSpan(name, {
2510
+ attributes: groupAttrs,
2511
+ startTime: startMs
2512
+ }, rootCtx);
2513
+ const groupCtx = trace.setSpan(rootCtx, container);
2514
+ return {
2515
+ span(spanName, s, e, attrs = {}, isError = false) {
2516
+ emitSpan(groupCtx, spanName, s, e, attrs, isError);
2517
+ },
2518
+ end(endMs) {
2519
+ try {
2520
+ container.end(endMs);
2521
+ } catch {}
2522
+ }
2523
+ };
2524
+ } catch {
2525
+ return NOOP_GROUP;
2526
+ }
2527
+ },
2528
+ end(ok = true, endTimeMs, endAttrs = {}) {
2529
+ try {
2530
+ for (const [k, v] of Object.entries(endAttrs)) root.setAttribute(k, v);
2531
+ const status = { code: ok ? SpanStatusCode.OK : SpanStatusCode.ERROR };
2532
+ root.setStatus(status);
2533
+ root.end(endTimeMs);
2534
+ drivenRequest.setStatus(status);
2535
+ drivenRequest.end(endTimeMs);
2536
+ tracerProvider?.forceFlush().catch(() => {});
2537
+ } catch {}
2538
+ }
2539
+ };
2540
+ } catch (error) {
2541
+ logger.warn("[OTel-Trace] Failed to start playback trace:", error instanceof Error ? error.message : String(error));
2542
+ return NOOP_TRACE;
2543
+ }
2544
+ }
2545
+ /**
2546
+ * Cleanup:flush 剩余 span 并关闭 provider。
2547
+ * @internal
2548
+ */
2549
+ function cleanupOtelTrace() {
2550
+ if (!isInitialized || !tracerProvider) return;
2551
+ try {
2552
+ tracerProvider.forceFlush().catch(() => {});
2553
+ tracerProvider.shutdown().catch((error) => {
2554
+ logger.warn("[OTel-Trace] Shutdown error:", error instanceof Error ? error.message : String(error));
2555
+ });
2556
+ } catch (error) {
2557
+ logger.warn("[OTel-Trace] Failed to cleanup:", error instanceof Error ? error.message : String(error));
2558
+ } finally {
2559
+ isInitialized = false;
2560
+ tracerProvider = null;
2561
+ tracer = null;
2562
+ }
2563
+ }
2564
+ //#endregion
2565
+ export { startPlaybackTrace as a, startLoadTrace as i, initializeOtelTrace as n, buildTraceparent as o, startInitTrace as r, cleanupOtelTrace as t };