@flareapp/core 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/index.cjs +806 -0
  2. package/dist/index.d.cts +411 -0
  3. package/dist/index.d.mts +411 -0
  4. package/dist/index.mjs +760 -0
  5. package/package.json +4 -1
  6. package/.oxlintrc.json +0 -7
  7. package/.release-it.json +0 -13
  8. package/CHANGELOG.md +0 -16
  9. package/src/Flare.ts +0 -543
  10. package/src/Scope.ts +0 -96
  11. package/src/api/Api.ts +0 -35
  12. package/src/api/index.ts +0 -1
  13. package/src/env/index.ts +0 -14
  14. package/src/index.ts +0 -41
  15. package/src/stacktrace/NullFileReader.ts +0 -28
  16. package/src/stacktrace/createStackTrace.ts +0 -74
  17. package/src/stacktrace/fileReader.ts +0 -96
  18. package/src/stacktrace/index.ts +0 -4
  19. package/src/types.ts +0 -81
  20. package/src/util/assert.ts +0 -9
  21. package/src/util/assertKey.ts +0 -11
  22. package/src/util/convertToError.ts +0 -22
  23. package/src/util/extractCode.ts +0 -11
  24. package/src/util/flatJsonStringify.ts +0 -45
  25. package/src/util/glowsToEvents.ts +0 -16
  26. package/src/util/index.ts +0 -8
  27. package/src/util/now.ts +0 -3
  28. package/src/util/redactUrl.ts +0 -83
  29. package/tests/api.test.ts +0 -95
  30. package/tests/configure.test.ts +0 -16
  31. package/tests/contextCollector.test.ts +0 -37
  32. package/tests/convertToError.test.ts +0 -95
  33. package/tests/createStackTrace.test.ts +0 -54
  34. package/tests/extractCode.test.ts +0 -30
  35. package/tests/fileReader.test.ts +0 -51
  36. package/tests/flatJsonStringify.test.ts +0 -31
  37. package/tests/flush.test.ts +0 -47
  38. package/tests/glows.test.ts +0 -47
  39. package/tests/glowsToEvents.test.ts +0 -41
  40. package/tests/helpers/FakeApi.ts +0 -20
  41. package/tests/helpers/index.ts +0 -1
  42. package/tests/hooks.test.ts +0 -123
  43. package/tests/light.test.ts +0 -25
  44. package/tests/nullFileReader.test.ts +0 -11
  45. package/tests/publicExports.test.ts +0 -17
  46. package/tests/redactUrl.test.ts +0 -151
  47. package/tests/report.test.ts +0 -146
  48. package/tests/sampleRate.test.ts +0 -88
  49. package/tests/scope.test.ts +0 -64
  50. package/tests/setEntryPoint.test.ts +0 -79
  51. package/tests/setFramework.test.ts +0 -48
  52. package/tests/setSdkInfo.test.ts +0 -62
  53. package/tsconfig.json +0 -4
  54. package/vitest.config.ts +0 -17
