@visulima/pail 3.2.2 → 4.0.0-alpha.10

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 (82) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/LICENSE.md +434 -6
  3. package/README.md +355 -24
  4. package/dist/error.d.ts +104 -0
  5. package/dist/error.js +76 -0
  6. package/dist/index.browser.d.ts +3 -1
  7. package/dist/index.browser.js +1490 -3
  8. package/dist/index.server.d.ts +3 -1
  9. package/dist/index.server.js +2668 -14
  10. package/dist/interactive/index.js +2 -2
  11. package/dist/middleware/elysia.d.ts +71 -0
  12. package/dist/middleware/elysia.js +70 -0
  13. package/dist/middleware/express.d.ts +86 -0
  14. package/dist/middleware/express.js +29 -0
  15. package/dist/middleware/fastify.d.ts +81 -0
  16. package/dist/middleware/fastify.js +46 -0
  17. package/dist/middleware/hono.d.ts +85 -0
  18. package/dist/middleware/hono.js +33 -0
  19. package/dist/middleware/next/handler.d.ts +36 -0
  20. package/dist/middleware/next/handler.js +53 -0
  21. package/dist/middleware/next/middleware.d.ts +59 -0
  22. package/dist/middleware/next/storage.d.ts +14 -0
  23. package/dist/middleware/shared/create-middleware-logger.d.ts +82 -0
  24. package/dist/middleware/shared/headers.d.ts +14 -0
  25. package/dist/middleware/shared/routes.d.ts +30 -0
  26. package/dist/middleware/shared/storage.d.ts +29 -0
  27. package/dist/middleware/sveltekit.d.ts +123 -0
  28. package/dist/middleware/sveltekit.js +43 -0
  29. package/dist/object-tree.d.ts +2 -2
  30. package/dist/object-tree.js +7 -7
  31. package/dist/packem_shared/{AbstractJsonReporter-intFdT_A.js → AbstractJsonReporter-CjtVgHbU.js} +112 -28
  32. package/dist/packem_shared/AbstractJsonReporter-DlugSJpY.js +288 -0
  33. package/dist/packem_shared/{InteractiveManager-CZ85hGNW.js → InteractiveManager-CowYA3Hx.js} +17 -11
  34. package/dist/packem_shared/{interactive-stream-hook-DG4BtN12.js → InteractiveStreamHook-BypRlYTX.js} +3 -11
  35. package/dist/packem_shared/{JsonReporter-C0AXk99i.js → JsonReporter-BgPvIyC2.js} +2 -2
  36. package/dist/packem_shared/{JsonReporter-DcM2LBX9.js → JsonReporter-Dbw82ewj.js} +2 -2
  37. package/dist/packem_shared/{PrettyReporter-CuLLKr6-.js → PrettyReporter-C2dCzIaf.js} +54 -8
  38. package/dist/packem_shared/{format-label-Btft2KGP.js → PrettyReporter-gMqa7j_m.js} +372 -78
  39. package/dist/packem_shared/Spinner-Cokext9b.js +2183 -0
  40. package/dist/packem_shared/abstract-pretty-reporter-szQO-IgK.js +2635 -0
  41. package/dist/packem_shared/constants-B1RjD_ps.js +99 -0
  42. package/dist/packem_shared/{constants-DfDr4MHC.js → constants-omsTHUWB.js} +1 -1
  43. package/dist/packem_shared/createPailError-B_sgL0nF.js +76 -0
  44. package/dist/packem_shared/getBarChar-D7JfmdTr.js +459 -0
  45. package/dist/packem_shared/headers-BxHWM6KI.js +127 -0
  46. package/dist/packem_shared/{index-DqKWykfa.js → index-BEfVUy9P.js} +174 -64
  47. package/dist/packem_shared/{index-BomQ3E6J.js → index-Bx3-C0j9.js} +29 -21
  48. package/dist/packem_shared/pailMiddleware-Ci88geIF.js +24 -0
  49. package/dist/packem_shared/storage-D0vqz8OX.js +36 -0
  50. package/dist/packem_shared/{InteractiveStreamHook-DiSubbJ1.js → useLogger-D0rU3lcX.js} +13 -1
  51. package/dist/packem_shared/{write-console-log-based-on-level-DBmRYXpj.js → write-console-log-based-on-level-ree2lDPw.js} +5 -4
  52. package/dist/packem_shared/{write-stream-BG8fhcs3.js → write-stream-BuFtjATz.js} +1 -1
  53. package/dist/pail.browser.d.ts +1 -1
  54. package/dist/processor/environment-processor.d.ts +124 -0
  55. package/dist/processor/environment-processor.js +82 -0
  56. package/dist/processor/message-formatter-processor.d.ts +2 -2
  57. package/dist/processor/message-formatter-processor.js +654 -6
  58. package/dist/processor/opentelemetry-processor.js +4 -4
  59. package/dist/processor/redact-processor.d.ts +1 -1
  60. package/dist/processor/redact-processor.js +2 -1
  61. package/dist/processor/sampling-processor.d.ts +111 -0
  62. package/dist/processor/sampling-processor.js +59 -0
  63. package/dist/progress-bar.d.ts +10 -1
  64. package/dist/progress-bar.js +75 -20
  65. package/dist/reporter/file/json-file-reporter.js +1 -1
  66. package/dist/reporter/http/abstract-http-reporter.js +23 -26
  67. package/dist/reporter/http/http-reporter.edge-light.js +134 -53
  68. package/dist/reporter/json/abstract-json-reporter.d.ts +1 -1
  69. package/dist/reporter/json/index.browser.js +2 -2
  70. package/dist/reporter/json/index.js +2 -2
  71. package/dist/reporter/pretty/index.browser.js +1 -1
  72. package/dist/reporter/pretty/index.js +1 -1
  73. package/dist/reporter/simple/simple-reporter.server.js +8 -12
  74. package/dist/spinner.js +37 -4
  75. package/dist/types.d.ts +4 -4
  76. package/dist/wide-event.d.ts +300 -0
  77. package/dist/wide-event.js +283 -0
  78. package/package.json +73 -8
  79. package/dist/packem_shared/PrettyReporter-BFWaYP_J.js +0 -222
  80. package/dist/packem_shared/abstract-pretty-reporter-DMPDCslJ.js +0 -50
  81. package/dist/packem_shared/get-longest-label-C9PWeyKq.js +0 -9
  82. package/dist/packem_shared/pail.browser-CPjQrsyy.js +0 -1427
