@logbrew/sdk 0.1.37 → 0.1.39

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 (103) hide show
  1. package/automatic-delivery.cjs +271 -0
  2. package/batch-sender.cjs +164 -0
  3. package/bounded-number.cjs +34 -0
  4. package/browser-breadcrumbs.cjs +346 -136
  5. package/capture-support.cjs +100 -0
  6. package/client-options.cjs +292 -0
  7. package/client-report.cjs +232 -0
  8. package/client.cjs +447 -0
  9. package/console-arguments.cjs +151 -0
  10. package/console-capture.cjs +194 -0
  11. package/core.cjs +35 -2984
  12. package/delivery-health.cjs +133 -0
  13. package/error-causes.cjs +130 -0
  14. package/error-details.cjs +124 -0
  15. package/error-issue.cjs +187 -0
  16. package/event-clone.cjs +55 -0
  17. package/event-metadata.cjs +40 -0
  18. package/event-pipeline.cjs +325 -0
  19. package/event-queue.cjs +306 -0
  20. package/event-store.cjs +237 -0
  21. package/event-validation.cjs +159 -0
  22. package/examples/agent-timeline.cjs +57 -46
  23. package/examples/agent-timeline.mjs +41 -35
  24. package/examples/index.mjs +122 -94
  25. package/examples/readme-example.cjs +36 -27
  26. package/examples/readme-example.mjs +21 -17
  27. package/examples/real-user-smoke.cjs +41 -32
  28. package/examples/real-user-smoke.mjs +26 -22
  29. package/exception-chain.cjs +205 -0
  30. package/index.d.ts +144 -1076
  31. package/index.js +1 -1
  32. package/issue-breadcrumbs.cjs +143 -0
  33. package/issue-diagnostics.cjs +94 -582
  34. package/issue-evidence.cjs +256 -0
  35. package/issue-exception.cjs +268 -0
  36. package/issue-stack-frames.cjs +220 -0
  37. package/issue-stack-text.cjs +101 -0
  38. package/issue-stack.cjs +188 -225
  39. package/issue-text.cjs +72 -0
  40. package/log-context.cjs +87 -67
  41. package/metric-validation.cjs +95 -0
  42. package/network-milestone.cjs +155 -0
  43. package/null-value.cjs +4 -0
  44. package/opentelemetry-bridge.cjs +330 -0
  45. package/opentelemetry-context.cjs +245 -0
  46. package/opentelemetry-exceptions.cjs +69 -0
  47. package/opentelemetry-keys.cjs +183 -0
  48. package/opentelemetry-span.cjs +286 -0
  49. package/opentelemetry-summary.cjs +213 -0
  50. package/opentelemetry-time.cjs +131 -0
  51. package/opentelemetry.cjs +99 -1068
  52. package/package.json +64 -1
  53. package/pino-destination.cjs +108 -0
  54. package/pino-record.cjs +237 -0
  55. package/product-action.cjs +163 -0
  56. package/provided-breadcrumbs.cjs +117 -0
  57. package/random-hex.cjs +29 -0
  58. package/react-native.js +1 -1
  59. package/recording-transport.cjs +68 -0
  60. package/release-artifacts-build.cjs +263 -84
  61. package/release-artifacts-common.js +347 -66
  62. package/release-artifacts-debug-id.js +178 -0
  63. package/release-artifacts-inspect.js +213 -0
  64. package/release-artifacts-issue-event.js +99 -0
  65. package/release-artifacts-manifest-artifact.js +107 -0
  66. package/release-artifacts-manifest.js +77 -0
  67. package/release-artifacts-mappings.js +265 -0
  68. package/release-artifacts-prepare.js +297 -0
  69. package/release-artifacts-source-context.js +210 -0
  70. package/release-artifacts-symbolication.js +272 -421
  71. package/release-artifacts-upload-files.js +122 -0
  72. package/release-artifacts-upload-request.js +246 -0
  73. package/release-artifacts-upload.js +155 -300
  74. package/release-artifacts-urls.js +49 -0
  75. package/release-artifacts.js +189 -662
  76. package/retry-delay.cjs +32 -0
  77. package/sdk-error.cjs +36 -0
  78. package/span-validation.cjs +191 -0
  79. package/stored-events.cjs +243 -0
  80. package/support-ticket.cjs +232 -122
  81. package/telemetry-context.cjs +343 -251
  82. package/trace-context.cjs +376 -179
  83. package/transport-error.cjs +23 -0
  84. package/types/client.d.ts +67 -0
  85. package/types/delivery.d.ts +125 -0
  86. package/types/issues.d.ts +249 -0
  87. package/types/logging.d.ts +175 -0
  88. package/types/opentelemetry.d.ts +205 -0
  89. package/types/product.d.ts +128 -0
  90. package/types/recording-transport.d.ts +15 -0
  91. package/types/sdk-error.d.ts +9 -0
  92. package/types/telemetry.d.ts +171 -0
  93. package/types/trace-context.d.ts +110 -0
  94. package/types/transport-error.d.ts +10 -0
  95. package/utf8.cjs +37 -0
  96. package/validation.cjs +327 -0
  97. package/vite-release-artifacts-config.cjs +120 -0
  98. package/vite-release-artifacts.cjs +199 -99
  99. package/vite-release-artifacts.d.cts +65 -40
  100. package/vite-release-artifacts.d.ts +65 -40
  101. package/vite-release-artifacts.js +2 -2
  102. package/winston-info.cjs +205 -0
  103. package/winston.cjs +189 -290
