@visulima/pail 4.0.0-alpha.9 → 4.0.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 (145) hide show
  1. package/CHANGELOG.md +511 -0
  2. package/LICENSE.md +270 -166
  3. package/README.md +53 -24
  4. package/dist/error.d.ts +95 -96
  5. package/dist/error.js +5 -76
  6. package/dist/index.browser.d.ts +568 -47
  7. package/dist/index.browser.js +19 -1499
  8. package/dist/index.server.d.ts +749 -65
  9. package/dist/index.server.js +32 -3179
  10. package/dist/middleware/elysia.d.ts +66 -63
  11. package/dist/middleware/elysia.js +1 -70
  12. package/dist/middleware/express.d.ts +74 -71
  13. package/dist/middleware/express.js +1 -29
  14. package/dist/middleware/fastify.d.ts +70 -67
  15. package/dist/middleware/fastify.js +1 -46
  16. package/dist/middleware/hono.d.ts +75 -72
  17. package/dist/middleware/hono.js +1 -33
  18. package/dist/middleware/next/handler.d.ts +102 -34
  19. package/dist/middleware/next/handler.js +1 -53
  20. package/dist/middleware/sveltekit.d.ts +101 -98
  21. package/dist/middleware/sveltekit.js +1 -43
  22. package/dist/object-tree.d.ts +67 -70
  23. package/dist/object-tree.js +2 -89
  24. package/dist/packem_shared/AbstractJsonReporter-Bp_JCrMQ.js +1 -0
  25. package/dist/packem_shared/AbstractJsonReporter-w_bGGiD-.js +1 -0
  26. package/dist/packem_shared/JsonReporter-Sd_lJGS-.js +2 -0
  27. package/dist/packem_shared/JsonReporter-bmem9lcg.js +1 -0
  28. package/dist/packem_shared/PailError-CbU1Ogfa.js +5 -0
  29. package/dist/packem_shared/PrettyReporter-CcDdPQSt.js +44 -0
  30. package/dist/packem_shared/PrettyReporter-DsHfKOU7.js +5 -0
  31. package/dist/packem_shared/abstract-json-reporter.d-wfESoEa-.d.ts +62 -0
  32. package/dist/packem_shared/abstract-pretty-reporter-DrLBJ6ds.js +57 -0
  33. package/dist/packem_shared/addKnownErrorConstructor-C1OJTj2D-0FlJMfXz.js +25 -0
  34. package/dist/packem_shared/constants-DKfCaSUR.js +1 -0
  35. package/dist/packem_shared/constants-ep2nsfdy.js +1 -0
  36. package/dist/packem_shared/create-middleware-logger.d-B-JmQ1Sl.d.ts +47 -0
  37. package/dist/packem_shared/headers-DH0H2s8W.js +1 -0
  38. package/dist/packem_shared/index-Q1764hvO.js +1 -0
  39. package/dist/packem_shared/index.d-T71KjNAr.d.ts +16 -0
  40. package/dist/packem_shared/pailMiddleware-B5DJoBYl.js +1 -0
  41. package/dist/packem_shared/serializeError-C-NFvZ8_-D0CA_Qlx.js +1 -0
  42. package/dist/packem_shared/storage-DaXAlpiO.js +1 -0
  43. package/dist/packem_shared/types.d-Cz9S7jZh.d.ts +201 -0
  44. package/dist/packem_shared/types.d-bWnqHJKL.d.ts +211 -0
  45. package/dist/packem_shared/types.d-xxE3FOD3.d.ts +229 -0
  46. package/dist/packem_shared/useLogger-DB34CuU5.js +1 -0
  47. package/dist/packem_shared/wide-event.d-D3ATYpoK.d.ts +717 -0
  48. package/dist/packem_shared/write-console-log-based-on-level-BqjxV016.js +1 -0
  49. package/dist/packem_shared/write-stream-C7jxLxIT.js +1 -0
  50. package/dist/processor/caller/caller-processor.d.ts +50 -47
  51. package/dist/processor/caller/caller-processor.js +1 -59
  52. package/dist/processor/environment-processor.d.ts +114 -113
  53. package/dist/processor/environment-processor.js +1 -78
  54. package/dist/processor/message-formatter-processor.d.ts +59 -49
  55. package/dist/processor/message-formatter-processor.js +1 -713
  56. package/dist/processor/opentelemetry-processor.d.ts +70 -66
  57. package/dist/processor/opentelemetry-processor.js +1 -52
  58. package/dist/processor/redact-processor.d.ts +99 -41
  59. package/dist/processor/redact-processor.js +1 -30
  60. package/dist/processor/sampling-processor.d.ts +103 -101
  61. package/dist/processor/sampling-processor.js +1 -59
  62. package/dist/reporter/file/json-file-reporter.d.ts +109 -42
  63. package/dist/reporter/file/json-file-reporter.js +2 -136
  64. package/dist/reporter/http/abstract-http-reporter.d.ts +256 -211
  65. package/dist/reporter/http/abstract-http-reporter.js +2 -435
  66. package/dist/reporter/http/http-reporter.d.ts +41 -36
  67. package/dist/reporter/http/http-reporter.edge-light.d.ts +487 -39
  68. package/dist/reporter/http/http-reporter.edge-light.js +2 -733
  69. package/dist/reporter/http/http-reporter.js +1 -13
  70. package/dist/reporter/json/index.browser.d.ts +98 -3
  71. package/dist/reporter/json/index.browser.js +1 -2
  72. package/dist/reporter/json/index.d.ts +53 -3
  73. package/dist/reporter/json/index.js +1 -2
  74. package/dist/reporter/pretty/index.browser.d.ts +105 -2
  75. package/dist/reporter/pretty/index.browser.js +1 -1
  76. package/dist/reporter/pretty/index.d.ts +270 -2
  77. package/dist/reporter/pretty/index.js +1 -1
  78. package/dist/reporter/simple/simple-reporter.server.d.ts +215 -18
  79. package/dist/reporter/simple/simple-reporter.server.js +8 -182
  80. package/dist/wide-event.d.ts +6 -300
  81. package/dist/wide-event.js +1 -281
  82. package/package.json +22 -37
  83. package/dist/constants.d.ts +0 -37
  84. package/dist/interactive/index.d.ts +0 -2
  85. package/dist/interactive/index.js +0 -2
  86. package/dist/interactive/interactive-manager.d.ts +0 -108
  87. package/dist/interactive/interactive-stream-hook.d.ts +0 -68
  88. package/dist/middleware/next/middleware.d.ts +0 -59
  89. package/dist/middleware/next/storage.d.ts +0 -14
  90. package/dist/middleware/shared/create-middleware-logger.d.ts +0 -82
  91. package/dist/middleware/shared/headers.d.ts +0 -14
  92. package/dist/middleware/shared/routes.d.ts +0 -30
  93. package/dist/middleware/shared/storage.d.ts +0 -29
  94. package/dist/packem_shared/AbstractJsonReporter-CGKHS8_M.js +0 -286
  95. package/dist/packem_shared/AbstractJsonReporter-DDjDkciI.js +0 -286
  96. package/dist/packem_shared/InteractiveManager-Cd6A14ZK.js +0 -172
  97. package/dist/packem_shared/InteractiveStreamHook-ePIURL_U.js +0 -133
  98. package/dist/packem_shared/JsonReporter-B3XX8GHN.js +0 -58
  99. package/dist/packem_shared/JsonReporter-p_BXg6Sj.js +0 -28
  100. package/dist/packem_shared/PrettyReporter-BYL3NrdA.js +0 -214
  101. package/dist/packem_shared/PrettyReporter-CvBn-hxP.js +0 -1459
  102. package/dist/packem_shared/Spinner-DIdVcfWq.js +0 -2183
  103. package/dist/packem_shared/abstract-pretty-reporter-jU8WL_6c.js +0 -2602
  104. package/dist/packem_shared/constants-B1RjD_ps.js +0 -99
  105. package/dist/packem_shared/constants-omsTHUWB.js +0 -119
  106. package/dist/packem_shared/createPailError-B11aRfrT.js +0 -76
  107. package/dist/packem_shared/getBarChar-BWj1UrH3.js +0 -404
  108. package/dist/packem_shared/headers-Cp4uLtr4.js +0 -123
  109. package/dist/packem_shared/index-DnkF86LQ.js +0 -658
  110. package/dist/packem_shared/index-frijFf5m.js +0 -1252
  111. package/dist/packem_shared/pailMiddleware-Ci88geIF.js +0 -24
  112. package/dist/packem_shared/storage-D0vqz8OX.js +0 -36
  113. package/dist/packem_shared/useLogger-D0rU3lcX.js +0 -33
  114. package/dist/packem_shared/write-console-log-based-on-level-DBmRYXpj.js +0 -14
  115. package/dist/packem_shared/write-stream-BG8fhcs3.js +0 -6
  116. package/dist/pail.browser.d.ts +0 -412
  117. package/dist/pail.server.d.ts +0 -233
  118. package/dist/processor/caller/get-caller-filename.d.ts +0 -23
  119. package/dist/progress-bar.d.ts +0 -136
  120. package/dist/progress-bar.js +0 -404
  121. package/dist/reporter/file/utils/rotating-file-stream.d.ts +0 -48
  122. package/dist/reporter/http/utils/compression.d.ts +0 -7
  123. package/dist/reporter/http/utils/log-size-error.d.ts +0 -30
  124. package/dist/reporter/http/utils/retry.d.ts +0 -27
  125. package/dist/reporter/json/abstract-json-reporter.d.ts +0 -61
  126. package/dist/reporter/json/json-reporter.browser.d.ts +0 -40
  127. package/dist/reporter/json/json-reporter.server.d.ts +0 -50
  128. package/dist/reporter/pretty/abstract-pretty-reporter.d.ts +0 -83
  129. package/dist/reporter/pretty/pretty-reporter.browser.d.ts +0 -36
  130. package/dist/reporter/pretty/pretty-reporter.server.d.ts +0 -70
  131. package/dist/reporter/raw/raw-reporter.browser.d.ts +0 -5
  132. package/dist/reporter/raw/raw-reporter.server.d.ts +0 -13
  133. package/dist/reporter/utils/default-inspector-config.d.ts +0 -3
  134. package/dist/reporter/utils/format-label.d.ts +0 -3
  135. package/dist/spinner.d.ts +0 -220
  136. package/dist/spinner.js +0 -2183
  137. package/dist/types.d.ts +0 -241
  138. package/dist/utils/ansi-escapes.d.ts +0 -4
  139. package/dist/utils/arrayify.d.ts +0 -2
  140. package/dist/utils/get-longest-badge.d.ts +0 -4
  141. package/dist/utils/get-longest-label.d.ts +0 -4
  142. package/dist/utils/merge-types.d.ts +0 -4
  143. package/dist/utils/stream/safe-stream-handler.d.ts +0 -21
  144. package/dist/utils/write-console-log-based-on-level.d.ts +0 -4
  145. package/dist/utils/write-stream.d.ts +0 -2
