@superblocksteam/library 2.0.26-next.2 → 2.0.26-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/dist/{allPaths-Cq-VDMuE.js → allPaths-BH4QocdC.js} +2 -2
  2. package/dist/{allPaths-Cq-VDMuE.js.map → allPaths-BH4QocdC.js.map} +1 -1
  3. package/dist/{allPaths-BFxE5B4h.js → allPaths-DmzVJVki.js} +2 -2
  4. package/dist/{allPaths-BFxE5B4h.js.map → allPaths-DmzVJVki.js.map} +1 -1
  5. package/dist/{allPathsLoader-BVd-S-Oq.js → allPathsLoader-DjISPY6j.js} +3 -3
  6. package/dist/{allPathsLoader-BVd-S-Oq.js.map → allPathsLoader-DjISPY6j.js.map} +1 -1
  7. package/dist/{allPathsLoader-DHqQ5Hkd.js → allPathsLoader-MU08k0t1.js} +3 -3
  8. package/dist/{allPathsLoader-DHqQ5Hkd.js.map → allPathsLoader-MU08k0t1.js.map} +1 -1
  9. package/dist/{devtools-consolidated-CjCnNEcm.js → devtools-consolidated-D63syp5s.js} +2 -2
  10. package/dist/{devtools-consolidated-CjCnNEcm.js.map → devtools-consolidated-D63syp5s.js.map} +1 -1
  11. package/dist/{index-BwWQ4Y3z.js → index-CdGno8TV.js} +692 -395
  12. package/dist/{index-BwWQ4Y3z.js.map → index-CdGno8TV.js.map} +1 -1
  13. package/dist/index.js +173 -173
  14. package/dist/logs-DWaPDDub.js +1475 -0
  15. package/dist/logs-DWaPDDub.js.map +1 -0
  16. package/dist/{splitPathsBySizeLoader-BP8OnaVl.js → splitPathsBySizeLoader-Ck8EBLzY.js} +2 -2
  17. package/dist/{splitPathsBySizeLoader-BP8OnaVl.js.map → splitPathsBySizeLoader-Ck8EBLzY.js.map} +1 -1
  18. package/dist/{splitPathsBySizeLoader-BS5wVBk9.js → splitPathsBySizeLoader-D4nBh9zt.js} +2 -2
  19. package/dist/{splitPathsBySizeLoader-BS5wVBk9.js.map → splitPathsBySizeLoader-D4nBh9zt.js.map} +1 -1
  20. package/dist-types/lib/tracing/early-console-buffer.d.ts +21 -0
  21. package/dist-types/lib/tracing/logs.d.ts +11 -0
  22. package/package.json +6 -3