package/core.cjs CHANGED
@@ -1,3004 +1,50 @@
1
- const { buildCreateSupportTicketDraft } = require("./support-ticket.cjs");
2
- const { buildIssueDiagnosticsHelpers } = require("./issue-diagnostics.cjs");
3
- const { buildIssueStackHelpers } = require("./issue-stack.cjs");
4
- const { buildLogContextHelpers } = require("./log-context.cjs");
5
- const { buildOpenTelemetryHelpers } = require("./opentelemetry.cjs");
6
- const { buildTelemetryContextHelpers } = require("./telemetry-context.cjs");
7
- const { buildTraceContextHelpers } = require("./trace-context.cjs");
8
-
9
- const SEVERITY_ALIASES = new Map([
10
- ["trace", "info"],
11
- ["debug", "info"],
12
- ["info", "info"],
13
- ["warn", "warning"],
14
- ["warning", "warning"],
15
- ["error", "error"],
16
- ["fatal", "critical"],
17
- ["critical", "critical"]
18
- ]);
19
- const SEVERITY_VALUES = new Set(SEVERITY_ALIASES.keys());
20
- const EVENT_ADMISSIONS = Object.freeze({
21
- admitted: Object.freeze({ status: "admitted" }),
22
- filtered: Object.freeze({ status: "filtered" }),
23
- unavailable: Object.freeze({ status: "unavailable" }),
24
- event_too_large: Object.freeze({ status: "dropped", reason: "event_too_large" }),
25
- queue_overflow: Object.freeze({ status: "dropped", reason: "queue_overflow" }),
26
- queue_bytes_overflow: Object.freeze({ status: "dropped", reason: "queue_bytes_overflow" })
27
- });
28
- const SPAN_STATUSES = new Set(["ok", "error"]);
29
- const ACTION_STATUSES = new Set(["queued", "running", "success", "failure"]);
30
- const PRODUCT_ANALYTICS_SCHEMA_VERSION = 1;
31
- const PRODUCT_ANALYTICS_KINDS = Object.freeze(["page_view", "screen_view", "interaction"]);
32
- const MAX_PRODUCT_ANALYTICS_SURFACE_LENGTH = 256;
33
- const METRIC_KINDS = new Set(["counter", "gauge", "histogram"]);
34
- const MAX_METRIC_DESCRIPTION_LENGTH = 1024;
35
- const NON_NEGATIVE_METRIC_KINDS = new Set(["counter", "histogram"]);
36
- const METRIC_TEMPORALITIES_BY_KIND = new Map([
37
- ["counter", new Set(["delta", "cumulative"])],
38
- ["gauge", new Set(["instant"])],
39
- ["histogram", new Set(["delta", "cumulative"])]
40
- ]);
41
- const CONSOLE_METHODS = new Set(["debug", "info", "log", "warn", "error"]);
42
- const DEFAULT_CONSOLE_LEVELS = ["debug", "info", "log", "warn", "error"];
43
- const PINO_HOST_FIELD = ["host", "name"].join("");
44
- const PINO_RESERVED_FIELDS = new Set(["level", "time", "timestamp", "msg", "message", "err", "error", "pid", PINO_HOST_FIELD, "v"]);
45
- const PINO_SENSITIVE_CONTEXT_FIELDS = new Set([
46
- "apikey",
47
- "authorization",
48
- "baggage",
49
- "body",
50
- "cookie",
51
- "credentials",
52
- "cwd",
53
- "directory",
54
- "dirname",
55
- "errorstack",
56
- "file",
57
- "filename",
58
- "filepath",
59
- "headers",
60
- "href",
61
- "key",
62
- "password",
63
- "payload",
64
- "proxyauthorization",
65
- "query",
66
- "querystring",
67
- "requestbody",
68
- "requestheaders",
69
- "requesturl",
70
- "responsebody",
71
- "responseheaders",
72
- "responseurl",
73
- "search",
74
- "secret",
75
- "setcookie",
76
- "stack",
77
- "token",
78
- "traceparent",
79
- "tracestate",
80
- "uri",
81
- "url"
82
- ]);
83
- const TRACEPARENT_PATTERN = /^([0-9a-fA-F]{2})-([0-9a-fA-F]{32})-([0-9a-fA-F]{16})-([0-9a-fA-F]{2})$/u;
84
- const ZERO_TRACE_ID = "00000000000000000000000000000000";
85
- const ZERO_SPAN_ID = "0000000000000000";
86
- const RFC3339_TIMESTAMP_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,9})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;
87
- const DEFAULT_MAX_QUEUE_SIZE = 1000;
88
- const DEFAULT_MAX_QUEUE_BYTES = 4 * 1024 * 1024;
89
- const DEFAULT_MAX_BATCH_EVENTS = 100;
90
- const DEFAULT_MAX_BATCH_BYTES = 256 * 1024;
91
- // One second matches the OpenTelemetry log processor default, so a lone event becomes readable quickly.
92
- const DEFAULT_DELIVERY_INTERVAL_MS = 1000;
93
- const MAX_DELIVERY_INTERVAL_MS = 60 * 1000;
94
- // A rate-limited batch waits from 1 second to 1 hour, plus up to 10 percent jitter, before it is sent again.
95
- const MIN_RATE_LIMIT_WAIT_MS = 1000;
96
- const MAX_RATE_LIMIT_WAIT_MS = 60 * 60 * 1000;
97
- const DEFAULT_DELIVERY_QUEUE_THRESHOLD = 50;
98
- const MAX_CLIENT_REPORT_REASONS = 16;
99
- const MAX_CLIENT_REPORT_COUNT = 1_000_000_000;
100
- const DELIVERY_HEALTH_SCHEMA_VERSION = 1;
101
- const EVENT_QUEUE_FACTORY = Symbol.for("@logbrew/sdk.eventQueueFactory");
102
- // Runtimes without an event store (browser storage) persist unreported drop counts through this seam.
103
- const CLIENT_REPORT_STORE = Symbol.for("@logbrew/sdk.clientReportStore");
104
- const CLIENT_REPORT_SAVE_INTERVAL_MS = 1_000;
105
- const CLIENT_REPORT_ID_PATTERN = /^[A-Za-z0-9_-]{16,64}$/u;
106
- const CLIENT_REPORT_REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/u;
107
- const CONTEXT_PROVIDER = Symbol.for("@logbrew/sdk.contextProvider");
108
- // Runtime packages supply request-scoped breadcrumbs through this seam; core merges them into issues.
109
- const BREADCRUMB_PROVIDER = Symbol.for("@logbrew/sdk.breadcrumbProvider");
110
- const MAX_ERROR_CAUSES = 5;
111
- const BUILTIN_ERROR_NAMES = new Set([
112
- "AggregateError",
113
- "Error",
114
- "EvalError",
115
- "RangeError",
116
- "ReferenceError",
117
- "SyntaxError",
118
- "TypeError",
119
- "URIError"
120
- ]);
121
- const MAX_SPAN_EVENTS = 8;
122
- const MAX_SPAN_LINKS = 8;
123
- const EVENT_VALIDATORS = new Map([
124
- ["release", validateRelease],
125
- ["environment", validateEnvironment],
126
- ["issue", validateIssue],
127
- ["log", validateLog],
128
- ["span", validateSpan],
129
- ["action", validateAction],
130
- ["metric", validateMetric]
131
- ]);
132
- class SdkError extends Error {
133
- constructor(code, message, details = {}) {
134
- super(message);
135
- this.name = "SdkError";
136
- this.code = code;
137
- const retryAfterMs = retryAfterMsOrUndefined(details?.retryAfterMs);
138
- if (retryAfterMs !== undefined) {
139
- this.retryAfterMs = retryAfterMs;
140
- }
141
- if (details?.retryable === true) {
142
- this.retryable = true;
143
- }
144
- }
145
- }
146
-
147
- const {
148
- compactMetadata,
149
- isMetadataValue,
150
- normalizeLogTraceContext,
151
- traceFromProvider,
152
- traceMetadataFromLogContext
153
- } = buildLogContextHelpers({ SdkError });
154
-
155
- const {
156
- javascriptStackEvidence,
157
- validateIssueStackFrames,
158
- validateNativeStackFrames
159
- } = buildIssueStackHelpers({ SdkError });
1
+ const { installBrowserBreadcrumbs } = require("./browser-breadcrumbs.cjs");
2
+ const { LogBrewClient } = require("./client.cjs");
3
+ const { installLogBrewConsoleCapture } = require("./console-capture.cjs");
4
+ const { logAttributesFromConsoleArgs, logbrewLevelFromConsoleMethod } = require("./console-arguments.cjs");
5
+ const { createIssueAttributesFromError } = require("./error-issue.cjs");
6
+ const { createNetworkMilestoneAttributes } = require("./network-milestone.cjs");
160
7
  const {
161
- MAX_ISSUE_BREADCRUMBS,
162
- cloneIssueDiagnostics,
163
- createIssueException,
164
- validateIssueBreadcrumb,
165
- validateIssueDiagnostics,
166
- validateIssueEvidence
167
- } = buildIssueDiagnosticsHelpers({ SdkError, requireTimestamp, validateIssueStackFrames });
8
+ createLogBrewOpenTelemetrySpanExporter,
9
+ createLogBrewOpenTelemetrySpanProcessor,
10
+ logbrewTraceContextFromCurrentOpenTelemetrySpan,
11
+ logbrewTraceContextFromOpenTelemetrySpan,
12
+ logbrewTraceContextFromOpenTelemetrySpanContext,
13
+ spanAttributesFromOpenTelemetryReadableSpan
14
+ } = require("./opentelemetry.cjs");
15
+ const { createLogBrewPinoDestination } = require("./pino-destination.cjs");
16
+ const { logAttributesFromPinoRecord } = require("./pino-record.cjs");
168
17
  const {
169
- cloneTelemetryContext,
170
- mergeTelemetryContexts,
171
- validateTelemetryContext
172
- } = buildTelemetryContextHelpers({ SdkError });
173
-
174
- class TransportError extends Error {
175
- constructor(code, message, retryable = false) {
176
- super(message);
177
- this.name = "TransportError";
178
- this.code = code;
179
- this.retryable = retryable;
180
- }
181
-
182
- static network(message) {
183
- return new TransportError("network_failure", message, true);
184
- }
185
- }
186
-
187
- class RecordingTransport {
188
- constructor(scriptedResponses = [{ statusCode: 202 }]) {
189
- this.scriptedResponses = [...scriptedResponses];
190
- this.sentBodies = [];
191
- }
192
-
193
- static alwaysAccept() {
194
- return new RecordingTransport([{ statusCode: 202 }]);
195
- }
196
-
197
- lastBody() {
198
- return this.sentBodies.at(-1) ?? null;
199
- }
200
-
201
- async send(apiKey, body) {
202
- requireNonEmpty("apiKey", apiKey);
203
- this.sentBodies.push(body);
204
-
205
- const next = this.scriptedResponses.length > 0
206
- ? this.scriptedResponses.shift()
207
- : { statusCode: 202 };
208
-
209
- if (next instanceof Error) {
210
- throw next;
211
- }
212
-
213
- const retryAfterMs = retryAfterMsOrUndefined(next.retryAfterMs);
214
- return {
215
- statusCode: next.statusCode,
216
- attempts: 1,
217
- ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
218
- ...(typeof next.errorCode === "string" ? { errorCode: next.errorCode } : {})
219
- };
220
- }
221
- }
222
-
223
- class LogBrewClient {
224
- static #issueCapture = LogBrewClient.prototype.issue;
225
-
226
- static create({
227
- apiKey,
228
- sdkName,
229
- sdkVersion,
230
- context,
231
- [CONTEXT_PROVIDER]: contextProvider,
232
- [BREADCRUMB_PROVIDER]: breadcrumbProvider,
233
- maxRetries = 2,
234
- eventFilter,
235
- maxQueueSize = DEFAULT_MAX_QUEUE_SIZE,
236
- maxQueueBytes = DEFAULT_MAX_QUEUE_BYTES,
237
- maxBatchEvents = DEFAULT_MAX_BATCH_EVENTS,
238
- maxBatchBytes = DEFAULT_MAX_BATCH_BYTES,
239
- onEventDropped,
240
- eventStore,
241
- [EVENT_QUEUE_FACTORY]: eventQueueFactory,
242
- [CLIENT_REPORT_STORE]: clientReportStore,
243
- transport,
244
- automaticDelivery = transport !== undefined,
245
- deliveryIntervalMs = DEFAULT_DELIVERY_INTERVAL_MS,
246
- deliveryQueueThreshold = Math.min(DEFAULT_DELIVERY_QUEUE_THRESHOLD, maxQueueSize)
247
- }) {
248
- requireNonEmpty("apiKey", apiKey);
249
- requireNonEmpty("sdkName", sdkName);
250
- requireNonEmpty("sdkVersion", sdkVersion);
251
- const clientContext = validateTelemetryContext(context, "client telemetry context");
252
- if (contextProvider !== undefined && typeof contextProvider !== "function") {
253
- throw new SdkError("validation_error", "context provider must be a function");
254
- }
255
- if (breadcrumbProvider !== undefined && typeof breadcrumbProvider !== "function") {
256
- throw new SdkError("validation_error", "breadcrumb provider must be a function");
257
- }
258
- requireNonNegativeInteger("maxRetries", maxRetries);
259
- if (eventFilter !== undefined && typeof eventFilter !== "function") {
260
- throw new SdkError("validation_error", "eventFilter must be a function");
261
- }
262
- requirePositiveInteger("maxQueueSize", maxQueueSize);
263
- requirePositiveInteger("maxQueueBytes", maxQueueBytes);
264
- requirePositiveInteger("maxBatchEvents", maxBatchEvents);
265
- requirePositiveInteger("maxBatchBytes", maxBatchBytes);
266
- if (onEventDropped !== undefined && typeof onEventDropped !== "function") {
267
- throw new SdkError("validation_error", "onEventDropped must be a function");
268
- }
269
- validateEventStore(eventStore);
270
- if (eventQueueFactory !== undefined && typeof eventQueueFactory !== "function") {
271
- throw new SdkError("validation_error", "event queue factory must be a function");
272
- }
273
- if (eventStore !== undefined && eventQueueFactory !== undefined) {
274
- throw new SdkError("validation_error", "eventStore and event queue factory are mutually exclusive");
275
- }
276
- if (clientReportStore !== undefined && !isClientReportStore(clientReportStore)) {
277
- throw new SdkError("validation_error", "client report store must provide loadClientReport and saveClientReport");
278
- }
279
- validateTransport(transport);
280
- if (typeof automaticDelivery !== "boolean") {
281
- throw new SdkError("validation_error", "automaticDelivery must be a boolean");
282
- }
283
- if (automaticDelivery && transport === undefined) {
284
- throw new SdkError("validation_error", "automaticDelivery requires transport");
285
- }
286
- requirePositiveInteger("deliveryIntervalMs", deliveryIntervalMs);
287
- if (deliveryIntervalMs > MAX_DELIVERY_INTERVAL_MS) {
288
- throw new SdkError("validation_error", `deliveryIntervalMs must be at most ${MAX_DELIVERY_INTERVAL_MS}`);
289
- }
290
- requirePositiveInteger("deliveryQueueThreshold", deliveryQueueThreshold);
291
- if (deliveryQueueThreshold > maxQueueSize) {
292
- throw new SdkError("validation_error", "deliveryQueueThreshold must not exceed maxQueueSize");
293
- }
294
-
295
- return new LogBrewClient({
296
- apiKey,
297
- automaticDelivery,
298
- deliveryIntervalMs,
299
- deliveryQueueThreshold,
300
- eventStore,
301
- eventQueueFactory,
302
- clientReportStore,
303
- eventFilter,
304
- maxBatchBytes,
305
- maxBatchEvents,
306
- maxQueueBytes,
307
- maxQueueSize,
308
- onEventDropped,
309
- context: clientContext,
310
- contextProvider,
311
- breadcrumbProvider,
312
- sdk: {
313
- name: sdkName,
314
- language: "javascript",
315
- version: sdkVersion
316
- },
317
- maxRetries,
318
- transport
319
- });
320
- }
321
-
322
- constructor({
323
- apiKey,
324
- sdk,
325
- maxRetries,
326
- eventFilter,
327
- maxBatchBytes,
328
- maxBatchEvents,
329
- maxQueueBytes,
330
- maxQueueSize,
331
- onEventDropped,
332
- context,
333
- contextProvider,
334
- breadcrumbProvider,
335
- eventStore,
336
- eventQueueFactory,
337
- clientReportStore,
338
- transport,
339
- automaticDelivery,
340
- deliveryIntervalMs,
341
- deliveryQueueThreshold
342
- }) {
343
- this.apiKey = apiKey;
344
- this.automaticDelivery = automaticDelivery;
345
- this.deliveryIntervalMs = deliveryIntervalMs;
346
- this.deliveryQueueThreshold = deliveryQueueThreshold;
347
- this.eventFilter = eventFilter;
348
- this.maxBatchBytes = maxBatchBytes;
349
- this.maxBatchEvents = maxBatchEvents;
350
- this.maxQueueBytes = maxQueueBytes;
351
- this.maxQueueSize = maxQueueSize;
352
- this.onEventDropped = onEventDropped;
353
- this.context = cloneTelemetryContext(context);
354
- this.contextProvider = contextProvider;
355
- this.breadcrumbProvider = breadcrumbProvider;
356
- this.transport = transport;
357
- this.sdk = sdk;
358
- this.maxRetries = maxRetries;
359
- this.batchPrefix = `{"sdk":${JSON.stringify(this.sdk)},"events":[`;
360
- this.batchPrefixBytes = utf8ByteLength(this.batchPrefix);
361
- this.batchSuffix = "]}";
362
- this.batchSuffixBytes = utf8ByteLength(this.batchSuffix);
363
- const ownsEventStore = eventQueueFactory !== undefined;
364
- const resolvedEventStore = ownsEventStore
365
- ? createEventStoreFromQueueFactory(eventQueueFactory, {
366
- batchPrefixBytes: this.batchPrefixBytes,
367
- batchSuffixBytes: this.batchSuffixBytes,
368
- maxBatchBytes,
369
- maxQueueBytes,
370
- maxQueueSize
371
- })
372
- : eventStore;
373
- this.eventStore = resolvedEventStore;
374
- let recovered;
375
- try {
376
- recovered = loadStoredEvents(this);
377
- } catch (error) {
378
- if (ownsEventStore) {
379
- try {
380
- requireSynchronousStoreResult("close", resolvedEventStore.close());
381
- } catch {
382
- // Preserve the queue construction or recovery failure.
383
- }
384
- }
385
- throw error;
386
- }
387
- this.events = recovered.events;
388
- this.serializedEvents = recovered.serializedEvents;
389
- this.serializedEventBytes = recovered.serializedEventBytes;
390
- this.queuedEventBytes = recovered.queuedEventBytes;
391
- this.operationTail = Promise.resolve();
392
- this.pendingOperations = 0;
393
- this.closing = false;
394
- this.closed = false;
395
- this.droppedEventCount = 0;
396
- this.droppedEventsByReason = {
397
- event_too_large: 0,
398
- evicted_for_fatal: 0,
399
- queue_bytes_overflow: 0,
400
- queue_overflow: 0
401
- };
402
- // A persistent store keeps counts not yet acknowledged by a 2xx across restarts.
403
- this.clientReportStore = clientReportStore
404
- ?? (isClientReportStore(resolvedEventStore) ? resolvedEventStore : undefined);
405
- this.clientReportSavedAtMs = 0;
406
- const restoredReport = loadClientReport(this.clientReportStore);
407
- this.unreportedDropsByReason = restoredReport.unreported;
408
- // Drop counts frozen under one report ID until a 2xx acknowledges a body that carried them.
409
- this.pendingClientReport = restoredReport.pending;
410
- this.lastDropReason = "none";
411
- this.storage = resolvedEventStore ? "persistent" : "memory";
412
- this.hydratedEventCount = recovered.events.length;
413
- this.hydratedEventBytes = recovered.queuedEventBytes;
414
- this.deliveryTimer = undefined;
415
- this.automaticFlushActive = false;
416
- this.automaticFlushPending = false;
417
- this.deliveryInFlight = false;
418
- this.lastDeliveryOutcome = "idle";
419
- this.automaticPauseReason = "none";
420
- this.consecutiveDeliveryFailures = 0;
421
- this.retryDelayMs = 0;
422
- this.successfulFlushCount = 0;
423
- this.failedFlushCount = 0;
424
- this.deliveryAttemptCount = 0;
425
- this.acceptedBatchCount = 0;
426
- this.acceptedEventCount = 0;
427
- this.lastStatusClass = "none";
428
- this.lastAttemptAtUnixMs = 0;
429
- this.lastAcceptedAtUnixMs = 0;
430
- this.lastDroppedAtUnixMs = 0;
431
- this.unacknowledgedBatch = undefined;
432
- this.issueBreadcrumbs = [];
433
- this.issueBreadcrumbsTruncated = false;
434
- this.#scheduleAutomaticDelivery();
435
- }
436
-
437
- pendingEvents() {
438
- return this.events.length;
439
- }
440
-
441
- pendingBytes() {
442
- return this.queuedEventBytes;
443
- }
444
-
445
- droppedEvents() {
446
- return this.droppedEventCount;
447
- }
448
-
449
- deliveryHealth() {
450
- const droppedByReason = Object.freeze({ ...this.droppedEventsByReason });
451
- return Object.freeze({
452
- schemaVersion: DELIVERY_HEALTH_SCHEMA_VERSION,
453
- automaticDelivery: this.automaticDelivery,
454
- lifecycle: this.closed ? "closed" : this.closing ? "shutting_down" : "active",
455
- deliveryState: this.#deliveryState(),
456
- storage: this.storage,
457
- queueEvents: this.events.length,
458
- queueBytes: this.queuedEventBytes,
459
- hydratedEvents: this.hydratedEventCount,
460
- hydratedBytes: this.hydratedEventBytes,
461
- droppedEvents: this.droppedEventCount,
462
- droppedByReason,
463
- lastDropReason: this.lastDropReason,
464
- scheduled: this.deliveryTimer !== undefined,
465
- inFlight: this.deliveryInFlight,
466
- coalesced: this.automaticFlushPending,
467
- pendingOperations: this.pendingOperations,
468
- lastOutcome: this.lastDeliveryOutcome,
469
- lastStatusClass: this.lastStatusClass,
470
- pausedReason: this.automaticPauseReason,
471
- consecutiveFailures: this.consecutiveDeliveryFailures,
472
- retryDelayMs: this.retryDelayMs,
473
- flushes: this.successfulFlushCount,
474
- failures: this.failedFlushCount,
475
- attempts: this.deliveryAttemptCount,
476
- batches: this.acceptedBatchCount,
477
- acceptedEvents: this.acceptedEventCount,
478
- lastAttemptAtUnixMs: this.lastAttemptAtUnixMs,
479
- lastAcceptedAtUnixMs: this.lastAcceptedAtUnixMs,
480
- lastDroppedAtUnixMs: this.lastDroppedAtUnixMs
481
- });
482
- }
483
-
484
- #deliveryState() {
485
- if (this.deliveryInFlight) {
486
- return "in_flight";
487
- }
488
- if (this.retryDelayMs > 0) {
489
- return "retrying";
490
- }
491
- if (this.automaticPauseReason !== "none") {
492
- return "paused";
493
- }
494
- if (this.events.length > 0) {
495
- return this.deliveryTimer !== undefined ? "scheduled" : "queued";
496
- }
497
- if (this.lastDeliveryOutcome === "accepted") {
498
- return "accepted";
499
- }
500
- if (this.lastDeliveryOutcome === "failed") {
501
- return "failed";
502
- }
503
- if (this.droppedEventCount > 0) {
504
- return "dropped";
505
- }
506
- return "idle";
507
- }
508
-
509
- previewJson() {
510
- return JSON.stringify({ sdk: this.sdk, events: this.events }, null, 2);
511
- }
512
-
513
- purgePendingEvents() {
514
- if (this.closed) {
515
- throw new SdkError("shutdown_error", "client is already shut down");
516
- }
517
- if (this.closing) {
518
- throw new SdkError("shutdown_error", "client is shutting down");
519
- }
520
- if (this.pendingOperations > 0 || this.automaticFlushActive) {
521
- throw new SdkError("persistence_error", "cannot purge while a delivery operation is active");
522
- }
523
- const purgedEvents = this.events.length;
524
- if (this.eventStore) {
525
- requireSynchronousStoreResult("purge", this.eventStore.purge());
526
- }
527
- this.#clearDeliveryTimer();
528
- this.automaticFlushPending = false;
529
- this.unacknowledgedBatch = undefined;
530
- this.events.splice(0, this.events.length);
531
- this.serializedEvents.splice(0, this.serializedEvents.length);
532
- this.serializedEventBytes.splice(0, this.serializedEventBytes.length);
533
- this.queuedEventBytes = 0;
534
- return purgedEvents;
535
- }
536
-
537
- addBreadcrumb(breadcrumb, timestamp = new Date().toISOString()) {
538
- if (this.closed) {
539
- throw new SdkError("shutdown_error", "client is already shut down");
540
- }
541
- if (this.closing) {
542
- throw new SdkError("shutdown_error", "client is shutting down");
543
- }
544
- const validated = validateIssueBreadcrumb(breadcrumb, timestamp);
545
- if (this.issueBreadcrumbs.length === MAX_ISSUE_BREADCRUMBS) {
546
- this.issueBreadcrumbs.shift();
547
- this.issueBreadcrumbsTruncated = true;
548
- }
549
- this.issueBreadcrumbs.push(validated);
550
- }
551
-
552
- clearBreadcrumbs() {
553
- const cleared = this.issueBreadcrumbs.length;
554
- this.issueBreadcrumbs.splice(0, cleared);
555
- this.issueBreadcrumbsTruncated = false;
556
- return cleared;
557
- }
558
-
559
- release(id, timestamp, attributes) {
560
- this.#pushEvent("release", id, timestamp, validateRelease(attributes));
561
- }
562
-
563
- environment(id, timestamp, attributes) {
564
- this.#pushEvent("environment", id, timestamp, validateEnvironment(attributes));
565
- }
566
-
567
- issue(id, timestamp, attributes) {
568
- this.#pushIssue(id, timestamp, attributes);
569
- }
570
-
571
- issueWithAdmission(id, timestamp, attributes) {
572
- const issue = this.issue;
573
- if (issue !== LogBrewClient.#issueCapture) {
574
- issue.call(this, id, timestamp, attributes);
575
- return EVENT_ADMISSIONS.unavailable;
576
- }
577
- return this.#pushIssue(id, timestamp, attributes);
578
- }
579
-
580
- log(id, timestamp, attributes) {
581
- this.#pushEvent("log", id, timestamp, validateLog(attributes));
582
- }
583
-
584
- span(id, timestamp, attributes) {
585
- this.#pushEvent("span", id, timestamp, validateSpan(attributes));
586
- }
587
-
588
- action(id, timestamp, attributes) {
589
- this.#pushEvent("action", id, timestamp, validateAction(attributes));
590
- }
591
-
592
- metric(id, timestamp, attributes) {
593
- this.#pushEvent("metric", id, timestamp, validateMetric(attributes));
594
- }
595
-
596
- async flush(transport) {
597
- if (this.closed) {
598
- throw new SdkError("shutdown_error", "client is already shut down");
599
- }
600
- if (this.closing) {
601
- throw new SdkError("shutdown_error", "client is shutting down");
602
- }
603
- const resolvedTransport = this.#resolveTransport(transport);
604
- const controlsAutomaticDelivery = this.automaticDelivery && resolvedTransport === this.transport;
605
- this.#clearDeliveryTimer();
606
- return this.#runSerialized(async () => {
607
- this.#clearDeliveryTimer();
608
- try {
609
- const response = await this.#flushWithHealth(resolvedTransport);
610
- if (controlsAutomaticDelivery) {
611
- this.#recordAutomaticSuccess();
612
- }
613
- return response;
614
- } catch (error) {
615
- if (controlsAutomaticDelivery) {
616
- this.#recordAutomaticFailure(error);
617
- }
618
- throw error;
619
- } finally {
620
- if (this.automaticDelivery && !this.closed && !this.closing) {
621
- this.#resumeAutomaticDelivery();
622
- }
623
- }
624
- });
625
- }
626
-
627
- async shutdown(transport) {
628
- if (this.closed) {
629
- throw new SdkError("shutdown_error", "client is already shut down");
630
- }
631
- if (this.closing) {
632
- throw new SdkError("shutdown_error", "client is shutting down");
633
- }
634
- const resolvedTransport = this.#resolveTransport(transport);
635
- const controlsAutomaticDelivery = this.automaticDelivery && resolvedTransport === this.transport;
636
- this.#clearDeliveryTimer();
637
- this.automaticFlushPending = false;
638
- this.closing = true;
639
- try {
640
- const response = await this.#runSerialized(() => this.#flushWithHealth(resolvedTransport));
641
- if (controlsAutomaticDelivery) {
642
- this.#recordAutomaticSuccess();
643
- }
644
- this.#saveClientReport(true);
645
- if (this.eventStore) {
646
- try {
647
- requireSynchronousStoreResult("close", this.eventStore.close());
648
- } catch (error) {
649
- this.closed = true;
650
- throw error;
651
- }
652
- }
653
- this.closed = true;
654
- return response;
655
- } catch (error) {
656
- if (!this.closed) {
657
- this.closing = false;
658
- if (controlsAutomaticDelivery) {
659
- this.#recordAutomaticFailure(error);
660
- }
661
- this.#resumeAutomaticDelivery();
662
- }
663
- throw error;
664
- }
665
- }
666
-
667
- #pushIssue(id, timestamp, attributes) {
668
- if (attributes.breadcrumbs !== undefined) {
669
- return this.#pushEvent("issue", id, timestamp, validateIssue(attributes));
670
- }
671
- const provided = this.#providedBreadcrumbs();
672
- const merged = provided.breadcrumbs.length === 0
673
- ? this.issueBreadcrumbs
674
- : [...this.issueBreadcrumbs, ...provided.breadcrumbs]
675
- .sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp));
676
- const breadcrumbs = merged.slice(-MAX_ISSUE_BREADCRUMBS);
677
- const truncated = attributes.breadcrumbsTruncated === true || this.issueBreadcrumbsTruncated
678
- || provided.truncated || merged.length > breadcrumbs.length;
679
- const withBreadcrumbs = breadcrumbs.length === 0
680
- ? attributes
681
- : { ...attributes, breadcrumbs, ...(truncated ? { breadcrumbsTruncated: true } : {}) };
682
- return this.#pushEvent("issue", id, timestamp, validateIssue(withBreadcrumbs));
683
- }
684
-
685
- // Provider failures and invalid entries never cost the issue itself.
686
- #providedBreadcrumbs() {
687
- let provided;
688
- try {
689
- provided = this.breadcrumbProvider?.();
690
- } catch {
691
- return { breadcrumbs: [], truncated: false };
692
- }
693
- if (!provided || !Array.isArray(provided.breadcrumbs)) {
694
- return { breadcrumbs: [], truncated: false };
695
- }
696
- const breadcrumbs = [];
697
- let truncated = provided.truncated === true || provided.breadcrumbs.length > MAX_ISSUE_BREADCRUMBS;
698
- for (const breadcrumb of provided.breadcrumbs.slice(-MAX_ISSUE_BREADCRUMBS)) {
699
- try {
700
- breadcrumbs.push(validateIssueBreadcrumb(breadcrumb));
701
- } catch {
702
- truncated = true;
703
- }
704
- }
705
- return { breadcrumbs, truncated };
706
- }
707
-
708
- #pushEvent(eventType, id, timestamp, attributes) {
709
- if (this.closed) {
710
- throw new SdkError("shutdown_error", "client is already shut down");
711
- }
712
- if (this.closing) {
713
- throw new SdkError("shutdown_error", "client is shutting down");
714
- }
715
- requireNonEmpty("event id", id);
716
- requireTimestamp(timestamp);
717
- const context = mergeTelemetryContexts(
718
- mergeTelemetryContexts(this.context, this.contextProvider?.()),
719
- attributes.context
720
- );
721
- const eventAttributes = context === undefined
722
- ? attributes
723
- : { ...attributes, context };
724
- const event = { type: eventType, id, timestamp, attributes: eventAttributes };
725
- if (this.eventFilter && this.eventFilter(cloneEvent(event)) === false) {
726
- return EVENT_ADMISSIONS.filtered;
727
- }
728
- const serializedEvent = JSON.stringify(event);
729
- const eventBytes = utf8ByteLength(serializedEvent);
730
- if (this.batchPrefixBytes + eventBytes + this.batchSuffixBytes > this.maxBatchBytes) {
731
- this.#recordDroppedEvent(event, "event_too_large");
732
- return EVENT_ADMISSIONS.event_too_large;
733
- }
734
- const fatal = isFatalEvent(event);
735
- if (fatal) {
736
- this.#synchronizeEventStore();
737
- }
738
- const overflow = this.#overflowReason(this.events.length, this.queuedEventBytes + eventBytes);
739
- const evicted = overflow && fatal ? this.#evictForFatal(eventBytes) : [];
740
- if (overflow && evicted.length === 0) {
741
- this.#recordDroppedEvent(event, overflow);
742
- return EVENT_ADMISSIONS[overflow];
743
- }
744
- try {
745
- if (this.eventStore) {
746
- requireSynchronousStoreResult("append", this.eventStore.append({
747
- event: cloneEvent(event),
748
- eventBytes,
749
- serializedEvent
750
- }));
751
- }
752
- this.events.push(event);
753
- this.serializedEvents.push(serializedEvent);
754
- this.serializedEventBytes.push(eventBytes);
755
- this.queuedEventBytes += eventBytes;
756
- } finally {
757
- // Report evictions only after admission so drop callbacks cannot refill the freed room.
758
- for (const evictedEvent of evicted) {
759
- this.#recordDroppedEvent(evictedEvent, "evicted_for_fatal");
760
- }
761
- }
762
- this.#scheduleAutomaticDelivery();
763
- return EVENT_ADMISSIONS.admitted;
764
- }
765
-
766
- #overflowReason(count, bytes) {
767
- if (count >= this.maxQueueSize) {
768
- return "queue_overflow";
769
- }
770
- return bytes > this.maxQueueBytes ? "queue_bytes_overflow" : undefined;
771
- }
772
-
773
- // Evicts the oldest non-fatal events outside the unacknowledged batch, only when that makes room.
774
- #evictForFatal(eventBytes) {
775
- if (this.eventStore && typeof this.eventStore.remove !== "function") {
776
- return [];
777
- }
778
- const indexes = [];
779
- let count = this.events.length;
780
- let bytes = this.queuedEventBytes + eventBytes;
781
- for (
782
- let index = this.unacknowledgedBatch?.eventsCount ?? 0;
783
- index < this.events.length && this.#overflowReason(count, bytes);
784
- index += 1
785
- ) {
786
- if (!isFatalEvent(this.events[index])) {
787
- indexes.push(index);
788
- count -= 1;
789
- bytes -= this.serializedEventBytes[index];
790
- }
791
- }
792
- if (this.#overflowReason(count, bytes)) {
793
- return [];
794
- }
795
- if (this.eventStore) {
796
- requireSynchronousStoreResult("remove", this.eventStore.remove(indexes));
797
- }
798
- const evicted = indexes.map((index) => this.events[index]);
799
- for (let position = indexes.length - 1; position >= 0; position -= 1) {
800
- const index = indexes[position];
801
- this.events.splice(index, 1);
802
- this.serializedEvents.splice(index, 1);
803
- this.queuedEventBytes -= this.serializedEventBytes.splice(index, 1)[0];
804
- }
805
- return evicted;
806
- }
807
-
808
- #recordDroppedEvent(event, reason) {
809
- this.droppedEventCount = incrementBounded(this.droppedEventCount);
810
- this.droppedEventsByReason[reason] = incrementBounded(this.droppedEventsByReason[reason]);
811
- const firstOfReason = this.unreportedDropsByReason[reason] === undefined;
812
- this.unreportedDropsByReason[reason] = Math.min(MAX_CLIENT_REPORT_COUNT, (this.unreportedDropsByReason[reason] ?? 0) + 1);
813
- this.#saveClientReport(firstOfReason);
814
- this.lastDropReason = reason;
815
- this.lastDroppedAtUnixMs = nextBoundedTimestamp(this.lastDroppedAtUnixMs);
816
- if (!this.onEventDropped) {
817
- return;
818
- }
819
- try {
820
- this.onEventDropped({
821
- droppedEvents: this.droppedEventCount,
822
- eventId: event.id,
823
- eventType: event.type,
824
- reason
825
- });
826
- } catch {
827
- // Drop callbacks are advisory and must not interrupt application logging.
828
- }
829
- }
830
-
831
- #runSerialized(operation) {
832
- this.pendingOperations = incrementBounded(this.pendingOperations);
833
- const result = this.operationTail.then(operation).finally(() => {
834
- this.pendingOperations = Math.max(0, this.pendingOperations - 1);
835
- });
836
- this.operationTail = result.then(
837
- () => undefined,
838
- () => undefined
839
- );
840
- return result;
841
- }
842
-
843
- #resolveTransport(transport) {
844
- const resolved = transport ?? this.transport;
845
- if (resolved === undefined) {
846
- throw new SdkError("validation_error", "flush and shutdown require transport");
847
- }
848
- validateTransport(resolved);
849
- return resolved;
850
- }
851
-
852
- async #flushWithHealth(transport) {
853
- this.deliveryInFlight = true;
854
- try {
855
- const response = await this.#flushSnapshot(transport);
856
- this.successfulFlushCount = incrementBounded(this.successfulFlushCount);
857
- this.lastDeliveryOutcome = response.batches === 0 ? "empty" : "accepted";
858
- return response;
859
- } catch (error) {
860
- this.failedFlushCount = incrementBounded(this.failedFlushCount);
861
- this.lastDeliveryOutcome = "failed";
862
- throw error;
863
- } finally {
864
- this.deliveryInFlight = false;
865
- }
866
- }
867
-
868
- #scheduleAutomaticDelivery() {
869
- if (!this.automaticDelivery || this.closed || this.closing || this.events.length === 0 || this.automaticPauseReason !== "none") {
870
- return;
871
- }
872
- if (this.automaticFlushActive) {
873
- this.automaticFlushPending = true;
874
- return;
875
- }
876
- if (this.retryDelayMs > 0) {
877
- this.#armAutomaticDeliveryTimer(this.retryDelayMs);
878
- return;
879
- }
880
- if (this.events.length >= this.deliveryQueueThreshold) {
881
- this.#requestAutomaticFlush();
882
- return;
883
- }
884
- this.#armAutomaticDeliveryTimer();
885
- }
886
-
887
- #armAutomaticDeliveryTimer(delayMs = this.deliveryIntervalMs) {
888
- if (!this.automaticDelivery || this.closed || this.closing || this.events.length === 0 || this.automaticPauseReason !== "none") {
889
- return;
890
- }
891
- if (this.deliveryTimer !== undefined) {
892
- return;
893
- }
894
- const timer = setTimeout(() => {
895
- if (this.deliveryTimer !== timer) {
896
- return;
897
- }
898
- this.deliveryTimer = undefined;
899
- this.retryDelayMs = 0;
900
- this.#requestAutomaticFlush();
901
- }, delayMs);
902
- this.deliveryTimer = timer;
903
- if (timer && typeof timer === "object" && typeof timer.unref === "function") {
904
- timer.unref();
905
- }
906
- }
907
-
908
- #clearDeliveryTimer() {
909
- if (this.deliveryTimer === undefined) {
910
- return;
911
- }
912
- globalThis.clearTimeout(this.deliveryTimer);
913
- this.deliveryTimer = undefined;
914
- }
915
-
916
- #requestAutomaticFlush() {
917
- if (!this.automaticDelivery || this.closed || this.closing || this.events.length === 0 || this.automaticPauseReason !== "none") {
918
- return;
919
- }
920
- this.#clearDeliveryTimer();
921
- if (this.automaticFlushActive) {
922
- this.automaticFlushPending = true;
923
- return;
924
- }
925
- this.automaticFlushActive = true;
926
- void Promise.resolve().then(() => this.#runAutomaticFlush());
927
- }
928
-
929
- async #runAutomaticFlush() {
930
- if (this.closed || this.closing) {
931
- this.automaticFlushActive = false;
932
- this.automaticFlushPending = false;
933
- return;
934
- }
935
- let succeeded = false;
936
- try {
937
- await this.#runSerialized(() => this.#flushWithHealth(this.transport));
938
- this.#recordAutomaticSuccess();
939
- succeeded = true;
940
- } catch (error) {
941
- this.#recordAutomaticFailure(error);
942
- } finally {
943
- this.automaticFlushActive = false;
944
- if (this.closed || this.closing) {
945
- this.automaticFlushPending = false;
946
- } else {
947
- const drainCoalesced = succeeded && this.automaticFlushPending && this.events.length > 0;
948
- this.automaticFlushPending = false;
949
- if (drainCoalesced) {
950
- this.#requestAutomaticFlush();
951
- } else if (!succeeded) {
952
- this.#resumeAutomaticDelivery();
953
- } else {
954
- this.#scheduleAutomaticDelivery();
955
- }
956
- }
957
- }
958
- }
959
-
960
- async #flushSnapshot(transport) {
961
- this.#synchronizeEventStore();
962
- let remainingEvents = this.events.length;
963
- if (remainingEvents === 0) {
964
- return { statusCode: 204, attempts: 0, batches: 0 };
965
- }
966
-
967
- let attempts = 0;
968
- let batches = 0;
969
- let statusCode = 204;
970
- while (remainingEvents > 0) {
971
- // Eviction for a fatal event can shrink the snapshot while a batch is in flight.
972
- this.unacknowledgedBatch ??= Object.freeze(
973
- this.#nextBatch(Math.min(remainingEvents, this.events.length, this.maxBatchEvents))
974
- );
975
- const batch = this.unacknowledgedBatch;
976
- const response = await this.#sendBatch(transport, batch.body);
977
- this.unacknowledgedBatch = undefined;
978
- // Drops recorded while this body was in flight stay pending under a new report ID.
979
- if (batch.carriesClientReport) {
980
- this.pendingClientReport = undefined;
981
- this.#saveClientReport(true);
982
- }
983
- this.#acknowledge(batch.eventsCount);
984
- this.acceptedBatchCount = incrementBounded(this.acceptedBatchCount);
985
- remainingEvents -= batch.eventsCount;
986
- attempts += response.attempts;
987
- batches += 1;
988
- statusCode = response.statusCode;
989
- }
990
-
991
- return { statusCode, attempts, batches };
992
- }
993
-
994
- #synchronizeEventStore() {
995
- if (!this.eventStore) {
996
- return;
997
- }
998
- const recovered = loadStoredEvents(this);
999
- if (!isOrderedSubsequence(this.serializedEvents, recovered.serializedEvents)) {
1000
- throw new SdkError("persistence_error", "event store lost a queued record");
1001
- }
1002
- this.events = recovered.events;
1003
- this.serializedEvents = recovered.serializedEvents;
1004
- this.serializedEventBytes = recovered.serializedEventBytes;
1005
- this.queuedEventBytes = recovered.queuedEventBytes;
1006
- }
1007
-
1008
- #nextBatch(maxEvents) {
1009
- const report = this.#pendingClientReport();
1010
- const reportSuffix = report && `],"client_report":${JSON.stringify(report)}}`;
1011
- const reportedEvents = reportSuffix ? this.#batchEventCount(maxEvents, utf8ByteLength(reportSuffix)) : 0;
1012
- const eventsCount = reportedEvents || this.#batchEventCount(maxEvents, this.batchSuffixBytes);
1013
- if (eventsCount === 0) {
1014
- throw new SdkError("transport_error", "queued event cannot fit the configured batch byte limit");
1015
- }
1016
- return {
1017
- body: `${this.batchPrefix}${this.serializedEvents.slice(0, eventsCount).join(",")}${reportedEvents ? reportSuffix : this.batchSuffix}`,
1018
- carriesClientReport: reportedEvents > 0,
1019
- eventsCount
1020
- };
1021
- }
1022
-
1023
- // Freezes unreported drops under one stable ID, so every resend of them is counted once.
1024
- #pendingClientReport() {
1025
- if (this.pendingClientReport === undefined) {
1026
- const reported = Object.entries(this.unreportedDropsByReason).filter(([, count]) => count > 0);
1027
- if (reported.length === 0) {
1028
- return undefined;
1029
- }
1030
- const droppedEvents = Object.fromEntries(reported.slice(0, MAX_CLIENT_REPORT_REASONS));
1031
- for (const reason of Object.keys(droppedEvents)) {
1032
- delete this.unreportedDropsByReason[reason];
1033
- }
1034
- this.pendingClientReport = Object.freeze({ report_id: randomHex(16), dropped_events: droppedEvents });
1035
- this.#saveClientReport(true);
1036
- }
1037
- return this.pendingClientReport;
1038
- }
1039
-
1040
- // Saves at once for a new report or reason, and at most once a second during a drop burst.
1041
- #saveClientReport(immediately) {
1042
- const now = Date.now();
1043
- if (!this.clientReportStore || (!immediately && now - this.clientReportSavedAtMs < CLIENT_REPORT_SAVE_INTERVAL_MS)) {
1044
- return;
1045
- }
1046
- this.clientReportSavedAtMs = now;
1047
- try {
1048
- requireSynchronousStoreResult("saveClientReport", this.clientReportStore.saveClientReport({
1049
- pending: this.pendingClientReport ?? null,
1050
- unreported: { ...this.unreportedDropsByReason }
1051
- }));
1052
- } catch {
1053
- // Drop counts are advisory: a failed save keeps them in memory and never blocks capture.
1054
- }
1055
- }
1056
-
1057
- #batchEventCount(maxEvents, suffixBytes) {
1058
- let bodyBytes = this.batchPrefixBytes + suffixBytes;
1059
- let eventsCount = 0;
1060
- const eventIds = new Set();
1061
- for (let index = 0; index < maxEvents; index += 1) {
1062
- if (eventIds.has(this.events[index].id)) {
1063
- break;
1064
- }
1065
- const separatorBytes = eventsCount === 0 ? 0 : 1;
1066
- const nextBodyBytes = bodyBytes + separatorBytes + this.serializedEventBytes[index];
1067
- if (nextBodyBytes > this.maxBatchBytes) {
1068
- break;
1069
- }
1070
- eventIds.add(this.events[index].id);
1071
- bodyBytes = nextBodyBytes;
1072
- eventsCount += 1;
1073
- }
1074
- return eventsCount;
1075
- }
1076
-
1077
- #acknowledge(eventsCount) {
1078
- if (this.eventStore) {
1079
- requireSynchronousStoreResult("acknowledge", this.eventStore.acknowledge(eventsCount));
1080
- }
1081
- let acknowledgedBytes = 0;
1082
- for (let index = 0; index < eventsCount; index += 1) {
1083
- acknowledgedBytes += this.serializedEventBytes[index];
1084
- }
1085
- this.events.splice(0, eventsCount);
1086
- this.serializedEvents.splice(0, eventsCount);
1087
- this.serializedEventBytes.splice(0, eventsCount);
1088
- this.queuedEventBytes -= acknowledgedBytes;
1089
- this.acceptedEventCount = addBounded(this.acceptedEventCount, eventsCount);
1090
- this.lastAcceptedAtUnixMs = nextBoundedTimestamp(Math.max(
1091
- this.lastAcceptedAtUnixMs,
1092
- this.lastAttemptAtUnixMs
1093
- ));
1094
- }
1095
-
1096
- #recordAutomaticSuccess() {
1097
- this.automaticPauseReason = "none";
1098
- this.consecutiveDeliveryFailures = 0;
1099
- this.retryDelayMs = 0;
1100
- }
1101
-
1102
- #recordAutomaticFailure(error) {
1103
- this.consecutiveDeliveryFailures = incrementBounded(this.consecutiveDeliveryFailures);
1104
- this.retryDelayMs = 0;
1105
- if (error instanceof SdkError && error.code === "unauthenticated") {
1106
- this.automaticPauseReason = "authentication";
1107
- return;
1108
- }
1109
- if (error instanceof SdkError && error.code === "rate_limited") {
1110
- if (error.retryable === true) {
1111
- this.automaticPauseReason = "none";
1112
- this.retryDelayMs = rateLimitWaitMs(
1113
- error.retryAfterMs ?? automaticRetryDelayMs(this.deliveryIntervalMs, this.consecutiveDeliveryFailures)
1114
- );
1115
- return;
1116
- }
1117
- this.automaticPauseReason = "rate_limit";
1118
- return;
1119
- }
1120
- if (error instanceof SdkError && error.retryable === true) {
1121
- this.automaticPauseReason = "none";
1122
- this.retryDelayMs = automaticRetryDelayMs(this.deliveryIntervalMs, this.consecutiveDeliveryFailures);
1123
- return;
1124
- }
1125
- this.automaticPauseReason = "non_retryable";
1126
- }
1127
-
1128
- #resumeAutomaticDelivery() {
1129
- if (this.automaticPauseReason !== "none") {
1130
- return;
1131
- }
1132
- if (this.retryDelayMs > 0) {
1133
- this.#armAutomaticDeliveryTimer(this.retryDelayMs);
1134
- return;
1135
- }
1136
- this.#scheduleAutomaticDelivery();
1137
- }
1138
-
1139
- async #sendBatch(transport, body) {
1140
- const maxAttempts = this.maxRetries + 1;
1141
- let attempts = 0;
1142
-
1143
- while (attempts < maxAttempts) {
1144
- attempts += 1;
1145
- this.deliveryAttemptCount = incrementBounded(this.deliveryAttemptCount);
1146
- this.lastAttemptAtUnixMs = nextBoundedTimestamp(this.lastAttemptAtUnixMs);
1147
- this.lastStatusClass = "transport_error";
1148
- try {
1149
- const response = await transport.send(this.apiKey, body);
1150
- if (
1151
- !response
1152
- || Array.isArray(response)
1153
- || typeof response !== "object"
1154
- || !Number.isSafeInteger(response.statusCode)
1155
- || response.statusCode < 100
1156
- || response.statusCode > 599
1157
- ) {
1158
- this.lastStatusClass = "invalid_response";
1159
- throw new SdkError("transport_error", "invalid transport response");
1160
- }
1161
- this.lastStatusClass = statusClass(response.statusCode);
1162
- if (response.statusCode === 401) {
1163
- throw new SdkError("unauthenticated", "transport rejected the API key");
1164
- }
1165
- if (response.statusCode === 429) {
1166
- throw new SdkError("rate_limited", "transport rate limited the batch", {
1167
- retryAfterMs: response.retryAfterMs,
1168
- retryable: response.errorCode !== "usage_limit_exceeded"
1169
- && (retryAfterMsOrUndefined(response.retryAfterMs) !== undefined || response.errorCode === "rate_limited")
1170
- });
1171
- }
1172
- if (response.statusCode >= 200 && response.statusCode < 300) {
1173
- return { statusCode: response.statusCode, attempts };
1174
- }
1175
- const retryableStatus = response.statusCode === 408 || response.statusCode >= 500;
1176
- if (retryableStatus && attempts < maxAttempts) {
1177
- continue;
1178
- }
1179
- throw new SdkError("transport_error", `unexpected transport status ${response.statusCode}`, {
1180
- retryable: retryableStatus
1181
- });
1182
- } catch (error) {
1183
- if (error instanceof SdkError) {
1184
- throw error;
1185
- }
1186
- if (error instanceof TransportError && error.retryable && attempts < maxAttempts) {
1187
- this.lastStatusClass = "network_error";
1188
- continue;
1189
- }
1190
- if (error instanceof TransportError) {
1191
- this.lastStatusClass = "network_error";
1192
- throw new SdkError(error.code, error.message, { retryable: error.retryable });
1193
- }
1194
- throw error;
1195
- }
1196
- }
1197
-
1198
- throw new SdkError("transport_error", "exhausted retries");
1199
- }
1200
- }
1201
-
1202
- function automaticRetryDelayMs(deliveryIntervalMs, consecutiveFailures) {
1203
- const exponent = Math.min(consecutiveFailures - 1, 30);
1204
- const maximumDelay = Math.min(MAX_DELIVERY_INTERVAL_MS, deliveryIntervalMs * (2 ** exponent));
1205
- const minimumDelay = Math.ceil(maximumDelay / 2);
1206
- return minimumDelay + Math.floor(Math.random() * (maximumDelay - minimumDelay + 1));
1207
- }
1208
-
1209
- function rateLimitWaitMs(delayMs) {
1210
- const bounded = Math.min(MAX_RATE_LIMIT_WAIT_MS, Math.max(MIN_RATE_LIMIT_WAIT_MS, delayMs));
1211
- return Math.min(MAX_RATE_LIMIT_WAIT_MS, bounded + Math.floor(Math.random() * (Math.floor(bounded / 10) + 1)));
1212
- }
1213
-
1214
- function statusClass(statusCode) {
1215
- if (statusCode >= 200 && statusCode < 300) {
1216
- return "success";
1217
- }
1218
- if (statusCode >= 400 && statusCode < 500) {
1219
- return "client_error";
1220
- }
1221
- if (statusCode >= 500) {
1222
- return "server_error";
1223
- }
1224
- return "other_status";
1225
- }
1226
-
1227
- function nextBoundedTimestamp(previous) {
1228
- const now = Date.now();
1229
- if (!Number.isFinite(now)) {
1230
- return previous;
1231
- }
1232
- const bounded = Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.floor(now)));
1233
- return Math.max(previous, bounded);
1234
- }
1235
-
1236
- function addBounded(current, increment) {
1237
- return Math.min(Number.MAX_SAFE_INTEGER, current + increment);
1238
- }
1239
-
1240
- function utf8ByteLength(value) {
1241
- let bytes = 0;
1242
- for (let index = 0; index < value.length; index += 1) {
1243
- const codeUnit = value.charCodeAt(index);
1244
- if (codeUnit < 0x80) {
1245
- bytes += 1;
1246
- } else if (codeUnit < 0x800) {
1247
- bytes += 2;
1248
- } else if (codeUnit >= 0xd800 && codeUnit <= 0xdbff && index + 1 < value.length) {
1249
- const nextCodeUnit = value.charCodeAt(index + 1);
1250
- if (nextCodeUnit >= 0xdc00 && nextCodeUnit <= 0xdfff) {
1251
- bytes += 4;
1252
- index += 1;
1253
- } else {
1254
- bytes += 3;
1255
- }
1256
- } else {
1257
- bytes += 3;
1258
- }
1259
- }
1260
- return bytes;
1261
- }
1262
-
1263
- // Fatal input severity is stored as critical; a critical issue is a crash report.
1264
- function isFatalEvent(event) {
1265
- return event.type === "issue" && event.attributes.level === "critical";
1266
- }
1267
-
1268
- // Report IDs only need uniqueness, so runtimes without Web Crypto fall back to Math.random.
1269
- function randomHex(byteLength) {
1270
- const bytes = new Uint8Array(byteLength);
1271
- if (typeof globalThis.crypto?.getRandomValues === "function") {
1272
- globalThis.crypto.getRandomValues(bytes);
1273
- } else {
1274
- for (let index = 0; index < bytes.length; index += 1) {
1275
- bytes[index] = Math.floor(Math.random() * 256);
1276
- }
1277
- }
1278
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1279
- }
1280
-
1281
- function isClientReportStore(store) {
1282
- return typeof store?.loadClientReport === "function" && typeof store.saveClientReport === "function";
1283
- }
1284
-
1285
- // Restores saved drop counts; anything unreadable or out of bounds is ignored, never fatal.
1286
- function loadClientReport(store) {
1287
- let state;
1288
- try {
1289
- state = store ? requireSynchronousStoreResult("loadClientReport", store.loadClientReport()) : undefined;
1290
- } catch {
1291
- state = undefined;
1292
- }
1293
- const pending = state?.pending;
1294
- const pendingCounts = validClientReportCounts(pending?.dropped_events);
1295
- return {
1296
- pending: CLIENT_REPORT_ID_PATTERN.test(pending?.report_id ?? "") && Object.keys(pendingCounts).length > 0
1297
- ? Object.freeze({ report_id: pending.report_id, dropped_events: pendingCounts })
1298
- : undefined,
1299
- unreported: validClientReportCounts(state?.unreported)
1300
- };
1301
- }
1302
-
1303
- function validClientReportCounts(counts) {
1304
- if (!counts || typeof counts !== "object" || Array.isArray(counts)) {
1305
- return {};
1306
- }
1307
- return Object.fromEntries(Object.entries(counts).filter(([reason, count]) => (
1308
- CLIENT_REPORT_REASON_PATTERN.test(reason) && Number.isSafeInteger(count) && count >= 1 && count <= MAX_CLIENT_REPORT_COUNT
1309
- )).slice(0, MAX_CLIENT_REPORT_REASONS));
1310
- }
1311
-
1312
- function incrementBounded(value) {
1313
- return value >= Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : value + 1;
1314
- }
1315
-
1316
- function validateTransport(transport) {
1317
- if (transport === undefined) {
1318
- return;
1319
- }
1320
- if (!transport || Array.isArray(transport) || typeof transport !== "object" || typeof transport.send !== "function") {
1321
- throw new SdkError("validation_error", "transport.send must be a function");
1322
- }
1323
- }
1324
-
1325
- function validateEventStore(eventStore) {
1326
- if (eventStore === undefined) {
1327
- return;
1328
- }
1329
- if (!eventStore || Array.isArray(eventStore) || typeof eventStore !== "object") {
1330
- throw new SdkError("validation_error", "eventStore must be an object");
1331
- }
1332
- for (const method of ["load", "append", "acknowledge", "purge", "close"]) {
1333
- if (typeof eventStore[method] !== "function") {
1334
- throw new SdkError("validation_error", `eventStore.${method} must be a function`);
1335
- }
1336
- }
1337
- }
1338
-
1339
- function createEventStoreFromQueueFactory(eventQueueFactory, config) {
1340
- const queue = eventQueueFactory({
1341
- ...config,
1342
- restoreEvent: restoreStoredEvent
1343
- });
1344
- validateEventQueue(queue);
1345
- const eventStore = {
1346
- load() {
1347
- const events = queue.events();
1348
- const count = queue.length();
1349
- if (!Array.isArray(events) || events.length !== count) {
1350
- throw invalidStoredRecord();
1351
- }
1352
- return events.map((event, index) => ({
1353
- event,
1354
- eventBytes: queue.eventBytesAt(index),
1355
- serializedEvent: queue.serializedAt(index)
1356
- }));
1357
- },
1358
- append(record) {
1359
- return queue.append({
1360
- event: record.event,
1361
- byteCount: record.eventBytes,
1362
- serialized: record.serializedEvent
1363
- });
1364
- },
1365
- acknowledge(count) {
1366
- return queue.acknowledge(count);
1367
- },
1368
- purge() {
1369
- return queue.acknowledge(queue.length());
1370
- },
1371
- close() {
1372
- return queue.close();
1373
- }
1374
- };
1375
- if (typeof queue.remove === "function") {
1376
- eventStore.remove = (indexes) => queue.remove(indexes);
1377
- }
1378
- if (isClientReportStore(queue)) {
1379
- eventStore.loadClientReport = () => queue.loadClientReport();
1380
- eventStore.saveClientReport = (state) => queue.saveClientReport(state);
1381
- }
1382
- return eventStore;
1383
- }
1384
-
1385
- function validateEventQueue(queue) {
1386
- const methods = [
1387
- "acknowledge",
1388
- "append",
1389
- "byteCount",
1390
- "close",
1391
- "eventBytesAt",
1392
- "events",
1393
- "length",
1394
- "serializedAt"
1395
- ];
1396
- if (!queue || Array.isArray(queue) || typeof queue !== "object" || methods.some((method) => typeof queue[method] !== "function")) {
1397
- throw new SdkError("validation_error", "event queue factory returned an invalid queue");
1398
- }
1399
- }
1400
-
1401
- function restoreStoredEvent(serializedEvent) {
1402
- if (typeof serializedEvent !== "string" || serializedEvent === "") {
1403
- throw invalidStoredRecord();
1404
- }
1405
- let event;
1406
- try {
1407
- event = JSON.parse(serializedEvent);
1408
- } catch {
1409
- throw invalidStoredRecord();
1410
- }
1411
- return normalizeStoredRecord({
1412
- event,
1413
- eventBytes: utf8ByteLength(serializedEvent),
1414
- serializedEvent
1415
- }).event;
1416
- }
1417
-
1418
- function requireSynchronousStoreResult(operation, result) {
1419
- if (result && typeof result.then === "function") {
1420
- throw new SdkError("persistence_error", `eventStore.${operation} must complete synchronously`);
1421
- }
1422
- return result;
1423
- }
1424
-
1425
- function loadStoredEvents({
1426
- batchPrefixBytes,
1427
- batchSuffixBytes,
1428
- eventStore,
1429
- maxBatchBytes,
1430
- maxQueueBytes,
1431
- maxQueueSize
1432
- }) {
1433
- if (!eventStore) {
1434
- return {
1435
- events: [],
1436
- queuedEventBytes: 0,
1437
- serializedEventBytes: [],
1438
- serializedEvents: []
1439
- };
1440
- }
1441
-
1442
- const records = requireSynchronousStoreResult("load", eventStore.load());
1443
- if (!Array.isArray(records)) {
1444
- throw invalidStoredRecord();
1445
- }
1446
- if (records.length > maxQueueSize) {
1447
- throw new SdkError("persistence_error", "recovered event count exceeds maxQueueSize");
1448
- }
1449
-
1450
- const events = [];
1451
- const serializedEvents = [];
1452
- const serializedEventBytes = [];
1453
- let queuedEventBytes = 0;
1454
- for (const record of records) {
1455
- const normalized = normalizeStoredRecord(record);
1456
- if (batchPrefixBytes + normalized.eventBytes + batchSuffixBytes > maxBatchBytes) {
1457
- throw new SdkError("persistence_error", "recovered event exceeds maxBatchBytes");
1458
- }
1459
- queuedEventBytes += normalized.eventBytes;
1460
- if (queuedEventBytes > maxQueueBytes) {
1461
- throw new SdkError("persistence_error", "recovered event bytes exceed maxQueueBytes");
1462
- }
1463
- events.push(normalized.event);
1464
- serializedEvents.push(normalized.serializedEvent);
1465
- serializedEventBytes.push(normalized.eventBytes);
1466
- }
1467
- return { events, queuedEventBytes, serializedEventBytes, serializedEvents };
1468
- }
1469
-
1470
- function isOrderedSubsequence(expected, actual) {
1471
- let index = 0;
1472
- for (const value of actual) {
1473
- index += value === expected[index] ? 1 : 0;
1474
- }
1475
- return index === expected.length;
1476
- }
1477
-
1478
- function structuralJson(value) {
1479
- return JSON.stringify(value, (_, entry) => entry && !Array.isArray(entry) && typeof entry === "object"
1480
- ? Object.fromEntries(Object.entries(entry).sort(([left], [right]) => left.localeCompare(right))) : entry);
1481
- }
1482
-
1483
- function normalizeStoredRecord(record) {
1484
- try {
1485
- if (!record || Array.isArray(record) || typeof record !== "object") {
1486
- throw invalidStoredRecord();
1487
- }
1488
- const { event, eventBytes, serializedEvent } = record;
1489
- if (!event || Array.isArray(event) || typeof event !== "object") {
1490
- throw invalidStoredRecord();
1491
- }
1492
- const validator = EVENT_VALIDATORS.get(event.type);
1493
- if (!validator || !Number.isSafeInteger(eventBytes) || eventBytes <= 0 || typeof serializedEvent !== "string") {
1494
- throw invalidStoredRecord();
1495
- }
1496
- requireNonEmpty("event id", event.id);
1497
- requireTimestamp(event.timestamp);
1498
- if (!event.attributes || Array.isArray(event.attributes) || typeof event.attributes !== "object") {
1499
- throw invalidStoredRecord();
1500
- }
1501
- if (JSON.stringify(event) !== serializedEvent || utf8ByteLength(serializedEvent) !== eventBytes) {
1502
- throw invalidStoredRecord();
1503
- }
1504
- const recoveredAttributes = event.type === "issue" && event.attributes.level === "fatal"
1505
- ? { ...event.attributes, level: "critical" }
1506
- : event.attributes;
1507
- const context = recoveredAttributes.context;
1508
- const recoveredEvent = context && !Array.isArray(context) && typeof context === "object"
1509
- && context.schemaVersion === undefined
1510
- ? { ...event, attributes: { ...recoveredAttributes, context: { schemaVersion: 1, ...context } } }
1511
- : { ...event, attributes: recoveredAttributes };
1512
- const normalizedEvent = {
1513
- type: recoveredEvent.type,
1514
- id: recoveredEvent.id,
1515
- timestamp: recoveredEvent.timestamp,
1516
- attributes: validator(recoveredEvent.attributes)
1517
- };
1518
- const normalizedSerializedEvent = JSON.stringify(normalizedEvent);
1519
- if (structuralJson(normalizedEvent) !== structuralJson(recoveredEvent)) {
1520
- throw invalidStoredRecord();
1521
- }
1522
- return {
1523
- event: cloneEvent(normalizedEvent),
1524
- eventBytes: utf8ByteLength(normalizedSerializedEvent),
1525
- serializedEvent: normalizedSerializedEvent
1526
- };
1527
- } catch (error) {
1528
- if (error instanceof SdkError && error.code === "persistence_error") {
1529
- throw error;
1530
- }
1531
- throw invalidStoredRecord();
1532
- }
1533
- }
1534
-
1535
- function invalidStoredRecord() {
1536
- return new SdkError("persistence_error", "event store returned an invalid record");
1537
- }
1538
-
1539
- function installLogBrewConsoleCapture(config) {
1540
- if (!config || typeof config !== "object") {
1541
- throw new SdkError("validation_error", "console capture config must be an object");
1542
- }
1543
-
1544
- const client = config.client;
1545
- if (!(client instanceof LogBrewClient)) {
1546
- throw new SdkError("validation_error", "console capture client must be a LogBrewClient");
1547
- }
1548
-
1549
- const targetConsole = config.console ?? globalThis.console;
1550
- if (!targetConsole || typeof targetConsole !== "object") {
1551
- throw new SdkError("validation_error", "console capture target must be an object");
1552
- }
1553
-
1554
- const transport = config.transport;
1555
- const flushOnCapture = config.flushOnCapture === true;
1556
- const includeErrorStack = config.includeErrorStack === true;
1557
- const logger = config.logger ?? "console";
1558
- const metadata = compactMetadata(config.metadata);
1559
- const timestamp = typeof config.timestamp === "function"
1560
- ? config.timestamp
1561
- : () => new Date().toISOString();
1562
- const eventIdPrefix = config.eventIdPrefix ?? "console";
1563
- const onError = typeof config.onError === "function" ? config.onError : () => {};
1564
- const levels = normalizeConsoleLevels(config.levels);
1565
- const originals = new Map();
1566
- const state = {
1567
- installed: true,
1568
- captured: 0,
1569
- pendingFlush: Promise.resolve(null)
1570
- };
1571
-
1572
- for (const method of levels) {
1573
- const original = targetConsole[method];
1574
- if (typeof original !== "function") {
1575
- continue;
1576
- }
1577
- originals.set(method, original);
1578
- targetConsole[method] = createConsoleCaptureMethod({
1579
- client,
1580
- eventIdPrefix,
1581
- flushOnCapture,
1582
- includeErrorStack,
1583
- logger,
1584
- metadata,
1585
- method,
1586
- onError,
1587
- original,
1588
- state,
1589
- timestamp,
1590
- transport
1591
- });
1592
- }
1593
-
1594
- return {
1595
- async flush() {
1596
- if (transport && client.pendingEvents() > 0) {
1597
- state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
1598
- onError(error);
1599
- return null;
1600
- });
1601
- }
1602
- return state.pendingFlush;
1603
- },
1604
- uninstall() {
1605
- if (!state.installed) {
1606
- return;
1607
- }
1608
- state.installed = false;
1609
- for (const [method, original] of originals.entries()) {
1610
- targetConsole[method] = original;
1611
- }
1612
- originals.clear();
1613
- }
1614
- };
1615
- }
1616
-
1617
- function createConsoleCaptureMethod(config) {
1618
- /** @this {*} */
1619
- return function logBrewConsoleMethod(...args) {
1620
- config.original.apply(this, args);
1621
- if (!config.state.installed) {
1622
- return;
1623
- }
1624
- try {
1625
- config.state.captured += 1;
1626
- config.client.log(
1627
- `${config.eventIdPrefix}_${config.state.captured}`,
1628
- config.timestamp(),
1629
- logAttributesFromConsoleArgs(config.method, args, {
1630
- includeErrorStack: config.includeErrorStack,
1631
- logger: config.logger,
1632
- metadata: config.metadata
1633
- })
1634
- );
1635
- if (config.flushOnCapture && config.transport) {
1636
- config.state.pendingFlush = Promise.resolve(config.client.flush(config.transport)).catch((error) => {
1637
- config.onError(error);
1638
- return null;
1639
- });
1640
- }
1641
- } catch (error) {
1642
- config.onError(error);
1643
- }
1644
- };
1645
- }
1646
-
1647
- function logAttributesFromConsoleArgs(method, args, options = {}) {
1648
- const logLevel = logbrewLevelFromConsoleMethod(method);
1649
- const includeErrorStack = options.includeErrorStack === true;
1650
- const message = consoleMessage(args, includeErrorStack);
1651
- const metadata = {
1652
- ...compactMetadata(options.metadata),
1653
- consoleMethod: method,
1654
- argumentCount: Array.isArray(args) ? args.length : 0
1655
- };
1656
- for (const value of Array.isArray(args) ? args : []) {
1657
- if (value instanceof Error) {
1658
- metadata.errorName = value.name || "Error";
1659
- if (value.message) {
1660
- metadata.errorMessage = value.message;
1661
- }
1662
- if (includeErrorStack && value.stack) {
1663
- metadata.errorStack = value.stack;
1664
- }
1665
- break;
1666
- }
1667
- }
1668
-
1669
- return {
1670
- message,
1671
- level: logLevel,
1672
- ...(options.logger ? { logger: options.logger } : {}),
1673
- metadata
1674
- };
1675
- }
1676
-
1677
- function createIssueAttributesFromError(error, options = {}) {
1678
- if (!options || Array.isArray(options) || typeof options !== "object") {
1679
- throw new SdkError("validation_error", "error issue options must be an object");
1680
- }
1681
- const details = errorDetails(error);
1682
- const stackEvidence = javascriptStackEvidence(details.stack, options.debugIdMap);
1683
- const stackFrames = stackEvidence.frames;
1684
- const frame = stackFrames[0] ?? null;
1685
- const source = stringOrUndefined(options.source) ?? "javascript.error";
1686
- const metadata = {
1687
- ...compactMetadata(options.metadata),
1688
- source,
1689
- errorName: details.name,
1690
- ...(details.message ? { errorMessage: details.message } : {}),
1691
- ...(frame ? {
1692
- errorFrameFile: frame.filename,
1693
- errorFrameLine: frame.line,
1694
- errorFrameColumn: frame.column
1695
- } : {}),
1696
- ...issueGroupingMetadata(source, details, frame, options.fingerprint),
1697
- ...errorCauseMetadata(error),
1698
- ...(stringOrUndefined(options.release) ? { release: options.release } : {}),
1699
- ...(stringOrUndefined(options.environment) ? { environment: options.environment } : {}),
1700
- ...(stringOrUndefined(options.service) ? { service: options.service } : {}),
1701
- ...(stringOrUndefined(options.runtime) ? { runtime: options.runtime } : {}),
1702
- ...(stringOrUndefined(options.platform) ? { platform: options.platform } : {}),
1703
- ...traceMetadata(options.trace),
1704
- ...releaseArtifactMetadata(frame),
1705
- ...(options.includeErrorStack === true && details.stack ? { errorStack: details.stack } : {})
1706
- };
1707
-
1708
- const exception = createIssueException(
1709
- boundedIssueExceptionType(details.name),
1710
- stringOrUndefined(options.mechanism) ?? "javascript.error",
1711
- options.handled === undefined ? true : options.handled
1712
- );
1713
- const exceptionChain = createJavaScriptExceptionChain(error, {
1714
- details,
1715
- exception,
1716
- stackEvidence,
1717
- debugIdMap: options.debugIdMap
1718
- });
1719
- return {
1720
- title: stringOrUndefined(options.title) ?? details.name,
1721
- level: normalizeSeverity("issue level", options.level ?? "error"),
1722
- ...(stringOrUndefined(options.message) ? { message: options.message } : details.message ? { message: details.message } : {}),
1723
- exception,
1724
- exceptionChain,
1725
- ...(stackFrames.length > 0 ? { stackFrames } : {}),
1726
- ...(options.evidence === undefined ? {} : { evidence: validateIssueEvidence(options.evidence) }),
1727
- metadata: compactMetadata(metadata)
1728
- };
1729
- }
1730
-
1731
- function createJavaScriptExceptionChain(error, root) {
1732
- const state = {
1733
- entries: [],
1734
- seen: new Set(),
1735
- truncated: false,
1736
- debugIdMap: root.debugIdMap
1737
- };
1738
- if (isObjectLike(error)) {
1739
- state.seen.add(error);
1740
- }
1741
- appendJavaScriptExceptionNode(error, undefined, "reported", state, root);
1742
- collectJavaScriptExceptionChildren(error, 0, state);
1743
- return { entries: state.entries, truncated: state.truncated };
1744
- }
1745
-
1746
- function appendJavaScriptExceptionNode(value, parentId, relationship, state, known = undefined) {
1747
- if (state.entries.length >= 8) {
1748
- state.truncated = true;
1749
- return undefined;
1750
- }
1751
- const details = known?.details ?? errorDetails(value);
1752
- const stackEvidence = known?.stackEvidence
1753
- ?? javascriptStackEvidence(details.stack, state.debugIdMap);
1754
- const mechanism = known?.exception?.mechanism ?? {
1755
- type: relationship === "aggregate_member" ? "javascript.aggregate_member" : "javascript.cause",
1756
- handled: true
1757
- };
1758
- const messageEvidence = exceptionMessageEvidence(details.message);
1759
- const id = state.entries.length;
1760
- state.entries.push({
1761
- id,
1762
- ...(parentId === undefined ? {} : { parentId }),
1763
- relationship,
1764
- type: known?.exception?.type ?? errorCauseType(value),
1765
- ...messageEvidence,
1766
- mechanism,
1767
- ...(stackEvidence.frames.length === 0 ? {} : { stackFrames: stackEvidence.frames }),
1768
- stackFramesState: stackEvidence.frames.length === 0
1769
- ? "not_captured"
1770
- : stackEvidence.truncated
1771
- ? "truncated"
1772
- : "captured"
1773
- });
1774
- return id;
1775
- }
1776
-
1777
- function collectJavaScriptExceptionChildren(value, parentId, state) {
1778
- if (!isObjectLike(value)) {
1779
- return;
1780
- }
1781
- const cause = safeProperty(value, "cause");
1782
- if (cause.available && cause.value !== undefined && cause.value !== null) {
1783
- collectJavaScriptExceptionChild(cause.value, parentId, "cause", state);
1784
- } else if (!cause.available) {
1785
- state.truncated = true;
1786
- }
1787
- const errors = safeProperty(value, "errors");
1788
- if (!errors.available) {
1789
- state.truncated = true;
1790
- } else if (Array.isArray(errors.value)) {
1791
- for (const child of errors.value) {
1792
- collectJavaScriptExceptionChild(child, parentId, "aggregate_member", state);
1793
- }
1794
- }
1795
- }
1796
-
1797
- function collectJavaScriptExceptionChild(value, parentId, relationship, state) {
1798
- if (state.entries.length >= 8) {
1799
- state.truncated = true;
1800
- return;
1801
- }
1802
- if (isObjectLike(value)) {
1803
- if (state.seen.has(value)) {
1804
- state.truncated = true;
1805
- return;
1806
- }
1807
- state.seen.add(value);
1808
- }
1809
- const id = appendJavaScriptExceptionNode(value, parentId, relationship, state);
1810
- if (id !== undefined) {
1811
- collectJavaScriptExceptionChildren(value, id, state);
1812
- }
1813
- }
1814
-
1815
- function exceptionMessageEvidence(value) {
1816
- if (typeof value !== "string") {
1817
- return { messageState: "not_captured" };
1818
- }
1819
- const normalized = value.replace(/\s+/gu, " ").trim();
1820
- if (normalized === "") {
1821
- return { messageState: "not_captured" };
1822
- }
1823
- return { messageState: "redacted" };
1824
- }
1825
-
1826
- function errorDetails(error) {
1827
- if (error instanceof Error) {
1828
- const name = safeProperty(error, "name");
1829
- const message = safeProperty(error, "message");
1830
- const stack = safeProperty(error, "stack");
1831
- return {
1832
- name: name.available ? stringOrUndefined(name.value) ?? "Error" : "Error",
1833
- message: message.available ? stringOrUndefined(message.value) : undefined,
1834
- stack: stack.available && typeof stack.value === "string" && stack.value.trim() !== ""
1835
- ? stack.value
1836
- : undefined
1837
- };
1838
- }
1839
- if (error && typeof error === "object") {
1840
- const name = safeProperty(error, "name");
1841
- const message = safeProperty(error, "message");
1842
- const stack = safeProperty(error, "stack");
1843
- return {
1844
- name: name.available && typeof name.value === "string" && name.value.trim() !== ""
1845
- ? name.value
1846
- : "Error",
1847
- message: message.available && typeof message.value === "string" && message.value.trim() !== ""
1848
- ? message.value
1849
- : undefined,
1850
- stack: stack.available && typeof stack.value === "string" && stack.value.trim() !== ""
1851
- ? stack.value
1852
- : undefined
1853
- };
1854
- }
1855
- if (typeof error === "string" && error.trim() !== "") {
1856
- return { name: "Error", message: error };
1857
- }
1858
- return { name: "Error" };
1859
- }
1860
-
1861
- function safeProperty(value, name) {
1862
- try {
1863
- return { available: true, value: value[name] };
1864
- } catch {
1865
- return { available: false, value: undefined };
1866
- }
1867
- }
1868
-
1869
- function boundedIssueExceptionType(value) {
1870
- const normalized = typeof value === "string" ? value.trim() : "";
1871
- const characters = Array.from(normalized);
1872
- if (
1873
- normalized === ""
1874
- || characters.length > 256
1875
- || /[?#]/u.test(normalized)
1876
- || characters.some((character) => {
1877
- const code = character.codePointAt(0);
1878
- return code !== undefined && (code <= 31 || (code >= 127 && code <= 159));
1879
- })
1880
- ) {
1881
- return "Error";
1882
- }
1883
- return normalized;
1884
- }
1885
-
1886
- function issueGroupingMetadata(source, details, frame, fingerprint) {
1887
- const groupingKey = frame
1888
- ? `${source}:${details.name}:${frame.filename}`
1889
- : `${source}:${details.name}`;
1890
- const explicitFingerprint = issueFingerprintOrUndefined(fingerprint);
1891
- return {
1892
- issueGroupingKey: groupingKey,
1893
- issueGroupingSource: explicitFingerprint ? "explicit_fingerprint" : frame ? "error_type_and_frame" : "error_type",
1894
- ...(explicitFingerprint ? { issueFingerprint: explicitFingerprint } : {})
1895
- };
1896
- }
1897
-
1898
- function issueFingerprintOrUndefined(value) {
1899
- if (value === undefined || value === null) {
1900
- return undefined;
1901
- }
1902
- if (typeof value !== "string" || value.trim() === "") {
1903
- throw new SdkError("validation_error", "issue fingerprint must be a non-empty string");
1904
- }
1905
- return value.trim();
1906
- }
1907
-
1908
- function errorCauseMetadata(error) {
1909
- const state = {
1910
- items: [],
1911
- seen: new Set(),
1912
- sawExceptionGroup: false,
1913
- truncated: false
1914
- };
1915
- if (isObjectLike(error)) {
1916
- state.seen.add(error);
1917
- collectNestedErrorCauses(error, state);
1918
- }
1919
- if (state.items.length === 0) {
1920
- return {};
1921
- }
1922
- return {
1923
- errorCauseCount: state.items.length,
1924
- errorCauseTypes: state.items.map((item) => item.type).join(","),
1925
- errorCauseSources: state.items.map((item) => item.source).join(","),
1926
- ...(state.sawExceptionGroup ? { errorExceptionGroup: true } : {}),
1927
- ...(state.truncated ? { errorCauseTruncated: true } : {})
1928
- };
1929
- }
1930
-
1931
- function collectNestedErrorCauses(parent, state) {
1932
- if (!isObjectLike(parent)) {
1933
- return;
1934
- }
1935
- const cause = safeProperty(parent, "cause");
1936
- if (!cause.available) {
1937
- state.truncated = true;
1938
- } else if (cause.value !== undefined && cause.value !== null) {
1939
- collectErrorCause(cause.value, "cause", state);
1940
- }
1941
- const errors = safeProperty(parent, "errors");
1942
- if (!errors.available) {
1943
- state.truncated = true;
1944
- } else if (Array.isArray(errors.value)) {
1945
- state.sawExceptionGroup = true;
1946
- for (const [index, child] of errors.value.entries()) {
1947
- collectErrorCause(child, `errors[${index}]`, state);
1948
- }
1949
- }
1950
- }
1951
-
1952
- function collectErrorCause(value, source, state) {
1953
- if (value === undefined || value === null) {
1954
- return;
1955
- }
1956
- if (state.items.length >= MAX_ERROR_CAUSES) {
1957
- state.truncated = true;
1958
- return;
1959
- }
1960
- if (isObjectLike(value)) {
1961
- if (state.seen.has(value)) {
1962
- state.truncated = true;
1963
- return;
1964
- }
1965
- state.seen.add(value);
1966
- }
1967
- state.items.push({
1968
- source,
1969
- type: errorCauseType(value)
1970
- });
1971
- collectNestedErrorCauses(value, state);
1972
- }
1973
-
1974
- function errorCauseType(value) {
1975
- if (isObjectLike(value)) {
1976
- const constructor = safeProperty(value, "constructor");
1977
- const constructorNameValue = constructor.available && isObjectLike(constructor.value)
1978
- ? safeProperty(constructor.value, "name")
1979
- : { available: false, value: undefined };
1980
- const constructorName = constructorNameValue.available
1981
- ? safeCauseTypeName(constructorNameValue.value)
1982
- : undefined;
1983
- if (value instanceof Error) {
1984
- if (constructorName && constructorName !== "Error") {
1985
- return constructorName;
1986
- }
1987
- const name = safeProperty(value, "name");
1988
- const builtinName = name.available && BUILTIN_ERROR_NAMES.has(name.value)
1989
- ? name.value
1990
- : undefined;
1991
- return builtinName ?? constructorName ?? "Error";
1992
- }
1993
- return constructorName ?? "Object";
1994
- }
1995
- return "NonError";
1996
- }
1997
-
1998
- function safeCauseTypeName(value) {
1999
- return typeof value === "string" && /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/u.test(value) ? value : undefined;
2000
- }
2001
-
2002
- function isObjectLike(value) {
2003
- return value !== null && (typeof value === "object" || typeof value === "function");
2004
- }
2005
-
2006
- function traceMetadata(trace) {
2007
- if (trace === undefined || trace === null) {
2008
- return {};
2009
- }
2010
- const normalized = normalizeLogTraceContext(trace);
2011
- if (!normalized) {
2012
- return {};
2013
- }
2014
- return {
2015
- traceId: normalized.traceId,
2016
- spanId: normalized.spanId,
2017
- ...(normalized.parentSpanId ? { parentSpanId: normalized.parentSpanId } : {}),
2018
- ...(normalized.sampled !== undefined ? { sampled: normalized.sampled } : {})
2019
- };
2020
- }
2021
-
2022
- function releaseArtifactMetadata(frame) {
2023
- if (!frame?.debugId) {
2024
- return {};
2025
- }
2026
- return {
2027
- releaseArtifactType: "sourcemap",
2028
- releaseArtifactCodeFile: frame.filename,
2029
- releaseArtifactDebugId: frame.debugId
2030
- };
2031
- }
2032
-
2033
- function logbrewLevelFromConsoleMethod(method) {
2034
- switch (method) {
2035
- case "debug":
2036
- return "info";
2037
- case "warn":
2038
- return "warning";
2039
- case "error":
2040
- return "error";
2041
- case "info":
2042
- case "log":
2043
- return "info";
2044
- default:
2045
- throw new SdkError("validation_error", `console method must be one of: ${Array.from(CONSOLE_METHODS).join(", ")}`);
2046
- }
2047
- }
2048
-
2049
- function createProductActionAttributes(action, options = {}) {
2050
- const details = productActionDetails(action);
2051
- const routeTemplate = sanitizeRouteTemplate(details.routeTemplate);
2052
- return {
2053
- name: details.name,
2054
- status: details.status,
2055
- metadata: compactMetadata({
2056
- source: "product.action",
2057
- ...compactMetadata(options.metadata),
2058
- ...compactMetadata(details.metadata),
2059
- routeTemplate,
2060
- sessionId: stringOrUndefined(details.sessionId),
2061
- traceId: stringOrUndefined(details.traceId),
2062
- screen: stringOrUndefined(details.screen),
2063
- funnel: stringOrUndefined(details.funnel),
2064
- step: stringOrUndefined(details.step),
2065
- ...productAnalyticsMetadata("interaction", routeTemplate || details.screen)
2066
- })
2067
- };
2068
- }
2069
-
2070
- function createNetworkMilestoneAttributes(request, options = {}) {
2071
- const details = networkMilestoneDetails(request);
2072
- return {
2073
- name: details.name,
2074
- status: details.status,
2075
- metadata: compactMetadata({
2076
- source: "network.milestone",
2077
- ...compactMetadata(options.metadata),
2078
- ...compactMetadata(details.metadata),
2079
- routeTemplate: details.routeTemplate,
2080
- method: details.method,
2081
- statusCode: details.statusCode,
2082
- durationMs: details.durationMs,
2083
- sessionId: stringOrUndefined(details.sessionId),
2084
- traceId: stringOrUndefined(details.traceId)
2085
- })
2086
- };
2087
- }
2088
-
2089
- function parseTraceparent(traceparent) {
2090
- if (typeof traceparent !== "string" || traceparent.trim() === "") {
2091
- throw new SdkError("validation_error", "traceparent must be non-empty");
2092
- }
2093
-
2094
- const match = TRACEPARENT_PATTERN.exec(traceparent.trim());
2095
- if (!match) {
2096
- throw new SdkError("validation_error", "traceparent must use W3C version-traceId-parentSpanId-traceFlags format");
2097
- }
2098
-
2099
- const version = match[1].toLowerCase();
2100
- const traceId = match[2].toLowerCase();
2101
- const parentSpanId = match[3].toLowerCase();
2102
- const traceFlags = match[4].toLowerCase();
2103
- if (version === "ff") {
2104
- throw new SdkError("validation_error", "traceparent version ff is not allowed");
2105
- }
2106
- if (traceId === ZERO_TRACE_ID) {
2107
- throw new SdkError("validation_error", "traceparent traceId must not be all zeros");
2108
- }
2109
- if (parentSpanId === ZERO_SPAN_ID) {
2110
- throw new SdkError("validation_error", "traceparent parentSpanId must not be all zeros");
2111
- }
2112
-
2113
- return {
2114
- version,
2115
- traceId,
2116
- parentSpanId,
2117
- traceFlags,
2118
- sampled: (Number.parseInt(traceFlags, 16) & 1) === 1
2119
- };
2120
- }
2121
-
2122
- function createTraceparent({ traceId, spanId, traceFlags = "01" }) {
2123
- requireTraceId(traceId);
2124
- requireSpanId("spanId", spanId);
2125
- requireTraceFlags(traceFlags);
2126
- return `00-${traceId.toLowerCase()}-${spanId.toLowerCase()}-${traceFlags.toLowerCase()}`;
2127
- }
2128
-
2129
- function createTraceparentHeaders(input) {
2130
- return { traceparent: createTraceparent(input) };
2131
- }
2132
-
18
+ PRODUCT_ANALYTICS_KINDS,
19
+ PRODUCT_ANALYTICS_SCHEMA_VERSION,
20
+ createProductActionAttributes
21
+ } = require("./product-action.cjs");
22
+ const { RecordingTransport } = require("./recording-transport.cjs");
23
+ const { SdkError } = require("./sdk-error.cjs");
24
+ const { spanAttributesFromTraceparent } = require("./span-validation.cjs");
25
+ const { createSupportTicketDraft } = require("./support-ticket.cjs");
2133
26
  const {
2134
27
  createBaggage,
2135
28
  createTraceContextHeaders,
29
+ createTraceparent,
30
+ createTraceparentHeaders,
2136
31
  createTracestate,
2137
32
  parseBaggage,
33
+ parseTraceparent,
2138
34
  parseTracestate
2139
- } = buildTraceContextHelpers({
2140
- SdkError,
2141
- createTraceparent
2142
- });
2143
-
2144
- const createSupportTicketDraft = buildCreateSupportTicketDraft({
2145
- SdkError,
2146
- requireAllowedValue,
2147
- requireNonEmpty,
2148
- requireTraceId
2149
- });
2150
-
2151
- const {
2152
- createLogBrewOpenTelemetrySpanExporter,
2153
- createLogBrewOpenTelemetrySpanProcessor,
2154
- logbrewTraceContextFromCurrentOpenTelemetrySpan,
2155
- logbrewTraceContextFromOpenTelemetrySpan,
2156
- logbrewTraceContextFromOpenTelemetrySpanContext,
2157
- spanAttributesFromOpenTelemetryReadableSpan
2158
- } = buildOpenTelemetryHelpers({
2159
- compactMetadata,
2160
- isMetadataValue,
2161
- LogBrewClient,
2162
- maxSpanEvents: MAX_SPAN_EVENTS,
2163
- maxSpanLinks: MAX_SPAN_LINKS,
2164
- requireNonEmpty,
2165
- requireSpanId,
2166
- requireTraceId,
2167
- SdkError,
2168
- stringOrUndefined
2169
- });
2170
-
2171
- function spanAttributesFromTraceparent(traceparent, attributes) {
2172
- if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") {
2173
- throw new SdkError("validation_error", "span attributes must be an object");
2174
- }
2175
- const context = parseTraceparent(traceparent);
2176
- requireNonEmpty("span name", attributes.name);
2177
- requireSpanId("spanId", attributes.spanId);
2178
- requireAllowedValue("span status", attributes.status, SPAN_STATUSES);
2179
- if (attributes.durationMs !== undefined) {
2180
- if (typeof attributes.durationMs !== "number" || Number.isNaN(attributes.durationMs) || attributes.durationMs < 0) {
2181
- throw new SdkError("validation_error", "span durationMs must be non-negative");
2182
- }
2183
- }
2184
- const events = validateSpanEvents(attributes.events);
2185
- const links = validateSpanLinks(attributes.links);
2186
-
2187
- return {
2188
- name: attributes.name,
2189
- traceId: context.traceId,
2190
- spanId: attributes.spanId.toLowerCase(),
2191
- parentSpanId: context.parentSpanId,
2192
- status: attributes.status,
2193
- ...(attributes.durationMs !== undefined ? { durationMs: attributes.durationMs } : {}),
2194
- ...(events !== undefined ? { events } : {}),
2195
- ...(links !== undefined ? { links } : {}),
2196
- ...(attributes.metadata !== undefined ? { metadata: compactMetadata(attributes.metadata) } : {})
2197
- };
2198
- }
2199
-
2200
- function createLogBrewPinoDestination(config) {
2201
- if (!config || typeof config !== "object") {
2202
- throw new SdkError("validation_error", "Pino destination config must be an object");
2203
- }
2204
-
2205
- const client = config.client;
2206
- if (!(client instanceof LogBrewClient)) {
2207
- throw new SdkError("validation_error", "Pino destination client must be a LogBrewClient");
2208
- }
2209
-
2210
- const transport = config.transport;
2211
- const flushOnWrite = config.flushOnWrite === true;
2212
- const includeErrorStack = config.includeErrorStack === true;
2213
- const logger = config.logger ?? "pino";
2214
- const metadata = compactMetadata(config.metadata);
2215
- const timestamp = typeof config.timestamp === "function"
2216
- ? config.timestamp
2217
- : () => new Date().toISOString();
2218
- const eventIdPrefix = config.eventIdPrefix ?? "pino";
2219
- const onError = typeof config.onError === "function" ? config.onError : () => {};
2220
- const traceProvider = typeof config.traceProvider === "function" ? config.traceProvider : null;
2221
- const state = {
2222
- captured: 0,
2223
- pendingFlush: Promise.resolve(null)
2224
- };
2225
-
2226
- return {
2227
- write(chunk) {
2228
- const lines = String(chunk).split(/\r?\n/u).filter((line) => line.trim() !== "");
2229
- for (const line of lines) {
2230
- try {
2231
- const record = JSON.parse(line);
2232
- state.captured += 1;
2233
- client.log(
2234
- `${eventIdPrefix}_${state.captured}`,
2235
- timestampFromPinoRecord(record, timestamp),
2236
- logAttributesFromPinoRecord(record, {
2237
- includeErrorStack,
2238
- logger,
2239
- metadata,
2240
- trace: traceFromProvider(traceProvider, onError)
2241
- })
2242
- );
2243
- if (flushOnWrite && transport) {
2244
- state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
2245
- onError(error);
2246
- return null;
2247
- });
2248
- }
2249
- } catch (error) {
2250
- onError(error);
2251
- }
2252
- }
2253
- return true;
2254
- },
2255
- async flush() {
2256
- if (transport && client.pendingEvents() > 0) {
2257
- state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
2258
- onError(error);
2259
- return null;
2260
- });
2261
- }
2262
- return state.pendingFlush;
2263
- },
2264
- end() {
2265
- return this.flush();
2266
- }
2267
- };
2268
- }
2269
-
2270
- function logAttributesFromPinoRecord(record, options = {}) {
2271
- if (!record || Array.isArray(record) || typeof record !== "object") {
2272
- throw new SdkError("validation_error", "Pino record must be an object");
2273
- }
2274
-
2275
- const level = logbrewLevelFromPinoLevel(record.level);
2276
- const metadata = {
2277
- ...compactMetadata(options.metadata),
2278
- pinoLevel: pinoLevelLabel(record.level),
2279
- ...pinoContextMetadata(record),
2280
- ...traceMetadataFromLogContext(options.trace)
2281
- };
2282
- if (typeof record.level === "number" && Number.isFinite(record.level)) {
2283
- metadata.pinoLevelNumber = record.level;
2284
- }
2285
- addPinoErrorMetadata(metadata, record.err ?? record.error, options.includeErrorStack === true);
2286
-
2287
- return {
2288
- message: pinoMessage(record),
2289
- level,
2290
- ...(options.logger ? { logger: options.logger } : {}),
2291
- metadata
2292
- };
2293
- }
2294
-
2295
- function timestampFromPinoRecord(record, fallbackTimestamp) {
2296
- const value = record?.time ?? record?.timestamp;
2297
- if (typeof value === "number" && Number.isFinite(value)) {
2298
- return new Date(value).toISOString();
2299
- }
2300
- if (typeof value === "string" && value.trim() !== "") {
2301
- const parsed = new Date(value);
2302
- if (!Number.isNaN(parsed.valueOf())) {
2303
- return parsed.toISOString();
2304
- }
2305
- return value;
2306
- }
2307
- return fallbackTimestamp();
2308
- }
2309
-
2310
- function logbrewLevelFromPinoLevel(level) {
2311
- if (typeof level === "number" && Number.isFinite(level)) {
2312
- if (level >= 60) {
2313
- return "critical";
2314
- }
2315
- if (level >= 50) {
2316
- return "error";
2317
- }
2318
- if (level >= 40) {
2319
- return "warning";
2320
- }
2321
- if (level >= 30) {
2322
- return "info";
2323
- }
2324
- return "info";
2325
- }
2326
-
2327
- switch (String(level).toLowerCase()) {
2328
- case "trace":
2329
- case "debug":
2330
- return "info";
2331
- case "warn":
2332
- case "warning":
2333
- return "warning";
2334
- case "error":
2335
- return "error";
2336
- case "fatal":
2337
- case "critical":
2338
- return "critical";
2339
- case "info":
2340
- default:
2341
- return "info";
2342
- }
2343
- }
2344
-
2345
- function pinoLevelLabel(level) {
2346
- if (typeof level === "string" && level.trim() !== "") {
2347
- return level;
2348
- }
2349
- switch (level) {
2350
- case 10:
2351
- return "trace";
2352
- case 20:
2353
- return "debug";
2354
- case 30:
2355
- return "info";
2356
- case 40:
2357
- return "warn";
2358
- case 50:
2359
- return "error";
2360
- case 60:
2361
- return "fatal";
2362
- default:
2363
- return typeof level === "number" && Number.isFinite(level) ? String(level) : "info";
2364
- }
2365
- }
2366
-
2367
- function pinoMessage(record) {
2368
- if (typeof record.msg === "string" && record.msg.trim() !== "") {
2369
- return record.msg;
2370
- }
2371
- if (typeof record.message === "string" && record.message.trim() !== "") {
2372
- return record.message;
2373
- }
2374
- const error = record.err ?? record.error;
2375
- if (error && typeof error === "object" && typeof error.message === "string" && error.message.trim() !== "") {
2376
- return error.message;
2377
- }
2378
- return "pino event";
2379
- }
2380
-
2381
- function pinoContextMetadata(record) {
2382
- const metadata = {};
2383
- for (const [key, value] of Object.entries(record)) {
2384
- if (!PINO_RESERVED_FIELDS.has(key) && !isSensitivePinoContextField(key) && isMetadataValue(value)) {
2385
- metadata[`context.${key}`] = value;
2386
- }
2387
- }
2388
- return metadata;
2389
- }
2390
-
2391
- function isSensitivePinoContextField(key) {
2392
- const normalized = key.toLowerCase().replace(/[^a-z0-9]+/gu, "");
2393
- return (
2394
- PINO_SENSITIVE_CONTEXT_FIELDS.has(normalized)
2395
- || normalized.endsWith("accesskey")
2396
- || normalized.endsWith("apikey")
2397
- || normalized.endsWith("authorization")
2398
- || normalized.endsWith("body")
2399
- || normalized.endsWith("cookie")
2400
- || normalized.endsWith("credentials")
2401
- || normalized.endsWith("headers")
2402
- || normalized.endsWith("password")
2403
- || normalized.endsWith("payload")
2404
- || normalized.endsWith("privatekey")
2405
- || normalized.endsWith("query")
2406
- || normalized.endsWith("secret")
2407
- || normalized.endsWith("stack")
2408
- || normalized.endsWith("token")
2409
- || normalized.endsWith("url")
2410
- );
2411
- }
2412
-
2413
- function addPinoErrorMetadata(metadata, error, includeErrorStack) {
2414
- if (!error) {
2415
- return;
2416
- }
2417
- if (error instanceof Error) {
2418
- metadata.errorName = error.name || "Error";
2419
- if (error.message) {
2420
- metadata.errorMessage = error.message;
2421
- }
2422
- if (includeErrorStack && error.stack) {
2423
- metadata.errorStack = error.stack;
2424
- }
2425
- return;
2426
- }
2427
- if (typeof error === "object") {
2428
- const name = error.type ?? error.name;
2429
- const message = error.message;
2430
- const stack = error.stack;
2431
- if (typeof name === "string" && name.trim() !== "") {
2432
- metadata.errorName = name;
2433
- }
2434
- if (typeof message === "string" && message.trim() !== "") {
2435
- metadata.errorMessage = message;
2436
- }
2437
- if (includeErrorStack && typeof stack === "string" && stack.trim() !== "") {
2438
- metadata.errorStack = stack;
2439
- }
2440
- return;
2441
- }
2442
- if (typeof error === "string" && error.trim() !== "") {
2443
- metadata.errorMessage = error;
2444
- }
2445
- }
2446
-
2447
- function requireNonEmpty(label, value) {
2448
- if (typeof value !== "string" || value.trim() === "") {
2449
- throw new SdkError("validation_error", `${label} must be non-empty`);
2450
- }
2451
- }
2452
-
2453
- function requireAllowedValue(label, value, allowedValues) {
2454
- requireNonEmpty(label, value);
2455
- if (!allowedValues.has(value)) {
2456
- throw new SdkError(
2457
- "validation_error",
2458
- `${label} must be one of: ${Array.from(allowedValues).join(", ")}`
2459
- );
2460
- }
2461
- }
2462
-
2463
- function requireFiniteNumber(label, value) {
2464
- if (typeof value !== "number" || !Number.isFinite(value)) {
2465
- throw new SdkError("validation_error", `${label} must be a finite number`);
2466
- }
2467
- }
2468
-
2469
- function requirePositiveInteger(label, value) {
2470
- if (!Number.isSafeInteger(value) || value <= 0) {
2471
- throw new SdkError("validation_error", `${label} must be a positive integer`);
2472
- }
2473
- }
2474
-
2475
- function requireNonNegativeInteger(label, value) {
2476
- if (!Number.isSafeInteger(value) || value < 0) {
2477
- throw new SdkError("validation_error", `${label} must be a non-negative integer`);
2478
- }
2479
- }
2480
-
2481
- function retryAfterMsOrUndefined(value) {
2482
- if (value === undefined) {
2483
- return undefined;
2484
- }
2485
- return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
2486
- }
2487
-
2488
- function requireTraceId(traceId) {
2489
- if (typeof traceId !== "string" || !/^[0-9a-fA-F]{32}$/u.test(traceId)) {
2490
- throw new SdkError("validation_error", "traceId must be 32 lowercase or uppercase hex characters");
2491
- }
2492
- if (traceId.toLowerCase() === ZERO_TRACE_ID) {
2493
- throw new SdkError("validation_error", "traceId must not be all zeros");
2494
- }
2495
- }
2496
-
2497
- function requireSpanId(label, spanId) {
2498
- if (typeof spanId !== "string" || !/^[0-9a-fA-F]{16}$/u.test(spanId)) {
2499
- throw new SdkError("validation_error", `${label} must be 16 lowercase or uppercase hex characters`);
2500
- }
2501
- if (spanId.toLowerCase() === ZERO_SPAN_ID) {
2502
- throw new SdkError("validation_error", `${label} must not be all zeros`);
2503
- }
2504
- }
2505
-
2506
- function requireTraceFlags(traceFlags) {
2507
- if (typeof traceFlags !== "string" || !/^[0-9a-fA-F]{2}$/u.test(traceFlags)) {
2508
- throw new SdkError("validation_error", "traceFlags must be 2 lowercase or uppercase hex characters");
2509
- }
2510
- }
2511
-
2512
- function requireTimestamp(timestamp) {
2513
- requireNonEmpty("timestamp", timestamp);
2514
- const timePortion = timestamp.split("T")[1];
2515
- if (!timestamp.endsWith("Z")
2516
- && !(timePortion && (timePortion.includes("+") || /.+-.+/.test(timePortion)))) {
2517
- throw new SdkError(
2518
- "validation_error",
2519
- `timestamp must include a timezone offset: ${timestamp}`
2520
- );
2521
- }
2522
- const match = timestamp.match(RFC3339_TIMESTAMP_PATTERN);
2523
- const calendar = new Date(0);
2524
- calendar.setUTCHours(0, 0, 0, 0);
2525
- calendar.setUTCFullYear(Number(match?.[1]), Number(match?.[2]) - 1, Number(match?.[3]));
2526
- if (!match
2527
- || Number(match[1]) === 0
2528
- || calendar.getUTCFullYear() !== Number(match[1])
2529
- || calendar.getUTCMonth() !== Number(match[2]) - 1
2530
- || calendar.getUTCDate() !== Number(match[3])) {
2531
- throw new SdkError("validation_error", `invalid timestamp: ${timestamp}`);
2532
- }
2533
- }
2534
-
2535
- function cloneMetadata(metadata) {
2536
- if (metadata === undefined) {
2537
- return undefined;
2538
- }
2539
- if (!metadata || Array.isArray(metadata) || typeof metadata !== "object") {
2540
- throw new SdkError("validation_error", "metadata must be an object");
2541
- }
2542
- return { ...metadata };
2543
- }
2544
-
2545
- function cloneSpanEvents(events) {
2546
- return events.map((event) => event.metadata === undefined
2547
- ? { ...event }
2548
- : { ...event, metadata: { ...event.metadata } });
2549
- }
2550
-
2551
- function cloneSpanLinks(links) {
2552
- return links.map((link) => link.metadata === undefined
2553
- ? { ...link }
2554
- : { ...link, metadata: { ...link.metadata } });
2555
- }
2556
-
2557
- function cloneEvent(event) {
2558
- const attributes = { ...event.attributes, ...cloneIssueDiagnostics(event.attributes) };
2559
- if (Array.isArray(event.attributes.nativeStackFrames)) {
2560
- attributes.nativeStackFrames = event.attributes.nativeStackFrames.map((frame) => ({ ...frame }));
2561
- }
2562
- if (event.attributes.metadata !== undefined) {
2563
- attributes.metadata = { ...event.attributes.metadata };
2564
- }
2565
- if (Array.isArray(event.attributes.events)) {
2566
- attributes.events = cloneSpanEvents(event.attributes.events);
2567
- }
2568
- if (Array.isArray(event.attributes.links)) {
2569
- attributes.links = cloneSpanLinks(event.attributes.links);
2570
- }
2571
- if (event.attributes.context !== undefined) {
2572
- attributes.context = cloneTelemetryContext(event.attributes.context);
2573
- }
2574
- return { ...event, attributes };
2575
- }
2576
-
2577
- function validateRelease(attributes) {
2578
- requireNonEmpty("release version", attributes.version);
2579
- if (attributes.commit !== undefined) {
2580
- requireNonEmpty("release commit", attributes.commit);
2581
- }
2582
- return withMetadata({
2583
- version: attributes.version,
2584
- ...(attributes.commit ? { commit: attributes.commit } : {}),
2585
- ...(attributes.notes !== undefined ? { notes: attributes.notes } : {})
2586
- }, attributes.metadata, attributes.context);
2587
- }
2588
-
2589
- function validateEnvironment(attributes) {
2590
- requireNonEmpty("environment name", attributes.name);
2591
- return withMetadata({
2592
- name: attributes.name,
2593
- ...(attributes.region !== undefined ? { region: attributes.region } : {})
2594
- }, attributes.metadata, attributes.context);
2595
- }
2596
-
2597
- function validateIssue(attributes) {
2598
- requireNonEmpty("issue title", attributes.title);
2599
- const level = normalizeSeverity("issue level", attributes.level);
2600
- const stackFrames = validateIssueStackFrames(attributes.stackFrames);
2601
- const nativeStackFrames = validateNativeStackFrames(attributes.nativeStackFrames);
2602
- return withMetadata({
2603
- title: attributes.title,
2604
- level,
2605
- ...(attributes.message !== undefined ? { message: attributes.message } : {}),
2606
- ...(stackFrames !== undefined ? { stackFrames } : {}),
2607
- ...(nativeStackFrames !== undefined ? { nativeStackFrames } : {}),
2608
- ...validateIssueDiagnostics(attributes)
2609
- }, attributes.metadata, attributes.context);
2610
- }
2611
-
2612
- function validateLog(attributes) {
2613
- requireNonEmpty("log message", attributes.message);
2614
- const level = normalizeSeverity("log level", attributes.level);
2615
- return withMetadata({
2616
- message: attributes.message,
2617
- level,
2618
- ...(attributes.logger !== undefined ? { logger: attributes.logger } : {})
2619
- }, attributes.metadata, attributes.context);
2620
- }
2621
-
2622
- function normalizeSeverity(label, value) {
2623
- requireAllowedValue(label, value, SEVERITY_VALUES);
2624
- return SEVERITY_ALIASES.get(value);
2625
- }
2626
-
2627
- function validateSpan(attributes) {
2628
- requireNonEmpty("span name", attributes.name);
2629
- requireNonEmpty("span traceId", attributes.traceId);
2630
- requireNonEmpty("span spanId", attributes.spanId);
2631
- requireAllowedValue("span status", attributes.status, SPAN_STATUSES);
2632
- if (attributes.parentSpanId !== undefined) {
2633
- requireNonEmpty("span parentSpanId", attributes.parentSpanId);
2634
- }
2635
- if (attributes.durationMs !== undefined) {
2636
- if (typeof attributes.durationMs !== "number" || Number.isNaN(attributes.durationMs) || attributes.durationMs < 0) {
2637
- throw new SdkError("validation_error", "span durationMs must be non-negative");
2638
- }
2639
- }
2640
- const events = validateSpanEvents(attributes.events);
2641
- const links = validateSpanLinks(attributes.links);
2642
- return withMetadata({
2643
- name: attributes.name,
2644
- traceId: attributes.traceId,
2645
- spanId: attributes.spanId,
2646
- status: attributes.status,
2647
- ...(attributes.parentSpanId !== undefined ? { parentSpanId: attributes.parentSpanId } : {}),
2648
- ...(attributes.durationMs !== undefined ? { durationMs: attributes.durationMs } : {}),
2649
- ...(events !== undefined ? { events } : {}),
2650
- ...(links !== undefined ? { links } : {})
2651
- }, attributes.metadata, attributes.context);
2652
- }
2653
-
2654
- function validateSpanEvents(events) {
2655
- if (events === undefined) {
2656
- return undefined;
2657
- }
2658
- if (!Array.isArray(events)) {
2659
- throw new SdkError("validation_error", "span events must be an array");
2660
- }
2661
- if (events.length > MAX_SPAN_EVENTS) {
2662
- throw new SdkError("validation_error", `span events must contain at most ${MAX_SPAN_EVENTS} entries`);
2663
- }
2664
- if (events.length === 0) {
2665
- return undefined;
2666
- }
2667
-
2668
- return events.map((event) => {
2669
- if (!event || Array.isArray(event) || typeof event !== "object") {
2670
- throw new SdkError("validation_error", "span event must be an object");
2671
- }
2672
- requireNonEmpty("span event name", event.name);
2673
- if (event.timestamp !== undefined) {
2674
- requireTimestamp(event.timestamp);
2675
- }
2676
- const summary = {
2677
- name: event.name,
2678
- ...(event.timestamp !== undefined ? { timestamp: event.timestamp } : {})
2679
- };
2680
- if (event.metadata !== undefined) {
2681
- const metadata = compactMetadata(event.metadata);
2682
- if (Object.keys(metadata).length > 0) {
2683
- summary.metadata = metadata;
2684
- }
2685
- }
2686
- return summary;
2687
- });
2688
- }
2689
-
2690
- function validateSpanLinks(links) {
2691
- if (links === undefined) {
2692
- return undefined;
2693
- }
2694
- if (!Array.isArray(links)) {
2695
- throw new SdkError("validation_error", "span links must be an array");
2696
- }
2697
- if (links.length > MAX_SPAN_LINKS) {
2698
- throw new SdkError("validation_error", `span links must contain at most ${MAX_SPAN_LINKS} entries`);
2699
- }
2700
- if (links.length === 0) {
2701
- return undefined;
2702
- }
2703
-
2704
- return links.map((link) => {
2705
- if (!link || Array.isArray(link) || typeof link !== "object") {
2706
- throw new SdkError("validation_error", "span link must be an object");
2707
- }
2708
- requireTraceId(link.traceId);
2709
- requireSpanId("span link spanId", link.spanId);
2710
- if (link.sampled !== undefined && typeof link.sampled !== "boolean") {
2711
- throw new SdkError("validation_error", "span link sampled must be a boolean");
2712
- }
2713
- const summary = {
2714
- traceId: link.traceId.toLowerCase(),
2715
- spanId: link.spanId.toLowerCase(),
2716
- ...(link.sampled !== undefined ? { sampled: link.sampled } : {})
2717
- };
2718
- if (link.metadata !== undefined) {
2719
- const metadata = compactMetadata(link.metadata);
2720
- if (Object.keys(metadata).length > 0) {
2721
- summary.metadata = metadata;
2722
- }
2723
- }
2724
- return summary;
2725
- });
2726
- }
2727
-
2728
- function validateAction(attributes) {
2729
- requireNonEmpty("action name", attributes.name);
2730
- requireAllowedValue("action status", attributes.status, ACTION_STATUSES);
2731
- return withMetadata({
2732
- name: attributes.name,
2733
- status: attributes.status
2734
- }, attributes.metadata, attributes.context);
2735
- }
2736
-
2737
- function validateMetric(attributes) {
2738
- requireNonEmpty("metric name", attributes.name);
2739
- requireAllowedValue("metric kind", attributes.kind, METRIC_KINDS);
2740
- requireFiniteNumber("metric value", attributes.value);
2741
- requireNonEmpty("metric unit", attributes.unit);
2742
-
2743
- const allowedTemporalities = METRIC_TEMPORALITIES_BY_KIND.get(attributes.kind);
2744
- requireAllowedValue(`metric temporality for ${attributes.kind}`, attributes.temporality, allowedTemporalities);
2745
- if (NON_NEGATIVE_METRIC_KINDS.has(attributes.kind) && attributes.value < 0) {
2746
- throw new SdkError("validation_error", `metric ${attributes.kind} value must be non-negative`);
2747
- }
2748
- const description = metricDescriptionOrUndefined(attributes.description);
2749
-
2750
- return withMetadata({
2751
- name: attributes.name,
2752
- ...(description === undefined ? {} : { description }),
2753
- kind: attributes.kind,
2754
- value: attributes.value,
2755
- unit: attributes.unit,
2756
- temporality: attributes.temporality
2757
- }, attributes.metadata, attributes.context);
2758
- }
2759
-
2760
- function metricDescriptionOrUndefined(value) {
2761
- if (value === undefined) {
2762
- return undefined;
2763
- }
2764
- const characters = typeof value === "string" ? Array.from(value) : [];
2765
- if (
2766
- typeof value !== "string"
2767
- || value.trim() === ""
2768
- || characters.length > MAX_METRIC_DESCRIPTION_LENGTH
2769
- || characters.some((character) => {
2770
- const code = character.codePointAt(0);
2771
- return code !== undefined && (
2772
- code <= 31
2773
- || (code >= 127 && code <= 159)
2774
- || (code >= 0xd800 && code <= 0xdfff)
2775
- || code === 0x2028
2776
- || code === 0x2029
2777
- );
2778
- })
2779
- ) {
2780
- throw new SdkError(
2781
- "validation_error",
2782
- `metric description must be a non-blank string of at most ${MAX_METRIC_DESCRIPTION_LENGTH} non-control characters`
2783
- );
2784
- }
2785
- return value.trim();
2786
- }
2787
-
2788
- function productActionDetails(action) {
2789
- if (typeof action === "string") {
2790
- return { name: action, status: "success" };
2791
- }
2792
- if (!action || Array.isArray(action) || typeof action !== "object") {
2793
- throw new SdkError("validation_error", "product action must be a string or object");
2794
- }
2795
- requireNonEmpty("product action name", action.name);
2796
- const status = action.status === undefined ? "success" : action.status;
2797
- requireAllowedValue("product action status", status, ACTION_STATUSES);
2798
- return {
2799
- funnel: action.funnel,
2800
- metadata: action.metadata,
2801
- name: action.name,
2802
- routeTemplate: action.routeTemplate,
2803
- screen: action.screen,
2804
- sessionId: action.sessionId,
2805
- status,
2806
- step: action.step,
2807
- traceId: action.traceId
2808
- };
2809
- }
2810
-
2811
- function networkMilestoneDetails(request) {
2812
- if (typeof request === "string") {
2813
- return networkMilestoneDetails({ routeTemplate: request });
2814
- }
2815
- if (!request || Array.isArray(request) || typeof request !== "object") {
2816
- throw new SdkError("validation_error", "network milestone must be a string or object");
2817
- }
2818
-
2819
- const routeTemplate = sanitizeRouteTemplate(request.routeTemplate);
2820
- requireNonEmpty("network milestone routeTemplate", routeTemplate);
2821
- const method = normalizeHttpMethod(request.method);
2822
- const statusCode = statusCodeOrUndefined(request.statusCode);
2823
- const status = request.status === undefined
2824
- ? statusFromStatusCode(statusCode)
2825
- : request.status;
2826
- requireAllowedValue("network milestone status", status, ACTION_STATUSES);
2827
- const durationMs = nonNegativeNumberOrUndefined("network milestone durationMs", request.durationMs);
2828
- const name = typeof request.name === "string" && request.name.trim() !== ""
2829
- ? request.name
2830
- : `network.${method.toLowerCase()} ${routeTemplate}`;
2831
-
2832
- return {
2833
- durationMs,
2834
- metadata: request.metadata,
2835
- method,
2836
- name,
2837
- routeTemplate,
2838
- sessionId: request.sessionId,
2839
- status,
2840
- statusCode,
2841
- traceId: request.traceId
2842
- };
2843
- }
2844
-
2845
- function sanitizeRouteTemplate(routeTemplate) {
2846
- if (routeTemplate === undefined) {
2847
- return undefined;
2848
- }
2849
- if (typeof routeTemplate !== "string") {
2850
- throw new SdkError("validation_error", "routeTemplate must be a string");
2851
- }
2852
- const trimmed = routeTemplate.trim();
2853
- if (trimmed === "") {
2854
- return "";
2855
- }
2856
- try {
2857
- const url = new URL(trimmed, "https://logbrew.example");
2858
- return url.pathname || "/";
2859
- } catch {
2860
- return trimmed.split(/[?#]/u)[0] || "/";
2861
- }
2862
- }
2863
-
2864
- function productAnalyticsMetadata(kind, surface) {
2865
- const normalizedSurface = boundedProductAnalyticsSurface(surface);
2866
- return {
2867
- analyticsSchemaVersion: PRODUCT_ANALYTICS_SCHEMA_VERSION,
2868
- analyticsKind: kind,
2869
- analyticsSurface: normalizedSurface
2870
- };
2871
- }
2872
-
2873
- function boundedProductAnalyticsSurface(surface) {
2874
- if (typeof surface !== "string") {
2875
- return undefined;
2876
- }
2877
- const normalized = surface.trim();
2878
- const characters = Array.from(normalized);
2879
- if (
2880
- normalized === ""
2881
- || characters.length > MAX_PRODUCT_ANALYTICS_SURFACE_LENGTH
2882
- || characters.some((character) => {
2883
- const code = character.codePointAt(0);
2884
- return code !== undefined && (code <= 31 || (code >= 127 && code <= 159));
2885
- })
2886
- ) {
2887
- return undefined;
2888
- }
2889
- return normalized;
2890
- }
2891
-
2892
- function normalizeHttpMethod(method) {
2893
- const value = method === undefined ? "GET" : method;
2894
- if (typeof value !== "string" || value.trim() === "") {
2895
- throw new SdkError("validation_error", "network milestone method must be a non-empty string");
2896
- }
2897
- const normalized = value.trim().toUpperCase();
2898
- if (!/^[A-Z][A-Z0-9_-]*$/u.test(normalized)) {
2899
- throw new SdkError("validation_error", "network milestone method must be a valid HTTP method");
2900
- }
2901
- return normalized;
2902
- }
2903
-
2904
- function statusCodeOrUndefined(value) {
2905
- if (value === undefined) {
2906
- return undefined;
2907
- }
2908
- if (!Number.isInteger(value) || value < 100 || value > 599) {
2909
- throw new SdkError("validation_error", "network milestone statusCode must be an integer from 100 to 599");
2910
- }
2911
- return value;
2912
- }
2913
-
2914
- function statusFromStatusCode(statusCode) {
2915
- if (statusCode !== undefined && statusCode >= 400) {
2916
- return "failure";
2917
- }
2918
- return "success";
2919
- }
2920
-
2921
- function nonNegativeNumberOrUndefined(label, value) {
2922
- if (value === undefined) {
2923
- return undefined;
2924
- }
2925
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
2926
- throw new SdkError("validation_error", `${label} must be a non-negative number`);
2927
- }
2928
- return value;
2929
- }
2930
-
2931
- function stringOrUndefined(value) {
2932
- return typeof value === "string" && value.trim() !== "" ? value : undefined;
2933
- }
2934
-
2935
- function withMetadata(attributes, metadata, context) {
2936
- const safeMetadata = cloneMetadata(metadata);
2937
- const safeContext = validateTelemetryContext(context);
2938
- return {
2939
- ...attributes,
2940
- ...(safeMetadata === undefined ? {} : { metadata: safeMetadata }),
2941
- ...(safeContext === undefined ? {} : { context: safeContext })
2942
- };
2943
- }
2944
-
2945
- function normalizeConsoleLevels(levels) {
2946
- const requestedLevels = levels === undefined ? DEFAULT_CONSOLE_LEVELS : levels;
2947
- if (!Array.isArray(requestedLevels)) {
2948
- throw new SdkError("validation_error", "console capture levels must be an array");
2949
- }
2950
- const normalized = [];
2951
- for (const method of requestedLevels) {
2952
- if (!CONSOLE_METHODS.has(method)) {
2953
- throw new SdkError("validation_error", `console method must be one of: ${Array.from(CONSOLE_METHODS).join(", ")}`);
2954
- }
2955
- if (!normalized.includes(method)) {
2956
- normalized.push(method);
2957
- }
2958
- }
2959
- return normalized;
2960
- }
2961
-
2962
- function consoleMessage(args, includeErrorStack) {
2963
- const values = Array.isArray(args) ? args : [];
2964
- const message = values.map((value) => formatConsoleArgument(value, includeErrorStack)).join(" ");
2965
- return message.trim() === "" ? "console event" : message;
2966
- }
2967
-
2968
- function formatConsoleArgument(value, includeErrorStack) {
2969
- if (value instanceof Error) {
2970
- if (includeErrorStack && value.stack) {
2971
- return value.stack;
2972
- }
2973
- return value.message ? `${value.name}: ${value.message}` : value.name;
2974
- }
2975
- if (typeof value === "string") {
2976
- return value;
2977
- }
2978
- if (typeof value === "number" || typeof value === "boolean" || value === null || value === undefined) {
2979
- return String(value);
2980
- }
2981
- if (typeof value === "bigint" || typeof value === "symbol") {
2982
- return String(value);
2983
- }
2984
- try {
2985
- const json = JSON.stringify(value);
2986
- return json === undefined ? String(value) : json;
2987
- } catch {
2988
- return Object.prototype.toString.call(value);
2989
- }
2990
- }
2991
-
2992
- const { installBrowserBreadcrumbs } = require("./browser-breadcrumbs.cjs");
35
+ } = require("./trace-context.cjs");
36
+ const { TransportError } = require("./transport-error.cjs");
2993
37
 