@@ -1,3179 +1,32 @@
1
- import { createRequire as __cjs_createRequire } from "node:module";
2
-
3
- const __cjs_require = __cjs_createRequire(import.meta.url);
4
-
5
- const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
-
7
- const __cjs_getBuiltinModule = (module) => {
8
- // Check if we're in Node.js and version supports getBuiltinModule
9
- if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
- const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
- // Node.js 20.16.0+ and 22.3.0+
12
- if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
- return __cjs_getProcess.getBuiltinModule(module);
14
- }
15
- }
16
- // Fallback to createRequire
17
- return __cjs_require(module);
18
- };
19
-
20
- const {
21
- stdout,
22
- stderr,
23
- env
24
- } = __cjs_getProcess;
25
- import { t as terminalSize, w as wordWrap, W as WrapMode, g as getLongestLabel, E as EXTENDED_RFC_5424_LOG_LEVELS, a as EMPTY_SYMBOL, L as LOG_TYPES, i as inspect, b as writeStream, A as AbstractPrettyReporter, d as defaultInspectorConfig, c as getLongestBadge, e as getStringWidth, f as formatLabel, r as renderError } from './packem_shared/abstract-pretty-reporter-jU8WL_6c.js';
26
- const {
27
- StringDecoder
28
- } = __cjs_getBuiltinModule("node:string_decoder");
29
- import { ProgressBar, applyStyleToOptions, MultiProgressBar } from './packem_shared/getBarChar-BWj1UrH3.js';
30
- export { getBarChar } from './packem_shared/getBarChar-BWj1UrH3.js';
31
- import { Spinner, MultiSpinner } from './packem_shared/Spinner-DIdVcfWq.js';
32
- import colorize, { red, greenBright, cyan, green, grey, bgGrey, underline, white } from '@visulima/colorize';
33
- export { PailError, createPailError } from './packem_shared/createPailError-B11aRfrT.js';
34
-
35
- class InteractiveManager {
36
- #stream;
37
- #isActive = false;
38
- #isSuspended = false;
39
- #lastLength = 0;
40
- #outside = 0;
41
- /**
42
- * Creates a new InteractiveManager with the given stream hooks.
43
- * @param stdout Hook for stdout stream
44
- * @param stderr Hook for stderr stream
45
- */
46
- constructor(stdout, stderr) {
47
- this.#stream = {
48
- stderr,
49
- stdout
50
- };
51
- }
52
- /**
53
- * Last printed rows count.
54
- *
55
- * Tracks the number of rows that were last written to the terminal.
56
- * Used internally for managing cursor positioning and output updates.
57
- */
58
- get lastLength() {
59
- return this.#lastLength;
60
- }
61
- /**
62
- * Rows count outside editable area.
63
- *
64
- * Tracks the number of rows that extend beyond the current terminal height.
65
- * Used for managing scrolling and ensuring all output remains visible.
66
- */
67
- get outside() {
68
- return this.#outside;
69
- }
70
- /**
71
- * Hook activity status.
72
- *
73
- * Indicates whether the interactive hooks are currently active.
74
- * When true, streams are being intercepted for interactive output.
75
- */
76
- get isHooked() {
77
- return this.#isActive;
78
- }
79
- /**
80
- * Suspend status for active hooks.
81
- *
82
- * Indicates whether interactive mode is temporarily suspended.
83
- * When suspended, external output can be written without interference.
84
- */
85
- get isSuspended() {
86
- return this.#isSuspended;
87
- }
88
- /**
89
- * Removes lines from the terminal output.
90
- *
91
- * Erases the specified number of lines from the bottom of the output,
92
- * moving the cursor up and clearing the lines. Useful for removing
93
- * previous interactive output before displaying new content.
94
- * @param stream The stream to erase lines from ("stdout" or "stderr")
95
- * @param count Number of lines to remove (defaults to lastLength)
96
- * @throws {TypeError} If the specified stream is not available
97
- */
98
- erase(stream, count = this.#lastLength) {
99
- if (this.#stream[stream] === void 0) {
100
- throw new TypeError(`Stream "${stream}" is not available`);
101
- }
102
- this.#stream[stream].erase(count);
103
- }
104
- /**
105
- * Hook stdout and stderr streams.
106
- * @returns Success status
107
- */
108
- hook() {
109
- if (!this.#isActive) {
110
- Object.values(this.#stream).forEach((hook) => hook.active());
111
- this.#clear(true);
112
- }
113
- return this.#isActive;
114
- }
115
- /**
116
- * Resume suspend hooks.
117
- * @param stream Stream to resume
118
- * @param eraseRowCount erase output rows count
119
- */
120
- resume(stream, eraseRowCount) {
121
- if (this.#isSuspended) {
122
- this.#isSuspended = false;
123
- if (eraseRowCount) {
124
- this.erase(stream, eraseRowCount);
125
- }
126
- this.#lastLength = 0;
127
- Object.values(this.#stream).forEach((hook) => hook.active());
128
- }
129
- }
130
- /**
131
- * Suspend active hooks for external output.
132
- * @param stream Stream to suspend
133
- * @param erase erase output
134
- */
135
- suspend(stream, erase = true) {
136
- if (!this.#isSuspended) {
137
- this.#isSuspended = true;
138
- if (erase) {
139
- this.erase(stream);
140
- }
141
- Object.values(this.#stream).forEach((hook) => hook.renew());
142
- }
143
- }
144
- /**
145
- * Unhooks both stdout and stderr streams and print their story of logs.
146
- * @param separateHistory If `true`, will add an empty line to the history output for individual recorded lines and console logs
147
- * @returns Success status
148
- */
149
- unhook(separateHistory = true) {
150
- if (this.#isActive) {
151
- Object.values(this.#stream).forEach((hook) => hook.inactive(separateHistory));
152
- this.#clear();
153
- }
154
- return !this.#isActive;
155
- }
156
- /**
157
- * Update output.
158
- * @param stream Stream to write to
159
- * @param rows Text lines to write to standard output
160
- * @param from Index of the line starting from which the contents of the terminal are being overwritten
161
- */
162
- update(stream, rows, from = 0) {
163
- if (rows.length > 0) {
164
- if (this.#stream[stream] === void 0) {
165
- throw new TypeError(`Stream "${stream}" is not available`);
166
- }
167
- const hook = this.#stream[stream];
168
- const { columns: width, rows: height } = terminalSize();
169
- const position = from > height ? height - 1 : Math.max(0, Math.min(height - 1, from));
170
- const actualLength = this.lastLength - position;
171
- const outside = Math.max(actualLength - height, this.outside);
172
- let output = rows.reduce(
173
- (accumulator, row) => [
174
- ...accumulator,
175
- wordWrap(row, {
176
- trim: false,
177
- width,
178
- wrapMode: WrapMode.STRICT_WIDTH
179
- })
180
- ],
181
- []
182
- );
183
- if (height <= actualLength) {
184
- hook.erase(height);
185
- if (position < outside) {
186
- output = output.slice(outside - position + 1);
187
- }
188
- } else if (actualLength) {
189
- hook.erase(actualLength);
190
- }
191
- hook.write(`${output.join("\n")}
192
- `);
193
- this.#lastLength = outside ? outside + output.length + 1 : output.length;
194
- this.#outside = Math.max(this.lastLength - height, this.outside);
195
- }
196
- }
197
- #clear(status = false) {
198
- this.#isActive = status;
199
- this.#lastLength = 0;
200
- this.#outside = 0;
201
- }
202
- }
203
-
204
- const ESC = "\x1B[";
205
- const eraseScreen = `${ESC}2J`;
206
- const eraseLine = `${ESC}2K`;
207
- const cursorLeft = `${ESC}G`;
208
- const cursorUp = (count = 1) => `${ESC + count}A`;
209
- const clearTerminal = process.platform === "win32" ? `${eraseScreen}${ESC}0f` : (
210
- // 1. Erases the screen (Only done in case `2` is not supported)
211
- // 2. Erases the whole screen including scrollback buffer
212
- // 3. Moves cursor to the top-left position
213
- // More info: https://www.real-world-systems.com/docs/ANSIcode.html
214
- `${eraseScreen}${ESC}3J${ESC}H`
215
- );
216
- const cursorHide = `${ESC}?25l`;
217
- const cursorShow = `${ESC}?25h`;
218
- const eraseLines = (count) => {
219
- let clear = "";
220
- for (let index = 0; index < count; index++) {
221
- clear += eraseLine + (index < count - 1 ? cursorUp() : "");
222
- }
223
- if (count) {
224
- clear += cursorLeft;
225
- }
226
- return clear;
227
- };
228
-
229
- class InteractiveStreamHook {
230
- /** Constant indicating the stream write operation was successful */
231
- static DRAIN = true;
232
- #decoder = new StringDecoder();
233
- #history = [];
234
- #method;
235
- #stream;
236
- /**
237
- * Creates a new InteractiveStreamHook for the given stream.
238
- * @param stream The Node.js WriteStream to hook into (usually stdout or stderr)
239
- */
240
- constructor(stream) {
241
- this.#method = stream.write;
242
- this.#stream = stream;
243
- }
244
- /**
245
- * Activates the stream hook.
246
- *
247
- * When active, all writes to the stream are captured in history instead of
248
- * being written immediately. This allows for interactive features like
249
- * progress bars that can update dynamically.
250
- */
251
- active() {
252
- this.write(cursorHide);
253
- this.#stream.write = (data, ...arguments_) => {
254
- const callback = arguments_.at(-1);
255
- this.#history.push(
256
- // prettier-ignore
257
- this.#decoder.write(
258
- typeof data === "string" ? Buffer.from(data, typeof arguments_[0] === "string" ? arguments_[0] : void 0) : Buffer.from(data)
259
- )
260
- );
261
- if (typeof callback === "function") {
262
- callback();
263
- }
264
- return InteractiveStreamHook.DRAIN;
265
- };
266
- }
267
- /**
268
- * Erases the specified number of lines from the terminal.
269
- *
270
- * Uses ANSI escape sequences to remove lines from the current cursor position
271
- * upwards, which is useful for clearing previous output in interactive applications.
272
- * @param count Number of lines to erase (including the current line)
273
- */
274
- erase(count) {
275
- if (count > 0) {
276
- this.write(eraseLines(count + 1));
277
- }
278
- }
279
- /**
280
- * Deactivates the stream hook and replays captured output.
281
- *
282
- * Restores normal stream operation and outputs all captured history.
283
- * Optionally adds a newline separator before replaying the history.
284
- * @param separateHistory Whether to add a newline before replaying history
285
- */
286
- inactive(separateHistory = false) {
287
- if (this.#history.length > 0) {
288
- if (separateHistory) {
289
- this.write("\n");
290
- }
291
- this.#history.forEach((element) => {
292
- this.write(element);
293
- });
294
- this.#history = [];
295
- }
296
- this.renew();
297
- }
298
- /**
299
- * Renews the stream hook state.
300
- *
301
- * Restores the original stream write method and shows the cursor.
302
- * This is typically called when temporarily suspending interactive mode.
303
- */
304
- renew() {
305
- this.#stream.write = this.#method;
306
- this.write(cursorShow);
307
- }
308
- /**
309
- * Writes a message directly to the underlying stream.
310
- *
311
- * Bypasses the hook mechanism and writes directly using the original
312
- * stream write method. Useful for writing control sequences or
313
- * messages that should not be captured in history.
314
- * @param message The message to write to the stream
315
- */
316
- write(message) {
317
- this.#method.apply(this.#stream, [message]);
318
- }
319
- }
320
-
321
- function getDefaultExportFromCjs(x) {
322
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
323
- }
324
-
325
- var safeStableStringify = {exports: {}};
326
-
327
- var hasRequiredSafeStableStringify;
328
-
329
- function requireSafeStableStringify () {
330
- if (hasRequiredSafeStableStringify) return safeStableStringify.exports;
331
- hasRequiredSafeStableStringify = 1;
332
- (function (module, exports$1) {
333
- const { hasOwnProperty } = Object.prototype;
334
- const stringify = configure();
335
- stringify.configure = configure;
336
- stringify.stringify = stringify;
337
- stringify.default = stringify;
338
- exports$1.stringify = stringify;
339
- exports$1.configure = configure;
340
- module.exports = stringify;
341
- const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;
342
- function strEscape(str) {
343
- if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) {
344
- return `"${str}"`;
345
- }
346
- return JSON.stringify(str);
347
- }
348
- function sort(array, comparator) {
349
- if (array.length > 200 || comparator) {
350
- return array.sort(comparator);
351
- }
352
- for (let i = 1; i < array.length; i++) {
353
- const currentValue = array[i];
354
- let position = i;
355
- while (position !== 0 && array[position - 1] > currentValue) {
356
- array[position] = array[position - 1];
357
- position--;
358
- }
359
- array[position] = currentValue;
360
- }
361
- return array;
362
- }
363
- const typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor(
364
- Object.getPrototypeOf(
365
- Object.getPrototypeOf(
366
- new Int8Array()
367
- )
368
- ),
369
- Symbol.toStringTag
370
- ).get;
371
- function isTypedArrayWithEntries(value) {
372
- return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0;
373
- }
374
- function stringifyTypedArray(array, separator, maximumBreadth) {
375
- if (array.length < maximumBreadth) {
376
- maximumBreadth = array.length;
377
- }
378
- const whitespace = separator === "," ? "" : " ";
379
- let res = `"0":${whitespace}${array[0]}`;
380
- for (let i = 1; i < maximumBreadth; i++) {
381
- res += `${separator}"${i}":${whitespace}${array[i]}`;
382
- }
383
- return res;
384
- }
385
- function getCircularValueOption(options) {
386
- if (hasOwnProperty.call(options, "circularValue")) {
387
- const circularValue = options.circularValue;
388
- if (typeof circularValue === "string") {
389
- return `"${circularValue}"`;
390
- }
391
- if (circularValue == null) {
392
- return circularValue;
393
- }
394
- if (circularValue === Error || circularValue === TypeError) {
395
- return {
396
- toString() {
397
- throw new TypeError("Converting circular structure to JSON");
398
- }
399
- };
400
- }
401
- throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined');
402
- }
403
- return '"[Circular]"';
404
- }
405
- function getDeterministicOption(options) {
406
- let value;
407
- if (hasOwnProperty.call(options, "deterministic")) {
408
- value = options.deterministic;
409
- if (typeof value !== "boolean" && typeof value !== "function") {
410
- throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');
411
- }
412
- }
413
- return value === void 0 ? true : value;
414
- }
415
- function getBooleanOption(options, key) {
416
- let value;
417
- if (hasOwnProperty.call(options, key)) {
418
- value = options[key];
419
- if (typeof value !== "boolean") {
420
- throw new TypeError(`The "${key}" argument must be of type boolean`);
421
- }
422
- }
423
- return value === void 0 ? true : value;
424
- }
425
- function getPositiveIntegerOption(options, key) {
426
- let value;
427
- if (hasOwnProperty.call(options, key)) {
428
- value = options[key];
429
- if (typeof value !== "number") {
430
- throw new TypeError(`The "${key}" argument must be of type number`);
431
- }
432
- if (!Number.isInteger(value)) {
433
- throw new TypeError(`The "${key}" argument must be an integer`);
434
- }
435
- if (value < 1) {
436
- throw new RangeError(`The "${key}" argument must be >= 1`);
437
- }
438
- }
439
- return value === void 0 ? Infinity : value;
440
- }
441
- function getItemCount(number) {
442
- if (number === 1) {
443
- return "1 item";
444
- }
445
- return `${number} items`;
446
- }
447
- function getUniqueReplacerSet(replacerArray) {
448
- const replacerSet = /* @__PURE__ */ new Set();
449
- for (const value of replacerArray) {
450
- if (typeof value === "string" || typeof value === "number") {
451
- replacerSet.add(String(value));
452
- }
453
- }
454
- return replacerSet;
455
- }
456
- function getStrictOption(options) {
457
- if (hasOwnProperty.call(options, "strict")) {
458
- const value = options.strict;
459
- if (typeof value !== "boolean") {
460
- throw new TypeError('The "strict" argument must be of type boolean');
461
- }
462
- if (value) {
463
- return (value2) => {
464
- let message = `Object can not safely be stringified. Received type ${typeof value2}`;
465
- if (typeof value2 !== "function") message += ` (${value2.toString()})`;
466
- throw new Error(message);
467
- };
468
- }
469
- }
470
- }
471
- function configure(options) {
472
- options = { ...options };
473
- const fail = getStrictOption(options);
474
- if (fail) {
475
- if (options.bigint === void 0) {
476
- options.bigint = false;
477
- }
478
- if (!("circularValue" in options)) {
479
- options.circularValue = Error;
480
- }
481
- }
482
- const circularValue = getCircularValueOption(options);
483
- const bigint = getBooleanOption(options, "bigint");
484
- const deterministic = getDeterministicOption(options);
485
- const comparator = typeof deterministic === "function" ? deterministic : void 0;
486
- const maximumDepth = getPositiveIntegerOption(options, "maximumDepth");
487
- const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth");
488
- function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) {
489
- let value = parent[key];
490
- if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
491
- value = value.toJSON(key);
492
- }
493
- value = replacer.call(parent, key, value);
494
- switch (typeof value) {
495
- case "string":
496
- return strEscape(value);
497
- case "object": {
498
- if (value === null) {
499
- return "null";
500
- }
501
- if (stack.indexOf(value) !== -1) {
502
- return circularValue;
503
- }
504
- let res = "";
505
- let join = ",";
506
- const originalIndentation = indentation;
507
- if (Array.isArray(value)) {
508
- if (value.length === 0) {
509
- return "[]";
510
- }
511
- if (maximumDepth < stack.length + 1) {
512
- return '"[Array]"';
513
- }
514
- stack.push(value);
515
- if (spacer !== "") {
516
- indentation += spacer;
517
- res += `
518
- ${indentation}`;
519
- join = `,
520
- ${indentation}`;
521
- }
522
- const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
523
- let i = 0;
524
- for (; i < maximumValuesToStringify - 1; i++) {
525
- const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
526
- res += tmp2 !== void 0 ? tmp2 : "null";
527
- res += join;
528
- }
529
- const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
530
- res += tmp !== void 0 ? tmp : "null";
531
- if (value.length - 1 > maximumBreadth) {
532
- const removedKeys = value.length - maximumBreadth - 1;
533
- res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
534
- }
535
- if (spacer !== "") {
536
- res += `
537
- ${originalIndentation}`;
538
- }
539
- stack.pop();
540
- return `[${res}]`;
541
- }
542
- let keys = Object.keys(value);
543
- const keyLength = keys.length;
544
- if (keyLength === 0) {
545
- return "{}";
546
- }
547
- if (maximumDepth < stack.length + 1) {
548
- return '"[Object]"';
549
- }
550
- let whitespace = "";
551
- let separator = "";
552
- if (spacer !== "") {
553
- indentation += spacer;
554
- join = `,
555
- ${indentation}`;
556
- whitespace = " ";
557
- }
558
- const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
559
- if (deterministic && !isTypedArrayWithEntries(value)) {
560
- keys = sort(keys, comparator);
561
- }
562
- stack.push(value);
563
- for (let i = 0; i < maximumPropertiesToStringify; i++) {
564
- const key2 = keys[i];
565
- const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation);
566
- if (tmp !== void 0) {
567
- res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
568
- separator = join;
569
- }
570
- }
571
- if (keyLength > maximumBreadth) {
572
- const removedKeys = keyLength - maximumBreadth;
573
- res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
574
- separator = join;
575
- }
576
- if (spacer !== "" && separator.length > 1) {
577
- res = `
578
- ${indentation}${res}
579
- ${originalIndentation}`;
580
- }
581
- stack.pop();
582
- return `{${res}}`;
583
- }
584
- case "number":
585
- return isFinite(value) ? String(value) : fail ? fail(value) : "null";
586
- case "boolean":
587
- return value === true ? "true" : "false";
588
- case "undefined":
589
- return void 0;
590
- case "bigint":
591
- if (bigint) {
592
- return String(value);
593
- }
594
- // fallthrough
595
- default:
596
- return fail ? fail(value) : void 0;
597
- }
598
- }
599
- function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) {
600
- if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
601
- value = value.toJSON(key);
602
- }
603
- switch (typeof value) {
604
- case "string":
605
- return strEscape(value);
606
- case "object": {
607
- if (value === null) {
608
- return "null";
609
- }
610
- if (stack.indexOf(value) !== -1) {
611
- return circularValue;
612
- }
613
- const originalIndentation = indentation;
614
- let res = "";
615
- let join = ",";
616
- if (Array.isArray(value)) {
617
- if (value.length === 0) {
618
- return "[]";
619
- }
620
- if (maximumDepth < stack.length + 1) {
621
- return '"[Array]"';
622
- }
623
- stack.push(value);
624
- if (spacer !== "") {
625
- indentation += spacer;
626
- res += `
627
- ${indentation}`;
628
- join = `,
629
- ${indentation}`;
630
- }
631
- const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
632
- let i = 0;
633
- for (; i < maximumValuesToStringify - 1; i++) {
634
- const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
635
- res += tmp2 !== void 0 ? tmp2 : "null";
636
- res += join;
637
- }
638
- const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
639
- res += tmp !== void 0 ? tmp : "null";
640
- if (value.length - 1 > maximumBreadth) {
641
- const removedKeys = value.length - maximumBreadth - 1;
642
- res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
643
- }
644
- if (spacer !== "") {
645
- res += `
646
- ${originalIndentation}`;
647
- }
648
- stack.pop();
649
- return `[${res}]`;
650
- }
651
- stack.push(value);
652
- let whitespace = "";
653
- if (spacer !== "") {
654
- indentation += spacer;
655
- join = `,
656
- ${indentation}`;
657
- whitespace = " ";
658
- }
659
- let separator = "";
660
- for (const key2 of replacer) {
661
- const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation);
662
- if (tmp !== void 0) {
663
- res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
664
- separator = join;
665
- }
666
- }
667
- if (spacer !== "" && separator.length > 1) {
668
- res = `
669
- ${indentation}${res}
670
- ${originalIndentation}`;
671
- }
672
- stack.pop();
673
- return `{${res}}`;
674
- }
675
- case "number":
676
- return isFinite(value) ? String(value) : fail ? fail(value) : "null";
677
- case "boolean":
678
- return value === true ? "true" : "false";
679
- case "undefined":
680
- return void 0;
681
- case "bigint":
682
- if (bigint) {
683
- return String(value);
684
- }
685
- // fallthrough
686
- default:
687
- return fail ? fail(value) : void 0;
688
- }
689
- }
690
- function stringifyIndent(key, value, stack, spacer, indentation) {
691
- switch (typeof value) {
692
- case "string":
693
- return strEscape(value);
694
- case "object": {
695
- if (value === null) {
696
- return "null";
697
- }
698
- if (typeof value.toJSON === "function") {
699
- value = value.toJSON(key);
700
- if (typeof value !== "object") {
701
- return stringifyIndent(key, value, stack, spacer, indentation);
702
- }
703
- if (value === null) {
704
- return "null";
705
- }
706
- }
707
- if (stack.indexOf(value) !== -1) {
708
- return circularValue;
709
- }
710
- const originalIndentation = indentation;
711
- if (Array.isArray(value)) {
712
- if (value.length === 0) {
713
- return "[]";
714
- }
715
- if (maximumDepth < stack.length + 1) {
716
- return '"[Array]"';
717
- }
718
- stack.push(value);
719
- indentation += spacer;
720
- let res2 = `
721
- ${indentation}`;
722
- const join2 = `,
723
- ${indentation}`;
724
- const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
725
- let i = 0;
726
- for (; i < maximumValuesToStringify - 1; i++) {
727
- const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
728
- res2 += tmp2 !== void 0 ? tmp2 : "null";
729
- res2 += join2;
730
- }
731
- const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
732
- res2 += tmp !== void 0 ? tmp : "null";
733
- if (value.length - 1 > maximumBreadth) {
734
- const removedKeys = value.length - maximumBreadth - 1;
735
- res2 += `${join2}"... ${getItemCount(removedKeys)} not stringified"`;
736
- }
737
- res2 += `
738
- ${originalIndentation}`;
739
- stack.pop();
740
- return `[${res2}]`;
741
- }
742
- let keys = Object.keys(value);
743
- const keyLength = keys.length;
744
- if (keyLength === 0) {
745
- return "{}";
746
- }
747
- if (maximumDepth < stack.length + 1) {
748
- return '"[Object]"';
749
- }
750
- indentation += spacer;
751
- const join = `,
752
- ${indentation}`;
753
- let res = "";
754
- let separator = "";
755
- let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
756
- if (isTypedArrayWithEntries(value)) {
757
- res += stringifyTypedArray(value, join, maximumBreadth);
758
- keys = keys.slice(value.length);
759
- maximumPropertiesToStringify -= value.length;
760
- separator = join;
761
- }
762
- if (deterministic) {
763
- keys = sort(keys, comparator);
764
- }
765
- stack.push(value);
766
- for (let i = 0; i < maximumPropertiesToStringify; i++) {
767
- const key2 = keys[i];
768
- const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation);
769
- if (tmp !== void 0) {
770
- res += `${separator}${strEscape(key2)}: ${tmp}`;
771
- separator = join;
772
- }
773
- }
774
- if (keyLength > maximumBreadth) {
775
- const removedKeys = keyLength - maximumBreadth;
776
- res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
777
- separator = join;
778
- }
779
- if (separator !== "") {
780
- res = `
781
- ${indentation}${res}
782
- ${originalIndentation}`;
783
- }
784
- stack.pop();
785
- return `{${res}}`;
786
- }
787
- case "number":
788
- return isFinite(value) ? String(value) : fail ? fail(value) : "null";
789
- case "boolean":
790
- return value === true ? "true" : "false";
791
- case "undefined":
792
- return void 0;
793
- case "bigint":
794
- if (bigint) {
795
- return String(value);
796
- }
797
- // fallthrough
798
- default:
799
- return fail ? fail(value) : void 0;
800
- }
801
- }
802
- function stringifySimple(key, value, stack) {
803
- switch (typeof value) {
804
- case "string":
805
- return strEscape(value);
806
- case "object": {
807
- if (value === null) {
808
- return "null";
809
- }
810
- if (typeof value.toJSON === "function") {
811
- value = value.toJSON(key);
812
- if (typeof value !== "object") {
813
- return stringifySimple(key, value, stack);
814
- }
815
- if (value === null) {
816
- return "null";
817
- }
818
- }
819
- if (stack.indexOf(value) !== -1) {
820
- return circularValue;
821
- }
822
- let res = "";
823
- const hasLength = value.length !== void 0;
824
- if (hasLength && Array.isArray(value)) {
825
- if (value.length === 0) {
826
- return "[]";
827
- }
828
- if (maximumDepth < stack.length + 1) {
829
- return '"[Array]"';
830
- }
831
- stack.push(value);
832
- const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
833
- let i = 0;
834
- for (; i < maximumValuesToStringify - 1; i++) {
835
- const tmp2 = stringifySimple(String(i), value[i], stack);
836
- res += tmp2 !== void 0 ? tmp2 : "null";
837
- res += ",";
838
- }
839
- const tmp = stringifySimple(String(i), value[i], stack);
840
- res += tmp !== void 0 ? tmp : "null";
841
- if (value.length - 1 > maximumBreadth) {
842
- const removedKeys = value.length - maximumBreadth - 1;
843
- res += `,"... ${getItemCount(removedKeys)} not stringified"`;
844
- }
845
- stack.pop();
846
- return `[${res}]`;
847
- }
848
- let keys = Object.keys(value);
849
- const keyLength = keys.length;
850
- if (keyLength === 0) {
851
- return "{}";
852
- }
853
- if (maximumDepth < stack.length + 1) {
854
- return '"[Object]"';
855
- }
856
- let separator = "";
857
- let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
858
- if (hasLength && isTypedArrayWithEntries(value)) {
859
- res += stringifyTypedArray(value, ",", maximumBreadth);
860
- keys = keys.slice(value.length);
861
- maximumPropertiesToStringify -= value.length;
862
- separator = ",";
863
- }
864
- if (deterministic) {
865
- keys = sort(keys, comparator);
866
- }
867
- stack.push(value);
868
- for (let i = 0; i < maximumPropertiesToStringify; i++) {
869
- const key2 = keys[i];
870
- const tmp = stringifySimple(key2, value[key2], stack);
871
- if (tmp !== void 0) {
872
- res += `${separator}${strEscape(key2)}:${tmp}`;
873
- separator = ",";
874
- }
875
- }
876
- if (keyLength > maximumBreadth) {
877
- const removedKeys = keyLength - maximumBreadth;
878
- res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`;
879
- }
880
- stack.pop();
881
- return `{${res}}`;
882
- }
883
- case "number":
884
- return isFinite(value) ? String(value) : fail ? fail(value) : "null";
885
- case "boolean":
886
- return value === true ? "true" : "false";
887
- case "undefined":
888
- return void 0;
889
- case "bigint":
890
- if (bigint) {
891
- return String(value);
892
- }
893
- // fallthrough
894
- default:
895
- return fail ? fail(value) : void 0;
896
- }
897
- }
898
- function stringify2(value, replacer, space) {
899
- if (arguments.length > 1) {
900
- let spacer = "";
901
- if (typeof space === "number") {
902
- spacer = " ".repeat(Math.min(space, 10));
903
- } else if (typeof space === "string") {
904
- spacer = space.slice(0, 10);
905
- }
906
- if (replacer != null) {
907
- if (typeof replacer === "function") {
908
- return stringifyFnReplacer("", { "": value }, [], replacer, spacer, "");
909
- }
910
- if (Array.isArray(replacer)) {
911
- return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, "");
912
- }
913
- }
914
- if (spacer.length !== 0) {
915
- return stringifyIndent("", value, [], spacer, "");
916
- }
917
- }
918
- return stringifySimple("", value, []);
919
- }
920
- return stringify2;
921
- }
922
- } (safeStableStringify, safeStableStringify.exports));
923
- return safeStableStringify.exports;
924
- }
925
-
926
- var safeStableStringifyExports = requireSafeStableStringify();
927
- const cjsModule = /*@__PURE__*/getDefaultExportFromCjs(safeStableStringifyExports);
928
-
929
- const configure = cjsModule.configure;
930
-
931
- const writeConsoleLogBasedOnLevel = (level) => {
932
- if (level === "error") {
933
- return console.__error ?? console.error;
934
- }
935
- if (level === "warn") {
936
- return console.__warn ?? console.warn;
937
- }
938
- if (level === "trace") {
939
- return console.__trace ?? console.trace;
940
- }
941
- return console.__log ?? console.log;
942
- };
943
-
944
- let RawReporter$1 = class RawReporter {
945
- // eslint-disable-next-line class-methods-use-this
946
- log(meta) {
947
- const { context = [], message, type } = meta;
948
- const consoleLogFunction = writeConsoleLogBasedOnLevel(type.level);
949
- consoleLogFunction(message, ...context);
950
- }
951
- };
952
-
953
- const arrayify = (x) => {
954
- if (x === void 0) {
955
- return [];
956
- }
957
- return Array.isArray(x) ? x : [x];
958
- };
959
-
960
- const mergeTypes = (standard, custom) => {
961
- const types = { ...standard };
962
- Object.keys(custom).forEach((type) => {
963
- types[type] = { ...types[type], ...custom[type] };
964
- });
965
- return types;
966
- };
967
-
968
- const preventLoop = (function_) => {
969
- let doing = false;
970
- return function(...args) {
971
- if (doing) {
972
- return void 0;
973
- }
974
- doing = true;
975
- try {
976
- const result = function_.apply(this, args);
977
- doing = false;
978
- return result;
979
- } catch (error) {
980
- doing = false;
981
- throw error;
982
- }
983
- };
984
- };
985
- class PailBrowserImpl {
986
- timersMap;
987
- countMap;
988
- seqTimers;
989
- lastLog;
990
- logLevels;
991
- disabled;
992
- paused;
993
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
994
- messageQueue;
995
- scopeName;
996
- types;
997
- longestLabel;
998
- processors;
999
- generalLogLevel;
1000
- reporters;
1001
- throttle;
1002
- throttleMin;
1003
- stringify;
1004
- groups;
1005
- startTimerMessage;
1006
- endTimerMessage;
1007
- rawReporter;
1008
- force = {};
1009
- /**
1010
- * Creates a new Pail browser logger instance.
1011
- *
1012
- * Initializes the logger with the provided configuration options,
1013
- * setting up reporters, processors, log levels, and other internal state.
1014
- * @param options Configuration options for the logger
1015
- */
1016
- constructor(options) {
1017
- this.throttle = options.throttle ?? 1e3;
1018
- this.throttleMin = options.throttleMin ?? 5;
1019
- const parentLongestLabel = options.parentLongestLabel;
1020
- const parentTypes = options.parentTypes;
1021
- const parentStringify = options.parentStringify;
1022
- const parentLogLevels = options.parentLogLevels;
1023
- this.stringify = parentStringify ?? configure({
1024
- strict: true
1025
- });
1026
- this.startTimerMessage = options.messages?.timerStart ?? "Initialized timer...";
1027
- this.endTimerMessage = options.messages?.timerEnd ?? "Timer run for:";
1028
- if (parentTypes && parentLongestLabel) {
1029
- this.types = parentTypes;
1030
- this.longestLabel = parentLongestLabel;
1031
- } else {
1032
- this.types = mergeTypes(LOG_TYPES, options.types ?? {});
1033
- this.longestLabel = getLongestLabel(this.types);
1034
- }
1035
- this.logLevels = parentLogLevels && !options.logLevels ? parentLogLevels : { ...EXTENDED_RFC_5424_LOG_LEVELS, ...options.logLevels };
1036
- this.generalLogLevel = this.#normalizeLogLevel(options.logLevel);
1037
- this.reporters = /* @__PURE__ */ new Set();
1038
- this.processors = /* @__PURE__ */ new Set();
1039
- this.disabled = options.disabled ?? false;
1040
- this.paused = false;
1041
- this.messageQueue = [];
1042
- this.scopeName = arrayify(options.scope).filter(Boolean);
1043
- this.timersMap = /* @__PURE__ */ new Map();
1044
- this.countMap = /* @__PURE__ */ new Map();
1045
- this.groups = [];
1046
- this.seqTimers = /* @__PURE__ */ new Set();
1047
- this.lastLog = {};
1048
- this.logger = preventLoop(this.logger).bind(this);
1049
- this.#initializeBoundMethods();
1050
- if (Array.isArray(options.reporters)) {
1051
- this.registerReporters(options.reporters);
1052
- }
1053
- this.rawReporter = this.extendReporter(options.rawReporter ?? new RawReporter$1());
1054
- if (Array.isArray(options.processors)) {
1055
- this.registerProcessors(options.processors);
1056
- }
1057
- }
1058
- /**
1059
- * Initializes bound methods for all logger types.
1060
- *
1061
- * Creates bound methods for both regular and force logging methods.
1062
- * This is separated to allow reuse when types haven't changed.
1063
- */
1064
- #initializeBoundMethods() {
1065
- for (const type in this.types) {
1066
- this[type] = this.logger.bind(this, type, false, false);
1067
- }
1068
- for (const type in this.types) {
1069
- this.force[type] = this.logger.bind(this, type, false, true);
1070
- }
1071
- }
1072
- /**
1073
- * Wraps the global console methods to redirect them through the logger.
1074
- *
1075
- * This method replaces console methods (log, info, warn, error, etc.) with
1076
- * calls to the corresponding logger methods. The original console methods
1077
- * are backed up and can be restored using restoreConsole().
1078
- * @example
1079
- * ```typescript
1080
- * const logger = createPail();
1081
- * logger.wrapConsole();
1082
- *
1083
- * console.log("This will go through the logger");
1084
- * console.error("This too!");
1085
- *
1086
- * logger.restoreConsole(); // Restore original console methods
1087
- * ```
1088
- */
1089
- wrapConsole() {
1090
- for (const type in this.types) {
1091
- if (!console[`__${type}`]) {
1092
- console[`__${type}`] = console[type];
1093
- }
1094
- console[type] = this[type];
1095
- }
1096
- }
1097
- /**
1098
- * Restores the original global console methods.
1099
- *
1100
- * This method restores the console methods that were backed up by wrapConsole().
1101
- * After calling this, console methods will work as they did before wrapping.
1102
- * @example
1103
- * ```typescript
1104
- * const logger = createPail();
1105
- * logger.wrapConsole();
1106
- *
1107
- * // Console methods are now wrapped
1108
- * logger.restoreConsole();
1109
- * // Console methods are restored to original behavior
1110
- * ```
1111
- */
1112
- restoreConsole() {
1113
- for (const type in this.types) {
1114
- if (console[`__${type}`]) {
1115
- console[type] = console[`__${type}`];
1116
- delete console[`__${type}`];
1117
- }
1118
- }
1119
- }
1120
- /**
1121
- * Wraps uncaught exception and unhandled rejection handlers.
1122
- *
1123
- * This method sets up global error handlers that will log uncaught exceptions
1124
- * and unhandled promise rejections through the logger. This is useful for
1125
- * capturing and logging application crashes.
1126
- * @example
1127
- * ```typescript
1128
- * const logger = createPail();
1129
- * logger.wrapException();
1130
- *
1131
- * // Now uncaught errors will be logged
1132
- * throw new Error("This will be logged");
1133
- * ```
1134
- */
1135
- wrapException() {
1136
- {
1137
- process.on("uncaughtException", (error) => {
1138
- this.error(error);
1139
- });
1140
- process.on("unhandledRejection", (error) => {
1141
- this.error(error);
1142
- });
1143
- }
1144
- }
1145
- /**
1146
- * Disables all logging output.
1147
- *
1148
- * When disabled, all log calls will be silently ignored and no output
1149
- * will be produced by any reporters. This can be useful for temporarily
1150
- * suppressing log output in production or during testing.
1151
- * @example
1152
- * ```typescript
1153
- * const logger = createPail();
1154
- * logger.disable();
1155
- * logger.info("This won't be logged"); // Silent
1156
- * logger.enable();
1157
- * logger.info("This will be logged"); // Output produced
1158
- * ```
1159
- */
1160
- disable() {
1161
- this.disabled = true;
1162
- }
1163
- /**
1164
- * Enables logging output.
1165
- *
1166
- * Re-enables logging after it has been disabled. All subsequent log calls
1167
- * will produce output according to the configured reporters.
1168
- * @example
1169
- * ```typescript
1170
- * const logger = createPail();
1171
- * logger.disable();
1172
- * logger.info("This won't be logged");
1173
- * logger.enable(); // Re-enable logging
1174
- * logger.info("This will be logged");
1175
- * ```
1176
- */
1177
- enable() {
1178
- this.disabled = false;
1179
- }
1180
- /**
1181
- * Checks if logging is currently enabled.
1182
- *
1183
- * Returns true if logging is enabled and false if it has been disabled.
1184
- * @returns True if logging is enabled, false if disabled
1185
- * @example
1186
- * ```typescript
1187
- * const logger = createPail();
1188
- * console.log(logger.isEnabled()); // true
1189
- * logger.disable();
1190
- * console.log(logger.isEnabled()); // false
1191
- * ```
1192
- */
1193
- isEnabled() {
1194
- return !this.disabled;
1195
- }
1196
- /**
1197
- * Pauses logging and starts queuing messages.
1198
- *
1199
- * When paused, all log calls will be queued instead of being output immediately.
1200
- * The queued messages will be processed when resume() is called. This is useful
1201
- * for temporarily buffering log output during critical operations.
1202
- * @example
1203
- * ```typescript
1204
- * const logger = createPail();
1205
- * logger.pause();
1206
- * logger.info("This will be queued"); // Queued, not output yet
1207
- * logger.warn("This too"); // Also queued
1208
- * logger.resume(); // Now both messages are output
1209
- * ```
1210
- */
1211
- pause() {
1212
- this.paused = true;
1213
- }
1214
- /**
1215
- * Resumes logging and flushes all queued messages.
1216
- *
1217
- * Processes all messages that were queued during the pause period and
1218
- * resumes normal logging behavior. Messages are output in the order
1219
- * they were originally called.
1220
- * @example
1221
- * ```typescript
1222
- * const logger = createPail();
1223
- * logger.pause();
1224
- * logger.info("Message 1"); // Queued
1225
- * logger.info("Message 2"); // Queued
1226
- * logger.resume(); // Both messages are now output in order
1227
- * logger.info("Message 3"); // Output immediately
1228
- * ```
1229
- */
1230
- resume() {
1231
- this.paused = false;
1232
- const queue = this.messageQueue.splice(0);
1233
- for (const { messageObject, raw, type } of queue) {
1234
- this.logger(type, raw, false, ...messageObject);
1235
- }
1236
- }
1237
- /**
1238
- * Creates a scoped logger instance.
1239
- *
1240
- * Returns a new logger instance that inherits all configuration but adds
1241
- * the specified scope names to all log messages. This is useful for
1242
- * categorizing logs by component, module, or feature.
1243
- * @template N - The new custom logger type names
1244
- * @param name Scope names to apply to all log messages
1245
- * @returns A new scoped logger instance
1246
- * @throws {Error} If no scope name is provided
1247
- * @example
1248
- * ```typescript
1249
- * const logger = createPail();
1250
- * const scopedLogger = logger.scope("auth", "login");
1251
- * scopedLogger.info("User logged in"); // Will include scope: ["auth", "login"]
1252
- * ```
1253
- */
1254
- scope(...name) {
1255
- if (name.length === 0) {
1256
- throw new Error("No scope name was defined.");
1257
- }
1258
- this.scopeName = name.flat();
1259
- return this;
1260
- }
1261
- /**
1262
- * Removes the current scope from the logger.
1263
- *
1264
- * Clears all scope names that were set by previous scope() calls.
1265
- * After calling this, log messages will no longer include scope information.
1266
- * @example
1267
- * ```typescript
1268
- * const logger = createPail();
1269
- * const scopedLogger = logger.scope("auth");
1270
- * scopedLogger.info("Scoped message"); // Has scope
1271
- * scopedLogger.unscope();
1272
- * scopedLogger.info("Unscoped message"); // No scope
1273
- * ```
1274
- */
1275
- unscope() {
1276
- this.scopeName = [];
1277
- }
1278
- /**
1279
- * Creates a child logger that inherits settings from the parent.
1280
- *
1281
- * Returns a new logger instance that inherits all configuration from the parent
1282
- * (reporters, processors, types, log levels, throttle settings, etc.) while allowing
1283
- * you to override only what you need. Child loggers are independent instances with
1284
- * their own state (timers, counters, etc.).
1285
- * @template N - The new custom logger type names
1286
- * @template LC - The new log level types
1287
- * @param options Configuration options to override or extend parent settings
1288
- * @returns A new child logger instance
1289
- * @example
1290
- * ```typescript
1291
- * const parent = createPail({
1292
- * logLevel: "info",
1293
- * types: { http: { label: "HTTP", logLevel: "info" } },
1294
- * reporters: [new PrettyReporter()],
1295
- * });
1296
- *
1297
- * // Child inherits parent settings but overrides log level
1298
- * const child = parent.child({ logLevel: "debug" });
1299
- * child.info("This will be logged"); // Uses debug level from child
1300
- * child.http("GET /api 200"); // Inherits http type from parent
1301
- *
1302
- * // Child can add new types
1303
- * const childWithNewType = parent.child({
1304
- * types: { db: { label: "DB", logLevel: "info" } },
1305
- * });
1306
- * childWithNewType.db("Query executed"); // New type available
1307
- * ```
1308
- */
1309
- // eslint-disable-next-line sonarjs/cognitive-complexity
1310
- child(options) {
1311
- const typesChanged = options?.types !== void 0 && options.types !== null;
1312
- const mergedTypes = typesChanged ? mergeTypes(this.types, options.types) : this.types;
1313
- const childReporters = options?.reporters ?? [];
1314
- const allReporters = childReporters.length > 0 ? [...this.reporters, ...childReporters] : [...this.reporters];
1315
- const childProcessors = options?.processors ?? [];
1316
- const allProcessors = childProcessors.length > 0 ? [...this.processors, ...childProcessors] : [...this.processors];
1317
- const mergedLogLevels = options?.logLevels ? { ...this.logLevels, ...options.logLevels } : this.logLevels;
1318
- let mergedScope;
1319
- if (options?.scope) {
1320
- const childScope = arrayify(options.scope).filter(Boolean);
1321
- mergedScope = this.scopeName.length > 0 ? [...this.scopeName, ...childScope] : childScope;
1322
- } else {
1323
- mergedScope = this.scopeName.length > 0 ? this.scopeName : [];
1324
- }
1325
- const mergedMessages = options?.messages ? {
1326
- timerEnd: this.endTimerMessage,
1327
- timerStart: this.startTimerMessage,
1328
- ...options.messages
1329
- } : {
1330
- timerEnd: this.endTimerMessage,
1331
- timerStart: this.startTimerMessage
1332
- };
1333
- const childOptions = {
1334
- disabled: options?.disabled ?? this.disabled,
1335
- logLevel: options?.logLevel ?? this.generalLogLevel,
1336
- logLevels: mergedLogLevels,
1337
- messages: mergedMessages,
1338
- processors: allProcessors,
1339
- rawReporter: options?.rawReporter ?? this.rawReporter,
1340
- reporters: allReporters,
1341
- scope: mergedScope,
1342
- throttle: options?.throttle ?? this.throttle,
1343
- throttleMin: options?.throttleMin ?? this.throttleMin
1344
- };
1345
- if (typesChanged) {
1346
- childOptions.parentTypes = mergedTypes;
1347
- childOptions.parentLongestLabel = getLongestLabel(mergedTypes);
1348
- } else {
1349
- childOptions.parentTypes = this.types;
1350
- childOptions.parentLongestLabel = this.longestLabel;
1351
- }
1352
- if (!options?.logLevels) {
1353
- childOptions.parentLogLevels = this.logLevels;
1354
- }
1355
- if (!options?.messages) {
1356
- childOptions.parentMessages = {
1357
- timerEnd: this.endTimerMessage,
1358
- timerStart: this.startTimerMessage
1359
- };
1360
- }
1361
- childOptions.parentStringify = this.stringify;
1362
- return new PailBrowserImpl(childOptions);
1363
- }
1364
- /**
1365
- * Starts a timer with the specified label.
1366
- *
1367
- * Records the current timestamp and associates it with the given label.
1368
- * Multiple timers can be active simultaneously with different labels.
1369
- * @param label The timer label (defaults to "default")
1370
- * @example
1371
- * ```typescript
1372
- * const logger = createPail();
1373
- * logger.time("operation");
1374
- * // ... some operation ...
1375
- * logger.timeEnd("operation"); // Logs: "Timer run for: X ms"
1376
- * ```
1377
- */
1378
- time(label = "default") {
1379
- if (this.seqTimers.has(label)) {
1380
- this.logger("warn", false, false, {
1381
- message: `Timer '${label}' already exists`,
1382
- prefix: label
1383
- });
1384
- } else {
1385
- this.seqTimers.add(label);
1386
- this.timersMap.set(label, Date.now());
1387
- this.logger("start", false, false, {
1388
- message: this.startTimerMessage,
1389
- prefix: label
1390
- });
1391
- }
1392
- }
1393
- /**
1394
- * Logs the current elapsed time for a timer without stopping it.
1395
- *
1396
- * Calculates and logs the time elapsed since the timer was started,
1397
- * but keeps the timer running. If no label is provided, uses the
1398
- * most recently started timer.
1399
- * @param label The timer label (uses last timer if not specified)
1400
- * @param data Additional data to include in the log message
1401
- * @example
1402
- * ```typescript
1403
- * const logger = createPail();
1404
- * logger.time("task");
1405
- * // ... some work ...
1406
- * logger.timeLog("task"); // Logs current elapsed time
1407
- * // ... more work ...
1408
- * logger.timeEnd("task"); // Logs final time and stops timer
1409
- * ```
1410
- */
1411
- timeLog(label, ...data) {
1412
- if (!label && this.seqTimers.size > 0) {
1413
- label = [...this.seqTimers].pop();
1414
- }
1415
- if (label && this.timersMap.has(label)) {
1416
- const span = Date.now() - this.timersMap.get(label);
1417
- this.logger("info", false, false, {
1418
- context: data,
1419
- message: span < 1e3 ? `${span} ms` : `${(span / 1e3).toFixed(2)} s`,
1420
- prefix: label
1421
- });
1422
- } else {
1423
- this.logger("warn", false, false, {
1424
- context: data,
1425
- message: "Timer not found",
1426
- prefix: label
1427
- });
1428
- }
1429
- }
1430
- /**
1431
- * Stops a timer and logs the final elapsed time.
1432
- *
1433
- * Calculates the total time elapsed since the timer was started,
1434
- * logs the result, and removes the timer. If no label is provided,
1435
- * uses the most recently started timer.
1436
- * @param label The timer label (uses last timer if not specified)
1437
- * @example
1438
- * ```typescript
1439
- * const logger = createPail();
1440
- * logger.time("operation");
1441
- * // ... perform operation ...
1442
- * logger.timeEnd("operation"); // Logs: "Timer run for: X ms"
1443
- * ```
1444
- */
1445
- timeEnd(label) {
1446
- if (!label && this.seqTimers.size > 0) {
1447
- label = [...this.seqTimers].pop();
1448
- }
1449
- if (label && this.timersMap.has(label)) {
1450
- const span = Date.now() - this.timersMap.get(label);
1451
- this.timersMap.delete(label);
1452
- this.logger("stop", false, false, {
1453
- message: `${this.endTimerMessage} ${span < 1e3 ? `${span} ms` : `${(span / 1e3).toFixed(2)} s`}`,
1454
- prefix: label
1455
- });
1456
- } else {
1457
- this.logger("warn", false, false, {
1458
- message: "Timer not found",
1459
- prefix: label
1460
- });
1461
- }
1462
- }
1463
- /**
1464
- * Starts a log group with the specified label.
1465
- *
1466
- * Groups related log messages together. In browser environments,
1467
- * this uses the native console.group() functionality. In other
1468
- * environments, it tracks group nesting internally.
1469
- * @param label The group label (defaults to "console.group")
1470
- * @example
1471
- * ```typescript
1472
- * const logger = createPail();
1473
- * logger.group("Database Operations");
1474
- * logger.info("Connecting to database");
1475
- * logger.info("Running migration");
1476
- * logger.groupEnd(); // End the group
1477
- * ```
1478
- */
1479
- group(label = "console.group") {
1480
- if (globalThis.window === void 0) {
1481
- this.groups.push(label);
1482
- } else {
1483
- console.group(label);
1484
- }
1485
- }
1486
- /**
1487
- * Ends the current log group.
1488
- *
1489
- * Closes the most recently opened log group. In browser environments,
1490
- * this uses the native console.groupEnd() functionality.
1491
- * @example
1492
- * ```typescript
1493
- * const logger = createPail();
1494
- * logger.group("Processing");
1495
- * logger.info("Step 1");
1496
- * logger.info("Step 2");
1497
- * logger.groupEnd(); // Closes the "Processing" group
1498
- * ```
1499
- */
1500
- groupEnd() {
1501
- if (globalThis.window === void 0) {
1502
- this.groups.pop();
1503
- } else {
1504
- console.groupEnd();
1505
- }
1506
- }
1507
- /**
1508
- * Increments and logs a counter with the specified label.
1509
- *
1510
- * Maintains an internal counter for each label and logs the current count
1511
- * each time it's called. Useful for tracking how many times certain
1512
- * code paths are executed.
1513
- * @param label The counter label (defaults to "default")
1514
- * @example
1515
- * ```typescript
1516
- * const logger = createPail();
1517
- * logger.count("requests"); // Logs: "requests: 1"
1518
- * logger.count("requests"); // Logs: "requests: 2"
1519
- * logger.count("errors"); // Logs: "errors: 1"
1520
- * ```
1521
- */
1522
- count(label = "default") {
1523
- const current = this.countMap.get(label) ?? 0;
1524
- this.countMap.set(label, current + 1);
1525
- this.logger("log", false, false, {
1526
- message: `${label}: ${current + 1}`,
1527
- prefix: label
1528
- });
1529
- }
1530
- /**
1531
- * Resets a counter to zero.
1532
- *
1533
- * Removes the counter with the specified label, effectively resetting
1534
- * it to zero. If the counter doesn't exist, logs a warning.
1535
- * @param label The counter label to reset (defaults to "default")
1536
- * @example
1537
- * ```typescript
1538
- * const logger = createPail();
1539
- * logger.count("requests"); // Logs: "requests: 1"
1540
- * logger.countReset("requests"); // Resets counter
1541
- * logger.count("requests"); // Logs: "requests: 1" (starts over)
1542
- * ```
1543
- */
1544
- countReset(label = "default") {
1545
- if (this.countMap.has(label)) {
1546
- this.countMap.delete(label);
1547
- } else {
1548
- this.logger("warn", false, false, {
1549
- message: `Count for ${label} does not exist`,
1550
- prefix: label
1551
- });
1552
- }
1553
- }
1554
- /**
1555
- * Clears the console output.
1556
- *
1557
- * Calls the native console.clear() method to clear all output from
1558
- * the console. This is a convenience method that wraps the native
1559
- * console.clear() functionality.
1560
- * @example
1561
- * ```typescript
1562
- * const logger = createPail();
1563
- * logger.info("Some message");
1564
- * logger.clear(); // Clears the console
1565
- * ```
1566
- */
1567
- // eslint-disable-next-line class-methods-use-this
1568
- clear() {
1569
- console.clear();
1570
- }
1571
- /**
1572
- * Logs a raw message bypassing normal processing.
1573
- *
1574
- * Sends a message directly to the raw reporter without going through
1575
- * the normal logging pipeline (processors, throttling, etc.). This is
1576
- * useful for logging that needs to bypass all formatting and processing.
1577
- * @param message The raw message to log
1578
- * @param arguments_ Additional arguments to include
1579
- * @example
1580
- * ```typescript
1581
- * const logger = createPail();
1582
- * logger.raw("Direct message", { data: "value" });
1583
- * ```
1584
- */
1585
- raw(message, ...arguments_) {
1586
- if (this.disabled) {
1587
- return;
1588
- }
1589
- this.logger("log", true, false, {
1590
- context: arguments_,
1591
- message
1592
- });
1593
- }
1594
- extendReporter(reporter) {
1595
- if (typeof reporter.setLoggerTypes === "function") {
1596
- reporter.setLoggerTypes(this.types);
1597
- }
1598
- if (typeof reporter.setStringify === "function") {
1599
- reporter.setStringify(this.stringify);
1600
- }
1601
- return reporter;
1602
- }
1603
- registerReporters(reporters) {
1604
- for (const reporter of reporters) {
1605
- this.reporters.add(this.extendReporter(reporter));
1606
- }
1607
- }
1608
- registerProcessors(processors) {
1609
- for (const processor of processors) {
1610
- if (typeof processor.setStringify === "function") {
1611
- processor.setStringify(this.stringify);
1612
- }
1613
- this.processors.add(processor);
1614
- }
1615
- }
1616
- #report(meta, raw) {
1617
- if (raw) {
1618
- this.rawReporter.log(Object.freeze(meta));
1619
- } else {
1620
- for (const reporter of this.reporters) {
1621
- reporter.log(Object.freeze(meta));
1622
- }
1623
- }
1624
- }
1625
- #normalizeLogLevel(level) {
1626
- return level && this.logLevels[level] ? level : "debug";
1627
- }
1628
- // eslint-disable-next-line sonarjs/cognitive-complexity
1629
- #buildMeta(typeName, type, ...arguments_) {
1630
- const meta = {
1631
- badge: void 0,
1632
- context: void 0,
1633
- error: void 0,
1634
- label: void 0,
1635
- message: EMPTY_SYMBOL,
1636
- prefix: void 0,
1637
- repeated: void 0,
1638
- scope: void 0,
1639
- suffix: void 0
1640
- };
1641
- meta.type = {
1642
- level: type.logLevel,
1643
- name: typeName
1644
- };
1645
- meta.groups = this.groups;
1646
- meta.scope = this.scopeName;
1647
- meta.date = /* @__PURE__ */ new Date();
1648
- if (arguments_.length > 0 && arguments_[0] instanceof Error) {
1649
- meta.error = arguments_[0];
1650
- if (arguments_.length > 1) {
1651
- meta.context = arguments_.slice(1);
1652
- }
1653
- } else if (arguments_.length > 0 && typeof arguments_[0] === "object" && arguments_[0] !== null && "message" in arguments_[0]) {
1654
- const { context, message, prefix, suffix } = arguments_[0];
1655
- if (context) {
1656
- meta.context = context;
1657
- }
1658
- if (prefix) {
1659
- meta.prefix = prefix;
1660
- }
1661
- if (suffix) {
1662
- meta.suffix = suffix;
1663
- }
1664
- meta.message = message;
1665
- if (arguments_.length > 1) {
1666
- const additionalContext = arguments_.slice(1);
1667
- if (meta.context) {
1668
- meta.context = Array.isArray(meta.context) ? [...meta.context, ...additionalContext] : [meta.context, ...additionalContext];
1669
- } else {
1670
- meta.context = additionalContext;
1671
- }
1672
- }
1673
- } else if (arguments_.length > 1) {
1674
- meta.message = arguments_[0];
1675
- meta.context = arguments_.slice(1);
1676
- } else if (arguments_.length === 1) {
1677
- meta.message = arguments_[0];
1678
- } else {
1679
- meta.message = void 0;
1680
- }
1681
- if (type.logLevel === "trace") {
1682
- meta.traceError = new Error("Trace");
1683
- }
1684
- if (type.badge) {
1685
- meta.badge = type.badge;
1686
- }
1687
- if (type.label) {
1688
- meta.label = type.label;
1689
- }
1690
- return meta;
1691
- }
1692
- // eslint-disable-next-line sonarjs/cognitive-complexity
1693
- logger(type, raw, force, ...messageObject) {
1694
- if (this.disabled) {
1695
- return;
1696
- }
1697
- if (this.paused) {
1698
- this.messageQueue.push({ messageObject, raw, type });
1699
- return;
1700
- }
1701
- const typeConfig = this.types[type];
1702
- if (!typeConfig) {
1703
- return;
1704
- }
1705
- const logLevel = this.#normalizeLogLevel(typeConfig.logLevel);
1706
- if (force || this.logLevels[logLevel] >= this.logLevels[this.generalLogLevel]) {
1707
- let meta = this.#buildMeta(type, typeConfig, ...messageObject);
1708
- const resolveLog = (newLog = false) => {
1709
- const repeated = (this.lastLog.count || 0) - this.throttleMin;
1710
- if (this.lastLog.object && repeated > 0) {
1711
- const lastMeta = { ...this.lastLog.object };
1712
- if (repeated > 1) {
1713
- lastMeta.repeated = repeated;
1714
- }
1715
- this.#report(lastMeta, raw);
1716
- this.lastLog.count = 1;
1717
- }
1718
- if (newLog) {
1719
- for (const processor of this.processors) {
1720
- meta = { ...processor.process(meta) };
1721
- }
1722
- this.lastLog.object = meta;
1723
- this.#report(meta, raw);
1724
- }
1725
- };
1726
- clearTimeout(this.lastLog.timeout);
1727
- const diffTime = this.lastLog.time && meta.date ? new Date(meta.date).getTime() - this.lastLog.time.getTime() : 0;
1728
- this.lastLog.time = new Date(meta.date);
1729
- if (diffTime < this.throttle) {
1730
- try {
1731
- const isSameLog = this.lastLog.object && JSON.stringify([meta.label, meta.scope, meta.type, meta.message, meta.prefix, meta.suffix, meta.context]) === JSON.stringify([
1732
- this.lastLog.object.label,
1733
- this.lastLog.object.scope,
1734
- this.lastLog.object.type,
1735
- this.lastLog.object.message,
1736
- this.lastLog.object.prefix,
1737
- this.lastLog.object.suffix,
1738
- this.lastLog.object.context
1739
- ]);
1740
- if (isSameLog) {
1741
- this.lastLog.count = (this.lastLog.count || 0) + 1;
1742
- if (this.lastLog.count > this.throttleMin) {
1743
- this.lastLog.timeout = setTimeout(resolveLog, this.throttle);
1744
- return;
1745
- }
1746
- }
1747
- } catch {
1748
- }
1749
- }
1750
- resolveLog(true);
1751
- }
1752
- }
1753
- }
1754
-
1755
- class RawReporter {
1756
- #stdout;
1757
- #stderr;
1758
- #interactiveManager;
1759
- #interactive = false;
1760
- #inspectOptions;
1761
- constructor(inspectOptions = {}) {
1762
- this.#stdout = stdout;
1763
- this.#stderr = stderr;
1764
- this.#inspectOptions = inspectOptions;
1765
- }
1766
- setStdout(stdout_) {
1767
- this.#stdout = stdout_;
1768
- }
1769
- setStderr(stderr_) {
1770
- this.#stderr = stderr_;
1771
- }
1772
- setInteractiveManager(manager) {
1773
- this.#interactiveManager = manager;
1774
- }
1775
- setIsInteractive(interactive) {
1776
- this.#interactive = interactive;
1777
- }
1778
- log(meta) {
1779
- const { context, groups, message, type } = meta;
1780
- const items = [];
1781
- if (message !== EMPTY_SYMBOL) {
1782
- const formattedMessage = typeof message === "string" ? message : inspect(message, this.#inspectOptions);
1783
- items.push(formattedMessage);
1784
- }
1785
- if (context) {
1786
- items.push(
1787
- ...context.map((value) => {
1788
- if (typeof value === "object") {
1789
- return ` ${inspect(value, this.#inspectOptions)}`;
1790
- }
1791
- return ` ${value}`;
1792
- })
1793
- );
1794
- }
1795
- const streamType = ["error", "trace", "warn"].includes(type.level) ? "stderr" : "stdout";
1796
- const stream = streamType === "stderr" ? this.#stderr : this.#stdout;
1797
- const groupSpaces = groups.map(() => " ").join("");
1798
- if (this.#interactive && this.#interactiveManager !== void 0 && stream.isTTY) {
1799
- this.#interactiveManager.update(streamType, (groupSpaces + items.join("")).split("\n"), 0);
1800
- } else {
1801
- writeStream(groupSpaces + items.join(""), stream);
1802
- }
1803
- }
1804
- }
1805
-
1806
- class PailServerImpl extends PailBrowserImpl {
1807
- /**
1808
- * Creates a new Pail server logger instance.
1809
- *
1810
- * Initializes the server-compatible logger with streams, interactive support,
1811
- * and server-specific configuration options.
1812
- * @param options Server-specific configuration options
1813
- */
1814
- constructor(options) {
1815
- const parentStderr = options.parentStderr;
1816
- const parentStdout = options.parentStdout;
1817
- const { interactive, processors, rawReporter, reporters, stderr: optionsStderr, stdout: optionsStdout } = options;
1818
- const stderr = parentStderr ?? optionsStderr;
1819
- const stdout = parentStdout ?? optionsStdout;
1820
- const parentLongestLabel = options.parentLongestLabel;
1821
- const parentTypes = options.parentTypes;
1822
- const { parentLogLevels, parentMessages, parentStringify } = options;
1823
- const parentOptions = {
1824
- disabled: options.disabled,
1825
- logLevel: options.logLevel,
1826
- logLevels: options.logLevels,
1827
- messages: options.messages,
1828
- processors: [],
1829
- rawReporter: options.rawReporter,
1830
- reporters: [],
1831
- scope: options.scope,
1832
- throttle: options.throttle,
1833
- throttleMin: options.throttleMin
1834
- };
1835
- const hasTypesProperty = "types" in options;
1836
- if (parentTypes && parentLongestLabel && !hasTypesProperty) {
1837
- parentOptions.parentTypes = parentTypes;
1838
- parentOptions.parentLongestLabel = parentLongestLabel;
1839
- } else if (hasTypesProperty && options.types !== void 0) {
1840
- parentOptions.types = options.types;
1841
- }
1842
- if (parentStringify) {
1843
- parentOptions.parentStringify = parentStringify;
1844
- }
1845
- if (parentLogLevels && !options.logLevels) {
1846
- parentOptions.parentLogLevels = parentLogLevels;
1847
- }
1848
- if (parentMessages && !options.messages) {
1849
- parentOptions.parentMessages = parentMessages;
1850
- }
1851
- super(parentOptions);
1852
- this.options = options;
1853
- this.interactive = interactive ?? false;
1854
- this.stdout = stdout;
1855
- this.stderr = stderr;
1856
- if (this.interactive) {
1857
- this.interactiveManager = new InteractiveManager(new InteractiveStreamHook(this.stdout), new InteractiveStreamHook(this.stderr));
1858
- }
1859
- if (Array.isArray(reporters)) {
1860
- this.registerReporters(reporters);
1861
- }
1862
- this.rawReporter = this.extendReporter(rawReporter ?? new RawReporter());
1863
- if (Array.isArray(processors)) {
1864
- this.registerProcessors(processors);
1865
- }
1866
- }
1867
- stdout;
1868
- stderr;
1869
- interactiveManager;
1870
- interactive;
1871
- // @ts-expect-error - this returns a different type
1872
- scope(...name) {
1873
- if (name.length === 0) {
1874
- throw new Error("No scope name was defined.");
1875
- }
1876
- this.scopeName = name.flat();
1877
- return this;
1878
- }
1879
- /**
1880
- * Creates a child logger that inherits settings from the parent.
1881
- *
1882
- * Returns a new logger instance that inherits all configuration from the parent
1883
- * (reporters, processors, types, log levels, throttle settings, etc.) while allowing
1884
- * you to override only what you need. Child loggers are independent instances with
1885
- * their own state (timers, counters, etc.).
1886
- * @template N - The new custom logger type names
1887
- * @template LC - The new log level types
1888
- * @param options Configuration options to override or extend parent settings
1889
- * @returns A new child logger instance
1890
- * @example
1891
- * ```typescript
1892
- * const parent = createPail({
1893
- * logLevel: "info",
1894
- * types: { http: { label: "HTTP", logLevel: "info" } },
1895
- * reporters: [new PrettyReporter()],
1896
- * });
1897
- *
1898
- * // Child inherits parent settings but overrides log level
1899
- * const child = parent.child({ logLevel: "debug" });
1900
- * child.info("This will be logged"); // Uses debug level from child
1901
- * child.http("GET /api 200"); // Inherits http type from parent
1902
- *
1903
- * // Child can add new types
1904
- * const childWithNewType = parent.child({
1905
- * types: { db: { label: "DB", logLevel: "info" } },
1906
- * });
1907
- * childWithNewType.db("Query executed"); // New type available
1908
- * ```
1909
- */
1910
- // @ts-expect-error - override signature differs due to server-specific options
1911
- child(options) {
1912
- const typesChanged = options?.types !== void 0 && options.types !== null;
1913
- const mergedTypes = typesChanged ? mergeTypes(this.types, options.types) : this.types;
1914
- const childReporters = options?.reporters ?? [];
1915
- const allReporters = childReporters.length > 0 ? [...this.reporters, ...childReporters] : [...this.reporters];
1916
- const childProcessors = options?.processors ?? [];
1917
- const allProcessors = childProcessors.length > 0 ? [...this.processors, ...childProcessors] : [...this.processors];
1918
- const mergedLogLevels = options?.logLevels ? { ...this.logLevels, ...options.logLevels } : this.logLevels;
1919
- let mergedScope;
1920
- if (options?.scope) {
1921
- const childScope = arrayify(options.scope).filter(Boolean);
1922
- mergedScope = this.scopeName.length > 0 ? [...this.scopeName, ...childScope] : childScope;
1923
- } else {
1924
- mergedScope = this.scopeName.length > 0 ? this.scopeName : [];
1925
- }
1926
- const mergedMessages = options?.messages ? {
1927
- timerEnd: this.endTimerMessage,
1928
- timerStart: this.startTimerMessage,
1929
- ...options.messages
1930
- } : {
1931
- timerEnd: this.endTimerMessage,
1932
- timerStart: this.startTimerMessage
1933
- };
1934
- const childOptions = {
1935
- disabled: options?.disabled ?? this.disabled,
1936
- interactive: options?.interactive ?? this.interactive,
1937
- logLevel: options?.logLevel ?? this.generalLogLevel,
1938
- logLevels: mergedLogLevels,
1939
- messages: mergedMessages,
1940
- processors: allProcessors,
1941
- rawReporter: options?.rawReporter ?? this.rawReporter,
1942
- reporters: allReporters,
1943
- scope: mergedScope,
1944
- stderr: options?.stderr ?? this.stderr,
1945
- stdout: options?.stdout ?? this.stdout,
1946
- throttle: options?.throttle ?? this.throttle,
1947
- throttleMin: options?.throttleMin ?? this.throttleMin
1948
- };
1949
- this.#assignParentValues(childOptions, options, typesChanged, mergedTypes);
1950
- return new PailServerImpl(childOptions);
1951
- }
1952
- /**
1953
- * Assigns parent values to child options for optimization.
1954
- *
1955
- * Reuses parent values when they haven't changed to avoid unnecessary recalculations.
1956
- */
1957
- /* eslint-disable no-param-reassign */
1958
- #assignParentValues(childOptions, options, typesChanged, mergedTypes) {
1959
- if (typesChanged) {
1960
- childOptions.parentTypes = mergedTypes;
1961
- childOptions.parentLongestLabel = getLongestLabel(mergedTypes);
1962
- } else {
1963
- childOptions.parentTypes = this.types;
1964
- childOptions.parentLongestLabel = this.longestLabel;
1965
- }
1966
- if (!options?.logLevels) {
1967
- childOptions.parentLogLevels = this.logLevels;
1968
- }
1969
- if (!options?.messages) {
1970
- childOptions.parentMessages = {
1971
- timerEnd: this.endTimerMessage,
1972
- timerStart: this.startTimerMessage
1973
- };
1974
- }
1975
- childOptions.parentStringify = this.stringify;
1976
- if (!options?.stdout) {
1977
- childOptions.parentStdout = this.stdout;
1978
- }
1979
- if (!options?.stderr) {
1980
- childOptions.parentStderr = this.stderr;
1981
- }
1982
- }
1983
- /* eslint-enable no-param-reassign */
1984
- /**
1985
- * Gets the interactive manager instance if interactive mode is enabled.
1986
- *
1987
- * Returns the InteractiveManager instance that handles interactive terminal
1988
- * features like progress bars and dynamic updates. Only available when
1989
- * interactive mode is enabled in the constructor options.
1990
- * @returns The interactive manager instance, or undefined if not in interactive mode
1991
- * @example
1992
- * ```typescript
1993
- * const logger = createPail({ interactive: true });
1994
- * const manager = logger.getInteractiveManager();
1995
- * if (manager) {
1996
- * manager.hook();
1997
- * // Use interactive features
1998
- * manager.unhook();
1999
- * }
2000
- * ```
2001
- */
2002
- getInteractiveManager() {
2003
- return this.interactiveManager;
2004
- }
2005
- /**
2006
- * Wraps stdout and stderr streams to redirect them through the logger.
2007
- *
2008
- * Intercepts writes to process.stdout and process.stderr, redirecting them
2009
- * through the logger instead of writing directly to the streams. This allows
2010
- * all output to be processed by the logging pipeline.
2011
- * @example
2012
- * ```typescript
2013
- * const logger = createPail();
2014
- * logger.wrapStd();
2015
- *
2016
- * console.log("This goes through logger");
2017
- * process.stdout.write("This too");
2018
- *
2019
- * logger.restoreStd(); // Restore original streams
2020
- * ```
2021
- */
2022
- wrapStd() {
2023
- this.#wrapStream(this.stdout, "log");
2024
- this.#wrapStream(this.stderr, "log");
2025
- }
2026
- /**
2027
- * Restores the original stdout and stderr streams.
2028
- *
2029
- * Removes the stream wrapping that was applied by wrapStd(),
2030
- * restoring the original stream write methods.
2031
- * @example
2032
- * ```typescript
2033
- * const logger = createPail();
2034
- * logger.wrapStd();
2035
- * // Streams are wrapped
2036
- * logger.restoreStd();
2037
- * // Streams are restored to original behavior
2038
- * ```
2039
- */
2040
- restoreStd() {
2041
- this.#restoreStream(this.stdout);
2042
- this.#restoreStream(this.stderr);
2043
- }
2044
- /**
2045
- * Wraps all output sources (console and streams).
2046
- *
2047
- * Convenience method that calls both wrapConsole() and wrapStd()
2048
- * to redirect all output through the logger.
2049
- * @example
2050
- * ```typescript
2051
- * const logger = createPail();
2052
- * logger.wrapAll(); // Wraps console and streams
2053
- *
2054
- * // All output now goes through logger
2055
- * console.log("Console output");
2056
- * process.stdout.write("Stream output");
2057
- *
2058
- * logger.restoreAll(); // Restore everything
2059
- * ```
2060
- */
2061
- wrapAll() {
2062
- this.wrapConsole();
2063
- this.wrapStd();
2064
- }
2065
- /**
2066
- * Restores all wrapped output sources.
2067
- *
2068
- * Convenience method that calls both restoreConsole() and restoreStd()
2069
- * to restore all original output behavior.
2070
- * @example
2071
- * ```typescript
2072
- * const logger = createPail();
2073
- * logger.wrapAll();
2074
- * // All output is wrapped
2075
- * logger.restoreAll();
2076
- * // All output sources are restored
2077
- * ```
2078
- */
2079
- restoreAll() {
2080
- this.restoreConsole();
2081
- this.restoreStd();
2082
- }
2083
- /**
2084
- * Creates a single progress bar.
2085
- * @param options Configuration options for the progress bar
2086
- * @returns A new ProgressBar instance
2087
- * @example
2088
- * ```typescript
2089
- * const logger = createPail({ interactive: true });
2090
- * const bar = logger.createProgressBar({
2091
- * total: 100,
2092
- * format: 'Downloading [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'
2093
- * });
2094
- *
2095
- * bar.start();
2096
- * // ... do work and update progress
2097
- * bar.update(50);
2098
- * bar.stop();
2099
- * ```
2100
- */
2101
- createProgressBar(options) {
2102
- if (!this.interactiveManager) {
2103
- throw new Error("Interactive mode is not enabled. Create Pail with { interactive: true } to use progress bars.");
2104
- }
2105
- const styledOptions = applyStyleToOptions(options);
2106
- return new ProgressBar(styledOptions, this.interactiveManager);
2107
- }
2108
- /**
2109
- * Creates a multi-bar progress manager for displaying multiple progress bars.
2110
- * @param options Configuration options for the multi-bar manager
2111
- * @returns A new MultiProgressBar instance
2112
- * @example
2113
- * ```typescript
2114
- * const logger = createPail({ interactive: true });
2115
- * const multiBar = logger.createMultiProgressBar();
2116
- *
2117
- * const bar1 = multiBar.create(100);
2118
- * const bar2 = multiBar.create(200);
2119
- *
2120
- * bar1.start();
2121
- * bar2.start();
2122
- * // ... update bars as needed
2123
- * multiBar.stop();
2124
- * ```
2125
- */
2126
- createMultiProgressBar(options = {}) {
2127
- if (!this.interactiveManager) {
2128
- throw new Error("Interactive mode is not enabled. Create Pail with { interactive: true } to use progress bars.");
2129
- }
2130
- const styledOptions = applyStyleToOptions(options);
2131
- return new MultiProgressBar(styledOptions, this.interactiveManager);
2132
- }
2133
- /**
2134
- * Creates a single spinner.
2135
- * @param options Configuration options for the spinner
2136
- * @returns A new Spinner instance
2137
- * @example
2138
- * ```typescript
2139
- * const logger = createPail({ interactive: true });
2140
- * const spinner = logger.createSpinner({ name: 'dots' });
2141
- * spinner.start('Loading...');
2142
- * // ... do work
2143
- * spinner.succeed('Done');
2144
- * ```
2145
- */
2146
- createSpinner(options = {}) {
2147
- if (!this.interactiveManager) {
2148
- throw new Error("Interactive mode is not enabled. Create Pail with { interactive: true } to use spinners.");
2149
- }
2150
- return new Spinner(options, this.interactiveManager);
2151
- }
2152
- /**
2153
- * Creates a multi-spinner manager for displaying multiple spinners.
2154
- * @param options Configuration options for the multi-spinner manager
2155
- * @returns A new MultiSpinner instance
2156
- * @example
2157
- * ```typescript
2158
- * const logger = createPail({ interactive: true });
2159
- * const multiSpinner = logger.createMultiSpinner();
2160
- *
2161
- * const spinner1 = multiSpinner.create('Loading 1');
2162
- * const spinner2 = multiSpinner.create('Loading 2');
2163
- *
2164
- * spinner1.start();
2165
- * spinner2.start();
2166
- * // ... update spinners as needed
2167
- * multiSpinner.stop();
2168
- * ```
2169
- */
2170
- createMultiSpinner(options = {}) {
2171
- if (!this.interactiveManager) {
2172
- throw new Error("Interactive mode is not enabled. Create Pail with { interactive: true } to use spinners.");
2173
- }
2174
- return new MultiSpinner(options, this.interactiveManager);
2175
- }
2176
- /**
2177
- * Clears the terminal screen.
2178
- *
2179
- * Sends ANSI escape sequences to clear the terminal screen and move
2180
- * the cursor to the top-left position. This overrides the browser
2181
- * implementation to work with terminal streams.
2182
- * @example
2183
- * ```typescript
2184
- * const logger = createPail();
2185
- * logger.info("Some output");
2186
- * logger.clear(); // Clears the terminal screen
2187
- * ```
2188
- */
2189
- clear() {
2190
- this.stdout.write(clearTerminal);
2191
- this.stderr.write(clearTerminal);
2192
- }
2193
- extendReporter(reporter) {
2194
- if (typeof reporter.setStdout === "function") {
2195
- reporter.setStdout(this.stdout);
2196
- }
2197
- if (typeof reporter.setStderr === "function") {
2198
- reporter.setStderr(this.stderr);
2199
- }
2200
- if (typeof reporter.setLoggerTypes === "function") {
2201
- reporter.setLoggerTypes(this.types);
2202
- }
2203
- if (typeof reporter.setStringify === "function") {
2204
- reporter.setStringify(this.stringify);
2205
- }
2206
- if (typeof reporter.setIsInteractive === "function") {
2207
- reporter.setIsInteractive(this.interactive);
2208
- }
2209
- if (this.interactive && typeof reporter.setInteractiveManager === "function") {
2210
- reporter.setInteractiveManager(this.interactiveManager);
2211
- }
2212
- return reporter;
2213
- }
2214
- #wrapStream(stream, type) {
2215
- if (!stream) {
2216
- return;
2217
- }
2218
- if (!stream.__write) {
2219
- stream.__write = stream.write;
2220
- }
2221
- stream.write = (data) => {
2222
- this[type](String(data).trim());
2223
- };
2224
- }
2225
- // eslint-disable-next-line class-methods-use-this
2226
- #restoreStream(stream) {
2227
- if (!stream) {
2228
- return;
2229
- }
2230
- if (stream.__write) {
2231
- stream.write = stream.__write;
2232
- delete stream.__write;
2233
- }
2234
- }
2235
- }
2236
- const PailServer = PailServerImpl;
2237
-
2238
- const colorKeywords = /* @__PURE__ */ new Map([
2239
- ["aliceblue", "#f0f8ff"],
2240
- ["antiquewhite", "#faebd7"],
2241
- ["aqua", "#00ffff"],
2242
- ["aquamarine", "#7fffd4"],
2243
- ["azure", "#f0ffff"],
2244
- ["beige", "#f5f5dc"],
2245
- ["bisque", "#ffe4c4"],
2246
- ["black", "#000000"],
2247
- ["blanchedalmond", "#ffebcd"],
2248
- ["blue", "#0000ff"],
2249
- ["blueviolet", "#8a2be2"],
2250
- ["brown", "#a52a2a"],
2251
- ["burlywood", "#deb887"],
2252
- ["cadetblue", "#5f9ea0"],
2253
- ["chartreuse", "#7fff00"],
2254
- ["chocolate", "#d2691e"],
2255
- ["coral", "#ff7f50"],
2256
- ["cornflowerblue", "#6495ed"],
2257
- ["cornsilk", "#fff8dc"],
2258
- ["crimson", "#dc143c"],
2259
- ["cyan", "#00ffff"],
2260
- ["darkblue", "#00008b"],
2261
- ["darkcyan", "#008b8b"],
2262
- ["darkgoldenrod", "#b8860b"],
2263
- ["darkgray", "#a9a9a9"],
2264
- ["darkgreen", "#006400"],
2265
- ["darkgrey", "#a9a9a9"],
2266
- ["darkkhaki", "#bdb76b"],
2267
- ["darkmagenta", "#8b008b"],
2268
- ["darkolivegreen", "#556b2f"],
2269
- ["darkorange", "#ff8c00"],
2270
- ["darkorchid", "#9932cc"],
2271
- ["darkred", "#8b0000"],
2272
- ["darksalmon", "#e9967a"],
2273
- ["darkseagreen", "#8fbc8f"],
2274
- ["darkslateblue", "#483d8b"],
2275
- ["darkslategray", "#2f4f4f"],
2276
- ["darkslategrey", "#2f4f4f"],
2277
- ["darkturquoise", "#00ced1"],
2278
- ["darkviolet", "#9400d3"],
2279
- ["deeppink", "#ff1493"],
2280
- ["deepskyblue", "#00bfff"],
2281
- ["dimgray", "#696969"],
2282
- ["dimgrey", "#696969"],
2283
- ["dodgerblue", "#1e90ff"],
2284
- ["firebrick", "#b22222"],
2285
- ["floralwhite", "#fffaf0"],
2286
- ["forestgreen", "#228b22"],
2287
- ["fuchsia", "#ff00ff"],
2288
- ["gainsboro", "#dcdcdc"],
2289
- ["ghostwhite", "#f8f8ff"],
2290
- ["gold", "#ffd700"],
2291
- ["goldenrod", "#daa520"],
2292
- ["gray", "#808080"],
2293
- ["green", "#008000"],
2294
- ["greenyellow", "#adff2f"],
2295
- ["grey", "#808080"],
2296
- ["honeydew", "#f0fff0"],
2297
- ["hotpink", "#ff69b4"],
2298
- ["indianred", "#cd5c5c"],
2299
- ["indigo", "#4b0082"],
2300
- ["ivory", "#fffff0"],
2301
- ["khaki", "#f0e68c"],
2302
- ["lavender", "#e6e6fa"],
2303
- ["lavenderblush", "#fff0f5"],
2304
- ["lawngreen", "#7cfc00"],
2305
- ["lemonchiffon", "#fffacd"],
2306
- ["lightblue", "#add8e6"],
2307
- ["lightcoral", "#f08080"],
2308
- ["lightcyan", "#e0ffff"],
2309
- ["lightgoldenrodyellow", "#fafad2"],
2310
- ["lightgray", "#d3d3d3"],
2311
- ["lightgreen", "#90ee90"],
2312
- ["lightgrey", "#d3d3d3"],
2313
- ["lightpink", "#ffb6c1"],
2314
- ["lightsalmon", "#ffa07a"],
2315
- ["lightseagreen", "#20b2aa"],
2316
- ["lightskyblue", "#87cefa"],
2317
- ["lightslategray", "#778899"],
2318
- ["lightslategrey", "#778899"],
2319
- ["lightsteelblue", "#b0c4de"],
2320
- ["lightyellow", "#ffffe0"],
2321
- ["lime", "#00ff00"],
2322
- ["limegreen", "#32cd32"],
2323
- ["linen", "#faf0e6"],
2324
- ["magenta", "#ff00ff"],
2325
- ["maroon", "#800000"],
2326
- ["mediumaquamarine", "#66cdaa"],
2327
- ["mediumblue", "#0000cd"],
2328
- ["mediumorchid", "#ba55d3"],
2329
- ["mediumpurple", "#9370db"],
2330
- ["mediumseagreen", "#3cb371"],
2331
- ["mediumslateblue", "#7b68ee"],
2332
- ["mediumspringgreen", "#00fa9a"],
2333
- ["mediumturquoise", "#48d1cc"],
2334
- ["mediumvioletred", "#c71585"],
2335
- ["midnightblue", "#191970"],
2336
- ["mintcream", "#f5fffa"],
2337
- ["mistyrose", "#ffe4e1"],
2338
- ["moccasin", "#ffe4b5"],
2339
- ["navajowhite", "#ffdead"],
2340
- ["navy", "#000080"],
2341
- ["oldlace", "#fdf5e6"],
2342
- ["olive", "#808000"],
2343
- ["olivedrab", "#6b8e23"],
2344
- ["orange", "#ffa500"],
2345
- ["orangered", "#ff4500"],
2346
- ["orchid", "#da70d6"],
2347
- ["palegoldenrod", "#eee8aa"],
2348
- ["palegreen", "#98fb98"],
2349
- ["paleturquoise", "#afeeee"],
2350
- ["palevioletred", "#db7093"],
2351
- ["papayawhip", "#ffefd5"],
2352
- ["peachpuff", "#ffdab9"],
2353
- ["peru", "#cd853f"],
2354
- ["pink", "#ffc0cb"],
2355
- ["plum", "#dda0dd"],
2356
- ["powderblue", "#b0e0e6"],
2357
- ["purple", "#800080"],
2358
- ["rebeccapurple", "#663399"],
2359
- ["red", "#ff0000"],
2360
- ["rosybrown", "#bc8f8f"],
2361
- ["royalblue", "#4169e1"],
2362
- ["saddlebrown", "#8b4513"],
2363
- ["salmon", "#fa8072"],
2364
- ["sandybrown", "#f4a460"],
2365
- ["seagreen", "#2e8b57"],
2366
- ["seashell", "#fff5ee"],
2367
- ["sienna", "#a0522d"],
2368
- ["silver", "#c0c0c0"],
2369
- ["skyblue", "#87ceeb"],
2370
- ["slateblue", "#6a5acd"],
2371
- ["slategray", "#708090"],
2372
- ["slategrey", "#708090"],
2373
- ["snow", "#fffafa"],
2374
- ["springgreen", "#00ff7f"],
2375
- ["steelblue", "#4682b4"],
2376
- ["tan", "#d2b48c"],
2377
- ["teal", "#008080"],
2378
- ["thistle", "#d8bfd8"],
2379
- ["tomato", "#ff6347"],
2380
- ["turquoise", "#40e0d0"],
2381
- ["violet", "#ee82ee"],
2382
- ["wheat", "#f5deb3"],
2383
- ["white", "#ffffff"],
2384
- ["whitesmoke", "#f5f5f5"],
2385
- ["yellow", "#ffff00"],
2386
- ["yellowgreen", "#9acd32"]
2387
- ]);
2388
- const HASH_PATTERN = /^#([\dA-F]{2})([\dA-F]{2})([\dA-F]{2})([\dA-F]{2})?$/i;
2389
- const SMALL_HASH_PATTERN = /^#([\dA-F])([\dA-F])([\dA-F])([\dA-F])?$/i;
2390
- const RGB_PATTERN = /^rgba?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*(,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*)?\)$/;
2391
- const HSL_PATTERN = /^hsla?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%\s*(,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*)?\)$/;
2392
- const getDefaultCss = () => {
2393
- return {
2394
- __proto__: null,
2395
- backgroundColor: null,
2396
- color: null,
2397
- fontStyle: null,
2398
- fontWeight: null,
2399
- textDecorationColor: null,
2400
- textDecorationLine: []
2401
- };
2402
- };
2403
- const SPACE_PATTERN = /\s+/g;
2404
- const parseCssColor = (colorString) => {
2405
- if (colorKeywords.has(colorString)) {
2406
- colorString = colorKeywords.get(colorString);
2407
- }
2408
- const hashMatch = HASH_PATTERN.exec(colorString);
2409
- if (hashMatch) {
2410
- return [Number.parseInt(hashMatch[1], 16), Number.parseInt(hashMatch[2], 16), Number.parseInt(hashMatch[3], 16)];
2411
- }
2412
- const smallHashMatch = SMALL_HASH_PATTERN.exec(colorString);
2413
- if (smallHashMatch) {
2414
- return [
2415
- Number.parseInt(`${smallHashMatch[1]}${smallHashMatch[1]}`, 16),
2416
- Number.parseInt(`${smallHashMatch[2]}${smallHashMatch[2]}`, 16),
2417
- Number.parseInt(`${smallHashMatch[3]}${smallHashMatch[3]}`, 16)
2418
- ];
2419
- }
2420
- const rgbMatch = RGB_PATTERN.exec(colorString);
2421
- if (rgbMatch) {
2422
- return [
2423
- Math.round(Math.max(0, Math.min(255, Number(rgbMatch[1])))),
2424
- Math.round(Math.max(0, Math.min(255, Number(rgbMatch[2])))),
2425
- Math.round(Math.max(0, Math.min(255, Number(rgbMatch[3]))))
2426
- ];
2427
- }
2428
- const hslMatch = HSL_PATTERN.exec(colorString);
2429
- if (hslMatch) {
2430
- let h = Number(hslMatch[1]) % 360;
2431
- if (h < 0) {
2432
- h += 360;
2433
- }
2434
- const s = Math.max(0, Math.min(100, Number(hslMatch[2]))) / 100;
2435
- const l = Math.max(0, Math.min(100, Number(hslMatch[3]))) / 100;
2436
- const c = (1 - Math.abs(2 * l - 1)) * s;
2437
- const x = c * (1 - Math.abs(h / 60 % 2 - 1));
2438
- const m = l - c / 2;
2439
- let r_;
2440
- let g_;
2441
- let b_;
2442
- if (h < 60) {
2443
- ({ 0: r_, 1: g_, 2: b_ } = [c, x, 0]);
2444
- } else if (h < 120) {
2445
- ({ 0: r_, 1: g_, 2: b_ } = [x, c, 0]);
2446
- } else if (h < 180) {
2447
- ({ 0: r_, 1: g_, 2: b_ } = [0, c, x]);
2448
- } else if (h < 240) {
2449
- ({ 0: r_, 1: g_, 2: b_ } = [0, x, c]);
2450
- } else if (h < 300) {
2451
- ({ 0: r_, 1: g_, 2: b_ } = [x, 0, c]);
2452
- } else {
2453
- ({ 0: r_, 1: g_, 2: b_ } = [c, 0, x]);
2454
- }
2455
- return [Math.round((r_ + m) * 255), Math.round((g_ + m) * 255), Math.round((b_ + m) * 255)];
2456
- }
2457
- return null;
2458
- };
2459
- const colorEquals = (color1, color2) => color1?.[0] === color2?.[0] && color1?.[1] === color2?.[1] && color1?.[2] === color2?.[2];
2460
- const parseCss = (cssString) => {
2461
- const css = getDefaultCss();
2462
- const rawEntries = [];
2463
- let inValue = false;
2464
- let currentKey = null;
2465
- let parenthesesDepth = 0;
2466
- let currentPart = "";
2467
- for (const c of cssString) {
2468
- if (c === "(") {
2469
- parenthesesDepth++;
2470
- } else if (parenthesesDepth > 0) {
2471
- if (c === ")") {
2472
- parenthesesDepth--;
2473
- }
2474
- } else if (inValue) {
2475
- if (c === ";") {
2476
- const value = currentPart.trim();
2477
- if (value !== "") {
2478
- rawEntries.push([currentKey, value]);
2479
- }
2480
- currentKey = null;
2481
- currentPart = "";
2482
- inValue = false;
2483
- continue;
2484
- }
2485
- } else if (c === ":") {
2486
- currentKey = currentPart.trim();
2487
- currentPart = "";
2488
- inValue = true;
2489
- continue;
2490
- }
2491
- currentPart += c;
2492
- }
2493
- if (inValue && parenthesesDepth === 0) {
2494
- const value = currentPart.trim();
2495
- if (value !== "") {
2496
- rawEntries.push([currentKey, value]);
2497
- }
2498
- currentKey = null;
2499
- currentPart = "";
2500
- }
2501
- for (const { 0: key, 1: value } of rawEntries) {
2502
- switch (key) {
2503
- case "background-color": {
2504
- if (value != void 0) {
2505
- css.backgroundColor = value;
2506
- }
2507
- break;
2508
- }
2509
- case "color": {
2510
- if (value != void 0) {
2511
- css.color = value;
2512
- }
2513
- break;
2514
- }
2515
- case "font-style": {
2516
- if (["italic", "oblique", "oblique 14deg"].includes(value)) {
2517
- css.fontStyle = "italic";
2518
- }
2519
- break;
2520
- }
2521
- case "font-weight": {
2522
- if (value === "bold") {
2523
- css.fontWeight = value;
2524
- }
2525
- break;
2526
- }
2527
- case "text-decoration": {
2528
- css.textDecorationColor = null;
2529
- css.textDecorationLine = [];
2530
- const arguments_ = value.split(SPACE_PATTERN);
2531
- for (const argument of arguments_) {
2532
- const maybeColor = parseCssColor(argument);
2533
- if (maybeColor != void 0) {
2534
- css.textDecorationColor = maybeColor;
2535
- } else if (["line-through", "overline", "underline"].includes(argument)) {
2536
- css.textDecorationLine.push(argument);
2537
- }
2538
- }
2539
- break;
2540
- }
2541
- case "text-decoration-color": {
2542
- const color = parseCssColor(value);
2543
- if (color != void 0) {
2544
- css.textDecorationColor = color;
2545
- }
2546
- break;
2547
- }
2548
- case "text-decoration-line": {
2549
- css.textDecorationLine = [];
2550
- const lineTypes = value.split(SPACE_PATTERN);
2551
- for (const lineType of lineTypes) {
2552
- if (["line-through", "overline", "underline"].includes(lineType)) {
2553
- css.textDecorationLine.push(lineType);
2554
- }
2555
- }
2556
- break;
2557
- }
2558
- }
2559
- }
2560
- return css;
2561
- };
2562
- const cssToAnsi = (css, previousCss = null) => {
2563
- previousCss = previousCss ?? getDefaultCss();
2564
- let ansi = "";
2565
- if (!colorEquals(css.backgroundColor, previousCss.backgroundColor)) {
2566
- if (css.backgroundColor == void 0) {
2567
- ansi += "\x1B[49m";
2568
- } else {
2569
- switch (css.backgroundColor) {
2570
- case "black": {
2571
- ansi += "\x1B[40m";
2572
- break;
2573
- }
2574
- case "blue": {
2575
- ansi += "\x1B[44m";
2576
- break;
2577
- }
2578
- case "cyan": {
2579
- ansi += "\x1B[46m";
2580
- break;
2581
- }
2582
- case "green": {
2583
- ansi += "\x1B[42m";
2584
- break;
2585
- }
2586
- case "magenta": {
2587
- ansi += "\x1B[45m";
2588
- break;
2589
- }
2590
- case "red": {
2591
- ansi += "\x1B[41m";
2592
- break;
2593
- }
2594
- case "white": {
2595
- ansi += "\x1B[47m";
2596
- break;
2597
- }
2598
- case "yellow": {
2599
- ansi += "\x1B[43m";
2600
- break;
2601
- }
2602
- default: {
2603
- if (Array.isArray(css.backgroundColor)) {
2604
- const { 0: r, 1: g, 2: b } = css.backgroundColor;
2605
- ansi += `\x1B[48;2;${r};${g};${b}m`;
2606
- } else {
2607
- const parsed = parseCssColor(css.backgroundColor);
2608
- if (parsed === null) {
2609
- ansi += "\x1B[49m";
2610
- } else {
2611
- const { 0: r, 1: g, 2: b } = parsed;
2612
- ansi += `\x1B[48;2;${r};${g};${b}m`;
2613
- }
2614
- }
2615
- }
2616
- }
2617
- }
2618
- }
2619
- if (!colorEquals(css.color, previousCss.color)) {
2620
- if (css.color == void 0) {
2621
- ansi += "\x1B[39m";
2622
- } else {
2623
- switch (css.color) {
2624
- case "black": {
2625
- ansi += "\x1B[30m";
2626
- break;
2627
- }
2628
- case "blue": {
2629
- ansi += "\x1B[34m";
2630
- break;
2631
- }
2632
- case "cyan": {
2633
- ansi += "\x1B[36m";
2634
- break;
2635
- }
2636
- case "green": {
2637
- ansi += "\x1B[32m";
2638
- break;
2639
- }
2640
- case "magenta": {
2641
- ansi += "\x1B[35m";
2642
- break;
2643
- }
2644
- case "red": {
2645
- ansi += "\x1B[31m";
2646
- break;
2647
- }
2648
- case "white": {
2649
- ansi += "\x1B[37m";
2650
- break;
2651
- }
2652
- case "yellow": {
2653
- ansi += "\x1B[33m";
2654
- break;
2655
- }
2656
- default: {
2657
- if (Array.isArray(css.color)) {
2658
- const { 0: r, 1: g, 2: b } = css.color;
2659
- ansi += `\x1B[38;2;${r};${g};${b}m`;
2660
- } else {
2661
- const parsed = parseCssColor(css.color);
2662
- if (parsed === null) {
2663
- ansi += "\x1B[39m";
2664
- } else {
2665
- const { 0: r, 1: g, 2: b } = parsed;
2666
- ansi += `\x1B[38;2;${r};${g};${b}m`;
2667
- }
2668
- }
2669
- }
2670
- }
2671
- }
2672
- }
2673
- if (css.fontWeight !== previousCss.fontWeight) {
2674
- ansi += css.fontWeight === "bold" ? "\x1B[1m" : "\x1B[22m";
2675
- }
2676
- if (css.fontStyle !== previousCss.fontStyle) {
2677
- ansi += css.fontStyle === "italic" ? "\x1B[3m" : "\x1B[23m";
2678
- }
2679
- if (!colorEquals(css.textDecorationColor, previousCss.textDecorationColor)) {
2680
- if (css.textDecorationColor == void 0) {
2681
- ansi += "\x1B[59m";
2682
- } else {
2683
- const { 0: r, 1: g, 2: b } = css.textDecorationColor;
2684
- ansi += `\x1B[58;2;${r};${g};${b}m`;
2685
- }
2686
- }
2687
- if (css.textDecorationLine.includes("line-through") !== previousCss.textDecorationLine.includes("line-through")) {
2688
- ansi += css.textDecorationLine.includes("line-through") ? "\x1B[9m" : "\x1B[29m";
2689
- }
2690
- if (css.textDecorationLine.includes("overline") !== previousCss.textDecorationLine.includes("overline")) {
2691
- ansi += css.textDecorationLine.includes("overline") ? "\x1B[53m" : "\x1B[55m";
2692
- }
2693
- if (css.textDecorationLine.includes("underline") !== previousCss.textDecorationLine.includes("underline")) {
2694
- ansi += css.textDecorationLine.includes("underline") ? "\x1B[4m" : "\x1B[24m";
2695
- }
2696
- return ansi;
2697
- };
2698
- const tryStringify = (o) => {
2699
- try {
2700
- return JSON.stringify(o);
2701
- } catch {
2702
- return '"[Circular]"';
2703
- }
2704
- };
2705
- const CHAR_PERCENT = "%".codePointAt(0);
2706
- const CHAR_s = "s".codePointAt(0);
2707
- const CHAR_d = "d".codePointAt(0);
2708
- const CHAR_f = "f".codePointAt(0);
2709
- const CHAR_i = "i".codePointAt(0);
2710
- const CHAR_O = "O".codePointAt(0);
2711
- const CHAR_o = "o".codePointAt(0);
2712
- const CHAR_j = "j".codePointAt(0);
2713
- const CHAR_c = "c".codePointAt(0);
2714
- const format = (fmt, arguments_ = [], options = {}) => {
2715
- if (typeof fmt !== "string" && typeof fmt !== "object" || fmt === null) {
2716
- throw new TypeError(`fmt must be a string or object, got ${fmt === null ? "null" : typeof fmt}`);
2717
- }
2718
- const stringify = options.stringify ?? tryStringify;
2719
- const offset = 1;
2720
- if (typeof fmt === "object") {
2721
- const argumentsLength = arguments_.length + offset;
2722
- if (argumentsLength === 1) {
2723
- return "{}";
2724
- }
2725
- const objects = Array.from({ length: argumentsLength });
2726
- objects[0] = stringify(fmt);
2727
- for (let index = 1; index < argumentsLength; index++) {
2728
- objects[index] = stringify(arguments_[index - offset]);
2729
- }
2730
- return objects.join(" ");
2731
- }
2732
- if (arguments_.length === 0) {
2733
- return fmt;
2734
- }
2735
- let result = "";
2736
- let a = 1 - offset;
2737
- let lastPosition = -1;
2738
- let usedStyle = false;
2739
- let previousCss = null;
2740
- for (let index = 0; index < fmt.length; ) {
2741
- if (fmt.codePointAt(index) === CHAR_PERCENT && index + 1 < fmt.length) {
2742
- lastPosition = lastPosition > -1 ? lastPosition : 0;
2743
- const c = fmt.codePointAt(index + 1);
2744
- if (c === void 0) {
2745
- ++a;
2746
- break;
2747
- }
2748
- switch (c) {
2749
- case CHAR_c: {
2750
- if (globalThis.window === void 0) {
2751
- const css = parseCss(arguments_[a]);
2752
- if (lastPosition < index) {
2753
- result += fmt.slice(lastPosition, index);
2754
- }
2755
- result += cssToAnsi(css, previousCss);
2756
- if (result !== "") {
2757
- usedStyle = true;
2758
- previousCss = css;
2759
- }
2760
- }
2761
- lastPosition = index + 2;
2762
- index++;
2763
- break;
2764
- }
2765
- case CHAR_d:
2766
- case CHAR_f: {
2767
- if (a >= arguments_.length || arguments_[a] == void 0) {
2768
- break;
2769
- }
2770
- if (lastPosition < index) {
2771
- result += fmt.slice(lastPosition, index);
2772
- }
2773
- result += Number(arguments_[a]).toString();
2774
- lastPosition = index + 2;
2775
- index++;
2776
- break;
2777
- }
2778
- case CHAR_i: {
2779
- if (a >= arguments_.length || arguments_[a] == void 0) {
2780
- break;
2781
- }
2782
- if (lastPosition < index) {
2783
- result += fmt.slice(lastPosition, index);
2784
- }
2785
- result += Math.floor(Number(arguments_[a])).toString();
2786
- lastPosition = index + 2;
2787
- index++;
2788
- break;
2789
- }
2790
- case CHAR_j:
2791
- case CHAR_O:
2792
- case CHAR_o: {
2793
- if (a >= arguments_.length || arguments_[a] === void 0) {
2794
- break;
2795
- }
2796
- if (lastPosition < index) {
2797
- result += fmt.slice(lastPosition, index);
2798
- }
2799
- const temporaryArgument = arguments_[a];
2800
- const type = typeof temporaryArgument;
2801
- if (type === "string") {
2802
- result += `'${temporaryArgument}'`;
2803
- lastPosition = index + 2;
2804
- break;
2805
- }
2806
- if (type === "function") {
2807
- result += temporaryArgument.name ? `[Function: ${temporaryArgument.name}]` : "[Function: <anonymous>]";
2808
- lastPosition = index + 2;
2809
- break;
2810
- }
2811
- result += stringify(temporaryArgument);
2812
- lastPosition = index + 2;
2813
- index++;
2814
- break;
2815
- }
2816
- case CHAR_PERCENT: {
2817
- if (lastPosition < index) {
2818
- result += fmt.slice(lastPosition, index);
2819
- }
2820
- result += "%";
2821
- lastPosition = index + 2;
2822
- index++;
2823
- a--;
2824
- break;
2825
- }
2826
- case CHAR_s: {
2827
- if (a >= arguments_.length) {
2828
- break;
2829
- }
2830
- if (lastPosition < index) {
2831
- result += fmt.slice(lastPosition, index);
2832
- }
2833
- result += typeof arguments_[a] === "object" ? stringify(arguments_[a]) : String(arguments_[a]);
2834
- lastPosition = index + 2;
2835
- index++;
2836
- break;
2837
- }
2838
- default: {
2839
- if (typeof options.formatters?.[c] === "function") {
2840
- if (lastPosition < index) {
2841
- result += fmt.slice(lastPosition, index);
2842
- }
2843
- result += options.formatters[c](arguments_[a]);
2844
- lastPosition = index + 2;
2845
- index++;
2846
- }
2847
- }
2848
- }
2849
- ++a;
2850
- }
2851
- ++index;
2852
- }
2853
- if (lastPosition === -1) {
2854
- return fmt;
2855
- }
2856
- if (lastPosition < fmt.length) {
2857
- result += fmt.slice(lastPosition);
2858
- }
2859
- if (usedStyle) {
2860
- result += "\x1B[0m";
2861
- }
2862
- return result;
2863
- };
2864
- const build = (options = {}) => {
2865
- const formatters = {};
2866
- if (typeof options.formatters === "object") {
2867
- Object.entries(options.formatters).forEach(([key, formatterFunction]) => {
2868
- if (key.length === 0) {
2869
- throw new Error(`Formatter %${key} has no characters`);
2870
- }
2871
- if (key.length > 1) {
2872
- throw new Error(`Formatter %${key} has more than one character`);
2873
- }
2874
- if (typeof formatterFunction !== "function") {
2875
- throw new TypeError(`Formatter for %${key} is not a function`);
2876
- }
2877
- const c = key.codePointAt(0);
2878
- if (c === void 0) {
2879
- throw new Error(`${key}.codePointAt(0) failed to return a value, please report this issue`);
2880
- }
2881
- formatters[c] = formatterFunction;
2882
- });
2883
- }
2884
- return (f, arguments_ = [], formatOptions = {}) => format(f, arguments_, { ...formatOptions, formatters });
2885
- };
2886
-
2887
- class MessageFormatterProcessor {
2888
- /** Custom stringify function for object serialization */
2889
- #stringify;
2890
- /** Custom formatters for message interpolation */
2891
- #formatters;
2892
- /**
2893
- * Creates a new MessageFormatterProcessor instance.
2894
- * @param options Configuration options
2895
- * @param options.formatters Custom formatters for message interpolation
2896
- */
2897
- constructor(options = {}) {
2898
- this.#formatters = options.formatters;
2899
- }
2900
- /**
2901
- * Sets the stringify function for object serialization.
2902
- * @param function_ The stringify function to use for serializing objects
2903
- */
2904
- setStringify(function_) {
2905
- this.#stringify = function_;
2906
- }
2907
- /**
2908
- * Processes log metadata to format messages.
2909
- *
2910
- * Applies string interpolation and custom formatters to the message
2911
- * and contextual data in the log metadata.
2912
- * @param meta The log metadata to process
2913
- * @returns The processed metadata with formatted messages
2914
- */
2915
- process(meta) {
2916
- const formatter = build({
2917
- formatters: this.#formatters});
2918
- if (meta.message !== void 0) {
2919
- meta.message = this.#format(formatter, meta.message, meta.context ?? []);
2920
- }
2921
- return meta;
2922
- }
2923
- /**
2924
- * Recursively formats data using the formatter.
2925
- *
2926
- * Applies string interpolation and formatting to strings, arrays, and objects.
2927
- * @param formatter The formatter function to use
2928
- * @param data The data to format (string, array, or object)
2929
- * @param arguments_ Additional arguments for formatting
2930
- * @returns The formatted data
2931
- * @private
2932
- */
2933
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2934
- #format(formatter, data, arguments_ = []) {
2935
- if (typeof data === "string") {
2936
- return formatter(data, arguments_);
2937
- }
2938
- if (typeof data === "object" && data !== null) {
2939
- for (const index in data) {
2940
- const value = data[index];
2941
- if (typeof value === "string" || Array.isArray(value) || typeof value === "object") {
2942
- data[index] = this.#format(formatter, value, arguments_);
2943
- }
2944
- }
2945
- }
2946
- return data;
2947
- }
2948
- }
2949
-
2950
- const PAIL_DIST_REGEX = /[\\/]pail[\\/]dist/;
2951
- const pailFileFilter = (line) => !PAIL_DIST_REGEX.test(line);
2952
- class PrettyReporter extends AbstractPrettyReporter {
2953
- #stdout;
2954
- #stderr;
2955
- #interactiveManager;
2956
- #interactive = false;
2957
- #inspectOptions;
2958
- #errorOptions;
2959
- /**
2960
- * Creates a new Server Pretty Reporter instance.
2961
- * @param options Configuration options for styling, error rendering, and object inspection
2962
- */
2963
- constructor(options = {}) {
2964
- const { error: errorOptions, inspect: inspectOptions, ...rest } = options;
2965
- super({
2966
- uppercase: {
2967
- label: true,
2968
- ...rest.uppercase
2969
- },
2970
- ...rest
2971
- });
2972
- this.#inspectOptions = { ...defaultInspectorConfig, ...inspectOptions };
2973
- this.#errorOptions = {
2974
- ...errorOptions,
2975
- color: {
2976
- fileLine: green,
2977
- hint: cyan,
2978
- marker: red,
2979
- message: red,
2980
- method: greenBright,
2981
- title: red
2982
- }
2983
- };
2984
- this.#stdout = stdout;
2985
- this.#stderr = stderr;
2986
- }
2987
- /**
2988
- * Sets the stdout stream for the reporter.
2989
- * @param stdout_ The writable stream to use for standard output
2990
- */
2991
- setStdout(stdout_) {
2992
- this.#stdout = stdout_;
2993
- }
2994
- /**
2995
- * Sets the stderr stream for the reporter.
2996
- * @param stderr_ The writable stream to use for error output
2997
- */
2998
- setStderr(stderr_) {
2999
- this.#stderr = stderr_;
3000
- }
3001
- /**
3002
- * Sets the interactive manager for handling interactive output.
3003
- * @param manager The interactive manager instance, or undefined to disable
3004
- */
3005
- setInteractiveManager(manager) {
3006
- this.#interactiveManager = manager;
3007
- }
3008
- /**
3009
- * Enables or disables interactive mode.
3010
- * @param interactive Whether to enable interactive terminal features
3011
- */
3012
- setIsInteractive(interactive) {
3013
- this.#interactive = interactive;
3014
- }
3015
- log(meta) {
3016
- this._log(this._formatMessage(meta), meta.type.level);
3017
- }
3018
- // eslint-disable-next-line sonarjs/cognitive-complexity, no-underscore-dangle
3019
- _formatMessage(data) {
3020
- const { columns } = terminalSize();
3021
- let size = columns;
3022
- if (typeof this.styles.messageLength === "number") {
3023
- size = this.styles.messageLength;
3024
- }
3025
- const { badge, context, date, error, file, groups, label, message, prefix, repeated, scope, suffix, traceError, type } = data;
3026
- const { color } = this.loggerTypes[type.name];
3027
- const colorized = color ? colorize[color] : white;
3028
- const groupSpaces = groups.map(() => " ").join("");
3029
- const items = [];
3030
- if (groups.length > 0) {
3031
- items.push(`${groupSpaces + grey(`[${groups.at(-1)}]`)} `);
3032
- }
3033
- if (date) {
3034
- items.push(`${grey(this.styles.dateFormatter(typeof date === "string" ? new Date(date) : date))} `);
3035
- }
3036
- if (badge) {
3037
- items.push(colorized(badge));
3038
- } else {
3039
- const longestBadge = getLongestBadge(this.loggerTypes);
3040
- if (longestBadge.length > 0) {
3041
- items.push(`${grey(".".repeat(longestBadge.length))} `);
3042
- }
3043
- }
3044
- const longestLabel = getLongestLabel(this.loggerTypes);
3045
- if (label) {
3046
- const longestLabelWidth = getStringWidth(longestLabel);
3047
- const labelWidth = getStringWidth(label);
3048
- items.push(`${colorized(formatLabel(label, this.styles))} `, grey(".".repeat(Math.max(0, longestLabelWidth - labelWidth))));
3049
- } else {
3050
- items.push(grey(".".repeat(longestLabel.length + 2)));
3051
- }
3052
- if (repeated) {
3053
- items.push(`${bgGrey.white(`[${repeated}x]`)} `);
3054
- }
3055
- if (Array.isArray(scope) && scope.length > 0) {
3056
- items.push(` ${grey(`[${scope.join(" > ")}]`)} `);
3057
- }
3058
- if (prefix) {
3059
- items.push(
3060
- `${grey(`${Array.isArray(scope) && scope.length > 0 ? ". " : " "}[${this.styles.underline.prefix ? underline(prefix) : prefix}]`)} `
3061
- );
3062
- }
3063
- const titleSize = getStringWidth(items.join(" "));
3064
- if (file) {
3065
- const fileMessage = file.name + (file.line ? `:${file.line}` : "");
3066
- const fileMessageSize = getStringWidth(fileMessage);
3067
- if (fileMessageSize + titleSize + 2 > size) {
3068
- items.push(grey(` ${fileMessage}`));
3069
- } else {
3070
- const dots = Math.max(0, size - titleSize - fileMessageSize - 2);
3071
- items.push(grey(`${".".repeat(dots)} ${fileMessage}`));
3072
- }
3073
- } else {
3074
- items.push(grey(".".repeat(Math.max(0, size - titleSize - 1))));
3075
- }
3076
- if (items.length > 0) {
3077
- items.push("\n\n");
3078
- }
3079
- if (message !== EMPTY_SYMBOL) {
3080
- const formattedMessage = typeof message === "string" ? message : inspect(message, this.#inspectOptions);
3081
- items.push(
3082
- groupSpaces + wordWrap(formattedMessage, {
3083
- trim: false,
3084
- width: size - 3,
3085
- wrapMode: WrapMode.STRICT_WIDTH
3086
- })
3087
- );
3088
- }
3089
- if (context) {
3090
- let hasError = false;
3091
- items.push(
3092
- ...context.map((value) => {
3093
- if (value instanceof Error) {
3094
- hasError = true;
3095
- return `
3096
-
3097
- ${renderError(value, {
3098
- ...this.#errorOptions,
3099
- filterStacktrace: pailFileFilter,
3100
- prefix: groupSpaces
3101
- })}`;
3102
- }
3103
- if (typeof value === "object") {
3104
- return ` ${inspect(value, this.#inspectOptions)}`;
3105
- }
3106
- const newValue = (hasError ? "\n\n" : " ") + value;
3107
- hasError = false;
3108
- return newValue;
3109
- })
3110
- );
3111
- }
3112
- if (error) {
3113
- items.push(
3114
- renderError(error, {
3115
- ...this.#errorOptions,
3116
- filterStacktrace: pailFileFilter,
3117
- prefix: groupSpaces
3118
- })
3119
- );
3120
- }
3121
- if (traceError) {
3122
- items.push(
3123
- `
3124
-
3125
- ${renderError(traceError, {
3126
- ...this.#errorOptions,
3127
- filterStacktrace: pailFileFilter,
3128
- hideErrorCauseCodeView: true,
3129
- hideErrorCodeView: true,
3130
- hideErrorErrorsCodeView: true,
3131
- hideMessage: true,
3132
- prefix: groupSpaces
3133
- })}`
3134
- );
3135
- }
3136
- if (suffix) {
3137
- items.push("\n", groupSpaces + grey(this.styles.underline.suffix ? underline(suffix) : suffix));
3138
- }
3139
- return items.join("");
3140
- }
3141
- // eslint-disable-next-line no-underscore-dangle
3142
- _log(message, logLevel) {
3143
- const streamType = ["error", "trace", "warn"].includes(logLevel) ? "stderr" : "stdout";
3144
- const stream = streamType === "stderr" ? this.#stderr : this.#stdout;
3145
- if (this.#interactive && this.#interactiveManager !== void 0 && stream.isTTY) {
3146
- this.#interactiveManager.update(streamType, message.split("\n"), 0);
3147
- } else {
3148
- writeStream(`${message}
3149
- `, stream);
3150
- }
3151
- }
3152
- }
3153
-
3154
- const getDefaultLogLevel = () => {
3155
- if (env.NODE_ENV === "debug" || env.DEBUG !== void 0) {
3156
- return "debug";
3157
- }
3158
- if (env.NODE_ENV === "test") {
3159
- return "warning";
3160
- }
3161
- return "informational";
3162
- };
3163
- const createPail = (options) => {
3164
- let logLevel = getDefaultLogLevel();
3165
- if (env.PAIL_LOG_LEVEL !== void 0) {
3166
- logLevel = env.PAIL_LOG_LEVEL;
3167
- }
3168
- return new PailServer({
3169
- logLevel,
3170
- processors: [new MessageFormatterProcessor()],
3171
- reporters: [new PrettyReporter()],
3172
- stderr,
3173
- stdout,
3174
- ...options
3175
- });
3176
- };
3177
- const pail = createPail();
3178
-
3179
- export { MultiProgressBar, MultiSpinner, ProgressBar, Spinner, createPail, pail };
1
+ import{createRequire as Ge}from"node:module";import{InteractiveManager as Je,InteractiveStreamHook as ke}from"@visulima/interactive-manager";import{g as ie,E as Ue,a as $e,L as We,j as oe,r as Ie,b as Ne,A as ze,c as Ye,d as He,e as Qe,f as Z,h as Xe,V as Ke,U as le,i as Ze}from"./packem_shared/abstract-pretty-reporter-DrLBJ6ds.js";import Pe from"@visulima/colorize";import{PailError as pr,createPailError as mr}from"./packem_shared/PailError-CbU1Ogfa.js";const Fe=Ge(import.meta.url),U=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,qe=r=>{if(typeof U<"u"&&U.versions&&U.versions.node){const[e,t]=U.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return U.getBuiltinModule(r)}return Fe(r)},{stdout:Se,stderr:ve,env:H}=U,{createRequire:Ve}=qe("node:module"),et="\x1B",me="\x1B[";Ve(import.meta.url);const tt=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ee=tt,rt=(r,e,t,s)=>{if(t==="length"||t==="prototype"||t==="arguments"||t==="caller")return;const i=Object.getOwnPropertyDescriptor(r,t),o=Object.getOwnPropertyDescriptor(e,t);!st(i,o)&&s||Object.defineProperty(r,t,o)},st=function(r,e){return r===void 0||r.configurable||r.writable===e.writable&&r.enumerable===e.enumerable&&r.configurable===e.configurable&&(r.writable||r.value===e.value)},it=(r,e)=>{const t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(r)&&Object.setPrototypeOf(r,t)},ot=(r,e)=>`/* Wrapped ${r}*/
2
+ ${e}`,nt=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),at=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),lt=(r,e,t)=>{const s=t===""?"":`with ${t.trim()}() `,i=ot.bind(null,s,e.toString());Object.defineProperty(i,"name",at);const{writable:o,enumerable:l,configurable:a}=nt;Object.defineProperty(r,"toString",{value:i,writable:o,enumerable:l,configurable:a})};function ct(r,e,{ignoreNonConfigurable:t=!1}={}){const{name:s}=r;for(const i of Reflect.ownKeys(e))rt(r,e,i,t);return it(r,e),lt(r,e,s),r}const ne=new WeakMap,Re=(r,e={})=>{if(typeof r!="function")throw new TypeError("Expected a function");let t,s=0;const i=r.displayName||r.name||"<anonymous>",o=function(...l){if(ne.set(o,++s),s===1)t=r.apply(this,l),r=void 0;else if(e.throw===!0)throw new Error(`Function \`${i}\` can only be called once`);return t};return ct(o,r),ne.set(o,s),o};Re.callCount=r=>{if(!ne.has(r))throw new Error(`The given function \`${r.name}\` is not wrapped by the \`onetime\` package`);return ne.get(r)};const W=[];W.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&W.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&W.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");const re=r=>!!r&&!0&&typeof r.removeListener=="function"&&typeof r.emit=="function"&&typeof r.reallyExit=="function"&&typeof r.listeners=="function"&&typeof r.kill=="function"&&typeof r.pid=="number"&&typeof r.on=="function",ce=Symbol.for("signal-exit emitter"),fe=globalThis,ft=Object.defineProperty.bind(Object);let ht=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(fe[ce])return fe[ce];ft(fe,ce,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const s=this.listeners[e],i=s.indexOf(t);i!==-1&&(i===0&&s.length===1?s.length=0:s.splice(i,1))}emit(e,t,s){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(const o of this.listeners[e])i=o(t,s)===!0||i;return e==="exit"&&(i=this.emit("afterExit",t,s)||i),i}},Ce=class{};const ut=r=>({onExit(e,t){return r.onExit(e,t)},load(){return r.load()},unload(){return r.unload()}});let gt=class extends Ce{onExit(){return()=>{}}load(){}unload(){}};class dt extends Ce{#r=be.platform==="win32"?"SIGINT":"SIGHUP";#t=new ht;#e;#i;#s;#n={};#o=!1;constructor(e){super(),this.#e=e,this.#n={};for(const t of W)this.#n[t]=()=>{const s=this.#e.listeners(t);let{count:i}=this.#t;const o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(i+=o.__signal_exit_emitter__.count),s.length===i){this.unload();const l=this.#t.emit("exit",null,t),a=t==="SIGHUP"?this.#r:t;l||e.kill(e.pid,a)}};this.#s=e.reallyExit,this.#i=e.emit}onExit(e,t){if(!re(this.#e))return()=>{};this.#o===!1&&this.load();const s=t?.alwaysLast?"afterExit":"exit";return this.#t.on(s,e),()=>{this.#t.removeListener(s,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#t.count+=1;for(const e of W)try{const t=this.#n[e];t&&this.#e.on(e,t)}catch{}this.#e.emit=(e,...t)=>this.#l(e,...t),this.#e.reallyExit=e=>this.#a(e)}}unload(){this.#o&&(this.#o=!1,W.forEach(e=>{const t=this.#n[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch{}}),this.#e.emit=this.#i,this.#e.reallyExit=this.#s,this.#t.count-=1)}#a(e){return re(this.#e)?(this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#s.call(this.#e,this.#e.exitCode)):0}#l(e,...t){const s=this.#i;if(e==="exit"&&re(this.#e)){typeof t[0]=="number"&&(this.#e.exitCode=t[0]);const i=s.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),i}else return s.call(this.#e,e,...t)}}const be=globalThis.process,{onExit:pt}=ut(re(be)?new dt(be):new gt),Ee=ee.stderr.isTTY?ee.stderr:ee.stdout.isTTY?ee.stdout:void 0;Ee&&Re(()=>{pt(()=>{Ee.write("\x1B[?25h")},{alwaysLast:!0})});const mt=typeof globalThis<"u"&&typeof globalThis.window=="object"&&globalThis.window.document!==void 0,bt=/^(?:msys|cygwin)$/,yt=!mt&&(process.platform==="win32"||bt.test(process.env.OSTYPE));var wt=(r=>(r[r.Default=0]="Default",r[r.BlinkingBlock=1]="BlinkingBlock",r[r.SteadyBlock=2]="SteadyBlock",r[r.BlinkingUnderline=3]="BlinkingUnderline",r[r.SteadyUnderline=4]="SteadyUnderline",r[r.BlinkingBar=5]="BlinkingBar",r[r.SteadyBar=6]="SteadyBar",r))(wt||{}),se=(r=>(r[r.ToEnd=0]="ToEnd",r[r.ToBeginning=1]="ToBeginning",r[r.EntireScreen=2]="EntireScreen",r[r.EntireScreenAndScrollback=3]="EntireScreenAndScrollback",r))(se||{});const he=r=>{const e=r>=0&&r<=3?r:0;return`${me}${e===0?"":String(e)}J`};var xt=(r=>(r[r.ToEnd=0]="ToEnd",r[r.ToBeginning=1]="ToBeginning",r[r.EntireLine=2]="EntireLine",r))(xt||{});const Me=yt?`${he(se.EntireScreen)}${me}0f`:`${he(se.EntireScreen)}${he(se.EntireScreenAndScrollback)}${me}H${et}c`;var te={exports:{}},Oe;function St(){return Oe||(Oe=1,(function(r,e){const{hasOwnProperty:t}=Object.prototype,s=R();s.configure=R,s.stringify=s,s.default=s,e.stringify=s,e.configure=R,r.exports=s;const i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function o(f){return f.length<5e3&&!i.test(f)?`"${f}"`:JSON.stringify(f)}function l(f,h){if(f.length>200||h)return f.sort(h);for(let u=1;u<f.length;u++){const I=f[u];let A=u;for(;A!==0&&f[A-1]>I;)f[A]=f[A-1],A--;f[A]=I}return f}const a=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function g(f){return a.call(f)!==void 0&&f.length!==0}function m(f,h,u){f.length<u&&(u=f.length);const I=h===","?"":" ";let A=`"0":${I}${f[0]}`;for(let M=1;M<u;M++)A+=`${h}"${M}":${I}${f[M]}`;return A}function y(f){if(t.call(f,"circularValue")){const h=f.circularValue;if(typeof h=="string")return`"${h}"`;if(h==null)return h;if(h===Error||h===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function c(f){let h;if(t.call(f,"deterministic")&&(h=f.deterministic,typeof h!="boolean"&&typeof h!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return h===void 0?!0:h}function w(f,h){let u;if(t.call(f,h)&&(u=f[h],typeof u!="boolean"))throw new TypeError(`The "${h}" argument must be of type boolean`);return u===void 0?!0:u}function d(f,h){let u;if(t.call(f,h)){if(u=f[h],typeof u!="number")throw new TypeError(`The "${h}" argument must be of type number`);if(!Number.isInteger(u))throw new TypeError(`The "${h}" argument must be an integer`);if(u<1)throw new RangeError(`The "${h}" argument must be >= 1`)}return u===void 0?1/0:u}function $(f){return f===1?"1 item":`${f} items`}function D(f){const h=new Set;for(const u of f)(typeof u=="string"||typeof u=="number")&&h.add(String(u));return h}function J(f){if(t.call(f,"strict")){const h=f.strict;if(typeof h!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(h)return u=>{let I=`Object can not safely be stringified. Received type ${typeof u}`;throw typeof u!="function"&&(I+=` (${u.toString()})`),new Error(I)}}}function R(f){f={...f};const h=J(f);h&&(f.bigint===void 0&&(f.bigint=!1),"circularValue"in f||(f.circularValue=Error));const u=y(f),I=w(f,"bigint"),A=c(f),M=typeof A=="function"?A:void 0,B=d(f,"maximumDepth"),k=d(f,"maximumBreadth");function Q(N,n,p,v,x,L){let b=n[N];switch(typeof b=="object"&&b!==null&&typeof b.toJSON=="function"&&(b=b.toJSON(N)),b=v.call(n,N,b),typeof b){case"string":return o(b);case"object":{if(b===null)return"null";if(p.indexOf(b)!==-1)return u;let S="",O=",";const j=L;if(Array.isArray(b)){if(b.length===0)return"[]";if(B<p.length+1)return'"[Array]"';p.push(b),x!==""&&(L+=x,S+=`
3
+ ${L}`,O=`,
4
+ ${L}`);const C=Math.min(b.length,k);let q=0;for(;q<C-1;q++){const K=Q(String(q),b,p,v,x,L);S+=K!==void 0?K:"null",S+=O}const V=Q(String(q),b,p,v,x,L);if(S+=V!==void 0?V:"null",b.length-1>k){const K=b.length-k-1;S+=`${O}"... ${$(K)} not stringified"`}return x!==""&&(S+=`
5
+ ${j}`),p.pop(),`[${S}]`}let E=Object.keys(b);const _=E.length;if(_===0)return"{}";if(B<p.length+1)return'"[Object]"';let T="",P="";x!==""&&(L+=x,O=`,
6
+ ${L}`,T=" ");const G=Math.min(_,k);A&&!g(b)&&(E=l(E,M)),p.push(b);for(let C=0;C<G;C++){const q=E[C],V=Q(q,b,p,v,x,L);V!==void 0&&(S+=`${P}${o(q)}:${T}${V}`,P=O)}if(_>k){const C=_-k;S+=`${P}"...":${T}"${$(C)} not stringified"`,P=O}return x!==""&&P.length>1&&(S=`
7
+ ${L}${S}
8
+ ${j}`),p.pop(),`{${S}}`}case"number":return isFinite(b)?String(b):h?h(b):"null";case"boolean":return b===!0?"true":"false";case"undefined":return;case"bigint":if(I)return String(b);default:return h?h(b):void 0}}function X(N,n,p,v,x,L){switch(typeof n=="object"&&n!==null&&typeof n.toJSON=="function"&&(n=n.toJSON(N)),typeof n){case"string":return o(n);case"object":{if(n===null)return"null";if(p.indexOf(n)!==-1)return u;const b=L;let S="",O=",";if(Array.isArray(n)){if(n.length===0)return"[]";if(B<p.length+1)return'"[Array]"';p.push(n),x!==""&&(L+=x,S+=`
9
+ ${L}`,O=`,
10
+ ${L}`);const _=Math.min(n.length,k);let T=0;for(;T<_-1;T++){const G=X(String(T),n[T],p,v,x,L);S+=G!==void 0?G:"null",S+=O}const P=X(String(T),n[T],p,v,x,L);if(S+=P!==void 0?P:"null",n.length-1>k){const G=n.length-k-1;S+=`${O}"... ${$(G)} not stringified"`}return x!==""&&(S+=`
11
+ ${b}`),p.pop(),`[${S}]`}p.push(n);let j="";x!==""&&(L+=x,O=`,
12
+ ${L}`,j=" ");let E="";for(const _ of v){const T=X(_,n[_],p,v,x,L);T!==void 0&&(S+=`${E}${o(_)}:${j}${T}`,E=O)}return x!==""&&E.length>1&&(S=`
13
+ ${L}${S}
14
+ ${b}`),p.pop(),`{${S}}`}case"number":return isFinite(n)?String(n):h?h(n):"null";case"boolean":return n===!0?"true":"false";case"undefined":return;case"bigint":if(I)return String(n);default:return h?h(n):void 0}}function z(N,n,p,v,x){switch(typeof n){case"string":return o(n);case"object":{if(n===null)return"null";if(typeof n.toJSON=="function"){if(n=n.toJSON(N),typeof n!="object")return z(N,n,p,v,x);if(n===null)return"null"}if(p.indexOf(n)!==-1)return u;const L=x;if(Array.isArray(n)){if(n.length===0)return"[]";if(B<p.length+1)return'"[Array]"';p.push(n),x+=v;let T=`
15
+ ${x}`;const P=`,
16
+ ${x}`,G=Math.min(n.length,k);let C=0;for(;C<G-1;C++){const V=z(String(C),n[C],p,v,x);T+=V!==void 0?V:"null",T+=P}const q=z(String(C),n[C],p,v,x);if(T+=q!==void 0?q:"null",n.length-1>k){const V=n.length-k-1;T+=`${P}"... ${$(V)} not stringified"`}return T+=`
17
+ ${L}`,p.pop(),`[${T}]`}let b=Object.keys(n);const S=b.length;if(S===0)return"{}";if(B<p.length+1)return'"[Object]"';x+=v;const O=`,
18
+ ${x}`;let j="",E="",_=Math.min(S,k);g(n)&&(j+=m(n,O,k),b=b.slice(n.length),_-=n.length,E=O),A&&(b=l(b,M)),p.push(n);for(let T=0;T<_;T++){const P=b[T],G=z(P,n[P],p,v,x);G!==void 0&&(j+=`${E}${o(P)}: ${G}`,E=O)}if(S>k){const T=S-k;j+=`${E}"...": "${$(T)} not stringified"`,E=O}return E!==""&&(j=`
19
+ ${x}${j}
20
+ ${L}`),p.pop(),`{${j}}`}case"number":return isFinite(n)?String(n):h?h(n):"null";case"boolean":return n===!0?"true":"false";case"undefined":return;case"bigint":if(I)return String(n);default:return h?h(n):void 0}}function Y(N,n,p){switch(typeof n){case"string":return o(n);case"object":{if(n===null)return"null";if(typeof n.toJSON=="function"){if(n=n.toJSON(N),typeof n!="object")return Y(N,n,p);if(n===null)return"null"}if(p.indexOf(n)!==-1)return u;let v="";const x=n.length!==void 0;if(x&&Array.isArray(n)){if(n.length===0)return"[]";if(B<p.length+1)return'"[Array]"';p.push(n);const j=Math.min(n.length,k);let E=0;for(;E<j-1;E++){const T=Y(String(E),n[E],p);v+=T!==void 0?T:"null",v+=","}const _=Y(String(E),n[E],p);if(v+=_!==void 0?_:"null",n.length-1>k){const T=n.length-k-1;v+=`,"... ${$(T)} not stringified"`}return p.pop(),`[${v}]`}let L=Object.keys(n);const b=L.length;if(b===0)return"{}";if(B<p.length+1)return'"[Object]"';let S="",O=Math.min(b,k);x&&g(n)&&(v+=m(n,",",k),L=L.slice(n.length),O-=n.length,S=","),A&&(L=l(L,M)),p.push(n);for(let j=0;j<O;j++){const E=L[j],_=Y(E,n[E],p);_!==void 0&&(v+=`${S}${o(E)}:${_}`,S=",")}if(b>k){const j=b-k;v+=`${S}"...":"${$(j)} not stringified"`}return p.pop(),`{${v}}`}case"number":return isFinite(n)?String(n):h?h(n):"null";case"boolean":return n===!0?"true":"false";case"undefined":return;case"bigint":if(I)return String(n);default:return h?h(n):void 0}}function De(N,n,p){if(arguments.length>1){let v="";if(typeof p=="number"?v=" ".repeat(Math.min(p,10)):typeof p=="string"&&(v=p.slice(0,10)),n!=null){if(typeof n=="function")return Q("",{"":N},[],n,v,"");if(Array.isArray(n))return X("",N,[],D(n),v,"")}if(v.length!==0)return z("",N,[],v,"")}return Y("",N,[])}return De}})(te,te.exports)),te.exports}var vt=St();class $t{#r=new Map;#t;constructor(e){this.#t=e}count(e="default"){const t=this.#r.get(e)??0;this.#r.set(e,t+1),this.#t("log",!1,!1,{message:`${e}: ${String(t+1)}`,prefix:e})}countReset(e="default"){this.#r.has(e)?this.#r.delete(e):this.#t("warn",!1,!1,{message:`Count for ${e} does not exist`,prefix:e})}}const Lt=new Set(["alert","critical","emergency","error"]),Tt=r=>{const e=console;return Lt.has(r)?e.__error??console.error:r==="warning"?e.__warn??console.warn:r==="trace"?e.__trace??console.trace:e.__log??console.log};class kt{log(e){const{context:t=[],message:s,type:i}=e;Tt(i.level)(s,...t)}}class Et{#r=new Map;#t=new Set;#e;#i;#s;constructor(e,t,s){this.#s=e,this.#e=t,this.#i=s}time(e="default"){this.#t.has(e)?this.#s("warn",!1,!1,{message:`Timer '${e}' already exists`,prefix:e}):(this.#t.add(e),this.#r.set(e,Date.now()),this.#s("start",!1,!1,{message:this.#e,prefix:e}))}timeLog(e,...t){if(!e&&this.#t.size>0&&(e=[...this.#t].pop()),e&&this.#r.has(e)){const s=Date.now()-this.#r.get(e);this.#s("info",!1,!1,{context:t,message:s<1e3?`${String(s)} ms`:`${(s/1e3).toFixed(2)} s`,prefix:e})}else this.#s("warn",!1,!1,{context:t,message:"Timer not found",prefix:e})}timeEnd(e){if(!e&&this.#t.size>0&&(e=[...this.#t].pop()),e&&this.#r.has(e)){const t=Date.now()-this.#r.get(e);this.#r.delete(e),this.#s("stop",!1,!1,{message:`${this.#i} ${t<1e3?`${String(t)} ms`:`${(t/1e3).toFixed(2)} s`}`,prefix:e})}else this.#s("warn",!1,!1,{message:"Timer not found",prefix:e})}}const ye=r=>r===void 0?[]:Array.isArray(r)?r:[r],we=(r,e)=>{const t={...r};return Object.keys(e).forEach(s=>{t[s]={...t[s],...e[s]}}),t},Mt=r=>{let e=!1;return function(...t){if(!e){e=!0;try{const s=r.apply(this,t);return e=!1,s}catch(s){throw e=!1,s}}}};class Le{timerManager;counterManager;lastLog;logLevels;disabled;paused;messageQueue;scopeName;types;longestLabel;processors;generalLogLevel;reporters;throttle;throttleMin;stringify;groups;startTimerMessage;endTimerMessage;rawReporter;force={};#r=new Set;#t;#e;constructor(e){this.throttle=e.throttle??1e3,this.throttleMin=e.throttleMin??5;const t=e.parentLongestLabel,s=e.parentTypes,i=e.parentStringify,o=e.parentLogLevels;this.stringify=i??vt.configure({strict:!0}),this.startTimerMessage=e.messages?.timerStart??"Initialized timer...",this.endTimerMessage=e.messages?.timerEnd??"Timer run for:",s&&t?(this.types=s,this.longestLabel=t):(this.types=we(We,e.types??{}),this.longestLabel=ie(this.types)),this.logLevels=o&&!e.logLevels?o:{...Ue,...e.logLevels},this.generalLogLevel=this.#n(e.logLevel),this.reporters=new Set,this.processors=new Set,this.disabled=e.disabled??!1,this.paused=!1,this.messageQueue=[],this.scopeName=ye(e.scope).filter(Boolean),this.timerManager=new Et((l,a,g,...m)=>{this.logger(l,a,g,...m)},this.startTimerMessage,this.endTimerMessage),this.counterManager=new $t((l,a,g,...m)=>{this.logger(l,a,g,...m)}),this.groups=[],this.lastLog={},this.logger=Mt(this.logger.bind(this)),this.#i(),Array.isArray(e.reporters)&&this.registerReporters(e.reporters),this.rawReporter=this.extendReporter(e.rawReporter??new kt),Array.isArray(e.processors)&&this.registerProcessors(e.processors)}#i(){for(const e in this.types)this[e]=this.logger.bind(this,e,!1,!1);for(const e in this.types)this.force[e]=this.logger.bind(this,e,!1,!0);this.raw=this.raw.bind(this)}wrapConsole(){for(const e in this.types)console[`__${e}`]||(console[`__${e}`]=console[e]),console[e]=this[e]}restoreConsole(){for(const e in this.types)console[`__${e}`]&&(console[e]=console[`__${e}`],delete console[`__${e}`])}wrapException(){this.#t||this.#e||(this.#t=e=>{this.error(e)},this.#e=e=>{this.error(e)},process.on("uncaughtException",this.#t),process.on("unhandledRejection",this.#e))}restoreException(){this.#t&&(process.off("uncaughtException",this.#t),this.#t=void 0),this.#e&&(process.off("unhandledRejection",this.#e),this.#e=void 0)}disable(){this.disabled=!0}enable(){this.disabled=!1}isEnabled(){return!this.disabled}pause(){this.paused=!0}resume(){this.paused=!1;const e=this.messageQueue.splice(0);for(let t=0;t<e.length;t+=1){const{messageObject:s,raw:i,type:o}=e[t];this.logger(o,i,!1,...s)}}scope(...e){if(e.length===0)throw new Error("No scope name was defined.");return this.child({scope:e})}unscope(){this.scopeName=[]}child(e){const t=e?.types!==void 0,s=t?we(this.types,e.types):this.types,i=e?.reporters??[],o=i.length>0?[...this.reporters,...i]:[...this.reporters],l=e?.processors??[],a=l.length>0?[...this.processors,...l]:[...this.processors],g=e?.logLevels?{...this.logLevels,...e.logLevels}:this.logLevels;let m;if(e?.scope){const w=ye(e.scope).filter(Boolean);m=this.scopeName.length>0?[...this.scopeName,...w]:w}else m=this.scopeName.length>0?this.scopeName:[];const y=e?.messages?{timerEnd:this.endTimerMessage,timerStart:this.startTimerMessage,...e.messages}:{timerEnd:this.endTimerMessage,timerStart:this.startTimerMessage},c={disabled:e?.disabled??this.disabled,logLevel:e?.logLevel??this.generalLogLevel,logLevels:g,messages:y,processors:a,rawReporter:e?.rawReporter??this.rawReporter,reporters:o,scope:m,throttle:e?.throttle??this.throttle,throttleMin:e?.throttleMin??this.throttleMin};return t?(c.parentTypes=s,c.parentLongestLabel=ie(s)):(c.parentTypes=this.types,c.parentLongestLabel=this.longestLabel),e?.logLevels||(c.parentLogLevels=this.logLevels),e?.messages||(c.parentMessages={timerEnd:this.endTimerMessage,timerStart:this.startTimerMessage}),c.parentStringify=this.stringify,new Le(c)}time(e="default"){this.timerManager.time(e)}timeLog(e,...t){this.timerManager.timeLog(e,...t)}timeEnd(e){this.timerManager.timeEnd(e)}group(e="console.group"){globalThis.window===void 0?this.groups.push(e):console.group(e)}groupEnd(){globalThis.window===void 0?this.groups.pop():console.groupEnd()}count(e="default"){this.counterManager.count(e)}countReset(e="default"){this.counterManager.countReset(e)}clear(){console.clear()}raw(e,...t){this.disabled||this.logger("log",!0,!1,{context:t,message:e})}extendReporter(e){return typeof e.setLoggerTypes=="function"&&e.setLoggerTypes(this.types),typeof e.setStringify=="function"&&e.setStringify(this.stringify),e}registerReporters(e){for(let t=0;t<e.length;t+=1)this.reporters.add(this.extendReporter(e[t]))}registerProcessors(e){for(let t=0;t<e.length;t+=1){const s=e[t];typeof s.setStringify=="function"&&s.setStringify(this.stringify),this.processors.add(s)}}#s(e,t){if(t)this.rawReporter.log(Object.freeze(e));else for(const s of this.reporters)s.log(Object.freeze(e))}#n(e){let t="debug";return e!==void 0&&Object.hasOwn(this.logLevels,e)?t=e:e!==void 0&&!this.#r.has(e)&&(this.#r.add(e),console.warn(`[pail] Unknown log level "${String(e)}". Valid levels: ${Object.keys(this.logLevels).join(", ")}. Falling back to "debug".`)),t}#o(e,t,...s){const i={badge:void 0,context:void 0,error:void 0,label:void 0,message:$e,prefix:void 0,repeated:void 0,scope:void 0,suffix:void 0};if(i.type={level:t.logLevel,name:e},i.groups=this.groups,i.scope=this.scopeName,i.date=new Date,s.length>0&&s[0]instanceof Error)i.error=s[0],s.length>1&&(i.context=s.slice(1));else if(s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"message"in s[0]){const{context:o,message:l,prefix:a,suffix:g}=s[0];if(o&&(i.context=o),a&&(i.prefix=a),g&&(i.suffix=g),i.message=l,s.length>1){const m=s.slice(1);i.context?i.context=Array.isArray(i.context)?[...i.context,...m]:[i.context,...m]:i.context=m}}else s.length>1?(i.message=s[0],i.context=s.slice(1)):s.length===1?i.message=s[0]:i.message=void 0;return t.logLevel==="trace"&&(i.traceError=new Error("Trace")),t.badge&&(i.badge=t.badge),t.label&&(i.label=t.label),i}logger(e,t,s,...i){if(this.disabled)return;if(this.paused){this.messageQueue.push({messageObject:i,raw:t,type:e});return}const o=this.types[e],l=this.#n(o.logLevel);if(s||this.logLevels[l]>=this.logLevels[this.generalLogLevel]){let a=this.#o(e,o,...i),g;try{g=JSON.stringify([a.label,a.scope,a.type,a.message,a.prefix,a.suffix,a.context])}catch{g=void 0}const m=this.processors.size>0,y=(d=!1)=>{const $=(this.lastLog.count??0)-this.throttleMin;if(this.lastLog.object&&$>0){const D={...this.lastLog.object};$>1&&(D.repeated=$),this.#s(D,t),this.lastLog.count=1}if(d){for(const D of this.processors)a=D.process(a);if(a.dropped===!0)return;if(this.lastLog.object=a,m)try{this.lastLog.signature=JSON.stringify([a.label,a.scope,a.type,a.message,a.prefix,a.suffix,a.context])}catch{this.lastLog.signature=void 0}else this.lastLog.signature=g;this.#s(a,t)}};clearTimeout(this.lastLog.timeout);const c=a.date instanceof Date?a.date:new Date(a.date),w=this.lastLog.time?c.getTime()-this.lastLog.time.getTime():0;if(this.lastLog.time=c,w<this.throttle)try{const d=g;if(this.lastLog.object&&d!==void 0&&d===this.lastLog.signature&&(this.lastLog.count=(this.lastLog.count??0)+1,this.lastLog.count>this.throttleMin)){this.lastLog.timeout=setTimeout(y,this.throttle);return}}catch{}y(!0)}}}let Ot=class{#r;#t;#e;#i=!1;#s;constructor(e={}){this.#r=Se,this.#t=ve,this.#s=e}setStdout(e){this.#r=e}setStderr(e){this.#t=e}setInteractiveManager(e){this.#e=e}setIsInteractive(e){this.#i=e}log(e){const{context:t,groups:s,message:i,type:o}=e,l=[];if(i!==$e){const y=typeof i=="string"?i:oe(i,this.#s);l.push(y)}t&&l.push(...t.map(y=>typeof y=="object"?` ${oe(y,this.#s)}`:` ${String(y)}`));const a=Ie(o.level)?"stderr":"stdout",g=a==="stderr"?this.#t:this.#r,m=s.map(()=>" ").join("");this.#i&&this.#e!==void 0&&g.isTTY?this.#e.update(a,(m+l.join("")).split(`
21
+ `),0):Ne(m+l.join(""),g)}};class Te extends Le{constructor(e){const t=e.parentStderr,s=e.parentStdout,{interactive:i,processors:o,rawReporter:l,reporters:a,stderr:g,stdout:m}=e,y=t??g,c=s??m,w=e.parentLongestLabel,d=e.parentTypes,{parentLogLevels:$,parentMessages:D,parentStringify:J}=e,R={disabled:e.disabled,logLevel:e.logLevel,logLevels:e.logLevels,messages:e.messages,processors:[],rawReporter:e.rawReporter,reporters:[],scope:e.scope,throttle:e.throttle,throttleMin:e.throttleMin},f="types"in e;d&&w&&!f?(R.parentTypes=d,R.parentLongestLabel=w):f&&e.types!==void 0&&(R.types=e.types),J&&(R.parentStringify=J),$&&!e.logLevels&&(R.parentLogLevels=$),D&&!e.messages&&(R.parentMessages=D),super(R),this.options=e,this.interactive=i??!1,this.stdout=c,this.stderr=y,this.interactive&&(this.interactiveManager=new Je(new ke(this.stdout),new ke(this.stderr))),Array.isArray(a)&&this.registerReporters(a),this.rawReporter=this.extendReporter(l??new Ot),Array.isArray(o)&&this.registerProcessors(o)}options;stdout;stderr;interactiveManager;interactive;scope(...e){if(e.length===0)throw new Error("No scope name was defined.");return this.child({scope:e})}child(e){const t=e?.types!==void 0,s=t?we(this.types,e.types):this.types,i=e?.reporters??[],o=i.length>0?[...this.reporters,...i]:[...this.reporters],l=e?.processors??[],a=l.length>0?[...this.processors,...l]:[...this.processors],g=e?.logLevels?{...this.logLevels,...e.logLevels}:this.logLevels;let m;if(e?.scope){const w=ye(e.scope).filter(Boolean);m=this.scopeName.length>0?[...this.scopeName,...w]:w}else m=this.scopeName.length>0?this.scopeName:[];const y=e?.messages?{timerEnd:this.endTimerMessage,timerStart:this.startTimerMessage,...e.messages}:{timerEnd:this.endTimerMessage,timerStart:this.startTimerMessage},c={disabled:e?.disabled??this.disabled,interactive:e?.interactive??this.interactive,logLevel:e?.logLevel??this.generalLogLevel,logLevels:g,messages:y,processors:a,rawReporter:e?.rawReporter??this.rawReporter,reporters:o,scope:m,stderr:e?.stderr??this.stderr,stdout:e?.stdout??this.stdout,throttle:e?.throttle??this.throttle,throttleMin:e?.throttleMin??this.throttleMin};return this.#r(c,e,t,s),new Te(c)}#r(e,t,s,i){s?(e.parentTypes=i,e.parentLongestLabel=ie(i)):(e.parentTypes=this.types,e.parentLongestLabel=this.longestLabel),t?.logLevels||(e.parentLogLevels=this.logLevels),t?.messages||(e.parentMessages={timerEnd:this.endTimerMessage,timerStart:this.startTimerMessage}),e.parentStringify=this.stringify,t?.stdout||(e.parentStdout=this.stdout),t?.stderr||(e.parentStderr=this.stderr)}getInteractiveManager(){return this.interactiveManager}wrapStd(){this.#t(this.stdout,"log"),this.#t(this.stderr,"error")}restoreStd(){this.#e(this.stdout),this.#e(this.stderr)}wrapAll(){this.wrapConsole(),this.wrapStd()}restoreAll(){this.restoreConsole(),this.restoreStd()}clear(){this.stdout.write(Me),this.stderr.write(Me)}extendReporter(e){return typeof e.setStdout=="function"&&e.setStdout(this.stdout),typeof e.setStderr=="function"&&e.setStderr(this.stderr),typeof e.setLoggerTypes=="function"&&e.setLoggerTypes(this.types),typeof e.setStringify=="function"&&e.setStringify(this.stringify),typeof e.setIsInteractive=="function"&&e.setIsInteractive(this.interactive),this.interactive&&typeof e.setInteractiveManager=="function"&&e.setInteractiveManager(this.interactiveManager),e}#t(e,t){e&&(e.__write||(e.__write=e.write),e.write=s=>{this[t](String(s).trim())})}#e(e){e&&e.__write&&(e.write=e.__write,delete e.__write)}}const jt=Te;let ue;const At=()=>(ue!==void 0||(ue=new Map([["aliceblue","#f0f8ff"],["antiquewhite","#faebd7"],["aqua","#00ffff"],["aquamarine","#7fffd4"],["azure","#f0ffff"],["beige","#f5f5dc"],["bisque","#ffe4c4"],["black","#000000"],["blanchedalmond","#ffebcd"],["blue","#0000ff"],["blueviolet","#8a2be2"],["brown","#a52a2a"],["burlywood","#deb887"],["cadetblue","#5f9ea0"],["chartreuse","#7fff00"],["chocolate","#d2691e"],["coral","#ff7f50"],["cornflowerblue","#6495ed"],["cornsilk","#fff8dc"],["crimson","#dc143c"],["cyan","#00ffff"],["darkblue","#00008b"],["darkcyan","#008b8b"],["darkgoldenrod","#b8860b"],["darkgray","#a9a9a9"],["darkgreen","#006400"],["darkgrey","#a9a9a9"],["darkkhaki","#bdb76b"],["darkmagenta","#8b008b"],["darkolivegreen","#556b2f"],["darkorange","#ff8c00"],["darkorchid","#9932cc"],["darkred","#8b0000"],["darksalmon","#e9967a"],["darkseagreen","#8fbc8f"],["darkslateblue","#483d8b"],["darkslategray","#2f4f4f"],["darkslategrey","#2f4f4f"],["darkturquoise","#00ced1"],["darkviolet","#9400d3"],["deeppink","#ff1493"],["deepskyblue","#00bfff"],["dimgray","#696969"],["dimgrey","#696969"],["dodgerblue","#1e90ff"],["firebrick","#b22222"],["floralwhite","#fffaf0"],["forestgreen","#228b22"],["fuchsia","#ff00ff"],["gainsboro","#dcdcdc"],["ghostwhite","#f8f8ff"],["gold","#ffd700"],["goldenrod","#daa520"],["gray","#808080"],["green","#008000"],["greenyellow","#adff2f"],["grey","#808080"],["honeydew","#f0fff0"],["hotpink","#ff69b4"],["indianred","#cd5c5c"],["indigo","#4b0082"],["ivory","#fffff0"],["khaki","#f0e68c"],["lavender","#e6e6fa"],["lavenderblush","#fff0f5"],["lawngreen","#7cfc00"],["lemonchiffon","#fffacd"],["lightblue","#add8e6"],["lightcoral","#f08080"],["lightcyan","#e0ffff"],["lightgoldenrodyellow","#fafad2"],["lightgray","#d3d3d3"],["lightgreen","#90ee90"],["lightgrey","#d3d3d3"],["lightpink","#ffb6c1"],["lightsalmon","#ffa07a"],["lightseagreen","#20b2aa"],["lightskyblue","#87cefa"],["lightslategray","#778899"],["lightslategrey","#778899"],["lightsteelblue","#b0c4de"],["lightyellow","#ffffe0"],["lime","#00ff00"],["limegreen","#32cd32"],["linen","#faf0e6"],["magenta","#ff00ff"],["maroon","#800000"],["mediumaquamarine","#66cdaa"],["mediumblue","#0000cd"],["mediumorchid","#ba55d3"],["mediumpurple","#9370db"],["mediumseagreen","#3cb371"],["mediumslateblue","#7b68ee"],["mediumspringgreen","#00fa9a"],["mediumturquoise","#48d1cc"],["mediumvioletred","#c71585"],["midnightblue","#191970"],["mintcream","#f5fffa"],["mistyrose","#ffe4e1"],["moccasin","#ffe4b5"],["navajowhite","#ffdead"],["navy","#000080"],["oldlace","#fdf5e6"],["olive","#808000"],["olivedrab","#6b8e23"],["orange","#ffa500"],["orangered","#ff4500"],["orchid","#da70d6"],["palegoldenrod","#eee8aa"],["palegreen","#98fb98"],["paleturquoise","#afeeee"],["palevioletred","#db7093"],["papayawhip","#ffefd5"],["peachpuff","#ffdab9"],["peru","#cd853f"],["pink","#ffc0cb"],["plum","#dda0dd"],["powderblue","#b0e0e6"],["purple","#800080"],["rebeccapurple","#663399"],["red","#ff0000"],["rosybrown","#bc8f8f"],["royalblue","#4169e1"],["saddlebrown","#8b4513"],["salmon","#fa8072"],["sandybrown","#f4a460"],["seagreen","#2e8b57"],["seashell","#fff5ee"],["sienna","#a0522d"],["silver","#c0c0c0"],["skyblue","#87ceeb"],["slateblue","#6a5acd"],["slategray","#708090"],["slategrey","#708090"],["snow","#fffafa"],["springgreen","#00ff7f"],["steelblue","#4682b4"],["tan","#d2b48c"],["teal","#008080"],["thistle","#d8bfd8"],["tomato","#ff6347"],["turquoise","#40e0d0"],["violet","#ee82ee"],["wheat","#f5deb3"],["white","#ffffff"],["whitesmoke","#f5f5f5"],["yellow","#ffff00"],["yellowgreen","#9acd32"]])),ue),_t=/^#([\dA-F]{2})([\dA-F]{2})([\dA-F]{2})([\dA-F]{2})?$/i,Bt=/^#([\dA-F])([\dA-F])([\dA-F])([\dA-F])?$/i,It=/^rgba?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*(,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*)?\)$/,Nt=/^hsla?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%\s*(,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*)?\)$/,xe=()=>({__proto__:null,backgroundColor:null,color:null,fontStyle:null,fontWeight:null,textDecorationColor:null,textDecorationLine:[]}),je=/\s+/,ae=r=>{const e=At();e.has(r)&&(r=e.get(r));const t=_t.exec(r);if(t)return[Number.parseInt(t[1],16),Number.parseInt(t[2],16),Number.parseInt(t[3],16)];const s=Bt.exec(r);if(s)return[Number.parseInt(`${s[1]}${s[1]}`,16),Number.parseInt(`${s[2]}${s[2]}`,16),Number.parseInt(`${s[3]}${s[3]}`,16)];const i=It.exec(r);if(i)return[Math.round(Math.max(0,Math.min(255,Number(i[1])))),Math.round(Math.max(0,Math.min(255,Number(i[2])))),Math.round(Math.max(0,Math.min(255,Number(i[3]))))];const o=Nt.exec(r);if(o){let l=Number(o[1])%360;l<0&&(l+=360);const a=Math.max(0,Math.min(100,Number(o[2])))/100,g=Math.max(0,Math.min(100,Number(o[3])))/100,m=(1-Math.abs(2*g-1))*a,y=m*(1-Math.abs(l/60%2-1)),c=g-m/2;let w,d,$;return l<60?{0:w,1:d,2:$}=[m,y,0]:l<120?{0:w,1:d,2:$}=[y,m,0]:l<180?{0:w,1:d,2:$}=[0,m,y]:l<240?{0:w,1:d,2:$}=[0,y,m]:l<300?{0:w,1:d,2:$}=[y,0,m]:{0:w,1:d,2:$}=[m,0,y],[Math.round((w+c)*255),Math.round((d+c)*255),Math.round(($+c)*255)]}return null},ge=(r,e)=>r?.[0]===e?.[0]&&r?.[1]===e?.[1]&&r?.[2]===e?.[2],Pt=r=>{if(typeof r!="string")return xe();const e=xe(),t=[];let s=!1,i=null,o=0,l="";for(const a of r){if(a==="(")o+=1;else if(o>0)a===")"&&(o-=1);else if(s){if(a===";"){const g=l.trim();g!==""&&t.push([i,g]),i=null,l="",s=!1;continue}}else if(a===":"){i=l.trim(),l="",s=!0;continue}l+=a}if(s&&o===0){const a=l.trim();a!==""&&t.push([i,a]),i=null,l=""}for(const{0:a,1:g}of t)switch(a){case"background-color":{g!=null&&(e.backgroundColor=g);break}case"color":{g!=null&&(e.color=g);break}case"font-style":{["italic","oblique","oblique 14deg"].includes(g)&&(e.fontStyle="italic");break}case"font-weight":{g==="bold"&&(e.fontWeight=g);break}case"text-decoration":{e.textDecorationColor=null,e.textDecorationLine=[];const m=g.split(je);for(const y of m){const c=ae(y);c!=null?e.textDecorationColor=c:["line-through","overline","underline"].includes(y)&&e.textDecorationLine.push(y)}break}case"text-decoration-color":{const m=ae(g);m!=null&&(e.textDecorationColor=m);break}case"text-decoration-line":{e.textDecorationLine=[];const m=g.split(je);for(const y of m)["line-through","overline","underline"].includes(y)&&e.textDecorationLine.push(y);break}}return e},Rt=(r,e)=>{e=e??xe();let t="";if(!ge(r.backgroundColor,e.backgroundColor))if(r.backgroundColor==null)t+="\x1B[49m";else switch(r.backgroundColor){case"black":{t+="\x1B[40m";break}case"blue":{t+="\x1B[44m";break}case"cyan":{t+="\x1B[46m";break}case"green":{t+="\x1B[42m";break}case"magenta":{t+="\x1B[45m";break}case"red":{t+="\x1B[41m";break}case"white":{t+="\x1B[47m";break}case"yellow":{t+="\x1B[43m";break}default:if(Array.isArray(r.backgroundColor)){const{0:s,1:i,2:o}=r.backgroundColor;t+=`\x1B[48;2;${String(s)};${String(i)};${String(o)}m`}else{const s=ae(r.backgroundColor);if(s===null)t+="\x1B[49m";else{const{0:i,1:o,2:l}=s;t+=`\x1B[48;2;${String(i)};${String(o)};${String(l)}m`}}}if(!ge(r.color,e.color))if(r.color==null)t+="\x1B[39m";else switch(r.color){case"black":{t+="\x1B[30m";break}case"blue":{t+="\x1B[34m";break}case"cyan":{t+="\x1B[36m";break}case"green":{t+="\x1B[32m";break}case"magenta":{t+="\x1B[35m";break}case"red":{t+="\x1B[31m";break}case"white":{t+="\x1B[37m";break}case"yellow":{t+="\x1B[33m";break}default:if(Array.isArray(r.color)){const{0:s,1:i,2:o}=r.color;t+=`\x1B[38;2;${String(s)};${String(i)};${String(o)}m`}else{const s=ae(r.color);if(s===null)t+="\x1B[39m";else{const{0:i,1:o,2:l}=s;t+=`\x1B[38;2;${String(i)};${String(o)};${String(l)}m`}}}if(r.fontWeight!==e.fontWeight&&(t+=r.fontWeight==="bold"?"\x1B[1m":"\x1B[22m"),r.fontStyle!==e.fontStyle&&(t+=r.fontStyle==="italic"?"\x1B[3m":"\x1B[23m"),!ge(r.textDecorationColor,e.textDecorationColor))if(r.textDecorationColor==null)t+="\x1B[59m";else{const{0:s,1:i,2:o}=r.textDecorationColor;t+=`\x1B[58;2;${String(s)};${String(i)};${String(o)}m`}return r.textDecorationLine.includes("line-through")!==e.textDecorationLine.includes("line-through")&&(t+=r.textDecorationLine.includes("line-through")?"\x1B[9m":"\x1B[29m"),r.textDecorationLine.includes("overline")!==e.textDecorationLine.includes("overline")&&(t+=r.textDecorationLine.includes("overline")?"\x1B[53m":"\x1B[55m"),r.textDecorationLine.includes("underline")!==e.textDecorationLine.includes("underline")&&(t+=r.textDecorationLine.includes("underline")?"\x1B[4m":"\x1B[24m"),t},Ct=r=>{try{return JSON.stringify(r)}catch{return'"[Circular]"'}},Ae="%".codePointAt(0),Dt="s".codePointAt(0),Gt="d".codePointAt(0),Ft="f".codePointAt(0),qt="i".codePointAt(0),Vt="O".codePointAt(0),Jt="o".codePointAt(0),Ut="j".codePointAt(0),Wt="c".codePointAt(0),_e=(r,e=[],t={})=>{if(typeof r!="string"&&typeof r!="object"||r===null)throw new TypeError(`fmt must be a string or object, got ${r===null?"null":typeof r}`);const s=t.stringify??Ct,i=1;if(typeof r=="object"){const c=e.length+i;if(c===1)return"{}";const w=Array.from({length:c});w[0]=s(r);for(let d=1;d<c;d+=1)w[d]=s(e[d-i]);return w.join(" ")}if(e.length===0)return r;let o="",l=1-i,a=-1,g=!1,m;const y=t.colors??globalThis.window===void 0;for(let c=0;c<r.length;){if(r.codePointAt(c)===Ae&&c+1<r.length){a=a>-1?a:0;const w=r.codePointAt(c+1);switch(w){case Wt:{if(y){const d=Pt(e[l]);a<c&&(o+=r.slice(a,c));const $=Rt(d,m);o+=$,$!==""&&(g=!0,m=d)}a=c+2,c+=1;break}case Gt:case Ft:{const d=e[l];if(l>=e.length||d==null)break;a<c&&(o+=r.slice(a,c)),o+=(typeof d=="symbol"?Number.NaN:Number(d)).toString(),a=c+2,c+=1;break}case qt:{const d=e[l];if(l>=e.length||d==null)break;a<c&&(o+=r.slice(a,c)),o+=Math.floor(typeof d=="symbol"?Number.NaN:Number(d)).toString(),a=c+2,c+=1;break}case Ut:case Vt:case Jt:{if(l>=e.length||e[l]===void 0)break;a<c&&(o+=r.slice(a,c));const d=e[l],$=typeof d;if($==="string"){o+=`'${d}'`,a=c+2,c+=1;break}if($==="function"){o+=d.name?`[Function: ${d.name}]`:"[Function: <anonymous>]",a=c+2,c+=1;break}o+=s(d),a=c+2,c+=1;break}case Ae:{a<c&&(o+=r.slice(a,c)),o+="%",a=c+2,c+=1,l-=1;break}case Dt:{if(l>=e.length)break;a<c&&(o+=r.slice(a,c));const d=e[l];o+=typeof d=="object"&&d!==null?s(d):String(d),a=c+2,c+=1;break}default:typeof t.formatters?.[w]=="function"?(a<c&&(o+=r.slice(a,c)),o+=t.formatters[w](e[l]),a=c+2,c+=1):l-=1}l+=1}c+=1}if(a===-1&&!(t.appendExtraArguments&&l<e.length))return r;if(a===-1?o=r:a<r.length&&(o+=r.slice(a)),a!==-1&&g&&(o+="\x1B[0m"),t.appendExtraArguments&&l<e.length)for(let c=Math.max(l,0);c<e.length;c+=1){const w=e[c];o+=` ${typeof w=="object"&&w!==null?s(w):String(w)}`}return o},zt=(r={})=>{const e={};typeof r.formatters=="object"&&Object.entries(r.formatters).forEach(([s,i])=>{if(s.length===0)throw new Error(`Formatter %${s} has no characters`);if(s.length>1)throw new Error(`Formatter %${s} has more than one character`);if(typeof i!="function")throw new TypeError(`Formatter for %${s} is not a function`);const o=s.codePointAt(0);if(o===void 0)throw new Error(`${s}.codePointAt(0) failed to return a value, please report this issue`);e[o]=i});const t=Object.freeze({formatters:e});return(s,i=[],o)=>o===void 0?_e(s,i,t):_e(s,i,{...o,formatters:e})};class Yt{#r;#t;#e;constructor(e={}){this.#t=e.formatters}setStringify(e){this.#r=e}process(e){this.#e===void 0&&(this.#e=zt({formatters:this.#t}));const t=this.#e;return e.message!==void 0&&(e.message=this.#i(t,e.message,e.context??[])),e}#i(e,t,s=[]){if(typeof t=="string")return e(t,s);if(typeof t=="object"&&t!==null){const i=t,o=Object.keys(i);for(let l=0;l<o.length;l+=1){const a=o[l],g=i[a];(typeof g=="string"||Array.isArray(g)||typeof g=="object")&&(i[a]=this.#i(e,g,s))}}return t}}const{bgGrey:Ht,cyan:Qt,green:Xt,greenBright:Kt,grey:F,red:de,underline:Be,white:Zt}=Pe,er=/[\\/]pail[\\/]dist/,pe=r=>!er.test(r);class tr extends ze{#r;#t;#e;#i=!1;#s;#n;#o;#a=!1;#l="";#c="";constructor(e={}){const{error:t,inspect:s,...i}=e;super({uppercase:{label:!0,...i.uppercase},...i}),this.#s={...Ye,...s},this.#n={...t,color:{fileLine:Xt,hint:Qt,marker:de,message:de,method:Kt,title:de}},this.#r=Se,this.#t=ve,this.#f()}setLoggerTypes(e){super.setLoggerTypes(e),this.#f()}setStdout(e){this.#r=e,this.#o=void 0,this.#a=!1}setStderr(e){this.#t=e}setInteractiveManager(e){this.#e=e}setIsInteractive(e){this.#i=e}log(e){this._log(this._formatMessage(e),e.type.level)}#f(){this.#l=He(this.loggerTypes),this.#c=ie(this.loggerTypes)}#h(){return!this.#a&&typeof this.#r.on=="function"&&(this.#a=!0,this.#r.on("resize",()=>{this.#o=void 0})),this.#o===void 0&&(this.#o=Qe().columns),this.#o}_formatMessage(e){let t=this.#h();typeof this.styles.messageLength=="number"&&(t=this.styles.messageLength);const{badge:s,context:i,date:o,error:l,file:a,groups:g,label:m,message:y,prefix:c,repeated:w,scope:d,suffix:$,traceError:D,type:J}=e,{color:R}=this.loggerTypes[J.name],f=R?Pe[R]:Zt,h=g.map(()=>" ").join(""),u=[];if(g.length>0&&u.push(`${h+F(`[${g.at(-1)??""}]`)} `),o&&u.push(`${F(this.styles.dateFormatter(typeof o=="string"?new Date(o):o))} `),s)u.push(f(s));else{const M=this.#l;M.length>0&&u.push(`${F(".".repeat(M.length))} `)}const I=this.#c;if(m){const M=Z(I),B=Z(m);u.push(`${f(Xe(m,this.styles))} `,F(".".repeat(Math.max(0,M-B))))}else u.push(F(".".repeat(I.length+2)));w&&u.push(`${Ht.white(`[${String(w)}x]`)} `),Array.isArray(d)&&d.length>0&&u.push(` ${F(`[${d.join(" > ")}]`)} `),c&&u.push(`${F(`${Array.isArray(d)&&d.length>0?". ":" "}[${this.styles.underline.prefix?Be(c):c}]`)} `);const A=Z(u.join(" "));if(a){const M=(a.name??"")+(a.line?`:${String(a.line)}`:""),B=Z(M);if(B+A+2>t)u.push(F(` ${M}`));else{const k=Math.max(0,t-A-B-2);u.push(F(`${".".repeat(k)} ${M}`))}}else u.push(F(".".repeat(Math.max(0,t-A-1))));if(u.length>0&&u.push(`
22
+
23
+ `),y!==$e){const M=typeof y=="string"?y:oe(y,this.#s);u.push(h+Ke(M,{trim:!1,width:t-3,wrapMode:Ze.STRICT_WIDTH}))}if(i){let M=!1;u.push(...i.map(B=>{if(B instanceof Error)return M=!0,`
24
+
25
+ ${le(B,{...this.#n,filterStacktrace:pe,prefix:h})}`;if(typeof B=="object")return` ${oe(B,this.#s)}`;const k=(M?`
26
+
27
+ `:" ")+String(B);return M=!1,k}))}return l&&u.push(le(l,{...this.#n,filterStacktrace:pe,prefix:h})),D&&u.push(`
28
+
29
+ ${le(D,{...this.#n,filterStacktrace:pe,hideErrorCauseCodeView:!0,hideErrorCodeView:!0,hideErrorErrorsCodeView:!0,hideMessage:!0,prefix:h})}`),$&&u.push(`
30
+ `,h+F(this.styles.underline.suffix?Be($):$)),u.join("")}_log(e,t){const s=Ie(t)?"stderr":"stdout",i=s==="stderr"?this.#t:this.#r;this.#i&&this.#e!==void 0&&i.isTTY?this.#e.update(s,e.split(`
31
+ `),0):Ne(`${e}
32
+ `,i)}}const rr=()=>H.NODE_ENV==="debug"||H.DEBUG!==void 0?"debug":H.NODE_ENV==="test"?"warning":"informational",sr=r=>{let e=rr();return H.PAIL_LOG_LEVEL!==void 0&&(e=H.PAIL_LOG_LEVEL),new jt({logLevel:e,processors:[new Yt],reporters:[new tr],stderr:ve,stdout:Se,...r})},ur=sr();export{pr as PailError,sr as createPail,mr as createPailError,ur as pail};