@@ -0,0 +1,1475 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ import { c as createContextKey, d as diag, a as context, t as trace, i as isSpanContextValid, b as defaultResource, r as resourceFromAttributes, L as LibraryEarlyConsoleBuffer, A as ATTR_SERVICE_NAME } from "./index-CdGno8TV.js";
5
+ class NoopLogger {
6
+ emit(_logRecord) {
7
+ }
8
+ }
9
+ const NOOP_LOGGER = new NoopLogger();
10
+ const SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
11
+ function suppressTracing(context2) {
12
+ return context2.setValue(SUPPRESS_TRACING_KEY, true);
13
+ }
14
+ function isAttributeValue(val) {
15
+ if (val == null) {
16
+ return true;
17
+ }
18
+ if (Array.isArray(val)) {
19
+ return isHomogeneousAttributeValueArray(val);
20
+ }
21
+ return isValidPrimitiveAttributeValue(val);
22
+ }
23
+ function isHomogeneousAttributeValueArray(arr) {
24
+ let type;
25
+ for (const element of arr) {
26
+ if (element == null)
27
+ continue;
28
+ if (!type) {
29
+ if (isValidPrimitiveAttributeValue(element)) {
30
+ type = typeof element;
31
+ continue;
32
+ }
33
+ return false;
34
+ }
35
+ if (typeof element === type) {
36
+ continue;
37
+ }
38
+ return false;
39
+ }
40
+ return true;
41
+ }
42
+ function isValidPrimitiveAttributeValue(val) {
43
+ switch (typeof val) {
44
+ case "number":
45
+ case "boolean":
46
+ case "string":
47
+ return true;
48
+ }
49
+ return false;
50
+ }
51
+ function loggingErrorHandler() {
52
+ return (ex) => {
53
+ diag.error(stringifyException(ex));
54
+ };
55
+ }
56
+ function stringifyException(ex) {
57
+ if (typeof ex === "string") {
58
+ return ex;
59
+ } else {
60
+ return JSON.stringify(flattenException(ex));
61
+ }
62
+ }
63
+ function flattenException(ex) {
64
+ const result = {};
65
+ let current = ex;
66
+ while (current !== null) {
67
+ Object.getOwnPropertyNames(current).forEach((propertyName) => {
68
+ if (result[propertyName])
69
+ return;
70
+ const value = current[propertyName];
71
+ if (value) {
72
+ result[propertyName] = String(value);
73
+ }
74
+ });
75
+ current = Object.getPrototypeOf(current);
76
+ }
77
+ return result;
78
+ }
79
+ let delegateHandler = loggingErrorHandler();
80
+ function globalErrorHandler(ex) {
81
+ try {
82
+ delegateHandler(ex);
83
+ } catch {
84
+ }
85
+ }
86
+ function getNumberFromEnv(_) {
87
+ return void 0;
88
+ }
89
+ const otperformance = performance;
90
+ function unrefTimer(_timer) {
91
+ }
92
+ const NANOSECOND_DIGITS = 9;
93
+ const NANOSECOND_DIGITS_IN_MILLIS = 6;
94
+ const MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
95
+ const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
96
+ function millisToHrTime(epochMillis) {
97
+ const epochSeconds = epochMillis / 1e3;
98
+ const seconds = Math.trunc(epochSeconds);
99
+ const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
100
+ return [seconds, nanos];
101
+ }
102
+ function getTimeOrigin() {
103
+ let timeOrigin = otperformance.timeOrigin;
104
+ if (typeof timeOrigin !== "number") {
105
+ const perf = otperformance;
106
+ timeOrigin = perf.timing && perf.timing.fetchStart;
107
+ }
108
+ return timeOrigin;
109
+ }
110
+ function hrTime(performanceNow) {
111
+ const timeOrigin = millisToHrTime(getTimeOrigin());
112
+ const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : otperformance.now());
113
+ return addHrTimes(timeOrigin, now);
114
+ }
115
+ function timeInputToHrTime(time) {
116
+ if (isTimeInputHrTime(time)) {
117
+ return time;
118
+ } else if (typeof time === "number") {
119
+ if (time < getTimeOrigin()) {
120
+ return hrTime(time);
121
+ } else {
122
+ return millisToHrTime(time);
123
+ }
124
+ } else if (time instanceof Date) {
125
+ return millisToHrTime(time.getTime());
126
+ } else {
127
+ throw TypeError("Invalid input type");
128
+ }
129
+ }
130
+ function hrTimeToNanoseconds(time) {
131
+ return time[0] * SECOND_TO_NANOSECONDS + time[1];
132
+ }
133
+ function isTimeInputHrTime(value) {
134
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number";
135
+ }
136
+ function addHrTimes(time1, time2) {
137
+ const out = [time1[0] + time2[0], time1[1] + time2[1]];
138
+ if (out[1] >= SECOND_TO_NANOSECONDS) {
139
+ out[1] -= SECOND_TO_NANOSECONDS;
140
+ out[0] += 1;
141
+ }
142
+ return out;
143
+ }
144
+ var ExportResultCode;
145
+ (function(ExportResultCode2) {
146
+ ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
147
+ ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
148
+ })(ExportResultCode || (ExportResultCode = {}));
149
+ const objectTag = "[object Object]";
150
+ const nullTag = "[object Null]";
151
+ const undefinedTag = "[object Undefined]";
152
+ const funcProto = Function.prototype;
153
+ const funcToString = funcProto.toString;
154
+ const objectCtorString = funcToString.call(Object);
155
+ const getPrototypeOf = Object.getPrototypeOf;
156
+ const objectProto = Object.prototype;
157
+ const hasOwnProperty = objectProto.hasOwnProperty;
158
+ const symToStringTag = Symbol ? Symbol.toStringTag : void 0;
159
+ const nativeObjectToString = objectProto.toString;
160
+ function isPlainObject(value) {
161
+ if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {
162
+ return false;
163
+ }
164
+ const proto = getPrototypeOf(value);
165
+ if (proto === null) {
166
+ return true;
167
+ }
168
+ const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
169
+ return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString;
170
+ }
171
+ function isObjectLike(value) {
172
+ return value != null && typeof value == "object";
173
+ }
174
+ function baseGetTag(value) {
175
+ if (value == null) {
176
+ return value === void 0 ? undefinedTag : nullTag;
177
+ }
178
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
179
+ }
180
+ function getRawTag(value) {
181
+ const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
182
+ let unmasked = false;
183
+ try {
184
+ value[symToStringTag] = void 0;
185
+ unmasked = true;
186
+ } catch (e) {
187
+ }
188
+ const result = nativeObjectToString.call(value);
189
+ if (unmasked) {
190
+ if (isOwn) {
191
+ value[symToStringTag] = tag;
192
+ } else {
193
+ delete value[symToStringTag];
194
+ }
195
+ }
196
+ return result;
197
+ }
198
+ function objectToString(value) {
199
+ return nativeObjectToString.call(value);
200
+ }
201
+ const MAX_LEVEL = 20;
202
+ function merge(...args) {
203
+ let result = args.shift();
204
+ const objects = /* @__PURE__ */ new WeakMap();
205
+ while (args.length > 0) {
206
+ result = mergeTwoObjects(result, args.shift(), 0, objects);
207
+ }
208
+ return result;
209
+ }
210
+ function takeValue(value) {
211
+ if (isArray(value)) {
212
+ return value.slice();
213
+ }
214
+ return value;
215
+ }
216
+ function mergeTwoObjects(one, two, level = 0, objects) {
217
+ let result;
218
+ if (level > MAX_LEVEL) {
219
+ return void 0;
220
+ }
221
+ level++;
222
+ if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {
223
+ result = takeValue(two);
224
+ } else if (isArray(one)) {
225
+ result = one.slice();
226
+ if (isArray(two)) {
227
+ for (let i = 0, j = two.length; i < j; i++) {
228
+ result.push(takeValue(two[i]));
229
+ }
230
+ } else if (isObject(two)) {
231
+ const keys = Object.keys(two);
232
+ for (let i = 0, j = keys.length; i < j; i++) {
233
+ const key = keys[i];
234
+ result[key] = takeValue(two[key]);
235
+ }
236
+ }
237
+ } else if (isObject(one)) {
238
+ if (isObject(two)) {
239
+ if (!shouldMerge(one, two)) {
240
+ return two;
241
+ }
242
+ result = Object.assign({}, one);
243
+ const keys = Object.keys(two);
244
+ for (let i = 0, j = keys.length; i < j; i++) {
245
+ const key = keys[i];
246
+ const twoValue = two[key];
247
+ if (isPrimitive(twoValue)) {
248
+ if (typeof twoValue === "undefined") {
249
+ delete result[key];
250
+ } else {
251
+ result[key] = twoValue;
252
+ }
253
+ } else {
254
+ const obj1 = result[key];
255
+ const obj2 = twoValue;
256
+ if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) {
257
+ delete result[key];
258
+ } else {
259
+ if (isObject(obj1) && isObject(obj2)) {
260
+ const arr1 = objects.get(obj1) || [];
261
+ const arr2 = objects.get(obj2) || [];
262
+ arr1.push({ obj: one, key });
263
+ arr2.push({ obj: two, key });
264
+ objects.set(obj1, arr1);
265
+ objects.set(obj2, arr2);
266
+ }
267
+ result[key] = mergeTwoObjects(result[key], twoValue, level, objects);
268
+ }
269
+ }
270
+ }
271
+ } else {
272
+ result = two;
273
+ }
274
+ }
275
+ return result;
276
+ }
277
+ function wasObjectReferenced(obj, key, objects) {
278
+ const arr = objects.get(obj[key]) || [];
279
+ for (let i = 0, j = arr.length; i < j; i++) {
280
+ const info = arr[i];
281
+ if (info.key === key && info.obj === obj) {
282
+ return true;
283
+ }
284
+ }
285
+ return false;
286
+ }
287
+ function isArray(value) {
288
+ return Array.isArray(value);
289
+ }
290
+ function isFunction(value) {
291
+ return typeof value === "function";
292
+ }
293
+ function isObject(value) {
294
+ return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object";
295
+ }
296
+ function isPrimitive(value) {
297
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
298
+ }
299
+ function shouldMerge(one, two) {
300
+ if (!isPlainObject(one) || !isPlainObject(two)) {
301
+ return false;
302
+ }
303
+ return true;
304
+ }
305
+ class TimeoutError extends Error {
306
+ constructor(message) {
307
+ super(message);
308
+ Object.setPrototypeOf(this, TimeoutError.prototype);
309
+ }
310
+ }
311
+ function callWithTimeout(promise, timeout) {
312
+ let timeoutHandle;
313
+ const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) {
314
+ timeoutHandle = setTimeout(function timeoutHandler() {
315
+ reject(new TimeoutError("Operation timed out."));
316
+ }, timeout);
317
+ });
318
+ return Promise.race([promise, timeoutPromise]).then((result) => {
319
+ clearTimeout(timeoutHandle);
320
+ return result;
321
+ }, (reason) => {
322
+ clearTimeout(timeoutHandle);
323
+ throw reason;
324
+ });
325
+ }
326
+ class Deferred {
327
+ constructor() {
328
+ __publicField(this, "_promise");
329
+ __publicField(this, "_resolve");
330
+ __publicField(this, "_reject");
331
+ this._promise = new Promise((resolve, reject) => {
332
+ this._resolve = resolve;
333
+ this._reject = reject;
334
+ });
335
+ }
336
+ get promise() {
337
+ return this._promise;
338
+ }
339
+ resolve(val) {
340
+ this._resolve(val);
341
+ }
342
+ reject(err) {
343
+ this._reject(err);
344
+ }
345
+ }
346
+ class BindOnceFuture {
347
+ constructor(_callback, _that) {
348
+ __publicField(this, "_callback");
349
+ __publicField(this, "_that");
350
+ __publicField(this, "_isCalled", false);
351
+ __publicField(this, "_deferred", new Deferred());
352
+ this._callback = _callback;
353
+ this._that = _that;
354
+ }
355
+ get isCalled() {
356
+ return this._isCalled;
357
+ }
358
+ get promise() {
359
+ return this._deferred.promise;
360
+ }
361
+ call(...args) {
362
+ if (!this._isCalled) {
363
+ this._isCalled = true;
364
+ try {
365
+ Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err));
366
+ } catch (err) {
367
+ this._deferred.reject(err);
368
+ }
369
+ }
370
+ return this._deferred.promise;
371
+ }
372
+ }
373
+ function _export(exporter, arg) {
374
+ return new Promise((resolve) => {
375
+ context.with(suppressTracing(context.active()), () => {
376
+ exporter.export(arg, (result) => {
377
+ resolve(result);
378
+ });
379
+ });
380
+ });
381
+ }
382
+ const internal = {
383
+ _export
384
+ };
385
+ class OTLPExporterBase {
386
+ constructor(_delegate) {
387
+ __publicField(this, "_delegate");
388
+ this._delegate = _delegate;
389
+ }
390
+ /**
391
+ * Export items.
392
+ * @param items
393
+ * @param resultCallback
394
+ */
395
+ export(items, resultCallback) {
396
+ this._delegate.export(items, resultCallback);
397
+ }
398
+ forceFlush() {
399
+ return this._delegate.forceFlush();
400
+ }
401
+ shutdown() {
402
+ return this._delegate.shutdown();
403
+ }
404
+ }
405
+ class OTLPExporterError extends Error {
406
+ constructor(message, code, data) {
407
+ super(message);
408
+ __publicField(this, "code");
409
+ __publicField(this, "name", "OTLPExporterError");
410
+ __publicField(this, "data");
411
+ this.data = data;
412
+ this.code = code;
413
+ }
414
+ }
415
+ function validateTimeoutMillis(timeoutMillis) {
416
+ if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {
417
+ return timeoutMillis;
418
+ }
419
+ throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`);
420
+ }
421
+ function wrapStaticHeadersInFunction(headers) {
422
+ if (headers == null) {
423
+ return void 0;
424
+ }
425
+ return () => headers;
426
+ }
427
+ function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
428
+ return {
429
+ timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? fallbackConfiguration.timeoutMillis ?? defaultConfiguration.timeoutMillis),
430
+ concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? fallbackConfiguration.concurrencyLimit ?? defaultConfiguration.concurrencyLimit,
431
+ compression: userProvidedConfiguration.compression ?? fallbackConfiguration.compression ?? defaultConfiguration.compression
432
+ };
433
+ }
434
+ function getSharedConfigurationDefaults() {
435
+ return {
436
+ timeoutMillis: 1e4,
437
+ concurrencyLimit: 30,
438
+ compression: "none"
439
+ };
440
+ }
441
+ class BoundedQueueExportPromiseHandler {
442
+ /**
443
+ * @param concurrencyLimit maximum promises allowed in a queue at the same time.
444
+ */
445
+ constructor(concurrencyLimit) {
446
+ __publicField(this, "_concurrencyLimit");
447
+ __publicField(this, "_sendingPromises", []);
448
+ this._concurrencyLimit = concurrencyLimit;
449
+ }
450
+ pushPromise(promise) {
451
+ if (this.hasReachedLimit()) {
452
+ throw new Error("Concurrency Limit reached");
453
+ }
454
+ this._sendingPromises.push(promise);
455
+ const popPromise = () => {
456
+ const index = this._sendingPromises.indexOf(promise);
457
+ void this._sendingPromises.splice(index, 1);
458
+ };
459
+ promise.then(popPromise, popPromise);
460
+ }
461
+ hasReachedLimit() {
462
+ return this._sendingPromises.length >= this._concurrencyLimit;
463
+ }
464
+ async awaitAll() {
465
+ await Promise.all(this._sendingPromises);
466
+ }
467
+ }
468
+ function createBoundedQueueExportPromiseHandler(options) {
469
+ return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);
470
+ }
471
+ function isPartialSuccessResponse(response) {
472
+ return Object.prototype.hasOwnProperty.call(response, "partialSuccess");
473
+ }
474
+ function createLoggingPartialSuccessResponseHandler() {
475
+ return {
476
+ handleResponse(response) {
477
+ if (response == null || !isPartialSuccessResponse(response) || response.partialSuccess == null || Object.keys(response.partialSuccess).length === 0) {
478
+ return;
479
+ }
480
+ diag.warn("Received Partial Success response:", JSON.stringify(response.partialSuccess));
481
+ }
482
+ };
483
+ }
484
+ class OTLPExportDelegate {
485
+ constructor(_transport, _serializer, _responseHandler, _promiseQueue, _timeout) {
486
+ __publicField(this, "_transport");
487
+ __publicField(this, "_serializer");
488
+ __publicField(this, "_responseHandler");
489
+ __publicField(this, "_promiseQueue");
490
+ __publicField(this, "_timeout");
491
+ __publicField(this, "_diagLogger");
492
+ this._transport = _transport;
493
+ this._serializer = _serializer;
494
+ this._responseHandler = _responseHandler;
495
+ this._promiseQueue = _promiseQueue;
496
+ this._timeout = _timeout;
497
+ this._diagLogger = diag.createComponentLogger({
498
+ namespace: "OTLPExportDelegate"
499
+ });
500
+ }
501
+ export(internalRepresentation, resultCallback) {
502
+ this._diagLogger.debug("items to be sent", internalRepresentation);
503
+ if (this._promiseQueue.hasReachedLimit()) {
504
+ resultCallback({
505
+ code: ExportResultCode.FAILED,
506
+ error: new Error("Concurrent export limit reached")
507
+ });
508
+ return;
509
+ }
510
+ const serializedRequest = this._serializer.serializeRequest(internalRepresentation);
511
+ if (serializedRequest == null) {
512
+ resultCallback({
513
+ code: ExportResultCode.FAILED,
514
+ error: new Error("Nothing to send")
515
+ });
516
+ return;
517
+ }
518
+ this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then((response) => {
519
+ if (response.status === "success") {
520
+ if (response.data != null) {
521
+ try {
522
+ this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data));
523
+ } catch (e) {
524
+ this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?", e, response.data);
525
+ }
526
+ }
527
+ resultCallback({
528
+ code: ExportResultCode.SUCCESS
529
+ });
530
+ return;
531
+ } else if (response.status === "failure" && response.error) {
532
+ resultCallback({
533
+ code: ExportResultCode.FAILED,
534
+ error: response.error
535
+ });
536
+ return;
537
+ } else if (response.status === "retryable") {
538
+ resultCallback({
539
+ code: ExportResultCode.FAILED,
540
+ error: new OTLPExporterError("Export failed with retryable status")
541
+ });
542
+ } else {
543
+ resultCallback({
544
+ code: ExportResultCode.FAILED,
545
+ error: new OTLPExporterError("Export failed with unknown error")
546
+ });
547
+ }
548
+ }, (reason) => resultCallback({
549
+ code: ExportResultCode.FAILED,
550
+ error: reason
551
+ })));
552
+ }
553
+ forceFlush() {
554
+ return this._promiseQueue.awaitAll();
555
+ }
556
+ async shutdown() {
557
+ this._diagLogger.debug("shutdown started");
558
+ await this.forceFlush();
559
+ this._transport.shutdown();
560
+ }
561
+ }
562
+ function createOtlpExportDelegate(components, settings) {
563
+ return new OTLPExportDelegate(components.transport, components.serializer, createLoggingPartialSuccessResponseHandler(), components.promiseHandler, settings.timeout);
564
+ }
565
+ function createOtlpNetworkExportDelegate(options, serializer, transport) {
566
+ return createOtlpExportDelegate({
567
+ transport,
568
+ serializer,
569
+ promiseHandler: createBoundedQueueExportPromiseHandler(options)
570
+ }, { timeout: options.timeoutMillis });
571
+ }
572
+ function intValue(charCode) {
573
+ if (charCode >= 48 && charCode <= 57) {
574
+ return charCode - 48;
575
+ }
576
+ if (charCode >= 97 && charCode <= 102) {
577
+ return charCode - 87;
578
+ }
579
+ return charCode - 55;
580
+ }
581
+ function hexToBinary(hexStr) {
582
+ const buf = new Uint8Array(hexStr.length / 2);
583
+ let offset = 0;
584
+ for (let i = 0; i < hexStr.length; i += 2) {
585
+ const hi = intValue(hexStr.charCodeAt(i));
586
+ const lo = intValue(hexStr.charCodeAt(i + 1));
587
+ buf[offset++] = hi << 4 | lo;
588
+ }
589
+ return buf;
590
+ }
591
+ function hrTimeToNanos(hrTime2) {
592
+ const NANOSECONDS = BigInt(1e9);
593
+ return BigInt(hrTime2[0]) * NANOSECONDS + BigInt(hrTime2[1]);
594
+ }
595
+ function toLongBits(value) {
596
+ const low = Number(BigInt.asUintN(32, value));
597
+ const high = Number(BigInt.asUintN(32, value >> BigInt(32)));
598
+ return { low, high };
599
+ }
600
+ function encodeAsLongBits(hrTime2) {
601
+ const nanos = hrTimeToNanos(hrTime2);
602
+ return toLongBits(nanos);
603
+ }
604
+ function encodeAsString(hrTime2) {
605
+ const nanos = hrTimeToNanos(hrTime2);
606
+ return nanos.toString();
607
+ }
608
+ const encodeTimestamp = typeof BigInt !== "undefined" ? encodeAsString : hrTimeToNanoseconds;
609
+ function identity(value) {
610
+ return value;
611
+ }
612
+ function optionalHexToBinary(str) {
613
+ if (str === void 0)
614
+ return void 0;
615
+ return hexToBinary(str);
616
+ }
617
+ const DEFAULT_ENCODER = {
618
+ encodeHrTime: encodeAsLongBits,
619
+ encodeSpanContext: hexToBinary,
620
+ encodeOptionalSpanContext: optionalHexToBinary
621
+ };
622
+ function getOtlpEncoder(options) {
623
+ if (options === void 0) {
624
+ return DEFAULT_ENCODER;
625
+ }
626
+ return {
627
+ encodeHrTime: encodeTimestamp,
628
+ encodeSpanContext: identity,
629
+ encodeOptionalSpanContext: identity
630
+ };
631
+ }
632
+ function createResource(resource) {
633
+ return {
634
+ attributes: toAttributes(resource.attributes),
635
+ droppedAttributesCount: 0
636
+ };
637
+ }
638
+ function createInstrumentationScope(scope) {
639
+ return {
640
+ name: scope.name,
641
+ version: scope.version
642
+ };
643
+ }
644
+ function toAttributes(attributes) {
645
+ return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key]));
646
+ }
647
+ function toKeyValue(key, value) {
648
+ return {
649
+ key,
650
+ value: toAnyValue(value)
651
+ };
652
+ }
653
+ function toAnyValue(value) {
654
+ const t = typeof value;
655
+ if (t === "string")
656
+ return { stringValue: value };
657
+ if (t === "number") {
658
+ if (!Number.isInteger(value))
659
+ return { doubleValue: value };
660
+ return { intValue: value };
661
+ }
662
+ if (t === "boolean")
663
+ return { boolValue: value };
664
+ if (value instanceof Uint8Array)
665
+ return { bytesValue: value };
666
+ if (Array.isArray(value))
667
+ return { arrayValue: { values: value.map(toAnyValue) } };
668
+ if (t === "object" && value != null)
669
+ return {
670
+ kvlistValue: {
671
+ values: Object.entries(value).map(([k, v]) => toKeyValue(k, v))
672
+ }
673
+ };
674
+ return {};
675
+ }
676
+ function createExportLogsServiceRequest(logRecords, options) {
677
+ const encoder = getOtlpEncoder(options);
678
+ return {
679
+ resourceLogs: logRecordsToResourceLogs(logRecords, encoder)
680
+ };
681
+ }
682
+ function createResourceMap(logRecords) {
683
+ const resourceMap = /* @__PURE__ */ new Map();
684
+ for (const record of logRecords) {
685
+ const { resource, instrumentationScope: { name, version = "", schemaUrl = "" } } = record;
686
+ let ismMap = resourceMap.get(resource);
687
+ if (!ismMap) {
688
+ ismMap = /* @__PURE__ */ new Map();
689
+ resourceMap.set(resource, ismMap);
690
+ }
691
+ const ismKey = `${name}@${version}:${schemaUrl}`;
692
+ let records = ismMap.get(ismKey);
693
+ if (!records) {
694
+ records = [];
695
+ ismMap.set(ismKey, records);
696
+ }
697
+ records.push(record);
698
+ }
699
+ return resourceMap;
700
+ }
701
+ function logRecordsToResourceLogs(logRecords, encoder) {
702
+ const resourceMap = createResourceMap(logRecords);
703
+ return Array.from(resourceMap, ([resource, ismMap]) => ({
704
+ resource: createResource(resource),
705
+ scopeLogs: Array.from(ismMap, ([, scopeLogs]) => {
706
+ return {
707
+ scope: createInstrumentationScope(scopeLogs[0].instrumentationScope),
708
+ logRecords: scopeLogs.map((log) => toLogRecord(log, encoder)),
709
+ schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl
710
+ };
711
+ }),
712
+ schemaUrl: void 0
713
+ }));
714
+ }
715
+ function toLogRecord(log, encoder) {
716
+ var _a, _b, _c;
717
+ return {
718
+ timeUnixNano: encoder.encodeHrTime(log.hrTime),
719
+ observedTimeUnixNano: encoder.encodeHrTime(log.hrTimeObserved),
720
+ severityNumber: toSeverityNumber(log.severityNumber),
721
+ severityText: log.severityText,
722
+ body: toAnyValue(log.body),
723
+ eventName: log.eventName,
724
+ attributes: toLogAttributes(log.attributes),
725
+ droppedAttributesCount: log.droppedAttributesCount,
726
+ flags: (_a = log.spanContext) == null ? void 0 : _a.traceFlags,
727
+ traceId: encoder.encodeOptionalSpanContext((_b = log.spanContext) == null ? void 0 : _b.traceId),
728
+ spanId: encoder.encodeOptionalSpanContext((_c = log.spanContext) == null ? void 0 : _c.spanId)
729
+ };
730
+ }
731
+ function toSeverityNumber(severityNumber) {
732
+ return severityNumber;
733
+ }
734
+ function toLogAttributes(attributes) {
735
+ return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key]));
736
+ }
737
+ const JsonLogsSerializer = {
738
+ serializeRequest: (arg) => {
739
+ const request = createExportLogsServiceRequest(arg, {});
740
+ const encoder = new TextEncoder();
741
+ return encoder.encode(JSON.stringify(request));
742
+ },
743
+ deserializeResponse: (arg) => {
744
+ if (arg.length === 0) {
745
+ return {};
746
+ }
747
+ const decoder = new TextDecoder();
748
+ return JSON.parse(decoder.decode(arg));
749
+ }
750
+ };
751
+ const MAX_ATTEMPTS = 5;
752
+ const INITIAL_BACKOFF = 1e3;
753
+ const MAX_BACKOFF = 5e3;
754
+ const BACKOFF_MULTIPLIER = 1.5;
755
+ const JITTER = 0.2;
756
+ function getJitter() {
757
+ return Math.random() * (2 * JITTER) - JITTER;
758
+ }
759
+ class RetryingTransport {
760
+ constructor(_transport) {
761
+ __publicField(this, "_transport");
762
+ this._transport = _transport;
763
+ }
764
+ retry(data, timeoutMillis, inMillis) {
765
+ return new Promise((resolve, reject) => {
766
+ setTimeout(() => {
767
+ this._transport.send(data, timeoutMillis).then(resolve, reject);
768
+ }, inMillis);
769
+ });
770
+ }
771
+ async send(data, timeoutMillis) {
772
+ const deadline = Date.now() + timeoutMillis;
773
+ let result = await this._transport.send(data, timeoutMillis);
774
+ let attempts = MAX_ATTEMPTS;
775
+ let nextBackoff = INITIAL_BACKOFF;
776
+ while (result.status === "retryable" && attempts > 0) {
777
+ attempts--;
778
+ const backoff = Math.max(Math.min(nextBackoff, MAX_BACKOFF) + getJitter(), 0);
779
+ nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;
780
+ const retryInMillis = result.retryInMillis ?? backoff;
781
+ const remainingTimeoutMillis = deadline - Date.now();
782
+ if (retryInMillis > remainingTimeoutMillis) {
783
+ return result;
784
+ }
785
+ result = await this.retry(data, remainingTimeoutMillis, retryInMillis);
786
+ }
787
+ return result;
788
+ }
789
+ shutdown() {
790
+ return this._transport.shutdown();
791
+ }
792
+ }
793
+ function createRetryingTransport(options) {
794
+ return new RetryingTransport(options.transport);
795
+ }
796
+ function isExportRetryable(statusCode) {
797
+ const retryCodes = [429, 502, 503, 504];
798
+ return retryCodes.includes(statusCode);
799
+ }
800
+ function parseRetryAfterToMills(retryAfter) {
801
+ if (retryAfter == null) {
802
+ return void 0;
803
+ }
804
+ const seconds = Number.parseInt(retryAfter, 10);
805
+ if (Number.isInteger(seconds)) {
806
+ return seconds > 0 ? seconds * 1e3 : -1;
807
+ }
808
+ const delay = new Date(retryAfter).getTime() - Date.now();
809
+ if (delay >= 0) {
810
+ return delay;
811
+ }
812
+ return 0;
813
+ }
814
+ class XhrTransport {
815
+ constructor(_parameters) {
816
+ __publicField(this, "_parameters");
817
+ this._parameters = _parameters;
818
+ }
819
+ send(data, timeoutMillis) {
820
+ return new Promise((resolve) => {
821
+ const xhr = new XMLHttpRequest();
822
+ xhr.timeout = timeoutMillis;
823
+ xhr.open("POST", this._parameters.url);
824
+ const headers = this._parameters.headers();
825
+ Object.entries(headers).forEach(([k, v]) => {
826
+ xhr.setRequestHeader(k, v);
827
+ });
828
+ xhr.ontimeout = (_) => {
829
+ resolve({
830
+ status: "failure",
831
+ error: new Error("XHR request timed out")
832
+ });
833
+ };
834
+ xhr.onreadystatechange = () => {
835
+ if (xhr.status >= 200 && xhr.status <= 299) {
836
+ diag.debug("XHR success");
837
+ resolve({
838
+ status: "success"
839
+ });
840
+ } else if (xhr.status && isExportRetryable(xhr.status)) {
841
+ resolve({
842
+ status: "retryable",
843
+ retryInMillis: parseRetryAfterToMills(xhr.getResponseHeader("Retry-After"))
844
+ });
845
+ } else if (xhr.status !== 0) {
846
+ resolve({
847
+ status: "failure",
848
+ error: new Error("XHR request failed with non-retryable status")
849
+ });
850
+ }
851
+ };
852
+ xhr.onabort = () => {
853
+ resolve({
854
+ status: "failure",
855
+ error: new Error("XHR request aborted")
856
+ });
857
+ };
858
+ xhr.onerror = () => {
859
+ resolve({
860
+ status: "failure",
861
+ error: new Error("XHR request errored")
862
+ });
863
+ };
864
+ xhr.send(data);
865
+ });
866
+ }
867
+ shutdown() {
868
+ }
869
+ }
870
+ function createXhrTransport(parameters) {
871
+ return new XhrTransport(parameters);
872
+ }
873
+ class SendBeaconTransport {
874
+ constructor(_params) {
875
+ __publicField(this, "_params");
876
+ this._params = _params;
877
+ }
878
+ send(data) {
879
+ return new Promise((resolve) => {
880
+ if (navigator.sendBeacon(this._params.url, new Blob([data], { type: this._params.blobType }))) {
881
+ diag.debug("SendBeacon success");
882
+ resolve({
883
+ status: "success"
884
+ });
885
+ } else {
886
+ resolve({
887
+ status: "failure",
888
+ error: new Error("SendBeacon failed")
889
+ });
890
+ }
891
+ });
892
+ }
893
+ shutdown() {
894
+ }
895
+ }
896
+ function createSendBeaconTransport(parameters) {
897
+ return new SendBeaconTransport(parameters);
898
+ }
899
+ function createOtlpXhrExportDelegate(options, serializer) {
900
+ return createOtlpNetworkExportDelegate(options, serializer, createRetryingTransport({
901
+ transport: createXhrTransport(options)
902
+ }));
903
+ }
904
+ function createOtlpSendBeaconExportDelegate(options, serializer) {
905
+ return createOtlpNetworkExportDelegate(options, serializer, createRetryingTransport({
906
+ transport: createSendBeaconTransport({
907
+ url: options.url,
908
+ blobType: options.headers()["Content-Type"]
909
+ })
910
+ }));
911
+ }
912
+ function validateAndNormalizeHeaders(partialHeaders) {
913
+ return () => {
914
+ const headers = {};
915
+ Object.entries((partialHeaders == null ? void 0 : partialHeaders()) ?? {}).forEach(([key, value]) => {
916
+ if (typeof value !== "undefined") {
917
+ headers[key] = String(value);
918
+ } else {
919
+ diag.warn(`Header "${key}" has invalid value (${value}) and will be ignored`);
920
+ }
921
+ });
922
+ return headers;
923
+ };
924
+ }
925
+ function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) {
926
+ const requiredHeaders = {
927
+ ...defaultHeaders()
928
+ };
929
+ const headers = {};
930
+ return () => {
931
+ if (fallbackHeaders != null) {
932
+ Object.assign(headers, fallbackHeaders());
933
+ }
934
+ if (userProvidedHeaders != null) {
935
+ Object.assign(headers, userProvidedHeaders());
936
+ }
937
+ return Object.assign(headers, requiredHeaders);
938
+ };
939
+ }
940
+ function validateUserProvidedUrl(url) {
941
+ if (url == null) {
942
+ return void 0;
943
+ }
944
+ try {
945
+ new URL(url);
946
+ return url;
947
+ } catch {
948
+ throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`);
949
+ }
950
+ }
951
+ function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
952
+ return {
953
+ ...mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
954
+ headers: mergeHeaders(validateAndNormalizeHeaders(userProvidedConfiguration.headers), fallbackConfiguration.headers, defaultConfiguration.headers),
955
+ url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? fallbackConfiguration.url ?? defaultConfiguration.url,
956
+ agentOptions: userProvidedConfiguration.agentOptions ?? fallbackConfiguration.agentOptions ?? defaultConfiguration.agentOptions
957
+ };
958
+ }
959
+ function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {
960
+ return {
961
+ ...getSharedConfigurationDefaults(),
962
+ headers: () => requiredHeaders,
963
+ url: "http://localhost:4318/" + signalResourcePath,
964
+ agentOptions: { keepAlive: true }
965
+ };
966
+ }
967
+ function convertLegacyBrowserHttpOptions(config, signalResourcePath, requiredHeaders) {
968
+ return mergeOtlpHttpConfigurationWithDefaults(
969
+ {
970
+ url: config.url,
971
+ timeoutMillis: config.timeoutMillis,
972
+ headers: wrapStaticHeadersInFunction(config.headers),
973
+ concurrencyLimit: config.concurrencyLimit
974
+ },
975
+ {},
976
+ // no fallback for browser case
977
+ getHttpConfigurationDefaults(requiredHeaders, signalResourcePath)
978
+ );
979
+ }
980
+ function createLegacyOtlpBrowserExportDelegate(config, serializer, signalResourcePath, requiredHeaders) {
981
+ const useXhr = !!config.headers || typeof navigator.sendBeacon !== "function";
982
+ const options = convertLegacyBrowserHttpOptions(config, signalResourcePath, requiredHeaders);
983
+ if (useXhr) {
984
+ return createOtlpXhrExportDelegate(options, serializer);
985
+ } else {
986
+ return createOtlpSendBeaconExportDelegate(options, serializer);
987
+ }
988
+ }
989
+ class OTLPLogExporter extends OTLPExporterBase {
990
+ constructor(config = {}) {
991
+ super(createLegacyOtlpBrowserExportDelegate(config, JsonLogsSerializer, "v1/logs", { "Content-Type": "application/json" }));
992
+ }
993
+ }
994
+ class LogRecordImpl {
995
+ constructor(_sharedState, instrumentationScope, logRecord) {
996
+ __publicField(this, "hrTime");
997
+ __publicField(this, "hrTimeObserved");
998
+ __publicField(this, "spanContext");
999
+ __publicField(this, "resource");
1000
+ __publicField(this, "instrumentationScope");
1001
+ __publicField(this, "attributes", {});
1002
+ __publicField(this, "_severityText");
1003
+ __publicField(this, "_severityNumber");
1004
+ __publicField(this, "_body");
1005
+ __publicField(this, "_eventName");
1006
+ __publicField(this, "totalAttributesCount", 0);
1007
+ __publicField(this, "_isReadonly", false);
1008
+ __publicField(this, "_logRecordLimits");
1009
+ const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, context: context2 } = logRecord;
1010
+ const now = Date.now();
1011
+ this.hrTime = timeInputToHrTime(timestamp ?? now);
1012
+ this.hrTimeObserved = timeInputToHrTime(observedTimestamp ?? now);
1013
+ if (context2) {
1014
+ const spanContext = trace.getSpanContext(context2);
1015
+ if (spanContext && isSpanContextValid(spanContext)) {
1016
+ this.spanContext = spanContext;
1017
+ }
1018
+ }
1019
+ this.severityNumber = severityNumber;
1020
+ this.severityText = severityText;
1021
+ this.body = body;
1022
+ this.resource = _sharedState.resource;
1023
+ this.instrumentationScope = instrumentationScope;
1024
+ this._logRecordLimits = _sharedState.logRecordLimits;
1025
+ this._eventName = eventName;
1026
+ this.setAttributes(attributes);
1027
+ }
1028
+ set severityText(severityText) {
1029
+ if (this._isLogRecordReadonly()) {
1030
+ return;
1031
+ }
1032
+ this._severityText = severityText;
1033
+ }
1034
+ get severityText() {
1035
+ return this._severityText;
1036
+ }
1037
+ set severityNumber(severityNumber) {
1038
+ if (this._isLogRecordReadonly()) {
1039
+ return;
1040
+ }
1041
+ this._severityNumber = severityNumber;
1042
+ }
1043
+ get severityNumber() {
1044
+ return this._severityNumber;
1045
+ }
1046
+ set body(body) {
1047
+ if (this._isLogRecordReadonly()) {
1048
+ return;
1049
+ }
1050
+ this._body = body;
1051
+ }
1052
+ get body() {
1053
+ return this._body;
1054
+ }
1055
+ get eventName() {
1056
+ return this._eventName;
1057
+ }
1058
+ set eventName(eventName) {
1059
+ if (this._isLogRecordReadonly()) {
1060
+ return;
1061
+ }
1062
+ this._eventName = eventName;
1063
+ }
1064
+ get droppedAttributesCount() {
1065
+ return this.totalAttributesCount - Object.keys(this.attributes).length;
1066
+ }
1067
+ setAttribute(key, value) {
1068
+ if (this._isLogRecordReadonly()) {
1069
+ return this;
1070
+ }
1071
+ if (value === null) {
1072
+ return this;
1073
+ }
1074
+ if (key.length === 0) {
1075
+ diag.warn(`Invalid attribute key: ${key}`);
1076
+ return this;
1077
+ }
1078
+ if (!isAttributeValue(value) && !(typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0)) {
1079
+ diag.warn(`Invalid attribute value set for key: ${key}`);
1080
+ return this;
1081
+ }
1082
+ this.totalAttributesCount += 1;
1083
+ if (Object.keys(this.attributes).length >= this._logRecordLimits.attributeCountLimit && !Object.prototype.hasOwnProperty.call(this.attributes, key)) {
1084
+ if (this.droppedAttributesCount === 1) {
1085
+ diag.warn("Dropping extra attributes.");
1086
+ }
1087
+ return this;
1088
+ }
1089
+ if (isAttributeValue(value)) {
1090
+ this.attributes[key] = this._truncateToSize(value);
1091
+ } else {
1092
+ this.attributes[key] = value;
1093
+ }
1094
+ return this;
1095
+ }
1096
+ setAttributes(attributes) {
1097
+ for (const [k, v] of Object.entries(attributes)) {
1098
+ this.setAttribute(k, v);
1099
+ }
1100
+ return this;
1101
+ }
1102
+ setBody(body) {
1103
+ this.body = body;
1104
+ return this;
1105
+ }
1106
+ setEventName(eventName) {
1107
+ this.eventName = eventName;
1108
+ return this;
1109
+ }
1110
+ setSeverityNumber(severityNumber) {
1111
+ this.severityNumber = severityNumber;
1112
+ return this;
1113
+ }
1114
+ setSeverityText(severityText) {
1115
+ this.severityText = severityText;
1116
+ return this;
1117
+ }
1118
+ /**
1119
+ * @internal
1120
+ * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
1121
+ * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
1122
+ */
1123
+ _makeReadonly() {
1124
+ this._isReadonly = true;
1125
+ }
1126
+ _truncateToSize(value) {
1127
+ const limit = this._logRecordLimits.attributeValueLengthLimit;
1128
+ if (limit <= 0) {
1129
+ diag.warn(`Attribute value limit must be positive, got ${limit}`);
1130
+ return value;
1131
+ }
1132
+ if (typeof value === "string") {
1133
+ return this._truncateToLimitUtil(value, limit);
1134
+ }
1135
+ if (Array.isArray(value)) {
1136
+ return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val);
1137
+ }
1138
+ return value;
1139
+ }
1140
+ _truncateToLimitUtil(value, limit) {
1141
+ if (value.length <= limit) {
1142
+ return value;
1143
+ }
1144
+ return value.substring(0, limit);
1145
+ }
1146
+ _isLogRecordReadonly() {
1147
+ if (this._isReadonly) {
1148
+ diag.warn("Can not execute the operation on emitted log record");
1149
+ }
1150
+ return this._isReadonly;
1151
+ }
1152
+ }
1153
+ class Logger {
1154
+ constructor(instrumentationScope, _sharedState) {
1155
+ __publicField(this, "instrumentationScope");
1156
+ __publicField(this, "_sharedState");
1157
+ this.instrumentationScope = instrumentationScope;
1158
+ this._sharedState = _sharedState;
1159
+ }
1160
+ emit(logRecord) {
1161
+ const currentContext = logRecord.context || context.active();
1162
+ const logRecordInstance = new LogRecordImpl(this._sharedState, this.instrumentationScope, {
1163
+ context: currentContext,
1164
+ ...logRecord
1165
+ });
1166
+ this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext);
1167
+ logRecordInstance._makeReadonly();
1168
+ }
1169
+ }
1170
+ function loadDefaultConfig() {
1171
+ return {
1172
+ forceFlushTimeoutMillis: 3e4,
1173
+ logRecordLimits: {
1174
+ attributeValueLengthLimit: Infinity,
1175
+ attributeCountLimit: 128
1176
+ },
1177
+ includeTraceContext: true
1178
+ };
1179
+ }
1180
+ function reconfigureLimits(logRecordLimits) {
1181
+ return {
1182
+ /**
1183
+ * Reassign log record attribute count limit to use first non null value defined by user or use default value
1184
+ */
1185
+ attributeCountLimit: logRecordLimits.attributeCountLimit ?? getNumberFromEnv() ?? getNumberFromEnv() ?? 128,
1186
+ /**
1187
+ * Reassign log record attribute value length limit to use first non null value defined by user or use default value
1188
+ */
1189
+ attributeValueLengthLimit: logRecordLimits.attributeValueLengthLimit ?? getNumberFromEnv() ?? getNumberFromEnv() ?? Infinity
1190
+ };
1191
+ }
1192
+ class NoopLogRecordProcessor {
1193
+ forceFlush() {
1194
+ return Promise.resolve();
1195
+ }
1196
+ onEmit(_logRecord, _context) {
1197
+ }
1198
+ shutdown() {
1199
+ return Promise.resolve();
1200
+ }
1201
+ }
1202
+ class MultiLogRecordProcessor {
1203
+ constructor(processors, forceFlushTimeoutMillis) {
1204
+ __publicField(this, "processors");
1205
+ __publicField(this, "forceFlushTimeoutMillis");
1206
+ this.processors = processors;
1207
+ this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
1208
+ }
1209
+ async forceFlush() {
1210
+ const timeout = this.forceFlushTimeoutMillis;
1211
+ await Promise.all(this.processors.map((processor) => callWithTimeout(processor.forceFlush(), timeout)));
1212
+ }
1213
+ onEmit(logRecord, context2) {
1214
+ this.processors.forEach((processors) => processors.onEmit(logRecord, context2));
1215
+ }
1216
+ async shutdown() {
1217
+ await Promise.all(this.processors.map((processor) => processor.shutdown()));
1218
+ }
1219
+ }
1220
+ class LoggerProviderSharedState {
1221
+ constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors) {
1222
+ __publicField(this, "resource");
1223
+ __publicField(this, "forceFlushTimeoutMillis");
1224
+ __publicField(this, "logRecordLimits");
1225
+ __publicField(this, "processors");
1226
+ __publicField(this, "loggers", /* @__PURE__ */ new Map());
1227
+ __publicField(this, "activeProcessor");
1228
+ __publicField(this, "registeredLogRecordProcessors", []);
1229
+ this.resource = resource;
1230
+ this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
1231
+ this.logRecordLimits = logRecordLimits;
1232
+ this.processors = processors;
1233
+ if (processors.length > 0) {
1234
+ this.registeredLogRecordProcessors = processors;
1235
+ this.activeProcessor = new MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis);
1236
+ } else {
1237
+ this.activeProcessor = new NoopLogRecordProcessor();
1238
+ }
1239
+ }
1240
+ }
1241
+ const DEFAULT_LOGGER_NAME = "unknown";
1242
+ class LoggerProvider {
1243
+ constructor(config = {}) {
1244
+ __publicField(this, "_shutdownOnce");
1245
+ __publicField(this, "_sharedState");
1246
+ const mergedConfig = merge({}, loadDefaultConfig(), config);
1247
+ const resource = config.resource ?? defaultResource();
1248
+ this._sharedState = new LoggerProviderSharedState(resource, mergedConfig.forceFlushTimeoutMillis, reconfigureLimits(mergedConfig.logRecordLimits), (config == null ? void 0 : config.processors) ?? []);
1249
+ this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
1250
+ }
1251
+ /**
1252
+ * Get a logger with the configuration of the LoggerProvider.
1253
+ */
1254
+ getLogger(name, version, options) {
1255
+ if (this._shutdownOnce.isCalled) {
1256
+ diag.warn("A shutdown LoggerProvider cannot provide a Logger");
1257
+ return NOOP_LOGGER;
1258
+ }
1259
+ if (!name) {
1260
+ diag.warn("Logger requested without instrumentation scope name.");
1261
+ }
1262
+ const loggerName = name || DEFAULT_LOGGER_NAME;
1263
+ const key = `${loggerName}@${version || ""}:${(options == null ? void 0 : options.schemaUrl) || ""}`;
1264
+ if (!this._sharedState.loggers.has(key)) {
1265
+ this._sharedState.loggers.set(key, new Logger({ name: loggerName, version, schemaUrl: options == null ? void 0 : options.schemaUrl }, this._sharedState));
1266
+ }
1267
+ return this._sharedState.loggers.get(key);
1268
+ }
1269
+ /**
1270
+ * Notifies all registered LogRecordProcessor to flush any buffered data.
1271
+ *
1272
+ * Returns a promise which is resolved when all flushes are complete.
1273
+ */
1274
+ forceFlush() {
1275
+ if (this._shutdownOnce.isCalled) {
1276
+ diag.warn("invalid attempt to force flush after LoggerProvider shutdown");
1277
+ return this._shutdownOnce.promise;
1278
+ }
1279
+ return this._sharedState.activeProcessor.forceFlush();
1280
+ }
1281
+ /**
1282
+ * Flush all buffered data and shut down the LoggerProvider and all registered
1283
+ * LogRecordProcessor.
1284
+ *
1285
+ * Returns a promise which is resolved when all flushes are complete.
1286
+ */
1287
+ shutdown() {
1288
+ if (this._shutdownOnce.isCalled) {
1289
+ diag.warn("shutdown may only be called once per LoggerProvider");
1290
+ return this._shutdownOnce.promise;
1291
+ }
1292
+ return this._shutdownOnce.call();
1293
+ }
1294
+ _shutdown() {
1295
+ return this._sharedState.activeProcessor.shutdown();
1296
+ }
1297
+ }
1298
+ class BatchLogRecordProcessorBase {
1299
+ constructor(_exporter, config) {
1300
+ __publicField(this, "_exporter");
1301
+ __publicField(this, "_maxExportBatchSize");
1302
+ __publicField(this, "_maxQueueSize");
1303
+ __publicField(this, "_scheduledDelayMillis");
1304
+ __publicField(this, "_exportTimeoutMillis");
1305
+ __publicField(this, "_finishedLogRecords", []);
1306
+ __publicField(this, "_timer");
1307
+ __publicField(this, "_shutdownOnce");
1308
+ this._exporter = _exporter;
1309
+ this._maxExportBatchSize = (config == null ? void 0 : config.maxExportBatchSize) ?? getNumberFromEnv() ?? 512;
1310
+ this._maxQueueSize = (config == null ? void 0 : config.maxQueueSize) ?? getNumberFromEnv() ?? 2048;
1311
+ this._scheduledDelayMillis = (config == null ? void 0 : config.scheduledDelayMillis) ?? getNumberFromEnv() ?? 5e3;
1312
+ this._exportTimeoutMillis = (config == null ? void 0 : config.exportTimeoutMillis) ?? getNumberFromEnv() ?? 3e4;
1313
+ this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
1314
+ if (this._maxExportBatchSize > this._maxQueueSize) {
1315
+ diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
1316
+ this._maxExportBatchSize = this._maxQueueSize;
1317
+ }
1318
+ }
1319
+ onEmit(logRecord) {
1320
+ if (this._shutdownOnce.isCalled) {
1321
+ return;
1322
+ }
1323
+ this._addToBuffer(logRecord);
1324
+ }
1325
+ forceFlush() {
1326
+ if (this._shutdownOnce.isCalled) {
1327
+ return this._shutdownOnce.promise;
1328
+ }
1329
+ return this._flushAll();
1330
+ }
1331
+ shutdown() {
1332
+ return this._shutdownOnce.call();
1333
+ }
1334
+ async _shutdown() {
1335
+ this.onShutdown();
1336
+ await this._flushAll();
1337
+ await this._exporter.shutdown();
1338
+ }
1339
+ /** Add a LogRecord in the buffer. */
1340
+ _addToBuffer(logRecord) {
1341
+ if (this._finishedLogRecords.length >= this._maxQueueSize) {
1342
+ return;
1343
+ }
1344
+ this._finishedLogRecords.push(logRecord);
1345
+ this._maybeStartTimer();
1346
+ }
1347
+ /**
1348
+ * Send all LogRecords to the exporter respecting the batch size limit
1349
+ * This function is used only on forceFlush or shutdown,
1350
+ * for all other cases _flush should be used
1351
+ * */
1352
+ _flushAll() {
1353
+ return new Promise((resolve, reject) => {
1354
+ const promises = [];
1355
+ const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
1356
+ for (let i = 0; i < batchCount; i++) {
1357
+ promises.push(this._flushOneBatch());
1358
+ }
1359
+ Promise.all(promises).then(() => {
1360
+ resolve();
1361
+ }).catch(reject);
1362
+ });
1363
+ }
1364
+ _flushOneBatch() {
1365
+ this._clearTimer();
1366
+ if (this._finishedLogRecords.length === 0) {
1367
+ return Promise.resolve();
1368
+ }
1369
+ return new Promise((resolve, reject) => {
1370
+ callWithTimeout(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis).then(() => resolve()).catch(reject);
1371
+ });
1372
+ }
1373
+ _maybeStartTimer() {
1374
+ if (this._timer !== void 0) {
1375
+ return;
1376
+ }
1377
+ this._timer = setTimeout(() => {
1378
+ this._flushOneBatch().then(() => {
1379
+ if (this._finishedLogRecords.length > 0) {
1380
+ this._clearTimer();
1381
+ this._maybeStartTimer();
1382
+ }
1383
+ }).catch((e) => {
1384
+ globalErrorHandler(e);
1385
+ });
1386
+ }, this._scheduledDelayMillis);
1387
+ unrefTimer(this._timer);
1388
+ }
1389
+ _clearTimer() {
1390
+ if (this._timer !== void 0) {
1391
+ clearTimeout(this._timer);
1392
+ this._timer = void 0;
1393
+ }
1394
+ }
1395
+ _export(logRecords) {
1396
+ const doExport = () => internal._export(this._exporter, logRecords).then((result) => {
1397
+ if (result.code !== ExportResultCode.SUCCESS) {
1398
+ globalErrorHandler(result.error ?? new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`));
1399
+ }
1400
+ }).catch(globalErrorHandler);
1401
+ const pendingResources = logRecords.map((logRecord) => logRecord.resource).filter((resource) => resource.asyncAttributesPending);
1402
+ if (pendingResources.length === 0) {
1403
+ return doExport();
1404
+ } else {
1405
+ return Promise.all(pendingResources.map((resource) => {
1406
+ var _a;
1407
+ return (_a = resource.waitForAsyncAttributes) == null ? void 0 : _a.call(resource);
1408
+ })).then(doExport, globalErrorHandler);
1409
+ }
1410
+ }
1411
+ }
1412
+ class BatchLogRecordProcessor extends BatchLogRecordProcessorBase {
1413
+ constructor(exporter, config) {
1414
+ super(exporter, config);
1415
+ __publicField(this, "_visibilityChangeListener");
1416
+ __publicField(this, "_pageHideListener");
1417
+ this._onInit(config);
1418
+ }
1419
+ onShutdown() {
1420
+ if (typeof document === "undefined") {
1421
+ return;
1422
+ }
1423
+ if (this._visibilityChangeListener) {
1424
+ document.removeEventListener("visibilitychange", this._visibilityChangeListener);
1425
+ }
1426
+ if (this._pageHideListener) {
1427
+ document.removeEventListener("pagehide", this._pageHideListener);
1428
+ }
1429
+ }
1430
+ _onInit(config) {
1431
+ if ((config == null ? void 0 : config.disableAutoFlushOnDocumentHide) === true || typeof document === "undefined") {
1432
+ return;
1433
+ }
1434
+ this._visibilityChangeListener = () => {
1435
+ if (document.visibilityState === "hidden") {
1436
+ void this.forceFlush();
1437
+ }
1438
+ };
1439
+ this._pageHideListener = () => {
1440
+ void this.forceFlush();
1441
+ };
1442
+ document.addEventListener("visibilitychange", this._visibilityChangeListener);
1443
+ document.addEventListener("pagehide", this._pageHideListener);
1444
+ }
1445
+ }
1446
+ function initLibraryLoggerProvider(context2) {
1447
+ const logExporter = new OTLPLogExporter({
1448
+ url: context2.windowOriginUrl + "/api/v1/logs",
1449
+ headers: {
1450
+ "Content-Type": "application/json"
1451
+ }
1452
+ });
1453
+ const resource = resourceFromAttributes({
1454
+ [ATTR_SERVICE_NAME]: "superblocks-ui-framework",
1455
+ "user-id": context2.userId,
1456
+ "user-email": context2.userEmail,
1457
+ "organization-id": context2.orgId,
1458
+ "organization-name": context2.orgName,
1459
+ "application-id": context2.appId,
1460
+ "deployment.environment": context2.environment
1461
+ });
1462
+ const loggerProvider = new LoggerProvider({
1463
+ resource,
1464
+ processors: [new BatchLogRecordProcessor(logExporter)]
1465
+ });
1466
+ const otelLogger = loggerProvider.getLogger(
1467
+ "superblocks-ui-framework",
1468
+ "1.0.0"
1469
+ );
1470
+ LibraryEarlyConsoleBuffer.getInstance().enableOpenTelemetry(otelLogger);
1471
+ }
1472
+ export {
1473
+ initLibraryLoggerProvider
1474
+ };
1475
+ //# sourceMappingURL=logs-DWaPDDub.js.map