@flareapp/core 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +4 -1
  2. package/dist/index.cjs +1152 -0
  3. package/dist/index.d.cts +544 -0
  4. package/dist/index.d.mts +544 -0
  5. package/dist/index.mjs +1104 -0
  6. package/package.json +4 -1
  7. package/.oxlintrc.json +0 -7
  8. package/.release-it.json +0 -13
  9. package/CHANGELOG.md +0 -16
  10. package/src/Flare.ts +0 -543
  11. package/src/Scope.ts +0 -96
  12. package/src/api/Api.ts +0 -35
  13. package/src/api/index.ts +0 -1
  14. package/src/env/index.ts +0 -14
  15. package/src/index.ts +0 -41
  16. package/src/stacktrace/NullFileReader.ts +0 -28
  17. package/src/stacktrace/createStackTrace.ts +0 -74
  18. package/src/stacktrace/fileReader.ts +0 -96
  19. package/src/stacktrace/index.ts +0 -4
  20. package/src/types.ts +0 -81
  21. package/src/util/assert.ts +0 -9
  22. package/src/util/assertKey.ts +0 -11
  23. package/src/util/convertToError.ts +0 -22
  24. package/src/util/extractCode.ts +0 -11
  25. package/src/util/flatJsonStringify.ts +0 -45
  26. package/src/util/glowsToEvents.ts +0 -16
  27. package/src/util/index.ts +0 -8
  28. package/src/util/now.ts +0 -3
  29. package/src/util/redactUrl.ts +0 -83
  30. package/tests/api.test.ts +0 -95
  31. package/tests/configure.test.ts +0 -16
  32. package/tests/contextCollector.test.ts +0 -37
  33. package/tests/convertToError.test.ts +0 -95
  34. package/tests/createStackTrace.test.ts +0 -54
  35. package/tests/extractCode.test.ts +0 -30
  36. package/tests/fileReader.test.ts +0 -51
  37. package/tests/flatJsonStringify.test.ts +0 -31
  38. package/tests/flush.test.ts +0 -47
  39. package/tests/glows.test.ts +0 -47
  40. package/tests/glowsToEvents.test.ts +0 -41
  41. package/tests/helpers/FakeApi.ts +0 -20
  42. package/tests/helpers/index.ts +0 -1
  43. package/tests/hooks.test.ts +0 -123
  44. package/tests/light.test.ts +0 -25
  45. package/tests/nullFileReader.test.ts +0 -11
  46. package/tests/publicExports.test.ts +0 -17
  47. package/tests/redactUrl.test.ts +0 -151
  48. package/tests/report.test.ts +0 -146
  49. package/tests/sampleRate.test.ts +0 -88
  50. package/tests/scope.test.ts +0 -64
  51. package/tests/setEntryPoint.test.ts +0 -79
  52. package/tests/setFramework.test.ts +0 -48
  53. package/tests/setSdkInfo.test.ts +0 -62
  54. package/tsconfig.json +0 -4
  55. package/vitest.config.ts +0 -17
