@visulima/pail 4.0.0-alpha.10 → 4.0.0-alpha.12

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