levix-bot 4.6.0 → 4.8.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.
@@ -29,6 +29,7 @@ const commandList = new Map(); // canonicalName -> command module
29
29
  // instead of posting a second message).
30
30
  const EDIT_IN_PLACE_EXCLUDE = new Set([
31
31
  "gemini",
32
+ "md",
32
33
  "prayer",
33
34
  "tts",
34
35
  "stt",
@@ -284,7 +285,7 @@ export async function handleCommand(sock, msg, body) {
284
285
  const prefix = runtimeConfig.getPrefix();
285
286
  if (!body.startsWith(prefix)) return false;
286
287
 
287
- const args = body.slice(prefix.length).trim().split(/ +/);
288
+ const args = body.slice(prefix.length).trim().split(/\s+/);
288
289
  const invokedName = args.shift().toLowerCase();
289
290
  const command = commands.get(invokedName);
290
291
  if (!command) return false;
package/src/index.js CHANGED
@@ -265,12 +265,20 @@ async function startWithPanel({ open }) {
265
265
  // living and dying
266
266
  // ---------------------------------------------------------------------------
267
267
 
268
- function installShutdownHandlers() {
268
+ export function installShutdownHandlers() {
269
269
  // After an uncaughtException the process state is unknown (a half-held lock,
270
270
  // a half-written auth row). Log and exit rather than keep working on top of
271
271
  // it. Run the bot under a supervisor (systemd / pm2 / docker restart) so it
272
272
  // comes back on its own — without one, this exit means the bot is down.
273
273
  const fatal = (error, label) => {
274
+ // One last local crash report, written synchronously before we die. It is
275
+ // never sent from here — the operator sends it from the panel later. The
276
+ // write is wrapped again here so a store failure cannot turn one fatal
277
+ // error into two.
278
+ try {
279
+ const category = label.startsWith("Unhandled Rejection") ? "node-rejection" : "node-uncaught";
280
+ require("./diagnostics/crashReports.cjs").captureNodeFatal(category, error);
281
+ } catch {}
274
282
  logger.error(error, `${label} exiting — restart is up to the supervisor`);
275
283
  console.error(label, error);
276
284
  // Half a second so pino can drain its worker before we die.
@@ -20,6 +20,7 @@
20
20
  const fs = require("node:fs");
21
21
  const logger = require("../utils/logger.cjs");
22
22
  const settings = require("../config/settings.cjs");
23
+ const { buildDiagnostics } = require("../diagnostics/device.cjs");
23
24
 
24
25
  const DEFAULT_ENDPOINT = "https://levix.leviro.net/api/feedback";
25
26
 
@@ -158,11 +159,18 @@ function safeRemoteError(value) {
158
159
  * "payload" part and the file as "file", and the endpoint delivers it to
159
160
  * Telegram as a document instead of a message.
160
161
  *
162
+ * `diagnosticsClient` is the raw section 1 client object, present only when the
163
+ * operator ticked the diagnostics box. When present the server rebuilds it with
164
+ * the same builder the preview route uses (so preview and send cannot diverge)
165
+ * and adds it to the envelope as `diagnostics`. When it is undefined the
166
+ * envelope has no `diagnostics` key at all.
167
+ *
161
168
  * @param {{ message: string, topic: string, rating: number|null, contact: string|null }} feedback
162
169
  * @param {{ buffer: Buffer, name: string, type: string, size: number } | null} attachment
170
+ * @param {object} [diagnosticsClient]
163
171
  * @returns {Promise<{ ok: true } | { ok: false, status: number, error: string }>}
164
172
  */
165
- async function submitFeedback(feedback, attachment = null) {
173
+ async function submitFeedback(feedback, attachment = null, diagnosticsClient = undefined) {
166
174
  const endpoint = process.env.LEVIX_FEEDBACK_URL || DEFAULT_ENDPOINT;
167
175
  const runtime = describeRuntime();
168
176
 
@@ -174,6 +182,10 @@ async function submitFeedback(feedback, attachment = null) {
174
182
  app: { version: runtime.version, platform: runtime.platform, locale: runtime.locale },
175
183
  };
176
184
 
185
+ if (diagnosticsClient !== undefined && diagnosticsClient !== null) {
186
+ envelope.diagnostics = buildDiagnostics(diagnosticsClient);
187
+ }
188
+
177
189
  let response;
178
190
  let data = null;
179
191
  try {
@@ -16,12 +16,13 @@ import fs from "node:fs";
16
16
  import path from "node:path";
17
17
  import { Router } from "express";
18
18
  import { createRequire } from "module";
19
- import { groupMetadataCache } from "../core/socket.js";
19
+ import { fetchWhatsAppImage, groupMetadataCache } from "../core/socket.js";
20
20
  import { getCommandCatalog, rebuildCommandIndex } from "../handlers/command.handler.js";
21
+ import { fileToBuffer, MultipartError, readMultipartForm } from "../utils/multipart.esm.js";
22
+ import normalizeJid, { isLidJid } from "../utils/normalizeJid.esm.js";
21
23
  import { grantRole, listRoles, revokeRole } from "../utils/permissions.esm.js";
22
24
  import {
23
25
  countDebts,
24
- countGroups,
25
26
  countNotes,
26
27
  countSchedules,
27
28
  countTodos,
@@ -41,8 +42,6 @@ import {
41
42
  resolveUserPhone,
42
43
  saveGroupSettings,
43
44
  } from "../utils/storage.esm.js";
44
- import normalizeJid, { isLidJid } from "../utils/normalizeJid.esm.js";
45
- import { fileToBuffer, MultipartError, readMultipartForm } from "../utils/multipart.esm.js";
46
45
 
47
46
  const require = createRequire(import.meta.url);
48
47
  const logger = require("../utils/logger.cjs");
@@ -64,6 +63,8 @@ const {
64
63
  } = require("../panel/feedback.cjs");
65
64
  const { stampPanelSession } = require("../panel/session-auth.cjs");
66
65
  const { DATA_DIR } = require("../config/paths.cjs");
66
+ const { buildDiagnostics } = require("../diagnostics/device.cjs");
67
+ const crashReports = require("../diagnostics/crashReports.cjs");
67
68
  const { PERSONA_FILE, activeProviderKeySetting } = require("../services/aiAgent.cjs");
68
69
  const {
69
70
  SCHEDULE_MEDIA_MAX_BYTES,
@@ -152,6 +153,28 @@ function asyncRoute(handler) {
152
153
  };
153
154
  }
154
155
 
156
+ /**
157
+ * The feedback `diagnostics` field arrives as a JSON object (JSON body) or as a
158
+ * JSON string (a multipart field). Both are normalized here; a present but
159
+ * broken value is a caller mistake, not something to silently drop.
160
+ *
161
+ * @returns {{ present: boolean, value: object|null, error?: string }}
162
+ */
163
+ function parseDiagnosticsInput(raw) {
164
+ if (raw === undefined || raw === null) return { present: false, value: null };
165
+ if (typeof raw === "string") {
166
+ const text = raw.trim();
167
+ if (!text) return { present: false, value: null };
168
+ try {
169
+ return { present: true, value: JSON.parse(text) };
170
+ } catch {
171
+ return { present: false, value: null, error: "diagnostics is not valid JSON" };
172
+ }
173
+ }
174
+ if (typeof raw === "object" && !Array.isArray(raw)) return { present: true, value: raw };
175
+ return { present: false, value: null, error: "diagnostics must be an object" };
176
+ }
177
+
155
178
  // ===========================================================================
156
179
  // Overview
157
180
  // ===========================================================================
@@ -164,7 +187,7 @@ router.get("/stats", (req, res) => {
164
187
  success: true,
165
188
  stats: {
166
189
  connection,
167
- totalGroups: countGroups(),
190
+ totalGroups: knownGroupIds().size,
168
191
  totalWarnings: countWarnings(),
169
192
  totalTodos: countTodos(),
170
193
  totalNotes: countNotes(),
@@ -194,6 +217,23 @@ router.get("/stats", (req, res) => {
194
217
  }
195
218
  });
196
219
 
220
+ router.get("/logs", (_req, res) => {
221
+ try {
222
+ res.json({ success: true, logs: logger.readLogs() });
223
+ } catch (error) {
224
+ fail(res, error, "Error reading logs");
225
+ }
226
+ });
227
+
228
+ router.delete("/logs", (_req, res) => {
229
+ try {
230
+ logger.clearLogs();
231
+ res.json({ success: true });
232
+ } catch (error) {
233
+ fail(res, error, "Error clearing logs");
234
+ }
235
+ });
236
+
197
237
  router.get("/health", (req, res) => {
198
238
  const connection = sessionState();
199
239
  res.json({
@@ -517,7 +557,7 @@ router.get("/ai/memory", (req, res) => {
517
557
  const stat = fs.statSync(path.join(memory.CHATS_DIR, file));
518
558
  scopes.push({
519
559
  scope: chatId,
520
- label: chatId,
560
+ label: chatIdentity(chatId).name || "",
521
561
  entries: memory.listMemory({ scope: "chat", chatId }).length,
522
562
  bytes: stat.size,
523
563
  updatedAt: stat.mtimeMs,
@@ -594,11 +634,22 @@ router.get("/ai/conversations/:chatId", (req, res) => {
594
634
  .catch((error) => fail(res, error, "Error reading conversation"));
595
635
  });
596
636
 
637
+ // Human-readable identity only; the JID remains the request key, never the label.
638
+ function chatIdentity(jid) {
639
+ const peer = describePeer(jid);
640
+ const name =
641
+ peer.kind === "group"
642
+ ? groupMetadataCache.get(jid)?.subject || getGroupDirectory(jid)?.subject || null
643
+ : peer.savedName || peer.pushName || peer.phone || null;
644
+ return { name, kind: peer.kind };
645
+ }
646
+
597
647
  async function getChatHistoryListAsync() {
598
648
  const { listChatHistoriesAsync } = require("../utils/storage-hub.cjs");
599
649
  const rows = await listChatHistoriesAsync();
600
650
  return (rows || []).map((row) => ({
601
651
  chatId: row.chatId,
652
+ ...chatIdentity(row.chatId),
602
653
  turns: row.turns ?? 0,
603
654
  updatedAt: row.updatedAt ?? null,
604
655
  }));
@@ -644,6 +695,7 @@ async function getChatConversationAsync(chatId) {
644
695
 
645
696
  return {
646
697
  chatId,
698
+ ...chatIdentity(chatId),
647
699
  updatedAt: meta.updatedAt ?? null,
648
700
  truncated: messages.length >= MAX_INSPECTOR_MESSAGES,
649
701
  messages,
@@ -654,6 +706,13 @@ async function getChatConversationAsync(chatId) {
654
706
  // Groups
655
707
  // ===========================================================================
656
708
 
709
+ function knownGroupIds() {
710
+ const ids = new Set(getAllGroupSettings().map((row) => row.group_id));
711
+ for (const jid of groupMetadataCache.keys()) ids.add(jid);
712
+ for (const row of getAllGroupDirectory()) ids.add(row.group_id);
713
+ return ids;
714
+ }
715
+
657
716
  function groupView(groupId, stored) {
658
717
  const live = groupMetadataCache.get(groupId) || null;
659
718
  const directory = getGroupDirectory(groupId) || null;
@@ -710,11 +769,7 @@ router.get("/groups", (req, res) => {
710
769
 
711
770
  // Groups the bot is in but that have no settings row yet still belong in
712
771
  // the list — that's exactly where the operator goes to configure them.
713
- const ids = new Set(stored.keys());
714
- for (const jid of groupMetadataCache.keys()) ids.add(jid);
715
- for (const row of getAllGroupDirectory()) ids.add(row.group_id);
716
-
717
- const groups = [...ids]
772
+ const groups = [...knownGroupIds()]
718
773
  .map((id) => groupView(id, stored.get(id)))
719
774
  .sort((a, b) => (a.subject || a.id).localeCompare(b.subject || b.id));
720
775
 
@@ -724,6 +779,40 @@ router.get("/groups", (req, res) => {
724
779
  }
725
780
  });
726
781
 
782
+ // Keep expiring WhatsApp photo URLs inside the authenticated panel. Images are
783
+ // fetched only for visible cards, never as part of a stats poll or group sync.
784
+ router.get(
785
+ "/groups/:id/photo",
786
+ asyncRoute(async (req, res) => {
787
+ const id = req.params.id;
788
+ if (!id.endsWith("@g.us") || !knownGroupIds().has(id)) return res.sendStatus(404);
789
+ const sock = currentSocket();
790
+ if (!sock) return res.sendStatus(404);
791
+ let response;
792
+ try {
793
+ const url = await sock.profilePictureUrl(id, "image", 8000);
794
+ response = await fetchWhatsAppImage(sock, url, { signal: AbortSignal.timeout(8000) });
795
+ const mime = response.headers.get("content-type")?.split(";")[0];
796
+ if (!response.ok || !["image/jpeg", "image/png", "image/webp"].includes(mime)) {
797
+ return res.sendStatus(404);
798
+ }
799
+ const chunks = [];
800
+ let bytes = 0;
801
+ for await (const chunk of response.body) {
802
+ bytes += chunk.length;
803
+ if (bytes > 1024 * 1024) throw new Error("Group photo exceeds size limit");
804
+ chunks.push(chunk);
805
+ }
806
+ res.type(mime).send(Buffer.concat(chunks));
807
+ } catch {
808
+ // No photo, expired URL or private group: the card uses its local fallback.
809
+ res.sendStatus(404);
810
+ } finally {
811
+ if (response?.body && !response.body.locked) await response.body.cancel().catch(() => {});
812
+ }
813
+ }),
814
+ );
815
+
727
816
  const MEDIA_TYPES = ["image", "video", "sticker", "audio"];
728
817
  const ANTILINK_MODES = ["ALL", "WHITELIST", "BLACKLIST"];
729
818
 
@@ -1309,10 +1398,22 @@ router.get("/feedback/meta", (req, res) => {
1309
1398
  });
1310
1399
  });
1311
1400
 
1401
+ // The exact object the server would forward as `diagnostics`, so the operator
1402
+ // can see what they are about to share before they send it. This is the same
1403
+ // builder submitFeedback() uses, so the preview cannot lie.
1404
+ router.post("/feedback/diagnostics-preview", (req, res) => {
1405
+ const parsed = parseDiagnosticsInput(req.body?.client);
1406
+ if (parsed.error) return badRequest(res, parsed.error);
1407
+ res.json({ success: true, diagnostics: buildDiagnostics(parsed.present ? parsed.value : {}) });
1408
+ });
1409
+
1312
1410
  // Leaves this machine only when the operator presses Send, and carries nothing
1313
1411
  // but the form's own fields plus the version and platform — see feedback.cjs.
1314
1412
  // An optional attachment (a screenshot, a log) rides along as multipart and is
1315
- // forwarded to the same endpoint, which delivers it to Telegram as a file.
1413
+ // forwarded to the same endpoint, which delivers it to Telegram as a file. An
1414
+ // optional `diagnostics` object (the preview's client object) is rebuilt by the
1415
+ // same sanitizer and attached to the envelope; without it there is no
1416
+ // `diagnostics` key on the wire.
1316
1417
  router.post(
1317
1418
  "/feedback",
1318
1419
  asyncRoute(async (req, res) => {
@@ -1343,6 +1444,9 @@ router.post(
1343
1444
  const parsed = validateFeedback(body);
1344
1445
  if (!parsed.ok) return badRequest(res, parsed.error);
1345
1446
 
1447
+ const diagnostics = parseDiagnosticsInput(body.diagnostics);
1448
+ if (diagnostics.error) return badRequest(res, diagnostics.error);
1449
+
1346
1450
  const retryAfter = feedbackRetryAfter();
1347
1451
  if (retryAfter) {
1348
1452
  res.set("Retry-After", String(retryAfter));
@@ -1352,7 +1456,11 @@ router.post(
1352
1456
  });
1353
1457
  }
1354
1458
 
1355
- const result = await submitFeedback(parsed.value, attachment);
1459
+ const result = await submitFeedback(
1460
+ parsed.value,
1461
+ attachment,
1462
+ diagnostics.present ? diagnostics.value : undefined,
1463
+ );
1356
1464
  if (!result.ok) {
1357
1465
  return res.status(result.status).json({ success: false, error: result.error });
1358
1466
  }
@@ -1600,12 +1708,12 @@ router.post("/auto-delete/rules/:id/reset", (req, res) => {
1600
1708
 
1601
1709
  router.get("/auto-delete/log", (req, res) => {
1602
1710
  try {
1603
- const log = autoDelete.listLog({
1711
+ const { log, total } = autoDelete.listLog({
1604
1712
  ruleId: req.query.ruleId,
1605
1713
  limit: req.query.limit,
1606
1714
  offset: req.query.offset,
1607
1715
  });
1608
- res.json({ success: true, log });
1716
+ res.json({ success: true, log, total });
1609
1717
  } catch (error) {
1610
1718
  autoDeleteFail(res, error, "Error listing auto-delete copies");
1611
1719
  }
@@ -1620,4 +1728,67 @@ router.delete("/auto-delete/log", (req, res) => {
1620
1728
  }
1621
1729
  });
1622
1730
 
1731
+ // ===========================================================================
1732
+ // Crash reports — local, and sent only when the operator presses Send
1733
+ // ===========================================================================
1734
+
1735
+ // Every pending report, as the exact upload object (plus the local status), and
1736
+ // the last 20 ids that went out. Listing sweeps expired reports first.
1737
+ router.get("/crash-reports", (_req, res) => {
1738
+ try {
1739
+ const { reports, sent } = crashReports.list();
1740
+ res.json({ success: true, reports, sent });
1741
+ } catch (error) {
1742
+ fail(res, error, "Error listing crash reports");
1743
+ }
1744
+ });
1745
+
1746
+ // The panel's own error hooks post here. Rate-limited because a render loop can
1747
+ // fire many times a second; the report itself is stored, nothing is sent.
1748
+ router.post("/crash-reports", (req, res) => {
1749
+ const retryAfter = crashReports.crashReportRetryAfter();
1750
+ if (retryAfter) {
1751
+ res.set("Retry-After", String(retryAfter));
1752
+ return res.status(429).json({
1753
+ success: false,
1754
+ error: "Too many crash reports for now. Try again in a little while.",
1755
+ });
1756
+ }
1757
+ crashReports.recordCrashReportAttempt();
1758
+ try {
1759
+ const report = crashReports.createReport(req.body || {});
1760
+ res.json({ success: true, id: report.id });
1761
+ } catch (error) {
1762
+ if (error?.status === 400) return badRequest(res, error.message);
1763
+ fail(res, error, "Error storing a crash report");
1764
+ }
1765
+ });
1766
+
1767
+ // One report out, by an explicit operator action. It never retries by itself.
1768
+ router.post(
1769
+ "/crash-reports/:id/send",
1770
+ asyncRoute(async (req, res) => {
1771
+ const result = await crashReports.sendReport(req.params.id);
1772
+ if (!result.ok) {
1773
+ return res.status(result.status || 502).json({ success: false, error: result.error });
1774
+ }
1775
+ res.json({ success: true });
1776
+ }),
1777
+ );
1778
+
1779
+ router.delete("/crash-reports/:id", (req, res) => {
1780
+ if (!crashReports.deleteReport(req.params.id)) {
1781
+ return res.status(404).json({ success: false, error: "Crash report not found" });
1782
+ }
1783
+ res.json({ success: true });
1784
+ });
1785
+
1786
+ router.delete("/crash-reports", (_req, res) => {
1787
+ try {
1788
+ res.json({ success: true, removed: crashReports.deleteAllReports() });
1789
+ } catch (error) {
1790
+ fail(res, error, "Error deleting crash reports");
1791
+ }
1792
+ });
1793
+
1623
1794
  export default router;
@@ -408,11 +408,13 @@ function listLog({ ruleId, limit, offset } = {}) {
408
408
  throw new AutoDeleteError("offset must be a non-negative integer");
409
409
  }
410
410
  }
411
- return store.listAutoDeleteLog({
411
+ const log = store.listAutoDeleteLog({
412
412
  ruleId: parsedRuleId,
413
413
  limit: parsedLimit,
414
414
  offset: parsedOffset,
415
415
  });
416
+ const total = store.countAutoDeleteLog({ ruleId: parsedRuleId });
417
+ return { log, total };
416
418
  }
417
419
 
418
420
  function clearLog(ruleId) {
@@ -1,4 +1,5 @@
1
1
  const path = require("path");
2
+ const fs = require("node:fs");
2
3
  const pino = require("pino");
3
4
 
4
5
  const { ensureDataDir } = require("../config/paths.cjs");
@@ -7,10 +8,7 @@ const { ensureDataDir } = require("../config/paths.cjs");
7
8
  // global install never tries to write next to its own code.
8
9
  const logDir = ensureDataDir("logs");
9
10
 
10
- // Pino's `transport` option runs each target in a worker thread, and a worker
11
- // loads its target by module path — which a single-file executable can't
12
- // provide. Same three destinations either way; packaged builds just wire them
13
- // as plain streams in this thread.
11
+ // A packaged executable cannot load a worker target by module path.
14
12
  function isPackaged() {
15
13
  try {
16
14
  return require("node:sea").isSea() === true;
@@ -44,35 +42,91 @@ const PRETTY = {
44
42
  const combined = path.join(logDir, "combined.log");
45
43
  const errors = path.join(logDir, "error.log");
46
44
 
47
- const logger = useInProcessLogs()
48
- ? pino(
49
- base,
50
- pino.multistream([
51
- { level: "trace", stream: pino.destination({ dest: combined, mkdir: true }) },
52
- { level: "error", stream: pino.destination({ dest: errors, mkdir: true }) },
53
- { level: "trace", stream: require("pino-pretty")(PRETTY) },
54
- ]),
55
- )
56
- : pino({
57
- ...base,
58
- transport: {
59
- targets: [
60
- // Combined log file (all levels)
61
- {
62
- target: "pino/file",
63
- level: "trace",
64
- options: { destination: combined, mkdir: true },
65
- },
66
- // Error log file (errors only)
67
- {
68
- target: "pino/file",
69
- level: "error",
70
- options: { destination: errors, mkdir: true },
71
- },
72
- // Pretty console output
73
- { target: "pino-pretty", level: "trace", options: PRETTY },
74
- ],
75
- },
76
- });
45
+ // Own file writes in this thread so clearing has a precise boundary. Async
46
+ // SonicBoom flushSync() does not wait for an already in-flight write, which
47
+ // could otherwise restore an old entry after truncation. Sync destinations
48
+ // are ready immediately and leave no pending file writes behind.
49
+ const combinedStream = pino.destination({ dest: combined, mkdir: true, sync: true });
50
+ const errorStream = pino.destination({ dest: errors, mkdir: true, sync: true });
51
+ const logger = pino(
52
+ base,
53
+ pino.multistream([
54
+ { level: "trace", stream: combinedStream },
55
+ { level: "error", stream: errorStream },
56
+ {
57
+ level: "trace",
58
+ stream: useInProcessLogs()
59
+ ? require("pino-pretty")(PRETTY)
60
+ : pino.transport({ target: "pino-pretty", options: PRETTY }),
61
+ },
62
+ ]),
63
+ );
64
+
65
+ const MAX_READ_BYTES = 256 * 1024;
66
+
67
+ /** Read only the bounded tail of the operational log, never arbitrary files. */
68
+ logger.readLogs = function readLogs(limit = 500) {
69
+ const requested = Number(limit);
70
+ const count = Number.isFinite(requested)
71
+ ? Math.max(1, Math.min(500, Math.trunc(requested)))
72
+ : 500;
73
+ const fd = fs.openSync(combined, "r");
74
+ let text;
75
+ try {
76
+ const size = fs.fstatSync(fd).size;
77
+ const start = Math.max(0, size - MAX_READ_BYTES);
78
+ const buffer = Buffer.alloc(Math.min(size, MAX_READ_BYTES));
79
+ const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, start);
80
+ text = buffer.toString("utf8", 0, bytesRead);
81
+ // The byte boundary can land inside a UTF-8 character or a JSON record.
82
+ if (start > 0) {
83
+ const newline = text.indexOf("\n");
84
+ text = newline < 0 ? "" : text.slice(newline + 1);
85
+ }
86
+ } finally {
87
+ fs.closeSync(fd);
88
+ }
89
+
90
+ const entries = [];
91
+ for (const line of text.split("\n")) {
92
+ if (!line) continue;
93
+ let entry;
94
+ try {
95
+ entry = JSON.parse(line);
96
+ } catch {
97
+ continue; // A truncated or malformed record must not hide newer logs.
98
+ }
99
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
100
+ const level = typeof entry.level === "number" ? entry.level : 30;
101
+ const normalizedLevel =
102
+ level >= 50 ? "error" : level >= 40 ? "warn" : level >= 30 ? "info" : "debug";
103
+ const date =
104
+ typeof entry.time === "number" || typeof entry.time === "string"
105
+ ? new Date(entry.time)
106
+ : new Date(NaN);
107
+ const time = Number.isFinite(date.getTime()) ? date.toISOString() : "";
108
+ let msg =
109
+ typeof entry.msg === "string"
110
+ ? entry.msg
111
+ : entry.msg == null
112
+ ? ""
113
+ : JSON.stringify(entry.msg);
114
+ const error = entry.err ?? entry.error;
115
+ if (error && typeof error === "object") {
116
+ const detail = error.stack || error.message;
117
+ if (typeof detail === "string" && detail !== msg) msg = msg ? `${msg}\n${detail}` : detail;
118
+ }
119
+ entries.push({ time, level: normalizedLevel, msg });
120
+ }
121
+ return entries.slice(-count);
122
+ };
123
+
124
+ /** Truncate the open files in place, keeping later writes on the same files. */
125
+ logger.clearLogs = function clearLogs() {
126
+ combinedStream.flushSync();
127
+ errorStream.flushSync();
128
+ fs.ftruncateSync(combinedStream.fd, 0);
129
+ fs.ftruncateSync(errorStream.fd, 0);
130
+ };
77
131
 
78
132
  module.exports = logger;