@visulima/pail 4.0.2 → 4.1.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 (83) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE.md +346 -0
  3. package/README.md +17 -0
  4. package/dist/error.d.ts +69 -69
  5. package/dist/index.browser.d.ts +446 -445
  6. package/dist/index.browser.js +17 -17
  7. package/dist/index.server.d.ts +582 -582
  8. package/dist/index.server.js +27 -27
  9. package/dist/middleware/elysia.d.ts +44 -42
  10. package/dist/middleware/elysia.js +1 -1
  11. package/dist/middleware/express.d.ts +58 -59
  12. package/dist/middleware/express.js +1 -1
  13. package/dist/middleware/fastify.d.ts +55 -56
  14. package/dist/middleware/fastify.js +1 -1
  15. package/dist/middleware/hono.d.ts +56 -57
  16. package/dist/middleware/hono.js +1 -1
  17. package/dist/middleware/next/handler.d.ts +67 -68
  18. package/dist/middleware/next/handler.js +1 -1
  19. package/dist/middleware/sveltekit.d.ts +72 -73
  20. package/dist/middleware/sveltekit.js +1 -1
  21. package/dist/object-tree.d.ts +44 -44
  22. package/dist/packem_shared/AbstractJsonReporter-BpWRnN0L.js +1 -0
  23. package/dist/packem_shared/AbstractJsonReporter-DxZwImm5.js +1 -0
  24. package/dist/packem_shared/JsonReporter-9IcELa1m.js +2 -0
  25. package/dist/packem_shared/JsonReporter-Dd3kuj8X.js +1 -0
  26. package/dist/packem_shared/{PrettyReporter-DsHfKOU7.js → PrettyReporter-BUWNEg3_.js} +1 -1
  27. package/dist/packem_shared/{PrettyReporter-CcDdPQSt.js → PrettyReporter-DbgD89ck.js} +56 -30
  28. package/dist/packem_shared/abstract-json-reporter.d-B6NoO-hG.d.ts +61 -0
  29. package/dist/packem_shared/{abstract-pretty-reporter-DrLBJ6ds.js → abstract-pretty-reporter-CyfTvmKf.js} +41 -39
  30. package/dist/packem_shared/create-middleware-logger.d-BRkkBMlk.d.ts +47 -0
  31. package/dist/packem_shared/headers-DI58djdG.js +1 -0
  32. package/dist/packem_shared/index-CbkPnylC.js +1 -0
  33. package/dist/packem_shared/serializeError-52C4oiKx-CrnRcq9R.js +1 -0
  34. package/dist/packem_shared/storage-DVcJumyk.js +1 -0
  35. package/dist/packem_shared/types.d-4ge_rME4.d.ts +246 -0
  36. package/dist/packem_shared/{types.d-Cz9S7jZh.d.ts → types.d-BW8kAXUv.d.ts} +95 -95
  37. package/dist/packem_shared/types.d-DGHeA2iJ.d.ts +194 -0
  38. package/dist/packem_shared/useLogger-7p55yvvc.js +1 -0
  39. package/dist/packem_shared/wide-event.d-BMLastMR.d.ts +716 -0
  40. package/dist/packem_shared/write-stream-ytl_vhg_.js +1 -0
  41. package/dist/processor/caller/caller-processor.d.ts +32 -33
  42. package/dist/processor/environment-processor.d.ts +83 -84
  43. package/dist/processor/message-formatter-processor.d.ts +40 -45
  44. package/dist/processor/message-formatter-processor.js +1 -1
  45. package/dist/processor/opentelemetry-processor.d.ts +51 -52
  46. package/dist/processor/redact-processor.d.ts +57 -65
  47. package/dist/processor/sampling-processor.d.ts +90 -91
  48. package/dist/reporter/file/json-file-reporter.d.ts +77 -78
  49. package/dist/reporter/file/json-file-reporter.js +1 -1
  50. package/dist/reporter/http/abstract-http-reporter.d.ts +125 -121
  51. package/dist/reporter/http/abstract-http-reporter.js +2 -2
  52. package/dist/reporter/http/http-reporter.d.ts +33 -34
  53. package/dist/reporter/http/http-reporter.edge-light.d.ts +235 -230
  54. package/dist/reporter/http/http-reporter.edge-light.js +2 -2
  55. package/dist/reporter/json/index.browser.d.ts +62 -61
  56. package/dist/reporter/json/index.browser.js +1 -1
  57. package/dist/reporter/json/index.d.ts +36 -37
  58. package/dist/reporter/json/index.js +1 -1
  59. package/dist/reporter/pretty/index.browser.d.ts +57 -56
  60. package/dist/reporter/pretty/index.browser.js +1 -1
  61. package/dist/reporter/pretty/index.d.ts +133 -133
  62. package/dist/reporter/pretty/index.js +1 -1
  63. package/dist/reporter/simple/simple-reporter.server.d.ts +91 -90
  64. package/dist/reporter/simple/simple-reporter.server.js +7 -7
  65. package/dist/wide-event.d.ts +2 -3
  66. package/dist/wide-event.js +1 -1
  67. package/package.json +58 -37
  68. package/dist/packem_shared/AbstractJsonReporter-Bp_JCrMQ.js +0 -1
  69. package/dist/packem_shared/AbstractJsonReporter-w_bGGiD-.js +0 -1
  70. package/dist/packem_shared/JsonReporter-Sd_lJGS-.js +0 -2
  71. package/dist/packem_shared/JsonReporter-bmem9lcg.js +0 -1
  72. package/dist/packem_shared/abstract-json-reporter.d-wfESoEa-.d.ts +0 -62
  73. package/dist/packem_shared/addKnownErrorConstructor-C1OJTj2D-0FlJMfXz.js +0 -25
  74. package/dist/packem_shared/create-middleware-logger.d-B-JmQ1Sl.d.ts +0 -47
  75. package/dist/packem_shared/headers-DH0H2s8W.js +0 -1
  76. package/dist/packem_shared/index-Q1764hvO.js +0 -1
  77. package/dist/packem_shared/serializeError-C-NFvZ8_-D0CA_Qlx.js +0 -1
  78. package/dist/packem_shared/storage-DaXAlpiO.js +0 -1
  79. package/dist/packem_shared/types.d-bWnqHJKL.d.ts +0 -211
  80. package/dist/packem_shared/types.d-xxE3FOD3.d.ts +0 -229
  81. package/dist/packem_shared/useLogger-DB34CuU5.js +0 -1
  82. package/dist/packem_shared/wide-event.d-D3ATYpoK.d.ts +0 -717
  83. package/dist/packem_shared/write-stream-C7jxLxIT.js +0 -1