@@ -0,0 +1,411 @@
1
+ //#region src/types.d.ts
2
+ type MessageLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';
3
+ type AttributeValue = string | number | boolean | null | AttributeValue[] | {
4
+ [key: string]: AttributeValue;
5
+ };
6
+ type Attributes = Record<string, AttributeValue>;
7
+ type Config = {
8
+ key: string | null;
9
+ version: string;
10
+ sourcemapVersionId: string;
11
+ stage: string;
12
+ maxGlowsPerReport: number;
13
+ reportBrowserExtensionErrors: boolean;
14
+ ingestUrl: string;
15
+ debug: boolean;
16
+ urlDenylist: RegExp;
17
+ replaceDefaultUrlDenylist: boolean;
18
+ sampleRate: number;
19
+ beforeEvaluate: (error: Error) => Error | false | null | Promise<Error | false | null>;
20
+ beforeSubmit: (report: Report) => Report | false | null | Promise<Report | false | null>;
21
+ };
22
+ type StackFrame = {
23
+ file: string;
24
+ lineNumber: number;
25
+ columnNumber?: number;
26
+ method?: string;
27
+ class?: string;
28
+ codeSnippet?: {
29
+ [line: number]: string;
30
+ };
31
+ isApplicationFrame?: boolean;
32
+ arguments?: unknown[];
33
+ };
34
+ type SpanEvent = {
35
+ type: string;
36
+ startTimeUnixNano: number;
37
+ endTimeUnixNano: number | null;
38
+ attributes: Attributes;
39
+ };
40
+ type OverriddenGrouping = 'exception_class' | 'exception_message' | 'exception_message_and_class' | 'full_stacktrace_and_exception_class_and_code';
41
+ type Report = {
42
+ exceptionClass?: string | null;
43
+ message?: string | null;
44
+ code?: string;
45
+ seenAtUnixNano: number;
46
+ isLog?: boolean;
47
+ level?: MessageLevel;
48
+ sourcemapVersionId?: string;
49
+ trackingUuid?: string;
50
+ handled?: boolean;
51
+ openFrameIndex?: number;
52
+ applicationPath?: string;
53
+ overriddenGrouping?: OverriddenGrouping | null;
54
+ stacktrace: StackFrame[];
55
+ events: SpanEvent[];
56
+ attributes: Attributes;
57
+ };
58
+ type Glow = {
59
+ time: number;
60
+ microtime: number;
61
+ name: string;
62
+ messageLevel: MessageLevel;
63
+ metaData: Record<string, unknown> | Record<string, unknown>[];
64
+ };
65
+ type EntryPointHandler = {
66
+ identifier?: string;
67
+ name?: string;
68
+ type?: string;
69
+ };
70
+ type SdkInfo = {
71
+ name: string;
72
+ version: string;
73
+ };
74
+ type Framework = {
75
+ name: string;
76
+ version?: string;
77
+ };
78
+ //#endregion
79
+ //#region src/util/assert.d.ts
80
+ declare function assert(value: unknown, message: string, debug: boolean): boolean;
81
+ //#endregion
82
+ //#region src/util/assertKey.d.ts
83
+ declare function assertKey(key: unknown, debug: boolean): boolean;
84
+ //#endregion
85
+ //#region src/util/convertToError.d.ts
86
+ declare function convertToError(error: unknown): Error;
87
+ //#endregion
88
+ //#region src/util/extractCode.d.ts
89
+ declare function extractCode(error: Error): string | undefined;
90
+ //#endregion
91
+ //#region src/util/flatJsonStringify.d.ts
92
+ declare function flatJsonStringify(json: object): string;
93
+ //#endregion
94
+ //#region src/util/glowsToEvents.d.ts
95
+ declare function glowsToEvents(glows: Glow[]): SpanEvent[];
96
+ //#endregion
97
+ //#region src/util/now.d.ts
98
+ declare function now(): number;
99
+ //#endregion
100
+ //#region src/util/redactUrl.d.ts
101
+ declare const DEFAULT_URL_DENYLIST: RegExp;
102
+ declare function resolveDenylist(custom?: RegExp, replaceDefault?: boolean, defaultDenylist?: RegExp): RegExp;
103
+ declare function redactUrlQuery(fullPath: string, denylist?: RegExp): string;
104
+ //#endregion
105
+ //#region src/api/Api.d.ts
106
+ declare class Api {
107
+ report(report: Report, url: string, key: string | null, reportBrowserExtensionErrors: boolean, debug?: boolean): Promise<void>;
108
+ }
109
+ //#endregion
110
+ //#region src/Scope.d.ts
111
+ /**
112
+ * Holds the per-call mutable state that used to live on the `Flare` instance:
113
+ * breadcrumbs (`glows`), custom attributes (`pendingAttributes`), and the
114
+ * current entry-point handler.
115
+ *
116
+ * Why this exists as its own class: in the browser there is one `Flare` per
117
+ * page and one user at a time, so a single shared bag of state is fine. In
118
+ * Node, a single `Flare` instance serves many concurrent requests, and each
119
+ * request wants its own breadcrumbs and its own custom context that do NOT
120
+ * leak into other requests. Splitting this state out of `Flare` lets the
121
+ * consumer choose: one global `Scope` (browser) or one `Scope` per request
122
+ * via AsyncLocalStorage (Node).
123
+ *
124
+ * `Flare` reads and writes this through `scopeProvider.active()` instead of
125
+ * holding the state directly, so the per-request behavior comes from the
126
+ * provider, not from the class itself.
127
+ *
128
+ * `NodeScope` (in `@flareapp/node`) extends this with two more buckets:
129
+ * `request` (HTTP method, path, headers) and `user` (id, email, ...). Browser
130
+ * does not need those.
131
+ */
132
+ declare class Scope {
133
+ glows: Glow[];
134
+ pendingAttributes: Attributes;
135
+ entryPoint: EntryPointHandler | null;
136
+ /**
137
+ * Append a breadcrumb. Caps the list at `maxGlowsPerReport` by dropping the
138
+ * OLDEST entries when the limit is exceeded; this keeps reports below a
139
+ * payload-size threshold while preserving the most recent events leading
140
+ * up to an error.
141
+ *
142
+ * `slice(length - max)` returns the trailing `max` items, which is the
143
+ * shortest way to drop from the front and keep insertion order.
144
+ */
145
+ addGlow(glow: Glow, maxGlowsPerReport: number): void;
146
+ clearGlows(): void;
147
+ /**
148
+ * Set a single attribute on this scope. Called from `Flare.addContext` and
149
+ * `Flare.addContextGroup`. Last write wins.
150
+ */
151
+ setAttribute(key: string, value: AttributeValue): void;
152
+ /**
153
+ * Shallow-merge a bag of attributes into this scope. Used by Node's
154
+ * AsyncLocalStorage provider when patching the live request context via
155
+ * `flare.mergeContext({ ... })`. Last write wins per key; nested objects
156
+ * are NOT deep-merged.
157
+ */
158
+ mergeAttributes(partial: Attributes): void;
159
+ }
160
+ /**
161
+ * The seam through which `Flare` reaches its current `Scope`. Implementations
162
+ * decide what "current" means.
163
+ *
164
+ * - `GlobalScopeProvider` always returns the same `Scope` instance (browser).
165
+ * - `AsyncLocalStorageScopeProvider` in `@flareapp/node` returns the per-request
166
+ * `NodeScope` stored in `node:async_hooks` for the in-flight async chain,
167
+ * falling back to a single shared scope when called outside any
168
+ * `runWithContext(...)` callback.
169
+ *
170
+ * Any consumer of `@flareapp/core` can supply its own provider to plug in
171
+ * different "current scope" semantics.
172
+ */
173
+ interface ScopeProvider {
174
+ active(): Scope;
175
+ }
176
+ /**
177
+ * The simplest provider: one `Scope` for the lifetime of the provider, shared
178
+ * by every caller. This is the right default for environments with a single
179
+ * logical context (browser tab, CLI script, etc.) and is the default that
180
+ * `Flare`'s constructor falls back to when no provider is supplied.
181
+ */
182
+ declare class GlobalScopeProvider implements ScopeProvider {
183
+ private scope;
184
+ active(): Scope;
185
+ }
186
+ //#endregion
187
+ //#region src/stacktrace/fileReader.d.ts
188
+ interface FileReader {
189
+ read(url: string): Promise<string | null>;
190
+ }
191
+ type CodeSnippet = {
192
+ [key: number]: string;
193
+ };
194
+ type ReaderResponse = {
195
+ codeSnippet: CodeSnippet;
196
+ trimmedColumnNumber: number | null;
197
+ };
198
+ declare function getCodeSnippet(fileReader: FileReader, url?: string, lineNumber?: number, columnNumber?: number): Promise<ReaderResponse>;
199
+ declare function readLinesFromFile(fileText: string, lineNumber: number, columnNumber?: number, maxSnippetLineLength?: number, maxSnippetLines?: number): ReaderResponse;
200
+ //#endregion
201
+ //#region src/Flare.d.ts
202
+ type ContextCollector = (config: Readonly<Config>) => Attributes;
203
+ declare class Flare {
204
+ api: Api;
205
+ private contextCollector;
206
+ private fileReader;
207
+ private scopeProvider;
208
+ private inflight;
209
+ private _config;
210
+ private sdkInfo;
211
+ private framework;
212
+ /**
213
+ * @param api sends the report over HTTP.
214
+ * @param contextCollector returns per-report attributes (browser DOM info, Node
215
+ * process info, etc). Default is a no-op.
216
+ * @param fileReader reads source files for stack-trace snippets. Default
217
+ * returns null (no snippets); `@flareapp/js` injects a
218
+ * fetch-based reader, `@flareapp/node` injects a disk reader.
219
+ * @param scopeProvider returns the current `Scope` (per-call mutable state:
220
+ * glows, pendingAttributes, entryPoint). Browser uses a
221
+ * single global scope; Node uses an AsyncLocalStorage-
222
+ * backed provider so each request gets its own.
223
+ */
224
+ constructor(api?: Api, contextCollector?: ContextCollector, fileReader?: FileReader, scopeProvider?: ScopeProvider);
225
+ /**
226
+ * Register an in-flight report so `flush()` can wait for it. Called by
227
+ * every public report entry point (`report`, `reportSilently`,
228
+ * `reportMessage`, `reportUnhandledRejection`, `test`); each wraps its
229
+ * full async pipeline (beforeEvaluate -> stack trace + source snippets ->
230
+ * beforeSubmit -> `api.report()`) so the entire roundtrip is what's
231
+ * tracked, not just the HTTP send at the end.
232
+ *
233
+ * Two problems this method solves at once.
234
+ *
235
+ * Problem 1: hold a reference to the work without leaking rejections.
236
+ *
237
+ * `p` is the real report pipeline; it can reject (network failure,
238
+ * `beforeSubmit` throws, etc). If we stored `p` directly in `inflight`
239
+ * and no caller attached a `.catch` (the global error listeners use
240
+ * `reportSilently` which DOES catch, but the path is still subtle), an
241
+ * eventual rejection would surface as an unhandled-rejection warning
242
+ * on Node and a console error in the browser. Bad citizen.
243
+ *
244
+ * So we build a SHADOW promise that mirrors `p`'s timing but cannot
245
+ * reject:
246
+ *
247
+ * p.then(
248
+ * () => undefined, // on fulfilment, value is undefined
249
+ * () => undefined, // on rejection, ALSO resolve with undefined
250
+ * )
251
+ *
252
+ * Providing the second argument means we have "handled" any rejection
253
+ * from `p`. The shadow always resolves with `undefined`, and `p`'s
254
+ * rejection is consumed at the boundary. From the runtime's point of
255
+ * view, the shadow is well-behaved.
256
+ *
257
+ * Problem 2: self-cleaning entry.
258
+ *
259
+ * `tracked.finally(() => this.inflight.delete(tracked))`. `finally`
260
+ * fires whether the shadow resolves or rejects, but the shadow can no
261
+ * longer reject (problem 1 normalized it), so this is effectively
262
+ * "when the underlying report has settled, remove me from the Set."
263
+ * No GC magic, no external cleanup, no race window.
264
+ *
265
+ * Note that `.finally` itself returns a new promise that we drop on
266
+ * the floor. If the cleanup callback ever throws, that would surface
267
+ * as an unhandled rejection on the dropped promise; `delete` does not
268
+ * throw so we are safe today, but anything more elaborate added here
269
+ * should be wrapped in try/catch.
270
+ *
271
+ * The return value is the ORIGINAL `p`. The caller awaits real success
272
+ * or failure; the tracking is completely invisible to them. This is why
273
+ * `await flare.report(err)` inside a fatal handler observes network
274
+ * errors the same as before tracking was added.
275
+ */
276
+ private track;
277
+ /**
278
+ * Wait until every in-flight report settles, or until `timeoutMs`
279
+ * elapses, whichever comes first. Always resolves; never rejects.
280
+ *
281
+ * The main consumer is `@flareapp/node`'s fatal handler:
282
+ *
283
+ * process.on('uncaughtException', async (err) => {
284
+ * process.exitCode = 1;
285
+ * try { await flare.report(err); } catch {}
286
+ * await flare.flush(shutdownTimeoutMs);
287
+ * process.exit(1);
288
+ * });
289
+ *
290
+ * The fatal `report` is awaited explicitly; `flush` then drains any
291
+ * OTHER reports that were already in flight (a request handler that
292
+ * fired `flare.report(...)` concurrently with the crash). The timeout
293
+ * caps the wait so a hung HTTP request cannot indefinitely block
294
+ * shutdown.
295
+ *
296
+ * Walking the implementation:
297
+ *
298
+ * const pending = [...this.inflight];
299
+ *
300
+ * Spread takes a SNAPSHOT of the Set at this instant. Reports that
301
+ * start AFTER this line are not included in `pending`, so they are
302
+ * not awaited by THIS flush call. This is intentional: it bounds
303
+ * the wait. Without the snapshot, a handler that kept emitting
304
+ * reports during shutdown could keep flush alive forever and block
305
+ * the process from exiting.
306
+ *
307
+ * if (pending.length === 0) return Promise.resolve();
308
+ *
309
+ * Fast path. No timer scheduled, no promise constructor needed.
310
+ * Resolves on the microtask queue. Cheap.
311
+ *
312
+ * return new Promise<void>((resolve) => {
313
+ * const timer = setTimeout(resolve, timeoutMs);
314
+ * Promise.allSettled(pending).then(() => {
315
+ * clearTimeout(timer);
316
+ * resolve();
317
+ * });
318
+ * });
319
+ *
320
+ * The race between two outcomes, both calling the same `resolve`:
321
+ *
322
+ * 1. `setTimeout(resolve, timeoutMs)` schedules a "give up" call.
323
+ * After `timeoutMs` it fires, calling `resolve()` from the
324
+ * timer-queue side. The outer promise resolves immediately,
325
+ * even if reports are still pending. Those reports are abandoned
326
+ * (they continue running but the process is about to die).
327
+ *
328
+ * 2. `Promise.allSettled(pending)` returns a promise that resolves
329
+ * when every promise in `pending` has either fulfilled or
330
+ * rejected. It NEVER rejects on its own. We use `allSettled`
331
+ * rather than `Promise.all` because `all` short-circuits on the
332
+ * first rejection -- we want to wait for everyone regardless of
333
+ * whether their HTTP calls succeed or fail. (Our shadows cannot
334
+ * reject anyway because `track` normalized them, but using
335
+ * `allSettled` documents the intent and survives future changes
336
+ * to shadow construction.) When it resolves, we call
337
+ * `clearTimeout(timer)` to cancel the pending timer (so it does
338
+ * not fire later and call `resolve` a second time -- a no-op,
339
+ * but wasted work) and then `resolve()` ourselves.
340
+ *
341
+ * Resolve can only meaningfully fire once. Subsequent calls to the
342
+ * same `resolve` are silently ignored by the Promise spec, so the
343
+ * race is safe even if for some reason both branches fired together.
344
+ *
345
+ * Things flush() deliberately does NOT do:
346
+ *
347
+ * - It does not reject. Even if every report failed, allSettled
348
+ * resolves. Callers do not need a `.catch`.
349
+ * - It does not retry. One pipeline attempt per report, then move on.
350
+ * - It does not stop new reports from starting. The Flare instance
351
+ * is still usable after flush resolves. flush is "wait for what is
352
+ * in flight," not "freeze the SDK."
353
+ * - It does not drain reports started after the snapshot. Call flush
354
+ * again if you need to wait for those too.
355
+ */
356
+ flush(timeoutMs?: number): Promise<void>;
357
+ get config(): Readonly<Config>;
358
+ get glows(): readonly Glow[];
359
+ light(key?: string, debug?: boolean): this;
360
+ configure(config: Partial<Config>): this;
361
+ test(): Promise<void>;
362
+ private testInternal;
363
+ glow(name: string, level?: MessageLevel, data?: Record<string, unknown> | Record<string, unknown>[]): this;
364
+ clearGlows(): this;
365
+ addContext(name: string, value: AttributeValue): this;
366
+ addContextGroup(groupName: string, value: Record<string, AttributeValue>): this;
367
+ setEntryPoint(handler: EntryPointHandler): this;
368
+ setSdkInfo(info: SdkInfo): this;
369
+ setFramework(framework: Framework): this;
370
+ report(error: Error, attributes?: Attributes): Promise<void>;
371
+ private reportInternal;
372
+ reportSilently(error: Error, attributes?: Attributes): void;
373
+ reportUnhandledRejection(message: string, attributes?: Attributes): Promise<void>;
374
+ private reportUnhandledRejectionInternal;
375
+ reportMessage(message: string, level?: MessageLevel, attributes?: Attributes): Promise<void>;
376
+ private reportMessageInternal;
377
+ createReportFromError(error: Error, attributes?: Attributes, seenAtUnixNano?: number): Promise<Report | false>;
378
+ private buildReport;
379
+ sendReport(report: Report): Promise<void>;
380
+ }
381
+ //#endregion
382
+ //#region src/stacktrace/NullFileReader.d.ts
383
+ /**
384
+ * No-op `FileReader` that returns `null` for every URL it is asked to read.
385
+ *
386
+ * Used as the default for `Flare`'s `fileReader` constructor parameter so the
387
+ * class is usable without picking a side: instantiated bare (`new Flare()`),
388
+ * reports still build, but stack frames omit source-code snippets — which is
389
+ * the correct, safe behavior in an environment we know nothing about.
390
+ *
391
+ * The two real implementations live in the consumer packages and take their
392
+ * place once the right environment is established:
393
+ *
394
+ * - `@flareapp/js` injects `FetchFileReader`, which `fetch()`s source maps
395
+ * and original files over HTTP for browser stack frames.
396
+ * - `@flareapp/node` injects `DiskFileReader`, which reads files from disk
397
+ * via `node:fs/promises` for server stack frames.
398
+ *
399
+ * The interface (`read(url) -> Promise<string | null>`) lets the stack-trace
400
+ * builder treat all three the same way: ask for a URL, render the snippet
401
+ * when text comes back, gracefully skip it when `null` does. No environment
402
+ * checks anywhere in core.
403
+ */
404
+ declare class NullFileReader implements FileReader {
405
+ read(_url: string): Promise<string | null>;
406
+ }
407
+ //#endregion
408
+ //#region src/stacktrace/createStackTrace.d.ts
409
+ declare function createStackTrace(error: Error, debug: boolean, fileReader: FileReader): Promise<Array<StackFrame>>;
410
+ //#endregion
411
+ export { Api, type AttributeValue, type Attributes, type Config, type ContextCollector, DEFAULT_URL_DENYLIST, type EntryPointHandler, type FileReader, Flare, type Framework, GlobalScopeProvider, type Glow, type MessageLevel, NullFileReader, type OverriddenGrouping, type Report, Scope, type ScopeProvider, type SdkInfo, type SpanEvent, type StackFrame, assert, assertKey, convertToError, createStackTrace, extractCode, flatJsonStringify, getCodeSnippet, glowsToEvents, now, readLinesFromFile, redactUrlQuery, resolveDenylist };