package/dist/index.mjs ADDED
@@ -0,0 +1,1104 @@
1
+ import ErrorStackParser from "error-stack-parser";
2
+
3
+ //#region src/env/index.ts
4
+ const CLIENT_VERSION = typeof process !== "undefined" && true ? "2.3.0" : "?";
5
+ const KEY = typeof FLARE_JS_KEY === "undefined" ? "" : FLARE_JS_KEY;
6
+ const SOURCEMAP_VERSION = typeof FLARE_SOURCEMAP_VERSION === "undefined" ? "" : FLARE_SOURCEMAP_VERSION;
7
+
8
+ //#endregion
9
+ //#region src/util/assert.ts
10
+ function assert(value, message, debug) {
11
+ if (debug && !value) console.error(`Flare JavaScript client v${CLIENT_VERSION}: ${message}`);
12
+ return !!value;
13
+ }
14
+
15
+ //#endregion
16
+ //#region src/util/assertKey.ts
17
+ function assertKey(key, debug) {
18
+ return assert(key, "The client was not yet initialised with an API key. Run client.light('<flare-project-key>') when you initialise your app. If you are running in dev mode and didn't run the light command on purpose, you can ignore this error.", debug);
19
+ }
20
+
21
+ //#endregion
22
+ //#region src/util/convertToError.ts
23
+ function convertToError(error) {
24
+ if (error instanceof Error) return error;
25
+ if (typeof error === "string") return new Error(error);
26
+ if (typeof error === "object" && error !== null) {
27
+ const obj = error;
28
+ const message = typeof obj.message === "string" ? obj.message : String(error);
29
+ const converted = new Error(message);
30
+ if (typeof obj.stack === "string") converted.stack = obj.stack;
31
+ if (typeof obj.name === "string") converted.name = obj.name;
32
+ return converted;
33
+ }
34
+ return new Error(String(error));
35
+ }
36
+
37
+ //#endregion
38
+ //#region src/util/extractCode.ts
39
+ const MAX_CODE_LENGTH = 64;
40
+ function extractCode(error) {
41
+ const code = error.code;
42
+ if (typeof code !== "string" || code.length === 0) return;
43
+ return code.slice(0, MAX_CODE_LENGTH);
44
+ }
45
+
46
+ //#endregion
47
+ //#region src/util/flatJsonStringify.ts
48
+ function flatJsonStringify(json) {
49
+ return JSON.stringify(decycle(json));
50
+ }
51
+ function isPlainObject(value) {
52
+ if (typeof value !== "object" || value === null) return false;
53
+ const proto = Object.getPrototypeOf(value);
54
+ return proto === Object.prototype || proto === null;
55
+ }
56
+ function decycle(root) {
57
+ const inPath = /* @__PURE__ */ new WeakSet();
58
+ function clone(node) {
59
+ if (Array.isArray(node)) {
60
+ if (inPath.has(node)) return "[Circular]";
61
+ inPath.add(node);
62
+ const result = node.map(clone);
63
+ inPath.delete(node);
64
+ return result;
65
+ }
66
+ if (isPlainObject(node)) {
67
+ if (inPath.has(node)) return "[Circular]";
68
+ inPath.add(node);
69
+ const result = {};
70
+ for (const [k, v] of Object.entries(node)) result[k] = clone(v);
71
+ inPath.delete(node);
72
+ return result;
73
+ }
74
+ return node;
75
+ }
76
+ return clone(root);
77
+ }
78
+
79
+ //#endregion
80
+ //#region src/util/glowsToEvents.ts
81
+ function glowsToEvents(glows) {
82
+ return glows.map((glow) => ({
83
+ type: "php_glow",
84
+ startTimeUnixNano: Math.round(glow.microtime * 1e9),
85
+ endTimeUnixNano: null,
86
+ attributes: {
87
+ "glow.name": String(glow.name),
88
+ "glow.level": glow.messageLevel,
89
+ "glow.context": glow.metaData ?? {}
90
+ }
91
+ }));
92
+ }
93
+
94
+ //#endregion
95
+ //#region src/util/now.ts
96
+ function now() {
97
+ return Math.round(Date.now() / 1e3);
98
+ }
99
+
100
+ //#endregion
101
+ //#region src/util/redactUrl.ts
102
+ const DEFAULT_URL_DENYLIST = /password|passwd|pwd|token|secret|authorization|\bauth\b|bearer|oauth|credentials?|cookie|api[-_]?key|private[-_]?key|session|csrf|xsrf|\bpin\b|\bssn\b|card[-_]?number|\bcvv\b/i;
103
+ function resolveDenylist(custom, replaceDefault = false, defaultDenylist = DEFAULT_URL_DENYLIST) {
104
+ if (!custom) return defaultDenylist;
105
+ if (replaceDefault) {
106
+ const safeFlags = custom.flags.replace(/[gy]/g, "");
107
+ return new RegExp(custom.source, safeFlags);
108
+ }
109
+ const flags = unionFlags(defaultDenylist.flags, custom.flags);
110
+ return new RegExp(`(?:${defaultDenylist.source})|(?:${custom.source})`, flags);
111
+ }
112
+ function unionFlags(a, b) {
113
+ const merged = /* @__PURE__ */ new Set();
114
+ for (const flag of a + b) {
115
+ if (flag === "g" || flag === "y") continue;
116
+ merged.add(flag);
117
+ }
118
+ return [...merged].join("");
119
+ }
120
+ function redactUrlQuery(fullPath, denylist = DEFAULT_URL_DENYLIST) {
121
+ const queryStart = fullPath.indexOf("?");
122
+ if (queryStart === -1) return fullPath;
123
+ const hashStart = fullPath.indexOf("#", queryStart);
124
+ const queryEnd = hashStart === -1 ? fullPath.length : hashStart;
125
+ const prefix = fullPath.slice(0, queryStart + 1);
126
+ const queryString = fullPath.slice(queryStart + 1, queryEnd);
127
+ const suffix = fullPath.slice(queryEnd);
128
+ return `${prefix}${queryString.split("&").map((pair) => {
129
+ if (pair === "") return pair;
130
+ const eq = pair.indexOf("=");
131
+ const rawKey = eq === -1 ? pair : pair.slice(0, eq);
132
+ const decodedKey = safeDecode(rawKey);
133
+ if (!denylist.test(decodedKey)) return pair;
134
+ return eq === -1 ? rawKey : `${rawKey}=[redacted]`;
135
+ }).join("&")}${suffix}`;
136
+ }
137
+ function safeDecode(value) {
138
+ try {
139
+ return decodeURIComponent(value);
140
+ } catch {
141
+ return value;
142
+ }
143
+ }
144
+
145
+ //#endregion
146
+ //#region src/api/Api.ts
147
+ var Api = class {
148
+ report(report, url, key, reportBrowserExtensionErrors, debug = false) {
149
+ return fetch(url, {
150
+ method: "POST",
151
+ headers: {
152
+ "Accept": "application/json",
153
+ "Content-Type": "application/json",
154
+ "X-Api-Token": key ?? "",
155
+ "X-Report-Browser-Extension-Errors": JSON.stringify(reportBrowserExtensionErrors),
156
+ "X-Flare-Client-Version": "2"
157
+ },
158
+ body: flatJsonStringify(report)
159
+ }).then((response) => {
160
+ if (debug && response.status !== 201) console.error(`Received response with status ${response.status} from Flare`);
161
+ }, (error) => {
162
+ if (debug) console.error(error);
163
+ });
164
+ }
165
+ logs(envelope, url, key, debug = false, keepalive = false) {
166
+ return fetch(url, {
167
+ method: "POST",
168
+ keepalive,
169
+ headers: {
170
+ "Accept": "application/json",
171
+ "Content-Type": "application/json",
172
+ "x-api-token": key ?? ""
173
+ },
174
+ body: flatJsonStringify(envelope)
175
+ }).then((response) => {
176
+ if (debug && response.status !== 201) console.error(`Received response with status ${response.status} from Flare logs`);
177
+ }, (error) => {
178
+ if (debug) console.error(error);
179
+ });
180
+ }
181
+ };
182
+
183
+ //#endregion
184
+ //#region src/logging/otel.ts
185
+ function valueToOpenTelemetry(value, inPath = /* @__PURE__ */ new WeakSet()) {
186
+ if (typeof value === "string") return { stringValue: value };
187
+ if (typeof value === "boolean") return { boolValue: value };
188
+ if (typeof value === "number") {
189
+ if (!Number.isFinite(value)) return null;
190
+ return Number.isInteger(value) ? { intValue: value } : { doubleValue: value };
191
+ }
192
+ if (value === null || value === void 0) return null;
193
+ if (Array.isArray(value)) {
194
+ if (inPath.has(value)) return { stringValue: "[Circular]" };
195
+ inPath.add(value);
196
+ const values = [];
197
+ for (const item of value) {
198
+ const mapped = valueToOpenTelemetry(item, inPath);
199
+ if (mapped !== null) values.push(mapped);
200
+ }
201
+ inPath.delete(value);
202
+ return { arrayValue: { values } };
203
+ }
204
+ if (typeof value === "object") {
205
+ if (inPath.has(value)) return { stringValue: "[Circular]" };
206
+ inPath.add(value);
207
+ const values = [];
208
+ for (const [key, item] of Object.entries(value)) {
209
+ const mapped = valueToOpenTelemetry(item, inPath);
210
+ if (mapped !== null) values.push({
211
+ key,
212
+ value: mapped
213
+ });
214
+ }
215
+ inPath.delete(value);
216
+ return { kvlistValue: { values } };
217
+ }
218
+ return null;
219
+ }
220
+ function attributesToOpenTelemetry(attributes) {
221
+ const out = [];
222
+ for (const [key, value] of Object.entries(attributes)) {
223
+ const mapped = valueToOpenTelemetry(value);
224
+ if (mapped !== null) out.push({
225
+ key,
226
+ value: mapped
227
+ });
228
+ }
229
+ return out;
230
+ }
231
+
232
+ //#endregion
233
+ //#region src/logging/envelope.ts
234
+ function buildLogsEnvelope(records, resourceAttributes, scopeName, scopeVersion) {
235
+ return { resourceLogs: [{
236
+ resource: {
237
+ attributes: attributesToOpenTelemetry(resourceAttributes),
238
+ droppedAttributesCount: 0
239
+ },
240
+ scopeLogs: [{
241
+ scope: {
242
+ name: scopeName,
243
+ version: scopeVersion,
244
+ attributes: [],
245
+ droppedAttributesCount: 0
246
+ },
247
+ logRecords: records.map((record) => ({
248
+ timeUnixNano: record.timeUnixNano,
249
+ observedTimeUnixNano: record.timeUnixNano,
250
+ severityNumber: record.severityNumber,
251
+ severityText: record.severityText,
252
+ body: { stringValue: record.message },
253
+ attributes: record.recordAttributes,
254
+ flags: 0,
255
+ droppedAttributesCount: 0
256
+ }))
257
+ }]
258
+ }] };
259
+ }
260
+
261
+ //#endregion
262
+ //#region src/logging/severity.ts
263
+ const SEVERITY_NUMBERS = {
264
+ debug: 5,
265
+ info: 9,
266
+ notice: 10,
267
+ warning: 13,
268
+ error: 17,
269
+ critical: 18,
270
+ alert: 19,
271
+ emergency: 21
272
+ };
273
+ function severityNumber(level) {
274
+ return SEVERITY_NUMBERS[level];
275
+ }
276
+ function severityText(level) {
277
+ return level.toUpperCase();
278
+ }
279
+ function isAtOrAboveMinimum(level, minimum) {
280
+ return severityNumber(level) >= severityNumber(minimum);
281
+ }
282
+
283
+ //#endregion
284
+ //#region src/logging/Logger.ts
285
+ var Logger = class {
286
+ buffer = [];
287
+ resourceAttributes = {};
288
+ timer;
289
+ timerActive = false;
290
+ constructor(deps) {
291
+ this.deps = deps;
292
+ const flush = (opts) => this.flush(opts);
293
+ this.deps.scheduler.register(flush);
294
+ }
295
+ debug(message, context = {}, attributes = {}) {
296
+ this.record("debug", message, context, attributes);
297
+ }
298
+ info(message, context = {}, attributes = {}) {
299
+ this.record("info", message, context, attributes);
300
+ }
301
+ notice(message, context = {}, attributes = {}) {
302
+ this.record("notice", message, context, attributes);
303
+ }
304
+ warning(message, context = {}, attributes = {}) {
305
+ this.record("warning", message, context, attributes);
306
+ }
307
+ error(message, context = {}, attributes = {}) {
308
+ this.record("error", message, context, attributes);
309
+ }
310
+ critical(message, context = {}, attributes = {}) {
311
+ this.record("critical", message, context, attributes);
312
+ }
313
+ alert(message, context = {}, attributes = {}) {
314
+ this.record("alert", message, context, attributes);
315
+ }
316
+ emergency(message, context = {}, attributes = {}) {
317
+ this.record("emergency", message, context, attributes);
318
+ }
319
+ bufferLength() {
320
+ return this.buffer.length;
321
+ }
322
+ record(level, message, context, attributes) {
323
+ const config = this.deps.getConfig();
324
+ if (!config.enableLogs) return;
325
+ if (config.minimumLogLevel && !isAtOrAboveMinimum(level, config.minimumLogLevel)) return;
326
+ const userAttributes = {
327
+ "log.context": context,
328
+ ...attributes
329
+ };
330
+ const { record, resource } = this.deps.buildLogAttributes(userAttributes);
331
+ const buffered = {
332
+ timeUnixNano: String(Date.now()) + "000000",
333
+ severityNumber: severityNumber(level),
334
+ severityText: severityText(level),
335
+ message,
336
+ recordAttributes: attributesToOpenTelemetry(record),
337
+ resourceAttributes: resource
338
+ };
339
+ if (this.estimateBytes(buffered) > config.logFlushMaxBytes) {
340
+ if (config.debug) console.error("Flare: dropping oversized log record");
341
+ return;
342
+ }
343
+ this.buffer.push(buffered);
344
+ this.resourceAttributes = resource;
345
+ this.evaluateTriggers(config);
346
+ this.trim(config);
347
+ }
348
+ evaluateTriggers(config) {
349
+ if (this.buffer.length >= config.maxLogBufferSize) {
350
+ this.flush();
351
+ return;
352
+ }
353
+ if (this.bufferBytes() >= config.logFlushMaxBytes) {
354
+ this.flush();
355
+ return;
356
+ }
357
+ this.armTimer(config);
358
+ }
359
+ armTimer(config) {
360
+ if (this.timerActive) return;
361
+ this.timerActive = true;
362
+ this.timer = setTimeout(() => this.flush(), config.logFlushIntervalMs);
363
+ this.timer.unref?.();
364
+ }
365
+ trim(config) {
366
+ if (this.buffer.length > config.maxLogBufferSize) this.buffer = this.buffer.slice(this.buffer.length - config.maxLogBufferSize);
367
+ while (this.buffer.length > 1 && this.bufferBytes() > config.logFlushMaxBytes) this.buffer.shift();
368
+ }
369
+ flush(opts) {
370
+ const config = this.deps.getConfig();
371
+ if (!config.enableLogs) return;
372
+ if (this.buffer.length === 0) return;
373
+ if (!assertKey(config.key, config.debug)) {
374
+ this.clearTimer();
375
+ return;
376
+ }
377
+ this.clearTimer();
378
+ let records;
379
+ if (opts?.keepalive) {
380
+ records = this.packForKeepalive(config);
381
+ this.buffer = this.buffer.filter((log) => !records.includes(log));
382
+ if (this.buffer.length > 0) this.armTimer(config);
383
+ } else {
384
+ records = this.buffer;
385
+ this.buffer = [];
386
+ }
387
+ if (records.length === 0) return;
388
+ this.deps.track(this.deps.api.logs(this.buildEnvelope(records), config.logsIngestUrl, config.key, config.debug, !!opts?.keepalive));
389
+ }
390
+ clear() {
391
+ this.buffer = [];
392
+ this.clearTimer();
393
+ }
394
+ packForKeepalive(config) {
395
+ let selected = [];
396
+ for (let i = this.buffer.length - 1; i >= 0; i--) {
397
+ const trial = [this.buffer[i], ...selected];
398
+ if (new TextEncoder().encode(flatJsonStringify(this.buildEnvelope(trial))).length <= config.keepaliveMaxBytes) selected = trial;
399
+ else if (config.debug) console.error("Flare: dropping log record from keepalive envelope (over budget)");
400
+ }
401
+ return selected;
402
+ }
403
+ buildEnvelope(records) {
404
+ const sdk = this.deps.getSdkInfo();
405
+ return buildLogsEnvelope(records, this.resourceForFlush(), sdk.name, sdk.version);
406
+ }
407
+ resourceForFlush() {
408
+ const config = this.deps.getConfig();
409
+ const sdk = this.deps.getSdkInfo();
410
+ const framework = this.deps.getFramework();
411
+ const identity = {
412
+ "telemetry.sdk.language": "javascript",
413
+ "telemetry.sdk.name": sdk.name,
414
+ "telemetry.sdk.version": sdk.version,
415
+ "flare.language.name": "javascript"
416
+ };
417
+ if (config.serviceName) identity["service.name"] = config.serviceName;
418
+ if (config.version) identity["service.version"] = config.version;
419
+ if (config.stage) identity["service.stage"] = config.stage;
420
+ if (framework?.name) identity["flare.framework.name"] = framework.name;
421
+ if (framework?.version) identity["flare.framework.version"] = framework.version;
422
+ return {
423
+ ...this.resourceAttributes,
424
+ ...identity
425
+ };
426
+ }
427
+ clearTimer() {
428
+ if (this.timer) {
429
+ clearTimeout(this.timer);
430
+ this.timer = void 0;
431
+ }
432
+ this.timerActive = false;
433
+ }
434
+ estimateBytes(log) {
435
+ return flatJsonStringify(log).length;
436
+ }
437
+ bufferBytes() {
438
+ return this.buffer.reduce((sum, log) => sum + this.estimateBytes(log), 0);
439
+ }
440
+ };
441
+
442
+ //#endregion
443
+ //#region src/logging/FlushScheduler.ts
444
+ var NoopFlushScheduler = class {
445
+ register() {}
446
+ };
447
+
448
+ //#endregion
449
+ //#region src/logging/partition.ts
450
+ const RESOURCE_PREFIXES = [
451
+ "service.",
452
+ "telemetry.",
453
+ "host.",
454
+ "os.",
455
+ "process.",
456
+ "flare.framework.",
457
+ "flare.language."
458
+ ];
459
+ const RECORD_LEVEL_EXCEPTIONS = new Set(["process.uptime"]);
460
+ function partitionAttributes(attributes) {
461
+ const resource = {};
462
+ const record = {};
463
+ for (const [key, value] of Object.entries(attributes)) if (!RECORD_LEVEL_EXCEPTIONS.has(key) && RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix))) resource[key] = value;
464
+ else record[key] = value;
465
+ return {
466
+ resource,
467
+ record
468
+ };
469
+ }
470
+
471
+ //#endregion
472
+ //#region src/Scope.ts
473
+ /**
474
+ * Holds the per-call mutable state that used to live on the `Flare` instance:
475
+ * breadcrumbs (`glows`), custom attributes (`pendingAttributes`), and the
476
+ * current entry-point handler.
477
+ *
478
+ * Why this exists as its own class: in the browser there is one `Flare` per
479
+ * page and one user at a time, so a single shared bag of state is fine. In
480
+ * Node, a single `Flare` instance serves many concurrent requests, and each
481
+ * request wants its own breadcrumbs and its own custom context that do NOT
482
+ * leak into other requests. Splitting this state out of `Flare` lets the
483
+ * consumer choose: one global `Scope` (browser) or one `Scope` per request
484
+ * via AsyncLocalStorage (Node).
485
+ *
486
+ * `Flare` reads and writes this through `scopeProvider.active()` instead of
487
+ * holding the state directly, so the per-request behavior comes from the
488
+ * provider, not from the class itself.
489
+ *
490
+ * `NodeScope` (in `@flareapp/node`) extends this with two more buckets:
491
+ * `request` (HTTP method, path, headers) and `user` (id, email, ...). Browser
492
+ * does not need those.
493
+ */
494
+ var Scope = class {
495
+ glows = [];
496
+ pendingAttributes = {};
497
+ entryPoint = null;
498
+ /**
499
+ * Append a breadcrumb. Caps the list at `maxGlowsPerReport` by dropping the
500
+ * OLDEST entries when the limit is exceeded; this keeps reports below a
501
+ * payload-size threshold while preserving the most recent events leading
502
+ * up to an error.
503
+ *
504
+ * `slice(length - max)` returns the trailing `max` items, which is the
505
+ * shortest way to drop from the front and keep insertion order.
506
+ */
507
+ addGlow(glow, maxGlowsPerReport) {
508
+ this.glows.push(glow);
509
+ if (this.glows.length > maxGlowsPerReport) this.glows = this.glows.slice(this.glows.length - maxGlowsPerReport);
510
+ }
511
+ clearGlows() {
512
+ this.glows = [];
513
+ }
514
+ /**
515
+ * Set a single attribute on this scope. Called from `Flare.addContext` and
516
+ * `Flare.addContextGroup`. Last write wins.
517
+ */
518
+ setAttribute(key, value) {
519
+ this.pendingAttributes[key] = value;
520
+ }
521
+ /**
522
+ * Shallow-merge a bag of attributes into this scope. Used by Node's
523
+ * AsyncLocalStorage provider when patching the live request context via
524
+ * `flare.mergeContext({ ... })`. Last write wins per key; nested objects
525
+ * are NOT deep-merged.
526
+ */
527
+ mergeAttributes(partial) {
528
+ Object.assign(this.pendingAttributes, partial);
529
+ }
530
+ };
531
+ /**
532
+ * The simplest provider: one `Scope` for the lifetime of the provider, shared
533
+ * by every caller. This is the right default for environments with a single
534
+ * logical context (browser tab, CLI script, etc.) and is the default that
535
+ * `Flare`'s constructor falls back to when no provider is supplied.
536
+ */
537
+ var GlobalScopeProvider = class {
538
+ scope = new Scope();
539
+ active() {
540
+ return this.scope;
541
+ }
542
+ };
543
+
544
+ //#endregion
545
+ //#region src/stacktrace/fileReader.ts
546
+ const cachedFiles = {};
547
+ function getCodeSnippet(fileReader, url, lineNumber, columnNumber) {
548
+ return new Promise((resolve) => {
549
+ if (!url || !lineNumber) return resolve({
550
+ codeSnippet: { 0: `Could not read from file: missing file URL or line number. URL: ${url} lineNumber: ${lineNumber}` },
551
+ trimmedColumnNumber: null
552
+ });
553
+ readFile(fileReader, url).then((fileText) => {
554
+ if (!fileText) return resolve({
555
+ codeSnippet: { 0: `Could not read from file: Error while opening file at URL ${url}` },
556
+ trimmedColumnNumber: null
557
+ });
558
+ return resolve(readLinesFromFile(fileText, lineNumber, columnNumber));
559
+ });
560
+ });
561
+ }
562
+ function readFile(fileReader, url) {
563
+ if (cachedFiles[url] !== void 0) return Promise.resolve(cachedFiles[url]);
564
+ return fileReader.read(url).then((text) => {
565
+ if (text !== null) cachedFiles[url] = text;
566
+ return text;
567
+ });
568
+ }
569
+ function readLinesFromFile(fileText, lineNumber, columnNumber, maxSnippetLineLength = 1e3, maxSnippetLines = 40) {
570
+ const codeSnippet = {};
571
+ let trimmedColumnNumber = null;
572
+ const lines = fileText.split("\n");
573
+ const errorLineIndex = lineNumber - 1;
574
+ const half = Math.floor(maxSnippetLines / 2);
575
+ for (let i = -half; i <= half; i++) {
576
+ const currentLineIndex = errorLineIndex + i;
577
+ if (currentLineIndex < 0 || !lines[currentLineIndex]) continue;
578
+ const displayLine = currentLineIndex + 1;
579
+ const line = lines[currentLineIndex];
580
+ if (line.length > maxSnippetLineLength) {
581
+ if (columnNumber && columnNumber > maxSnippetLineLength / 2) {
582
+ const start = columnNumber - Math.round(maxSnippetLineLength / 2);
583
+ codeSnippet[displayLine] = line.slice(start, start + maxSnippetLineLength);
584
+ if (displayLine === lineNumber) trimmedColumnNumber = Math.round(maxSnippetLineLength / 2);
585
+ continue;
586
+ }
587
+ codeSnippet[displayLine] = line.slice(0, maxSnippetLineLength) + "…";
588
+ continue;
589
+ }
590
+ codeSnippet[displayLine] = line;
591
+ }
592
+ return {
593
+ codeSnippet,
594
+ trimmedColumnNumber
595
+ };
596
+ }
597
+
598
+ //#endregion
599
+ //#region src/stacktrace/createStackTrace.ts
600
+ function createStackTrace(error, debug, fileReader) {
601
+ return new Promise((resolve) => {
602
+ if (!hasStack(error)) return resolve([fallbackFrame("stacktrace missing")]);
603
+ let parsedFrames;
604
+ try {
605
+ parsedFrames = ErrorStackParser.parse(error);
606
+ } catch (parseError) {
607
+ assert(false, "Couldn't parse stacktrace of below error:", debug);
608
+ if (debug) {
609
+ console.error(parseError);
610
+ console.error(error);
611
+ }
612
+ return resolve([fallbackFrame("stacktrace could not be parsed")]);
613
+ }
614
+ Promise.all(parsedFrames.map((frame) => {
615
+ return getCodeSnippet(fileReader, frame.fileName, frame.lineNumber, frame.columnNumber).then((snippet) => ({
616
+ lineNumber: frame.lineNumber || 1,
617
+ columnNumber: frame.columnNumber || 1,
618
+ method: frame.functionName || "Anonymous or unknown function",
619
+ file: frame.fileName || "Unknown file",
620
+ codeSnippet: snippet.codeSnippet,
621
+ class: "",
622
+ isApplicationFrame: isApplicationFrame(frame.fileName)
623
+ }));
624
+ })).then(resolve);
625
+ });
626
+ }
627
+ function fallbackFrame(reason) {
628
+ return {
629
+ lineNumber: 0,
630
+ columnNumber: 0,
631
+ method: "unknown",
632
+ file: "unknown",
633
+ codeSnippet: { 0: `Could not read from file: ${reason}` },
634
+ class: "unknown"
635
+ };
636
+ }
637
+ function hasStack(err) {
638
+ if (!err || typeof err !== "object") return false;
639
+ const e = err;
640
+ const stack = e.stack ?? e.stacktrace ?? e["opera#sourceloc"];
641
+ return typeof stack === "string" && stack !== `${e.name}: ${e.message}`;
642
+ }
643
+ function isApplicationFrame(fileName) {
644
+ if (!fileName) return true;
645
+ if (/[/\\]node_modules[/\\]/.test(fileName)) return false;
646
+ if (/(^|[/\\])(vendor|vendors)[.~-][^/\\]*\.js/i.test(fileName)) return false;
647
+ return true;
648
+ }
649
+
650
+ //#endregion
651
+ //#region src/stacktrace/NullFileReader.ts
652
+ /**
653
+ * No-op `FileReader` that returns `null` for every URL it is asked to read.
654
+ *
655
+ * Used as the default for `Flare`'s `fileReader` constructor parameter so the
656
+ * class is usable without picking a side: instantiated bare (`new Flare()`),
657
+ * reports still build, but stack frames omit source-code snippets — which is
658
+ * the correct, safe behavior in an environment we know nothing about.
659
+ *
660
+ * The two real implementations live in the consumer packages and take their
661
+ * place once the right environment is established:
662
+ *
663
+ * - `@flareapp/js` injects `FetchFileReader`, which `fetch()`s source maps
664
+ * and original files over HTTP for browser stack frames.
665
+ * - `@flareapp/node` injects `DiskFileReader`, which reads files from disk
666
+ * via `node:fs/promises` for server stack frames.
667
+ *
668
+ * The interface (`read(url) -> Promise<string | null>`) lets the stack-trace
669
+ * builder treat all three the same way: ask for a URL, render the snippet
670
+ * when text comes back, gracefully skip it when `null` does. No environment
671
+ * checks anywhere in core.
672
+ */
673
+ var NullFileReader = class {
674
+ read(_url) {
675
+ return Promise.resolve(null);
676
+ }
677
+ };
678
+
679
+ //#endregion
680
+ //#region src/Flare.ts
681
+ const DEFAULT_SDK_NAME = "@flareapp/core";
682
+ var Flare = class {
683
+ inflight = /* @__PURE__ */ new Set();
684
+ _logger;
685
+ _config = {
686
+ key: null,
687
+ version: "",
688
+ sourcemapVersionId: SOURCEMAP_VERSION,
689
+ stage: "",
690
+ maxGlowsPerReport: 30,
691
+ ingestUrl: "https://ingress.flareapp.io/v1/errors",
692
+ reportBrowserExtensionErrors: false,
693
+ debug: false,
694
+ urlDenylist: DEFAULT_URL_DENYLIST,
695
+ replaceDefaultUrlDenylist: false,
696
+ sampleRate: 1,
697
+ beforeEvaluate: (error) => error,
698
+ beforeSubmit: (report) => report,
699
+ enableLogs: false,
700
+ logsIngestUrl: "https://ingress.flareapp.io/v1/logs",
701
+ maxLogBufferSize: 100,
702
+ logFlushIntervalMs: 5e3,
703
+ logFlushMaxBytes: 8e5,
704
+ keepaliveMaxBytes: 6e4
705
+ };
706
+ sdkInfo = {
707
+ name: DEFAULT_SDK_NAME,
708
+ version: CLIENT_VERSION
709
+ };
710
+ framework = null;
711
+ /**
712
+ * @param api sends the report over HTTP.
713
+ * @param contextCollector returns per-report attributes (browser DOM info, Node
714
+ * process info, etc). Default is a no-op.
715
+ * @param fileReader reads source files for stack-trace snippets. Default
716
+ * returns null (no snippets); `@flareapp/js` injects a
717
+ * fetch-based reader, `@flareapp/node` injects a disk reader.
718
+ * @param scopeProvider returns the current `Scope` (per-call mutable state:
719
+ * glows, pendingAttributes, entryPoint). Browser uses a
720
+ * single global scope; Node uses an AsyncLocalStorage-
721
+ * backed provider so each request gets its own.
722
+ */
723
+ constructor(api = new Api(), contextCollector = () => ({}), fileReader = new NullFileReader(), scopeProvider = new GlobalScopeProvider(), scheduler = new NoopFlushScheduler()) {
724
+ this.api = api;
725
+ this.contextCollector = contextCollector;
726
+ this.fileReader = fileReader;
727
+ this.scopeProvider = scopeProvider;
728
+ this._logger = new Logger({
729
+ api: this.api,
730
+ getConfig: () => this._config,
731
+ getSdkInfo: () => this.sdkInfo,
732
+ getFramework: () => this.framework,
733
+ buildLogAttributes: (userAttributes) => this.buildLogAttributes(userAttributes),
734
+ track: (p) => this.track(p),
735
+ scheduler
736
+ });
737
+ }
738
+ /**
739
+ * Register an in-flight report so `flush()` can wait for it. Called by
740
+ * every public report entry point (`report`, `reportSilently`,
741
+ * `reportMessage`, `reportUnhandledRejection`, `test`); each wraps its
742
+ * full async pipeline (beforeEvaluate -> stack trace + source snippets ->
743
+ * beforeSubmit -> `api.report()`) so the entire roundtrip is what's
744
+ * tracked, not just the HTTP send at the end.
745
+ *
746
+ * Two problems this method solves at once.
747
+ *
748
+ * Problem 1: hold a reference to the work without leaking rejections.
749
+ *
750
+ * `p` is the real report pipeline; it can reject (network failure,
751
+ * `beforeSubmit` throws, etc). If we stored `p` directly in `inflight`
752
+ * and no caller attached a `.catch` (the global error listeners use
753
+ * `reportSilently` which DOES catch, but the path is still subtle), an
754
+ * eventual rejection would surface as an unhandled-rejection warning
755
+ * on Node and a console error in the browser. Bad citizen.
756
+ *
757
+ * So we build a SHADOW promise that mirrors `p`'s timing but cannot
758
+ * reject:
759
+ *
760
+ * p.then(
761
+ * () => undefined, // on fulfilment, value is undefined
762
+ * () => undefined, // on rejection, ALSO resolve with undefined
763
+ * )
764
+ *
765
+ * Providing the second argument means we have "handled" any rejection
766
+ * from `p`. The shadow always resolves with `undefined`, and `p`'s
767
+ * rejection is consumed at the boundary. From the runtime's point of
768
+ * view, the shadow is well-behaved.
769
+ *
770
+ * Problem 2: self-cleaning entry.
771
+ *
772
+ * `tracked.finally(() => this.inflight.delete(tracked))`. `finally`
773
+ * fires whether the shadow resolves or rejects, but the shadow can no
774
+ * longer reject (problem 1 normalized it), so this is effectively
775
+ * "when the underlying report has settled, remove me from the Set."
776
+ * No GC magic, no external cleanup, no race window.
777
+ *
778
+ * Note that `.finally` itself returns a new promise that we drop on
779
+ * the floor. If the cleanup callback ever throws, that would surface
780
+ * as an unhandled rejection on the dropped promise; `delete` does not
781
+ * throw so we are safe today, but anything more elaborate added here
782
+ * should be wrapped in try/catch.
783
+ *
784
+ * The return value is the ORIGINAL `p`. The caller awaits real success
785
+ * or failure; the tracking is completely invisible to them. This is why
786
+ * `await flare.report(err)` inside a fatal handler observes network
787
+ * errors the same as before tracking was added.
788
+ */
789
+ track(p) {
790
+ const tracked = p.then(() => void 0, () => void 0);
791
+ this.inflight.add(tracked);
792
+ tracked.finally(() => this.inflight.delete(tracked));
793
+ return p;
794
+ }
795
+ /**
796
+ * Wait until every in-flight report settles, or until `timeoutMs`
797
+ * elapses, whichever comes first. Always resolves; never rejects.
798
+ *
799
+ * The main consumer is `@flareapp/node`'s fatal handler:
800
+ *
801
+ * process.on('uncaughtException', async (err) => {
802
+ * process.exitCode = 1;
803
+ * try { await flare.report(err); } catch {}
804
+ * await flare.flush(shutdownTimeoutMs);
805
+ * process.exit(1);
806
+ * });
807
+ *
808
+ * The fatal `report` is awaited explicitly; `flush` then drains any
809
+ * OTHER reports that were already in flight (a request handler that
810
+ * fired `flare.report(...)` concurrently with the crash). The timeout
811
+ * caps the wait so a hung HTTP request cannot indefinitely block
812
+ * shutdown.
813
+ *
814
+ * Walking the implementation:
815
+ *
816
+ * const pending = [...this.inflight];
817
+ *
818
+ * Spread takes a SNAPSHOT of the Set at this instant. Reports that
819
+ * start AFTER this line are not included in `pending`, so they are
820
+ * not awaited by THIS flush call. This is intentional: it bounds
821
+ * the wait. Without the snapshot, a handler that kept emitting
822
+ * reports during shutdown could keep flush alive forever and block
823
+ * the process from exiting.
824
+ *
825
+ * if (pending.length === 0) return Promise.resolve();
826
+ *
827
+ * Fast path. No timer scheduled, no promise constructor needed.
828
+ * Resolves on the microtask queue. Cheap.
829
+ *
830
+ * return new Promise<void>((resolve) => {
831
+ * const timer = setTimeout(resolve, timeoutMs);
832
+ * Promise.allSettled(pending).then(() => {
833
+ * clearTimeout(timer);
834
+ * resolve();
835
+ * });
836
+ * });
837
+ *
838
+ * The race between two outcomes, both calling the same `resolve`:
839
+ *
840
+ * 1. `setTimeout(resolve, timeoutMs)` schedules a "give up" call.
841
+ * After `timeoutMs` it fires, calling `resolve()` from the
842
+ * timer-queue side. The outer promise resolves immediately,
843
+ * even if reports are still pending. Those reports are abandoned
844
+ * (they continue running but the process is about to die).
845
+ *
846
+ * 2. `Promise.allSettled(pending)` returns a promise that resolves
847
+ * when every promise in `pending` has either fulfilled or
848
+ * rejected. It NEVER rejects on its own. We use `allSettled`
849
+ * rather than `Promise.all` because `all` short-circuits on the
850
+ * first rejection -- we want to wait for everyone regardless of
851
+ * whether their HTTP calls succeed or fail. (Our shadows cannot
852
+ * reject anyway because `track` normalized them, but using
853
+ * `allSettled` documents the intent and survives future changes
854
+ * to shadow construction.) When it resolves, we call
855
+ * `clearTimeout(timer)` to cancel the pending timer (so it does
856
+ * not fire later and call `resolve` a second time -- a no-op,
857
+ * but wasted work) and then `resolve()` ourselves.
858
+ *
859
+ * Resolve can only meaningfully fire once. Subsequent calls to the
860
+ * same `resolve` are silently ignored by the Promise spec, so the
861
+ * race is safe even if for some reason both branches fired together.
862
+ *
863
+ * Things flush() deliberately does NOT do:
864
+ *
865
+ * - It does not reject. Even if every report failed, allSettled
866
+ * resolves. Callers do not need a `.catch`.
867
+ * - It does not retry. One pipeline attempt per report, then move on.
868
+ * - It does not stop new reports from starting. The Flare instance
869
+ * is still usable after flush resolves. flush is "wait for what is
870
+ * in flight," not "freeze the SDK."
871
+ * - It does not drain reports started after the snapshot. Call flush
872
+ * again if you need to wait for those too.
873
+ */
874
+ flush(timeoutMs = 2e3) {
875
+ this._logger.flush();
876
+ const pending = [...this.inflight];
877
+ if (pending.length === 0) return Promise.resolve();
878
+ return new Promise((resolve) => {
879
+ const timer = setTimeout(resolve, timeoutMs);
880
+ Promise.allSettled(pending).then(() => {
881
+ clearTimeout(timer);
882
+ resolve();
883
+ });
884
+ });
885
+ }
886
+ get config() {
887
+ return this._config;
888
+ }
889
+ get glows() {
890
+ return this.scopeProvider.active().glows;
891
+ }
892
+ get logger() {
893
+ return this._logger;
894
+ }
895
+ light(key = KEY, debug) {
896
+ this._config.key = key;
897
+ if (debug !== void 0) this._config.debug = debug;
898
+ this._logger.flush();
899
+ return this;
900
+ }
901
+ configure(config) {
902
+ const wasLogsEnabled = this._config.enableLogs;
903
+ this._config = {
904
+ ...this._config,
905
+ ...config
906
+ };
907
+ if (config.sampleRate !== void 0) this._config.sampleRate = Math.max(0, Math.min(1, config.sampleRate));
908
+ this._config.urlDenylist = resolveDenylist(config.urlDenylist, config.replaceDefaultUrlDenylist ?? this._config.replaceDefaultUrlDenylist);
909
+ if (wasLogsEnabled && this._config.enableLogs === false) this._logger.clear();
910
+ if (config.key !== void 0) this._logger.flush();
911
+ return this;
912
+ }
913
+ test() {
914
+ return this.track(this.testInternal());
915
+ }
916
+ async testInternal() {
917
+ const report = await this.createReportFromError(/* @__PURE__ */ new Error("The Flare client is set up correctly!"));
918
+ if (!report) return;
919
+ return this.sendReport(report);
920
+ }
921
+ glow(name, level = "info", data = []) {
922
+ const time = now();
923
+ this.scopeProvider.active().addGlow({
924
+ name,
925
+ messageLevel: level,
926
+ metaData: data,
927
+ time,
928
+ microtime: time
929
+ }, this._config.maxGlowsPerReport);
930
+ return this;
931
+ }
932
+ clearGlows() {
933
+ this.scopeProvider.active().clearGlows();
934
+ return this;
935
+ }
936
+ addContext(name, value) {
937
+ const scope = this.scopeProvider.active();
938
+ const existing = scope.pendingAttributes["context.custom"] ?? {};
939
+ scope.setAttribute("context.custom", {
940
+ ...existing,
941
+ [name]: value
942
+ });
943
+ return this;
944
+ }
945
+ addContextGroup(groupName, value) {
946
+ this.scopeProvider.active().setAttribute(`context.${groupName}`, value);
947
+ return this;
948
+ }
949
+ setEntryPoint(handler) {
950
+ this.scopeProvider.active().entryPoint = handler;
951
+ return this;
952
+ }
953
+ setSdkInfo(info) {
954
+ this.sdkInfo = info;
955
+ return this;
956
+ }
957
+ setFramework(framework) {
958
+ this.framework = framework;
959
+ return this;
960
+ }
961
+ report(error, attributes = {}) {
962
+ return this.track(this.reportInternal(error, attributes));
963
+ }
964
+ async reportInternal(error, attributes = {}) {
965
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
966
+ const seenAtUnixNano = Date.now() * 1e6;
967
+ const coerced = error instanceof Error ? error : new Error(typeof error === "string" ? error : String(error));
968
+ const errorToReport = await this._config.beforeEvaluate(coerced);
969
+ if (!errorToReport) return;
970
+ const report = await this.createReportFromError(errorToReport, attributes, seenAtUnixNano);
971
+ if (!report) return;
972
+ return this.sendReport(report);
973
+ }
974
+ reportSilently(error, attributes = {}) {
975
+ this.track(this.reportInternal(error, attributes).catch(() => {}));
976
+ }
977
+ reportUnhandledRejection(message, attributes = {}) {
978
+ return this.track(this.reportUnhandledRejectionInternal(message, attributes));
979
+ }
980
+ async reportUnhandledRejectionInternal(message, attributes = {}) {
981
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
982
+ const seenAtUnixNano = Date.now() * 1e6;
983
+ const report = this.buildReport({
984
+ exceptionClass: "UnhandledRejection",
985
+ message,
986
+ stacktrace: [],
987
+ isLog: false,
988
+ level: void 0,
989
+ extraAttributes: attributes,
990
+ code: void 0,
991
+ seenAtUnixNano
992
+ });
993
+ return this.sendReport(report);
994
+ }
995
+ reportMessage(message, level, attributes = {}) {
996
+ return this.track(this.reportMessageInternal(message, level, attributes));
997
+ }
998
+ async reportMessageInternal(message, level, attributes = {}) {
999
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
1000
+ const seenAtUnixNano = Date.now() * 1e6;
1001
+ const stackTrace = await createStackTrace(/* @__PURE__ */ new Error(), this._config.debug, this.fileReader);
1002
+ stackTrace.shift();
1003
+ const report = this.buildReport({
1004
+ exceptionClass: "Log",
1005
+ message,
1006
+ stacktrace: stackTrace,
1007
+ isLog: true,
1008
+ level,
1009
+ extraAttributes: attributes,
1010
+ code: void 0,
1011
+ seenAtUnixNano
1012
+ });
1013
+ return this.sendReport(report);
1014
+ }
1015
+ async createReportFromError(error, attributes = {}, seenAtUnixNano = Date.now() * 1e6) {
1016
+ if (!assert(error, "No error provided.", this._config.debug)) return false;
1017
+ const stacktrace = await createStackTrace(error, this._config.debug, this.fileReader);
1018
+ assert(stacktrace.length, "Couldn't generate stacktrace of this error: " + error, this._config.debug);
1019
+ const exceptionClass = error.constructor && error.constructor.name ? error.constructor.name : "undefined";
1020
+ return this.buildReport({
1021
+ exceptionClass,
1022
+ message: error.message,
1023
+ stacktrace,
1024
+ isLog: false,
1025
+ level: void 0,
1026
+ extraAttributes: attributes,
1027
+ code: extractCode(error),
1028
+ seenAtUnixNano
1029
+ });
1030
+ }
1031
+ buildBaseAttributes() {
1032
+ const baseAttributes = {
1033
+ "telemetry.sdk.language": "javascript",
1034
+ "telemetry.sdk.name": this.sdkInfo.name,
1035
+ "telemetry.sdk.version": this.sdkInfo.version,
1036
+ "flare.language.name": "javascript"
1037
+ };
1038
+ if (this._config.stage) baseAttributes["service.stage"] = this._config.stage;
1039
+ if (this._config.version) baseAttributes["service.version"] = this._config.version;
1040
+ if (this.framework?.name) baseAttributes["flare.framework.name"] = this.framework.name;
1041
+ if (this.framework?.version) baseAttributes["flare.framework.version"] = this.framework.version;
1042
+ return baseAttributes;
1043
+ }
1044
+ assembleAttributes(collectorAttributes, extraAttributes, includeBase) {
1045
+ const activeScope = this.scopeProvider.active();
1046
+ const baseAttributes = includeBase ? this.buildBaseAttributes() : {};
1047
+ const entryPoint = activeScope.entryPoint;
1048
+ const entryPointOverrides = {};
1049
+ if (entryPoint?.identifier !== void 0) entryPointOverrides["flare.entry_point.handler.identifier"] = entryPoint.identifier;
1050
+ if (entryPoint?.type !== void 0) entryPointOverrides["flare.entry_point.handler.type"] = entryPoint.type;
1051
+ if (entryPoint?.name !== void 0) entryPointOverrides["flare.entry_point.handler.name"] = entryPoint.name;
1052
+ const attributes = {
1053
+ ...baseAttributes,
1054
+ ...collectorAttributes,
1055
+ ...entryPointOverrides,
1056
+ ...activeScope.pendingAttributes,
1057
+ ...extraAttributes
1058
+ };
1059
+ const pendingCustom = activeScope.pendingAttributes["context.custom"];
1060
+ const extraCustom = extraAttributes["context.custom"];
1061
+ if (pendingCustom && extraCustom && typeof pendingCustom === "object" && typeof extraCustom === "object" && !Array.isArray(pendingCustom) && !Array.isArray(extraCustom)) attributes["context.custom"] = {
1062
+ ...pendingCustom,
1063
+ ...extraCustom
1064
+ };
1065
+ if (this.framework?.name) attributes["context.custom"] = {
1066
+ ...attributes["context.custom"] ?? {},
1067
+ framework: this.framework.name.toLowerCase()
1068
+ };
1069
+ return attributes;
1070
+ }
1071
+ buildLogAttributes(userAttributes) {
1072
+ const { resource, record: collectorRecord } = partitionAttributes(this.contextCollector(this._config));
1073
+ return {
1074
+ resource,
1075
+ record: this.assembleAttributes(collectorRecord, userAttributes, false)
1076
+ };
1077
+ }
1078
+ buildReport(input) {
1079
+ const activeScope = this.scopeProvider.active();
1080
+ const attributes = this.assembleAttributes(this.contextCollector(this._config), input.extraAttributes, true);
1081
+ const report = {
1082
+ exceptionClass: input.exceptionClass,
1083
+ message: input.message,
1084
+ seenAtUnixNano: input.seenAtUnixNano,
1085
+ stacktrace: input.stacktrace,
1086
+ events: glowsToEvents(activeScope.glows),
1087
+ attributes
1088
+ };
1089
+ if (input.isLog) report.isLog = true;
1090
+ if (input.level !== void 0) report.level = input.level;
1091
+ if (this._config.sourcemapVersionId) report.sourcemapVersionId = this._config.sourcemapVersionId;
1092
+ if (input.code !== void 0) report.code = input.code;
1093
+ return report;
1094
+ }
1095
+ async sendReport(report) {
1096
+ if (!assertKey(this._config.key, this._config.debug)) return;
1097
+ const reportToSubmit = await this._config.beforeSubmit(report);
1098
+ if (!reportToSubmit) return;
1099
+ return this.api.report(reportToSubmit, this._config.ingestUrl, this._config.key, this._config.reportBrowserExtensionErrors, this._config.debug);
1100
+ }
1101
+ };
1102
+
1103
+ //#endregion
1104
+ export { Api, DEFAULT_URL_DENYLIST, Flare, GlobalScopeProvider, Logger, NoopFlushScheduler, NullFileReader, Scope, assert, assertKey, convertToError, createStackTrace, extractCode, flatJsonStringify, getCodeSnippet, glowsToEvents, now, readLinesFromFile, redactUrlQuery, resolveDenylist };