@@ -0,0 +1,300 @@
1
+ import type { PailBrowserImpl } from "./pail.d.ts";
2
+ import type { DefaultLogTypes, LoggerFunction } from "./types.d.ts";
3
+ /**
4
+ * A pail instance with dynamically generated log methods.
5
+ * This is the minimal interface WideEvent needs from a pail logger.
6
+ */
7
+ type PailLike<T extends string = string> = PailBrowserImpl<T> & Record<DefaultLogTypes | T, LoggerFunction>;
8
+ /**
9
+ * Makes all properties in T optional recursively.
10
+ */
11
+ type DeepPartial<T> = {
12
+ [K in keyof T]?: T[K] extends Record<string, unknown> ? DeepPartial<T[K]> : T[K];
13
+ };
14
+ /**
15
+ * Severity levels for wide events.
16
+ */
17
+ export type WideEventLevel = "debug" | "error" | "info" | "warn";
18
+ /**
19
+ * An entry in the request lifecycle log.
20
+ */
21
+ export interface RequestLogEntry {
22
+ /**
23
+ * Additional structured context for this log entry.
24
+ */
25
+ context?: Record<string, unknown>;
26
+ /**
27
+ * Severity level of this entry.
28
+ */
29
+ level: WideEventLevel;
30
+ /**
31
+ * Human-readable message describing what happened.
32
+ */
33
+ message: string;
34
+ /**
35
+ * ISO 8601 timestamp of when this entry was recorded.
36
+ */
37
+ timestamp: string;
38
+ }
39
+ /**
40
+ * Serialized error information included in the emitted wide event.
41
+ */
42
+ export interface SerializedError {
43
+ cause?: SerializedError;
44
+ data?: unknown;
45
+ message: string;
46
+ name: string;
47
+ stack?: string;
48
+ status?: number;
49
+ }
50
+ /**
51
+ * Options for finishing a wide event with HTTP context.
52
+ */
53
+ export interface WideEventFinishOptions {
54
+ /**
55
+ * An error that occurred during the operation.
56
+ * Will be serialized and included in the emitted event.
57
+ */
58
+ error?: Error;
59
+ /**
60
+ * HTTP response status code.
61
+ */
62
+ status?: number;
63
+ }
64
+ /**
65
+ * Options for creating a WideEvent instance.
66
+ * @template T - Custom logger type names
67
+ */
68
+ export interface WideEventOptions<T extends string = string> {
69
+ /**
70
+ * Auto-emit the event when disposed via `Symbol.dispose`.
71
+ * Works with TC39 Explicit Resource Management (`using`).
72
+ * @default true
73
+ */
74
+ autoEmit?: boolean;
75
+ /**
76
+ * Event name identifying this wide event, e.g. "api.checkout", "worker.send-email".
77
+ */
78
+ name: string;
79
+ /**
80
+ * The pail logger instance to use for emission.
81
+ */
82
+ pail: PailLike<T>;
83
+ /**
84
+ * Service name for this event. Overrides any service name from pail's scope.
85
+ */
86
+ service?: string;
87
+ /**
88
+ * Base log type to use when emitting. Defaults to "info".
89
+ * The actual type may be escalated based on logged warnings/errors.
90
+ */
91
+ type?: DefaultLogTypes | T;
92
+ }
93
+ /**
94
+ * A wide event logger that accumulates context incrementally and emits
95
+ * a single comprehensive log event through pail.
96
+ *
97
+ * Instead of scattering multiple log calls throughout an operation,
98
+ * use `set()` to build up context as information becomes available,
99
+ * then emit once at the end. Lifecycle methods (`info()`, `warn()`, `error()`,
100
+ * `debug()`) record timestamped entries in a `requestLogs` array and
101
+ * automatically escalate the event's severity level.
102
+ *
103
+ * Implements `Disposable` for use with TC39 Explicit Resource Management.
104
+ * @template TData - Shape of the accumulated event data
105
+ * @template T - Custom logger type names from the pail instance
106
+ * @example
107
+ * ```typescript
108
+ * // Manual finish
109
+ * const ev = createWideEvent({ pail: logger, name: "api.checkout" });
110
+ * ev.set({ user: { id: 1 } });
111
+ * ev.info("Validated cart");
112
+ * ev.set({ cart: { items: 3, total: 9999 } });
113
+ * ev.finish({ status: 200 });
114
+ *
115
+ * // Auto-emit with Explicit Resource Management
116
+ * using ev = createWideEvent({ pail: logger, name: "api.checkout" });
117
+ * ev.set({ user: { id: 1 } });
118
+ * // emits automatically when scope exits
119
+ *
120
+ * // Typed data shape
121
+ * interface CheckoutData {
122
+ * user: { id: number; plan: string };
123
+ * cart: { items: number; total: number };
124
+ * }
125
+ * const ev = createWideEvent<CheckoutData>({ pail: logger, name: "api.checkout" });
126
+ * ev.set({ user: { id: 1, plan: "pro" } }); // fully typed
127
+ * ```
128
+ */
129
+ export declare class WideEvent<TData extends Record<string, unknown> = Record<string, unknown>, T extends string = string> implements Disposable {
130
+ [Symbol.dispose]: () => void;
131
+ readonly name: string;
132
+ private readonly autoEmit;
133
+ private data;
134
+ private emitted;
135
+ private attachedError?;
136
+ private level;
137
+ private readonly pail;
138
+ private readonly requestLogs;
139
+ private readonly service;
140
+ private readonly startTime;
141
+ private status;
142
+ private readonly timestamp;
143
+ private readonly type;
144
+ constructor(options: WideEventOptions<T>);
145
+ /**
146
+ * Record a debug-level lifecycle log entry.
147
+ * Does not escalate the event level.
148
+ * @param message Description of what happened
149
+ * @param context Optional structured context
150
+ * @returns `this` for chaining
151
+ */
152
+ debug(message: string, context?: Record<string, unknown>): this;
153
+ /**
154
+ * Emit the wide event through the pail logger. Can only be called once;
155
+ * subsequent calls are no-ops.
156
+ *
157
+ * Automatically calculates duration, determines the log type based on
158
+ * the highest severity level reached, and serializes any attached error.
159
+ *
160
+ * Prefer `finish()` for HTTP request contexts where you have a status code.
161
+ * @param typeOverride Override the log type for this emission
162
+ */
163
+ emit(typeOverride?: DefaultLogTypes | T): void;
164
+ /**
165
+ * Record an error-level lifecycle log entry and attach the error.
166
+ * Escalates the event level to "error".
167
+ * @param message Description of what went wrong
168
+ * @param error The error that occurred
169
+ * @param context Optional structured context
170
+ * @returns `this` for chaining
171
+ */
172
+ error(message: string, error?: Error, context?: Record<string, unknown>): this;
173
+ /**
174
+ * Finish and emit the wide event with HTTP context.
175
+ * Sets the response status and optional error before emitting.
176
+ * @example
177
+ * ```typescript
178
+ * ev.finish({ status: 200 });
179
+ * ev.finish({ status: 500, error: new Error("DB timeout") });
180
+ * ```
181
+ * @param options Status code and/or error
182
+ */
183
+ finish(options?: WideEventFinishOptions): void;
184
+ /**
185
+ * Get a read-only snapshot of the accumulated data.
186
+ */
187
+ getData(): Readonly<TData>;
188
+ /**
189
+ * Get the current severity level of the event.
190
+ * The level auto-escalates as `warn()` or `error()` entries are added.
191
+ */
192
+ getLevel(): WideEventLevel;
193
+ /**
194
+ * Get a read-only copy of the request lifecycle log entries.
195
+ */
196
+ getRequestLogs(): ReadonlyArray<RequestLogEntry>;
197
+ /**
198
+ * Record an info-level lifecycle log entry.
199
+ * Does not escalate the event level.
200
+ * @param message Description of what happened
201
+ * @param context Optional structured context
202
+ * @returns `this` for chaining
203
+ */
204
+ info(message: string, context?: Record<string, unknown>): this;
205
+ /**
206
+ * Accumulate context into the wide event via deep merge.
207
+ * Call as many times as needed throughout the operation.
208
+ * @example
209
+ * ```typescript
210
+ * ev.set({ user: { id: 1 } });
211
+ * ev.set({ user: { plan: "pro" } });
212
+ * // data = { user: { id: 1, plan: "pro" } }
213
+ * ```
214
+ * @param data Partial data to merge into the event
215
+ * @returns `this` for chaining
216
+ */
217
+ set(data: DeepPartial<TData>): this;
218
+ /**
219
+ * Attach an error to the event. Automatically escalates the event
220
+ * level to "error".
221
+ * @param error The error to attach
222
+ * @returns `this` for chaining
223
+ */
224
+ setError(error: Error): this;
225
+ /**
226
+ * Set the HTTP response status code.
227
+ * @param status HTTP status code
228
+ * @returns `this` for chaining
229
+ */
230
+ setStatus(status: number): this;
231
+ /**
232
+ * Record a warn-level lifecycle log entry.
233
+ * Escalates the event level to "warn" (unless already "error").
234
+ * @param message Description of the warning
235
+ * @param context Optional structured context
236
+ * @returns `this` for chaining
237
+ */
238
+ warn(message: string, context?: Record<string, unknown>): this;
239
+ /**
240
+ * Disposable implementation. Auto-emits the event if `autoEmit` is true
241
+ * and the event hasn't been manually emitted yet.
242
+ *
243
+ * Enables usage with TC39 Explicit Resource Management:
244
+ * ```typescript
245
+ * using ev = createWideEvent({ pail: logger, name: "api.checkout" });
246
+ * ev.set({ user: { id: 1 } });
247
+ * // auto-emits here when scope exits
248
+ * ```
249
+ */
250
+ [Symbol.dispose](): void;
251
+ /**
252
+ * Add an entry to the request lifecycle log and escalate level if needed.
253
+ */
254
+ private addLogEntry;
255
+ /**
256
+ * Escalate the event level if the new level has higher severity.
257
+ */
258
+ private escalateLevel;
259
+ }
260
+ /**
261
+ * Create a wide event logger that accumulates context and emits a single
262
+ * comprehensive log event through pail.
263
+ * @template TData - Shape of the accumulated event data
264
+ * @template T - Custom logger type names from the pail instance
265
+ * @param options Configuration options
266
+ * @returns A new WideEvent instance
267
+ * @example
268
+ * ```typescript
269
+ * import { createPail } from "@visulima/pail";
270
+ * import { createWideEvent } from "@visulima/pail/wide-event";
271
+ *
272
+ * const logger = createPail();
273
+ *
274
+ * // In a request handler:
275
+ * const ev = createWideEvent({ pail: logger, name: "api.checkout" });
276
+ *
277
+ * ev.set({ user: { id: 1, plan: "pro" } });
278
+ * ev.info("Validated cart", { itemCount: 3 });
279
+ * ev.set({ cart: { id: 42, items: 3, total: 9999 } });
280
+ * ev.info("Payment processed");
281
+ * ev.finish({ status: 200 });
282
+ *
283
+ * // Emits a single structured log:
284
+ * // {
285
+ * // event: "api.checkout",
286
+ * // timestamp: "2025-01-24T10:23:45.612Z",
287
+ * // duration: "127ms",
288
+ * // duration_ms: 127,
289
+ * // status: 200,
290
+ * // user: { id: 1, plan: "pro" },
291
+ * // cart: { id: 42, items: 3, total: 9999 },
292
+ * // requestLogs: [
293
+ * // { level: "info", message: "Validated cart", timestamp: "...", context: { itemCount: 3 } },
294
+ * // { level: "info", message: "Payment processed", timestamp: "..." }
295
+ * // ]
296
+ * // }
297
+ * ```
298
+ */
299
+ export declare const createWideEvent: <TData extends Record<string, unknown> = Record<string, unknown>, T extends string = string>(options: WideEventOptions<T>) => WideEvent<TData, T>;
300
+ export {};
@@ -0,0 +1,283 @@
1
+ const LEVEL_PRIORITY = {
2
+ debug: 0,
3
+ error: 3,
4
+ info: 1,
5
+ warn: 2
6
+ };
7
+ const LEVEL_TO_LOG_TYPE = {
8
+ debug: "debug",
9
+ error: "error",
10
+ info: "info",
11
+ warn: "warn"
12
+ };
13
+ const deepMerge = (target, source) => {
14
+ const result = { ...target };
15
+ const keys = Object.keys(source);
16
+ for (let i = 0; i < keys.length; i += 1) {
17
+ const key = keys[i];
18
+ const sourceValue = source[key];
19
+ const targetValue = result[key];
20
+ if (sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue)) {
21
+ result[key] = deepMerge(targetValue, sourceValue);
22
+ } else {
23
+ result[key] = sourceValue;
24
+ }
25
+ }
26
+ return result;
27
+ };
28
+ const formatDuration = (ms) => {
29
+ if (ms < 1e3) {
30
+ return `${String(ms)}ms`;
31
+ }
32
+ return `${(ms / 1e3).toFixed(2)}s`;
33
+ };
34
+ const serializeError = (error) => {
35
+ const serialized = {
36
+ message: error.message,
37
+ name: error.name
38
+ };
39
+ if (error.stack) {
40
+ serialized.stack = error.stack;
41
+ }
42
+ const errorWithStatus = error;
43
+ if (errorWithStatus.status !== void 0) {
44
+ serialized.status = errorWithStatus.status;
45
+ } else if (errorWithStatus.statusCode !== void 0) {
46
+ serialized.status = errorWithStatus.statusCode;
47
+ }
48
+ if (errorWithStatus.data !== void 0) {
49
+ serialized.data = errorWithStatus.data;
50
+ }
51
+ if (error.cause instanceof Error) {
52
+ serialized.cause = serializeError(error.cause);
53
+ }
54
+ return serialized;
55
+ };
56
+ class WideEvent {
57
+ name;
58
+ autoEmit;
59
+ data;
60
+ emitted;
61
+ attachedError;
62
+ level;
63
+ pail;
64
+ requestLogs;
65
+ service;
66
+ startTime;
67
+ status;
68
+ timestamp;
69
+ type;
70
+ constructor(options) {
71
+ this.name = options.name;
72
+ this.pail = options.pail;
73
+ this.data = {};
74
+ this.startTime = performance.now();
75
+ this.timestamp = (/* @__PURE__ */ new Date()).toISOString();
76
+ this.emitted = false;
77
+ this.autoEmit = options.autoEmit ?? true;
78
+ this.type = options.type ?? "info";
79
+ this.level = "info";
80
+ this.requestLogs = [];
81
+ this.service = options.service;
82
+ }
83
+ /**
84
+ * Record a debug-level lifecycle log entry.
85
+ * Does not escalate the event level.
86
+ * @param message Description of what happened
87
+ * @param context Optional structured context
88
+ * @returns `this` for chaining
89
+ */
90
+ debug(message, context) {
91
+ return this.addLogEntry("debug", message, context);
92
+ }
93
+ /**
94
+ * Emit the wide event through the pail logger. Can only be called once;
95
+ * subsequent calls are no-ops.
96
+ *
97
+ * Automatically calculates duration, determines the log type based on
98
+ * the highest severity level reached, and serializes any attached error.
99
+ *
100
+ * Prefer `finish()` for HTTP request contexts where you have a status code.
101
+ * @param typeOverride Override the log type for this emission
102
+ */
103
+ emit(typeOverride) {
104
+ if (this.emitted) {
105
+ return;
106
+ }
107
+ this.emitted = true;
108
+ const durationMs = Math.round(performance.now() - this.startTime);
109
+ const resolvedLevel = this.attachedError ? "error" : this.level;
110
+ const type = typeOverride ?? LEVEL_TO_LOG_TYPE[resolvedLevel];
111
+ const payload = {
112
+ duration: formatDuration(durationMs),
113
+ duration_ms: durationMs,
114
+ event: this.name,
115
+ timestamp: this.timestamp,
116
+ ...this.data
117
+ };
118
+ if (this.service) {
119
+ payload.service = this.service;
120
+ }
121
+ if (this.status !== void 0) {
122
+ payload.status = this.status;
123
+ }
124
+ if (this.attachedError) {
125
+ payload.error = serializeError(this.attachedError);
126
+ }
127
+ if (this.requestLogs.length > 0) {
128
+ payload.requestLogs = this.requestLogs;
129
+ }
130
+ const logFunction = this.pail[type];
131
+ logFunction({ message: payload });
132
+ }
133
+ /**
134
+ * Record an error-level lifecycle log entry and attach the error.
135
+ * Escalates the event level to "error".
136
+ * @param message Description of what went wrong
137
+ * @param error The error that occurred
138
+ * @param context Optional structured context
139
+ * @returns `this` for chaining
140
+ */
141
+ error(message, error, context) {
142
+ if (error) {
143
+ this.attachedError = error;
144
+ }
145
+ return this.addLogEntry("error", message, context);
146
+ }
147
+ /**
148
+ * Finish and emit the wide event with HTTP context.
149
+ * Sets the response status and optional error before emitting.
150
+ * @example
151
+ * ```typescript
152
+ * ev.finish({ status: 200 });
153
+ * ev.finish({ status: 500, error: new Error("DB timeout") });
154
+ * ```
155
+ * @param options Status code and/or error
156
+ */
157
+ finish(options) {
158
+ if (options?.status !== void 0) {
159
+ this.status = options.status;
160
+ }
161
+ if (options?.error) {
162
+ this.attachedError = options.error;
163
+ }
164
+ this.emit();
165
+ }
166
+ /**
167
+ * Get a read-only snapshot of the accumulated data.
168
+ */
169
+ getData() {
170
+ return this.data;
171
+ }
172
+ /**
173
+ * Get the current severity level of the event.
174
+ * The level auto-escalates as `warn()` or `error()` entries are added.
175
+ */
176
+ getLevel() {
177
+ return this.attachedError ? "error" : this.level;
178
+ }
179
+ /**
180
+ * Get a read-only copy of the request lifecycle log entries.
181
+ */
182
+ getRequestLogs() {
183
+ return this.requestLogs;
184
+ }
185
+ /**
186
+ * Record an info-level lifecycle log entry.
187
+ * Does not escalate the event level.
188
+ * @param message Description of what happened
189
+ * @param context Optional structured context
190
+ * @returns `this` for chaining
191
+ */
192
+ info(message, context) {
193
+ return this.addLogEntry("info", message, context);
194
+ }
195
+ /**
196
+ * Accumulate context into the wide event via deep merge.
197
+ * Call as many times as needed throughout the operation.
198
+ * @example
199
+ * ```typescript
200
+ * ev.set({ user: { id: 1 } });
201
+ * ev.set({ user: { plan: "pro" } });
202
+ * // data = { user: { id: 1, plan: "pro" } }
203
+ * ```
204
+ * @param data Partial data to merge into the event
205
+ * @returns `this` for chaining
206
+ */
207
+ set(data) {
208
+ this.data = deepMerge(this.data, data);
209
+ return this;
210
+ }
211
+ /**
212
+ * Attach an error to the event. Automatically escalates the event
213
+ * level to "error".
214
+ * @param error The error to attach
215
+ * @returns `this` for chaining
216
+ */
217
+ setError(error) {
218
+ this.attachedError = error;
219
+ return this;
220
+ }
221
+ /**
222
+ * Set the HTTP response status code.
223
+ * @param status HTTP status code
224
+ * @returns `this` for chaining
225
+ */
226
+ setStatus(status) {
227
+ this.status = status;
228
+ return this;
229
+ }
230
+ /**
231
+ * Record a warn-level lifecycle log entry.
232
+ * Escalates the event level to "warn" (unless already "error").
233
+ * @param message Description of the warning
234
+ * @param context Optional structured context
235
+ * @returns `this` for chaining
236
+ */
237
+ warn(message, context) {
238
+ return this.addLogEntry("warn", message, context);
239
+ }
240
+ /**
241
+ * Disposable implementation. Auto-emits the event if `autoEmit` is true
242
+ * and the event hasn't been manually emitted yet.
243
+ *
244
+ * Enables usage with TC39 Explicit Resource Management:
245
+ * ```typescript
246
+ * using ev = createWideEvent({ pail: logger, name: "api.checkout" });
247
+ * ev.set({ user: { id: 1 } });
248
+ * // auto-emits here when scope exits
249
+ * ```
250
+ */
251
+ [Symbol.dispose]() {
252
+ if (this.autoEmit && !this.emitted) {
253
+ this.emit();
254
+ }
255
+ }
256
+ /**
257
+ * Add an entry to the request lifecycle log and escalate level if needed.
258
+ */
259
+ addLogEntry(level, message, context) {
260
+ const entry = {
261
+ level,
262
+ message,
263
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
264
+ };
265
+ if (context) {
266
+ entry.context = context;
267
+ }
268
+ this.requestLogs.push(entry);
269
+ this.escalateLevel(level);
270
+ return this;
271
+ }
272
+ /**
273
+ * Escalate the event level if the new level has higher severity.
274
+ */
275
+ escalateLevel(level) {
276
+ if ((LEVEL_PRIORITY[level] ?? 0) > (LEVEL_PRIORITY[this.level] ?? 0)) {
277
+ this.level = level;
278
+ }
279
+ }
280
+ }
281
+ const createWideEvent = (options) => new WideEvent(options);
282
+
283
+ export { WideEvent, createWideEvent };