2994
38
  module.exports = {
2995
39
  PRODUCT_ANALYTICS_KINDS,
2996
40
  installBrowserBreadcrumbs,
41
+
2997
42
  PRODUCT_ANALYTICS_SCHEMA_VERSION,
2998
43
  createBaggage,
2999
44
  createIssueAttributesFromError,
3000
45
  createNetworkMilestoneAttributes,
3001
46
  createProductActionAttributes,
47
+
3002
48
  createLogBrewOpenTelemetrySpanExporter,
3003
49
  createLogBrewOpenTelemetrySpanProcessor,
3004
50
  createSupportTicketDraft,
@@ -3006,21 +52,26 @@ module.exports = {
3006
52
  createTraceparent,
3007
53
  createTraceparentHeaders,
3008
54
  createTracestate,
55
+
3009
56
  createLogBrewPinoDestination,
3010
57
  installLogBrewConsoleCapture,
58
+
3011
59
  LogBrewClient,
3012
60
  logbrewTraceContextFromCurrentOpenTelemetrySpan,
3013
61
  logbrewTraceContextFromOpenTelemetrySpan,
3014
62
  logbrewTraceContextFromOpenTelemetrySpanContext,
63
+
3015
64
  logAttributesFromConsoleArgs,
3016
65
  logAttributesFromPinoRecord,
3017
66
  logbrewLevelFromConsoleMethod,
3018
67
  parseBaggage,
3019
68
  parseTraceparent,
3020
69
  parseTracestate,
70
+
3021
71
  RecordingTransport,
3022
72
  SdkError,
3023
73
  spanAttributesFromOpenTelemetryReadableSpan,
3024
74
  spanAttributesFromTraceparent,
75
+
3025
76
  TransportError
3026
77
  };