@@ -0,0 +1,716 @@
1
+ import { s as stringify } from "./index.d-T71KjNAr.js";
2
+ import { M as Meta, D as DefaultLogTypes, L as LiteralUnion, d as LoggerTypesConfig, P as Processor, E as ExtendedRfc5424LogLevels, e as Reporter, b as LoggerFunction, C as ConstructorOptions } from "./types.d-4ge_rME4.js";
3
+ /**
4
+ * Pail Browser Implementation.
5
+ *
6
+ * A comprehensive logging library for browser environments with support for
7
+ * multiple log levels, custom types, processors, reporters, and advanced features
8
+ * like throttling, scoping, timers, and counters.
9
+ * @template T - Custom logger types (string union)
10
+ * @template L - Log level types (string union)
11
+ * @example
12
+ * ```typescript
13
+ * const logger = new PailBrowserImpl({
14
+ * logLevel: "debug",
15
+ * types: {
16
+ * http: { color: "blue", label: "HTTP", logLevel: "info" }
17
+ * },
18
+ * reporters: [new JsonReporter()]
19
+ * });
20
+ *
21
+ * logger.info("Application started");
22
+ * logger.http("GET /api/users 200");
23
+ * logger.error("Something went wrong", error);
24
+ * ```
25
+ */
26
+ declare class PailBrowserImpl<T extends string = string, L extends string = string> {
27
+ #private;
28
+ protected readonly lastLog: {
29
+ count?: number;
30
+ object?: Meta<L>;
31
+ signature?: string;
32
+ time?: Date;
33
+ timeout?: ReturnType<typeof setTimeout>;
34
+ };
35
+ protected readonly logLevels: Record<string, number>;
36
+ protected disabled: boolean;
37
+ protected paused: boolean;
38
+ protected messageQueue: {
39
+ messageObject: any[];
40
+ raw: boolean;
41
+ type: LiteralUnion<DefaultLogTypes, T>;
42
+ }[];
43
+ protected scopeName: string[];
44
+ protected readonly types: LoggerTypesConfig<LiteralUnion<DefaultLogTypes, T>, L>;
45
+ protected readonly longestLabel: string;
46
+ protected readonly processors: Set<Processor<L>>;
47
+ protected readonly generalLogLevel: LiteralUnion<ExtendedRfc5424LogLevels, L>;
48
+ protected reporters: Set<Reporter<L>>;
49
+ protected readonly throttle: number;
50
+ protected readonly throttleMin: number;
51
+ protected readonly stringify: typeof stringify;
52
+ protected groups: string[];
53
+ protected readonly startTimerMessage: string;
54
+ protected readonly endTimerMessage: string;
55
+ protected rawReporter: Reporter<L>;
56
+ protected force: Record<string, LoggerFunction>;
57
+ /**
58
+ * Creates a new Pail browser logger instance.
59
+ *
60
+ * Initializes the logger with the provided configuration options,
61
+ * setting up reporters, processors, log levels, and other internal state.
62
+ * @param options Configuration options for the logger
63
+ */
64
+ constructor(options: ConstructorOptions<T, L>);
65
+ /**
66
+ * Wraps the global console methods to redirect them through the logger.
67
+ *
68
+ * This method replaces console methods (log, info, warn, error, etc.) with
69
+ * calls to the corresponding logger methods. The original console methods
70
+ * are backed up and can be restored using restoreConsole().
71
+ * @example
72
+ * ```typescript
73
+ * const logger = createPail();
74
+ * logger.wrapConsole();
75
+ *
76
+ * console.log("This will go through the logger");
77
+ * console.error("This too!");
78
+ *
79
+ * logger.restoreConsole(); // Restore original console methods
80
+ * ```
81
+ */
82
+ wrapConsole(): void;
83
+ /**
84
+ * Restores the original global console methods.
85
+ *
86
+ * This method restores the console methods that were backed up by wrapConsole().
87
+ * After calling this, console methods will work as they did before wrapping.
88
+ * @example
89
+ * ```typescript
90
+ * const logger = createPail();
91
+ * logger.wrapConsole();
92
+ *
93
+ * // Console methods are now wrapped
94
+ * logger.restoreConsole();
95
+ * // Console methods are restored to original behavior
96
+ * ```
97
+ */
98
+ restoreConsole(): void;
99
+ /**
100
+ * Wraps uncaught exception and unhandled rejection handlers.
101
+ *
102
+ * This method sets up global error handlers that will log uncaught exceptions
103
+ * and unhandled promise rejections through the logger. This is useful for
104
+ * capturing and logging application crashes.
105
+ * @example
106
+ * ```typescript
107
+ * const logger = createPail();
108
+ * logger.wrapException();
109
+ *
110
+ * // Now uncaught errors will be logged
111
+ * throw new Error("This will be logged");
112
+ * ```
113
+ */
114
+ wrapException(): void;
115
+ /**
116
+ * Removes the global exception/rejection handlers installed by {@link wrapException}.
117
+ *
118
+ * Counterpart to `wrapException()` (mirrors `wrapConsole()`/`restoreConsole()`).
119
+ * Safe to call when no handlers are installed.
120
+ * @example
121
+ * ```typescript
122
+ * const logger = createPail();
123
+ * logger.wrapException();
124
+ * // ... later ...
125
+ * logger.restoreException(); // global handlers removed
126
+ * ```
127
+ */
128
+ restoreException(): void;
129
+ /**
130
+ * Disables all logging output.
131
+ *
132
+ * When disabled, all log calls will be silently ignored and no output
133
+ * will be produced by any reporters. This can be useful for temporarily
134
+ * suppressing log output in production or during testing.
135
+ * @example
136
+ * ```typescript
137
+ * const logger = createPail();
138
+ * logger.disable();
139
+ * logger.info("This won't be logged"); // Silent
140
+ * logger.enable();
141
+ * logger.info("This will be logged"); // Output produced
142
+ * ```
143
+ */
144
+ disable(): void;
145
+ /**
146
+ * Enables logging output.
147
+ *
148
+ * Re-enables logging after it has been disabled. All subsequent log calls
149
+ * will produce output according to the configured reporters.
150
+ * @example
151
+ * ```typescript
152
+ * const logger = createPail();
153
+ * logger.disable();
154
+ * logger.info("This won't be logged");
155
+ * logger.enable(); // Re-enable logging
156
+ * logger.info("This will be logged");
157
+ * ```
158
+ */
159
+ enable(): void;
160
+ /**
161
+ * Checks if logging is currently enabled.
162
+ *
163
+ * Returns true if logging is enabled and false if it has been disabled.
164
+ * @returns True if logging is enabled, false if disabled
165
+ * @example
166
+ * ```typescript
167
+ * const logger = createPail();
168
+ * console.log(logger.isEnabled()); // true
169
+ * logger.disable();
170
+ * console.log(logger.isEnabled()); // false
171
+ * ```
172
+ */
173
+ isEnabled(): boolean;
174
+ /**
175
+ * Pauses logging and starts queuing messages.
176
+ *
177
+ * When paused, all log calls will be queued instead of being output immediately.
178
+ * The queued messages will be processed when resume() is called. This is useful
179
+ * for temporarily buffering log output during critical operations.
180
+ * @example
181
+ * ```typescript
182
+ * const logger = createPail();
183
+ * logger.pause();
184
+ * logger.info("This will be queued"); // Queued, not output yet
185
+ * logger.warn("This too"); // Also queued
186
+ * logger.resume(); // Now both messages are output
187
+ * ```
188
+ */
189
+ pause(): void;
190
+ /**
191
+ * Resumes logging and flushes all queued messages.
192
+ *
193
+ * Processes all messages that were queued during the pause period and
194
+ * resumes normal logging behavior. Messages are output in the order
195
+ * they were originally called.
196
+ * @example
197
+ * ```typescript
198
+ * const logger = createPail();
199
+ * logger.pause();
200
+ * logger.info("Message 1"); // Queued
201
+ * logger.info("Message 2"); // Queued
202
+ * logger.resume(); // Both messages are now output in order
203
+ * logger.info("Message 3"); // Output immediately
204
+ * ```
205
+ */
206
+ resume(): void;
207
+ /**
208
+ * Creates a scoped logger instance.
209
+ *
210
+ * Returns a new logger instance that inherits all configuration but adds
211
+ * the specified scope names to all log messages. This is useful for
212
+ * categorizing logs by component, module, or feature.
213
+ * @template N - The new custom logger type names
214
+ * @param name Scope names to apply to all log messages
215
+ * @returns A new scoped logger instance
216
+ * @throws {Error} If no scope name is provided
217
+ * @example
218
+ * ```typescript
219
+ * const logger = createPail();
220
+ * const scopedLogger = logger.scope("auth", "login");
221
+ * scopedLogger.info("User logged in"); // Will include scope: ["auth", "login"]
222
+ * ```
223
+ */
224
+ scope<N extends string = T>(...name: string[]): PailBrowserType<N, L>;
225
+ /**
226
+ * Removes the current scope from the logger.
227
+ *
228
+ * Clears all scope names that were set by previous scope() calls.
229
+ * After calling this, log messages will no longer include scope information.
230
+ * @example
231
+ * ```typescript
232
+ * const logger = createPail();
233
+ * const scopedLogger = logger.scope("auth");
234
+ * scopedLogger.info("Scoped message"); // Has scope
235
+ * scopedLogger.unscope();
236
+ * scopedLogger.info("Unscoped message"); // No scope
237
+ * ```
238
+ */
239
+ unscope(): void;
240
+ /**
241
+ * Creates a child logger that inherits settings from the parent.
242
+ *
243
+ * Returns a new logger instance that inherits all configuration from the parent
244
+ * (reporters, processors, types, log levels, throttle settings, etc.) while allowing
245
+ * you to override only what you need. Child loggers are independent instances with
246
+ * their own state (timers, counters, etc.).
247
+ * @template N - The new custom logger type names
248
+ * @template LC - The new log level types
249
+ * @param options Configuration options to override or extend parent settings
250
+ * @returns A new child logger instance
251
+ * @example
252
+ * ```typescript
253
+ * const parent = createPail({
254
+ * logLevel: "info",
255
+ * types: { http: { label: "HTTP", logLevel: "info" } },
256
+ * reporters: [new PrettyReporter()],
257
+ * });
258
+ *
259
+ * // Child inherits parent settings but overrides log level
260
+ * const child = parent.child({ logLevel: "debug" });
261
+ * child.info("This will be logged"); // Uses debug level from child
262
+ * child.http("GET /api 200"); // Inherits http type from parent
263
+ *
264
+ * // Child can add new types
265
+ * const childWithNewType = parent.child({
266
+ * types: { db: { label: "DB", logLevel: "info" } },
267
+ * });
268
+ * childWithNewType.db("Query executed"); // New type available
269
+ * ```
270
+ */
271
+ child<N extends string = T, LC extends string = L>(options?: Partial<ConstructorOptions<N, LC>>): PailBrowserType<N, LC>;
272
+ /**
273
+ * Starts a timer with the specified label.
274
+ *
275
+ * Records the current timestamp and associates it with the given label.
276
+ * Multiple timers can be active simultaneously with different labels.
277
+ * @param label The timer label (defaults to "default")
278
+ * @example
279
+ * ```typescript
280
+ * const logger = createPail();
281
+ * logger.time("operation");
282
+ * // ... some operation ...
283
+ * logger.timeEnd("operation"); // Logs: "Timer run for: X ms"
284
+ * ```
285
+ */
286
+ time(label?: string): void;
287
+ /**
288
+ * Logs the current elapsed time for a timer without stopping it.
289
+ *
290
+ * Calculates and logs the time elapsed since the timer was started,
291
+ * but keeps the timer running. If no label is provided, uses the
292
+ * most recently started timer.
293
+ * @param label The timer label (uses last timer if not specified)
294
+ * @param data Additional data to include in the log message
295
+ * @example
296
+ * ```typescript
297
+ * const logger = createPail();
298
+ * logger.time("task");
299
+ * // ... some work ...
300
+ * logger.timeLog("task"); // Logs current elapsed time
301
+ * // ... more work ...
302
+ * logger.timeEnd("task"); // Logs final time and stops timer
303
+ * ```
304
+ */
305
+ timeLog(label?: string, ...data: unknown[]): void;
306
+ /**
307
+ * Stops a timer and logs the final elapsed time.
308
+ *
309
+ * Calculates the total time elapsed since the timer was started,
310
+ * logs the result, and removes the timer. If no label is provided,
311
+ * uses the most recently started timer.
312
+ * @param label The timer label (uses last timer if not specified)
313
+ * @example
314
+ * ```typescript
315
+ * const logger = createPail();
316
+ * logger.time("operation");
317
+ * // ... perform operation ...
318
+ * logger.timeEnd("operation"); // Logs: "Timer run for: X ms"
319
+ * ```
320
+ */
321
+ timeEnd(label?: string): void;
322
+ /**
323
+ * Starts a log group with the specified label.
324
+ *
325
+ * Groups related log messages together. In browser environments,
326
+ * this uses the native console.group() functionality. In other
327
+ * environments, it tracks group nesting internally.
328
+ * @param label The group label (defaults to "console.group")
329
+ * @example
330
+ * ```typescript
331
+ * const logger = createPail();
332
+ * logger.group("Database Operations");
333
+ * logger.info("Connecting to database");
334
+ * logger.info("Running migration");
335
+ * logger.groupEnd(); // End the group
336
+ * ```
337
+ */
338
+ group(label?: string): void;
339
+ /**
340
+ * Ends the current log group.
341
+ *
342
+ * Closes the most recently opened log group. In browser environments,
343
+ * this uses the native console.groupEnd() functionality.
344
+ * @example
345
+ * ```typescript
346
+ * const logger = createPail();
347
+ * logger.group("Processing");
348
+ * logger.info("Step 1");
349
+ * logger.info("Step 2");
350
+ * logger.groupEnd(); // Closes the "Processing" group
351
+ * ```
352
+ */
353
+ groupEnd(): void;
354
+ /**
355
+ * Increments and logs a counter with the specified label.
356
+ *
357
+ * Maintains an internal counter for each label and logs the current count
358
+ * each time it's called. Useful for tracking how many times certain
359
+ * code paths are executed.
360
+ * @param label The counter label (defaults to "default")
361
+ * @example
362
+ * ```typescript
363
+ * const logger = createPail();
364
+ * logger.count("requests"); // Logs: "requests: 1"
365
+ * logger.count("requests"); // Logs: "requests: 2"
366
+ * logger.count("errors"); // Logs: "errors: 1"
367
+ * ```
368
+ */
369
+ count(label?: string): void;
370
+ /**
371
+ * Resets a counter to zero.
372
+ *
373
+ * Removes the counter with the specified label, effectively resetting
374
+ * it to zero. If the counter doesn't exist, logs a warning.
375
+ * @param label The counter label to reset (defaults to "default")
376
+ * @example
377
+ * ```typescript
378
+ * const logger = createPail();
379
+ * logger.count("requests"); // Logs: "requests: 1"
380
+ * logger.countReset("requests"); // Resets counter
381
+ * logger.count("requests"); // Logs: "requests: 1" (starts over)
382
+ * ```
383
+ */
384
+ countReset(label?: string): void;
385
+ /**
386
+ * Clears the console output.
387
+ *
388
+ * Calls the native console.clear() method to clear all output from
389
+ * the console. This is a convenience method that wraps the native
390
+ * console.clear() functionality.
391
+ * @example
392
+ * ```typescript
393
+ * const logger = createPail();
394
+ * logger.info("Some message");
395
+ * logger.clear(); // Clears the console
396
+ * ```
397
+ */
398
+ clear(): void;
399
+ /**
400
+ * Logs a raw message bypassing normal processing.
401
+ *
402
+ * Sends a message directly to the raw reporter without going through
403
+ * the normal logging pipeline (processors, throttling, etc.). This is
404
+ * useful for logging that needs to bypass all formatting and processing.
405
+ * @param message The raw message to log
406
+ * @param arguments_ Additional arguments to include
407
+ * @example
408
+ * ```typescript
409
+ * const logger = createPail();
410
+ * logger.raw("Direct message", { data: "value" });
411
+ * ```
412
+ */
413
+ raw(message: string, ...arguments_: unknown[]): void;
414
+ protected extendReporter(reporter: Reporter<L>): Reporter<L>;
415
+ protected registerReporters(reporters: Reporter<L>[]): void;
416
+ protected registerProcessors(processors: Processor<L>[]): void;
417
+ protected logger(type: LiteralUnion<DefaultLogTypes, T>, raw: boolean, force: boolean, ...messageObject: unknown[]): void;
418
+ }
419
+ type PailBrowserType<T extends string = string, L extends string = string> = Console & (new <TC extends string = string, LC extends string = string>(options?: ConstructorOptions<TC, LC>) => PailBrowserType<TC, LC>) & PailBrowserImpl<T, L> & Record<DefaultLogTypes, LoggerFunction> & Record<T, LoggerFunction> & {
420
+ force: Record<DefaultLogTypes, LoggerFunction> & Record<T, LoggerFunction>;
421
+ };
422
+ /**
423
+ * A pail instance with dynamically generated log methods.
424
+ * This is the minimal interface WideEvent needs from a pail logger.
425
+ */
426
+ type PailLike<T extends string = string> = PailBrowserImpl<T> & Record<DefaultLogTypes | T, LoggerFunction>;
427
+ /**
428
+ * Makes all properties in T optional recursively.
429
+ */
430
+ type DeepPartial<T> = { [K in keyof T]?: T[K] extends Record<string, unknown> ? DeepPartial<T[K]> : T[K]; };
431
+ /**
432
+ * Severity levels for wide events.
433
+ */
434
+ type WideEventLevel = "debug" | "error" | "info" | "warn";
435
+ /**
436
+ * An entry in the request lifecycle log.
437
+ */
438
+ interface RequestLogEntry {
439
+ /**
440
+ * Additional structured context for this log entry.
441
+ */
442
+ context?: Record<string, unknown>;
443
+ /**
444
+ * Severity level of this entry.
445
+ */
446
+ level: WideEventLevel;
447
+ /**
448
+ * Human-readable message describing what happened.
449
+ */
450
+ message: string;
451
+ /**
452
+ * ISO 8601 timestamp of when this entry was recorded.
453
+ */
454
+ timestamp: string;
455
+ }
456
+ /**
457
+ * Serialized error information included in the emitted wide event.
458
+ */
459
+ interface SerializedError {
460
+ cause?: SerializedError;
461
+ data?: unknown;
462
+ message: string;
463
+ name: string;
464
+ stack?: string;
465
+ status?: number;
466
+ }
467
+ /**
468
+ * Options for finishing a wide event with HTTP context.
469
+ */
470
+ interface WideEventFinishOptions {
471
+ /**
472
+ * An error that occurred during the operation.
473
+ * Will be serialized and included in the emitted event.
474
+ */
475
+ error?: Error;
476
+ /**
477
+ * HTTP response status code.
478
+ */
479
+ status?: number;
480
+ }
481
+ /**
482
+ * Options for creating a WideEvent instance.
483
+ * @template T - Custom logger type names
484
+ */
485
+ interface WideEventOptions<T extends string = string> {
486
+ /**
487
+ * Auto-emit the event when disposed via `Symbol.dispose`.
488
+ * Works with TC39 Explicit Resource Management (`using`).
489
+ * @default true
490
+ */
491
+ autoEmit?: boolean;
492
+ /**
493
+ * Event name identifying this wide event, e.g. "api.checkout", "worker.send-email".
494
+ */
495
+ name: string;
496
+ /**
497
+ * The pail logger instance to use for emission.
498
+ */
499
+ pail: PailLike<T>;
500
+ /**
501
+ * Service name for this event. Overrides any service name from pail's scope.
502
+ */
503
+ service?: string;
504
+ /**
505
+ * Base log type to use when emitting. Defaults to "info".
506
+ * The actual type may be escalated based on logged warnings/errors.
507
+ */
508
+ type?: DefaultLogTypes | T;
509
+ }
510
+ /**
511
+ * A wide event logger that accumulates context incrementally and emits
512
+ * a single comprehensive log event through pail.
513
+ *
514
+ * Instead of scattering multiple log calls throughout an operation,
515
+ * use `set()` to build up context as information becomes available,
516
+ * then emit once at the end. Lifecycle methods (`info()`, `warn()`, `error()`,
517
+ * `debug()`) record timestamped entries in a `requestLogs` array and
518
+ * automatically escalate the event's severity level.
519
+ *
520
+ * Implements `Disposable` for use with TC39 Explicit Resource Management.
521
+ * @template TData - Shape of the accumulated event data
522
+ * @template T - Custom logger type names from the pail instance
523
+ * @example
524
+ * ```typescript
525
+ * // Manual finish
526
+ * const ev = createWideEvent({ pail: logger, name: "api.checkout" });
527
+ * ev.set({ user: { id: 1 } });
528
+ * ev.info("Validated cart");
529
+ * ev.set({ cart: { items: 3, total: 9999 } });
530
+ * ev.finish({ status: 200 });
531
+ *
532
+ * // Auto-emit with Explicit Resource Management
533
+ * using ev = createWideEvent({ pail: logger, name: "api.checkout" });
534
+ * ev.set({ user: { id: 1 } });
535
+ * // emits automatically when scope exits
536
+ *
537
+ * // Typed data shape
538
+ * interface CheckoutData {
539
+ * user: { id: number; plan: string };
540
+ * cart: { items: number; total: number };
541
+ * }
542
+ * const ev = createWideEvent<CheckoutData>({ pail: logger, name: "api.checkout" });
543
+ * ev.set({ user: { id: 1, plan: "pro" } }); // fully typed
544
+ * ```
545
+ */
546
+ declare class WideEvent<TData extends Record<string, unknown> = Record<string, unknown>, T extends string = string> implements Disposable {
547
+ readonly name: string;
548
+ private readonly autoEmit;
549
+ private data;
550
+ private emitted;
551
+ private attachedError?;
552
+ private level;
553
+ private readonly pail;
554
+ private readonly requestLogs;
555
+ private readonly service;
556
+ private readonly startTime;
557
+ private status;
558
+ private readonly timestamp;
559
+ private readonly _type;
560
+ constructor(options: WideEventOptions<T>);
561
+ /**
562
+ * Record a debug-level lifecycle log entry.
563
+ * Does not escalate the event level.
564
+ * @param message Description of what happened
565
+ * @param context Optional structured context
566
+ * @returns `this` for chaining
567
+ */
568
+ debug(message: string, context?: Record<string, unknown>): this;
569
+ /**
570
+ * Emit the wide event through the pail logger. Can only be called once;
571
+ * subsequent calls are no-ops.
572
+ *
573
+ * Automatically calculates duration, determines the log type based on
574
+ * the highest severity level reached, and serializes any attached error.
575
+ *
576
+ * Prefer `finish()` for HTTP request contexts where you have a status code.
577
+ * @param typeOverride Override the log type for this emission
578
+ */
579
+ emit(typeOverride?: DefaultLogTypes | T): void;
580
+ /**
581
+ * Record an error-level lifecycle log entry and attach the error.
582
+ * Escalates the event level to "error".
583
+ * @param message Description of what went wrong
584
+ * @param error The error that occurred
585
+ * @param context Optional structured context
586
+ * @returns `this` for chaining
587
+ */
588
+ error(message: string, error?: Error, context?: Record<string, unknown>): this;
589
+ /**
590
+ * Finish and emit the wide event with HTTP context.
591
+ * Sets the response status and optional error before emitting.
592
+ * @example
593
+ * ```typescript
594
+ * ev.finish({ status: 200 });
595
+ * ev.finish({ status: 500, error: new Error("DB timeout") });
596
+ * ```
597
+ * @param options Status code and/or error
598
+ */
599
+ finish(options?: WideEventFinishOptions): void;
600
+ /**
601
+ * Get a read-only snapshot of the accumulated data.
602
+ */
603
+ getData(): Readonly<TData>;
604
+ /**
605
+ * Get the current severity level of the event.
606
+ * The level auto-escalates as `warn()` or `error()` entries are added.
607
+ */
608
+ getLevel(): WideEventLevel;
609
+ /**
610
+ * Get a read-only copy of the request lifecycle log entries.
611
+ */
612
+ getRequestLogs(): ReadonlyArray<RequestLogEntry>;
613
+ /**
614
+ * Record an info-level lifecycle log entry.
615
+ * Does not escalate the event level.
616
+ * @param message Description of what happened
617
+ * @param context Optional structured context
618
+ * @returns `this` for chaining
619
+ */
620
+ info(message: string, context?: Record<string, unknown>): this;
621
+ /**
622
+ * Accumulate context into the wide event via deep merge.
623
+ * Call as many times as needed throughout the operation.
624
+ * @example
625
+ * ```typescript
626
+ * ev.set({ user: { id: 1 } });
627
+ * ev.set({ user: { plan: "pro" } });
628
+ * // data = { user: { id: 1, plan: "pro" } }
629
+ * ```
630
+ * @param data Partial data to merge into the event
631
+ * @returns `this` for chaining
632
+ */
633
+ set(data: DeepPartial<TData>): this;
634
+ /**
635
+ * Attach an error to the event. Automatically escalates the event
636
+ * level to "error".
637
+ * @param error The error to attach
638
+ * @returns `this` for chaining
639
+ */
640
+ setError(error: Error): this;
641
+ /**
642
+ * Set the HTTP response status code.
643
+ * @param status HTTP status code
644
+ * @returns `this` for chaining
645
+ */
646
+ setStatus(status: number): this;
647
+ /**
648
+ * Record a warn-level lifecycle log entry.
649
+ * Escalates the event level to "warn" (unless already "error").
650
+ * @param message Description of the warning
651
+ * @param context Optional structured context
652
+ * @returns `this` for chaining
653
+ */
654
+ warn(message: string, context?: Record<string, unknown>): this;
655
+ /**
656
+ * Disposable implementation. Auto-emits the event if `autoEmit` is true
657
+ * and the event hasn't been manually emitted yet.
658
+ *
659
+ * Enables usage with TC39 Explicit Resource Management:
660
+ * ```typescript
661
+ * using ev = createWideEvent({ pail: logger, name: "api.checkout" });
662
+ * ev.set({ user: { id: 1 } });
663
+ * // auto-emits here when scope exits
664
+ * ```
665
+ */
666
+ [Symbol.dispose](): void;
667
+ /**
668
+ * Add an entry to the request lifecycle log and escalate level if needed.
669
+ */
670
+ private addLogEntry;
671
+ /**
672
+ * Escalate the event level if the new level has higher severity.
673
+ */
674
+ private escalateLevel;
675
+ }
676
+ /**
677
+ * Create a wide event logger that accumulates context and emits a single
678
+ * comprehensive log event through pail.
679
+ * @template TData - Shape of the accumulated event data
680
+ * @template T - Custom logger type names from the pail instance
681
+ * @param options Configuration options
682
+ * @returns A new WideEvent instance
683
+ * @example
684
+ * ```typescript
685
+ * import { createPail } from "@visulima/pail";
686
+ * import { createWideEvent } from "@visulima/pail/wide-event";
687
+ *
688
+ * const logger = createPail();
689
+ *
690
+ * // In a request handler:
691
+ * const ev = createWideEvent({ pail: logger, name: "api.checkout" });
692
+ *
693
+ * ev.set({ user: { id: 1, plan: "pro" } });
694
+ * ev.info("Validated cart", { itemCount: 3 });
695
+ * ev.set({ cart: { id: 42, items: 3, total: 9999 } });
696
+ * ev.info("Payment processed");
697
+ * ev.finish({ status: 200 });
698
+ *
699
+ * // Emits a single structured log:
700
+ * // {
701
+ * // event: "api.checkout",
702
+ * // timestamp: "2025-01-24T10:23:45.612Z",
703
+ * // duration: "127ms",
704
+ * // duration_ms: 127,
705
+ * // status: 200,
706
+ * // user: { id: 1, plan: "pro" },
707
+ * // cart: { id: 42, items: 3, total: 9999 },
708
+ * // requestLogs: [
709
+ * // { level: "info", message: "Validated cart", timestamp: "...", context: { itemCount: 3 } },
710
+ * // { level: "info", message: "Payment processed", timestamp: "..." }
711
+ * // ]
712
+ * // }
713
+ * ```
714
+ */
715
+ declare const createWideEvent: <TData extends Record<string, unknown> = Record<string, unknown>, T extends string = string>(options: WideEventOptions<T>) => WideEvent<TData, T>;
716
+ export { PailBrowserImpl as P, RequestLogEntry as R, SerializedError as S, WideEvent as W, WideEventFinishOptions as a, WideEventLevel as b, WideEventOptions as c, createWideEvent as d };