@napuketto/kernel 0.9.0 → 0.10.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.
- package/dist/index.d.mts +34 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +255 -127
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -13
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { createRequire } from "node:module";
|
|
2
1
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
2
|
import { readFile, rename, stat, writeFile } from "node:fs/promises";
|
|
4
3
|
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
@@ -329,16 +328,19 @@ function parseLogConfig(section, env = {}) {
|
|
|
329
328
|
}
|
|
330
329
|
// src/infra/log-format.ts
|
|
331
330
|
/**
|
|
332
|
-
*
|
|
331
|
+
* 控制台渲染流(pretty / single-line / json,2026-10-25 日志可配置化;
|
|
332
|
+
* 2026-11-03 起 pretty 自渲染,移除对 pino-pretty 的依赖)。
|
|
333
333
|
*
|
|
334
|
-
* pino
|
|
335
|
-
*
|
|
336
|
-
* 嵌入式宿主的「一条记录一行、字段 k=v / NDJSON」契约,故自写轻量渲染流:
|
|
334
|
+
* 三种格式共用同一个「pino JSON 行 → 人读行」渲染入口(文件目的地恒为 JSON 行,
|
|
335
|
+
* 不受本模块影响):
|
|
337
336
|
*
|
|
338
|
-
*
|
|
337
|
+
* pretty:多行彩色,终端交互形态
|
|
338
|
+
* `[HH:MM:ss.l] INFO (name/pid): 消息` + 逐行 `key: value`(4 空格缩进,
|
|
339
|
+
* 嵌套对象/数组按 JSON 形状展开;字段名紫、消息青、级别按级别着色)
|
|
340
|
+
* single-line:`[时间] LEVEL (name/pid): 消息 key=value key=value`
|
|
339
341
|
* json:NDJSON,每行 {time, level, module, account?, pid, msg, ...fields}
|
|
340
342
|
*
|
|
341
|
-
* 时间渲染(LogConfig.timestamp):local = [HH:MM:ss.l](与
|
|
343
|
+
* 时间渲染(LogConfig.timestamp):local = [HH:MM:ss.l](与 history 一致)、
|
|
342
344
|
* iso8601 = 2026-10-25T16:01:33.294+08:00、elapsed = +123.456s(进程内单调秒)。
|
|
343
345
|
* json 的 time 恒为 ISO8601(机器可解析契约,不受 timestamp 键影响)。
|
|
344
346
|
*/
|
|
@@ -351,7 +353,7 @@ const LEVEL_LABELS = {
|
|
|
351
353
|
50: "error",
|
|
352
354
|
60: "fatal"
|
|
353
355
|
};
|
|
354
|
-
/** single-line
|
|
356
|
+
/** 级别颜色(pretty 级别标签 / single-line 级别与元数据头共用)。 */
|
|
355
357
|
const LEVEL_COLORS = {
|
|
356
358
|
trace: "\x1B[34m",
|
|
357
359
|
debug: "\x1B[36m",
|
|
@@ -361,7 +363,17 @@ const LEVEL_COLORS = {
|
|
|
361
363
|
fatal: "\x1B[91m"
|
|
362
364
|
};
|
|
363
365
|
const DIM = "\x1B[2m";
|
|
366
|
+
/** 字段名(紫,沿用原 pino-pretty 缺省配色)。 */
|
|
367
|
+
const KEY_COLOR = "\x1B[35m";
|
|
368
|
+
/** 消息(青,沿用原 pino-pretty 缺省配色)。 */
|
|
369
|
+
const MESSAGE_COLOR = "\x1B[36m";
|
|
364
370
|
const RESET = "\x1B[0m";
|
|
371
|
+
/** pretty 顶层字段缩进(4 空格,与原多行输出一致)。 */
|
|
372
|
+
const PRETTY_INDENT = " ";
|
|
373
|
+
/** pretty 嵌套值缩进(2 空格 JSON 缩进,与原多行输出一致)。 */
|
|
374
|
+
const NESTED_INDENT = " ";
|
|
375
|
+
/** 换行切分(多行字符串展开用;顶层常量避免每次调用重建正则)。 */
|
|
376
|
+
const NEWLINE = /\r?\n/;
|
|
365
377
|
/** 2 位补零。 */
|
|
366
378
|
function pad2(n) {
|
|
367
379
|
return String(n).padStart(2, "0");
|
|
@@ -374,7 +386,7 @@ function isoLocalTime(epochMs) {
|
|
|
374
386
|
const abs = Math.abs(offsetMinutes);
|
|
375
387
|
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}.${String(d.getMilliseconds()).padStart(3, "0")}${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
|
|
376
388
|
}
|
|
377
|
-
/** 单调墙钟毫秒 →
|
|
389
|
+
/** 单调墙钟毫秒 → 本地时分秒(原 `SYS:HH:MM:ss.l` 短格式)。 */
|
|
378
390
|
function localShortTime(epochMs) {
|
|
379
391
|
const d = new Date(epochMs);
|
|
380
392
|
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}.${String(d.getMilliseconds()).padStart(3, "0")}`;
|
|
@@ -396,12 +408,16 @@ function levelLabel(raw) {
|
|
|
396
408
|
if (typeof raw === "number") return LEVEL_LABELS[raw] ?? String(raw);
|
|
397
409
|
return typeof raw === "string" ? raw.toUpperCase() : "LOG";
|
|
398
410
|
}
|
|
411
|
+
/** 着色(useColor=false / 空串 / 未知级别无色码时原样返回,避免多余转义)。 */
|
|
412
|
+
function paint(code, text, useColor) {
|
|
413
|
+
return useColor && code !== "" && text !== "" ? `${code}${text}${RESET}` : text;
|
|
414
|
+
}
|
|
399
415
|
/** k=v 内联值:字符串裸输出(含空格时不加引号——宽松人类格式),其余 JSON 序列化。 */
|
|
400
416
|
function inlineValue(value) {
|
|
401
417
|
if (typeof value === "string") return value;
|
|
402
418
|
return JSON.stringify(value) ?? "null";
|
|
403
419
|
}
|
|
404
|
-
/**
|
|
420
|
+
/** 结构化输出忽略的标准字段(渲染进头/独立字段,不进字段尾部)。 */
|
|
405
421
|
const RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
406
422
|
"pid",
|
|
407
423
|
"hostname",
|
|
@@ -425,7 +441,7 @@ function renderJsonLine(record, ctx) {
|
|
|
425
441
|
};
|
|
426
442
|
return `${JSON.stringify(jsonLine)}\n`;
|
|
427
443
|
}
|
|
428
|
-
/**
|
|
444
|
+
/** 元数据头:(name/pid),无 name 时 (pid)。 */
|
|
429
445
|
function renderMeta(record) {
|
|
430
446
|
const pid = record["pid"] ?? "-";
|
|
431
447
|
const name = record["name"];
|
|
@@ -437,7 +453,7 @@ function renderKvFields(record) {
|
|
|
437
453
|
for (const [key, value] of Object.entries(record)) if (!RESERVED_KEYS.has(key)) fields.push(`${key}=${inlineValue(value)}`);
|
|
438
454
|
return fields.length > 0 ? ` ${fields.join(" ")}` : "";
|
|
439
455
|
}
|
|
440
|
-
/** single-line 渲染:[时间] LEVEL (name/pid): 消息 k=v k=v
|
|
456
|
+
/** single-line 渲染:[时间] LEVEL (name/pid): 消息 k=v k=v(级别大写)。 */
|
|
441
457
|
function renderSingleLine(record, ctx) {
|
|
442
458
|
const label = levelLabel(record["level"]);
|
|
443
459
|
const msg = typeof record["msg"] === "string" ? record["msg"] : "";
|
|
@@ -451,15 +467,97 @@ function renderSingleLine(record, ctx) {
|
|
|
451
467
|
}
|
|
452
468
|
return `[${time}] ${labelUpper} ${meta}: ${msg}${fieldsSuffix}\n`;
|
|
453
469
|
}
|
|
454
|
-
/**
|
|
470
|
+
/** 标量渲染(字符串 JSON 引号;数字/布尔/null/undefined 原样)。 */
|
|
471
|
+
function renderScalar(value) {
|
|
472
|
+
if (typeof value === "string") return JSON.stringify(value);
|
|
473
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
474
|
+
if (value === null || value === void 0) return String(value);
|
|
475
|
+
return String(value);
|
|
476
|
+
}
|
|
477
|
+
/** 给渲染块末行追加逗号(容器内非末项用)。 */
|
|
478
|
+
function withTrailingComma(lines, trailing) {
|
|
479
|
+
if (!trailing || lines.length === 0) return lines;
|
|
480
|
+
const copy = [...lines];
|
|
481
|
+
const last = copy.length - 1;
|
|
482
|
+
copy[last] = `${copy[last] ?? ""},`;
|
|
483
|
+
return copy;
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* 容器(对象/数组)内一条属性的行:首行接 `key: 值`,续行保持嵌套缩进。
|
|
487
|
+
* 多行字符串的首行为空串,此时 key 行不带尾随内容(值从下一行开始)。
|
|
488
|
+
*/
|
|
489
|
+
function renderEntryLines(pad, key, value, depth) {
|
|
490
|
+
const entryPad = `${pad}${NESTED_INDENT}`;
|
|
491
|
+
const [first = "", ...rest] = renderValueLines(value, depth + 1);
|
|
492
|
+
const inline = first.slice(entryPad.length);
|
|
493
|
+
const keyText = `${entryPad}${JSON.stringify(key)}:`;
|
|
494
|
+
const head = inline === "" ? keyText : `${keyText} ${inline}`;
|
|
495
|
+
return rest.length === 0 ? [head] : [head, ...rest];
|
|
496
|
+
}
|
|
497
|
+
/** 数组渲染:`[` / 元素(逗号分隔)/ `]`。 */
|
|
498
|
+
function renderArrayLines(value, depth) {
|
|
499
|
+
const pad = NESTED_INDENT.repeat(depth);
|
|
500
|
+
if (value.length === 0) return [`${pad}[]`];
|
|
501
|
+
const lines = [`${pad}[`];
|
|
502
|
+
const lastIndex = value.length - 1;
|
|
503
|
+
for (const [index, item] of value.entries()) lines.push(...withTrailingComma(renderValueLines(item, depth + 1), index < lastIndex));
|
|
504
|
+
lines.push(`${pad}]`);
|
|
505
|
+
return lines;
|
|
506
|
+
}
|
|
507
|
+
/** 对象渲染:`{` / 属性(逗号分隔)/ `}`。 */
|
|
508
|
+
function renderObjectLines(value, depth) {
|
|
509
|
+
const pad = NESTED_INDENT.repeat(depth);
|
|
510
|
+
const entries = Object.entries(value);
|
|
511
|
+
if (entries.length === 0) return [`${pad}{}`];
|
|
512
|
+
const lines = [`${pad}{`];
|
|
513
|
+
const lastIndex = entries.length - 1;
|
|
514
|
+
for (const [index, [key, entryValue]] of entries.entries()) lines.push(...withTrailingComma(renderEntryLines(pad, key, entryValue, depth), index < lastIndex));
|
|
515
|
+
lines.push(`${pad}}`);
|
|
516
|
+
return lines;
|
|
517
|
+
}
|
|
518
|
+
/** 多行字符串展开:首行留空,内容逐行多缩进一级(典型 err.stack)。 */
|
|
519
|
+
function renderMultilineStringLines(value, depth) {
|
|
520
|
+
const pad = NESTED_INDENT.repeat(depth);
|
|
521
|
+
return [`${pad}`, ...value.split(NEWLINE).map((line) => `${pad}${PRETTY_INDENT}${line}`)];
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* pretty 值渲染成行(每行带 depth 级 2 空格缩进):
|
|
525
|
+
* - 对象/数组按 JSON 形状展开(嵌套键带引号);空容器渲染成 `[]` / `{}`;
|
|
526
|
+
* - 多行字符串(典型为 err.stack)不带引号展开,避免整段堆栈被转义成一行 `\n`;
|
|
527
|
+
* - 其余标量原样(字符串带 JSON 引号)。
|
|
528
|
+
*/
|
|
529
|
+
function renderValueLines(value, depth) {
|
|
530
|
+
if (Array.isArray(value)) return renderArrayLines(value, depth);
|
|
531
|
+
if (typeof value === "object" && value !== null) return renderObjectLines(value, depth);
|
|
532
|
+
if (typeof value === "string" && value.includes("\n")) return renderMultilineStringLines(value, depth);
|
|
533
|
+
return [`${NESTED_INDENT.repeat(depth)}${renderScalar(value)}`];
|
|
534
|
+
}
|
|
535
|
+
/** pretty 单条顶层字段:` key: 值`(嵌套续行按 JSON 缩进对齐)。 */
|
|
536
|
+
function renderPrettyField(key, value, useColor) {
|
|
537
|
+
const [first = "", ...rest] = renderValueLines(value, 0);
|
|
538
|
+
const label = paint(KEY_COLOR, key, useColor);
|
|
539
|
+
return [first === "" ? `${PRETTY_INDENT}${label}:` : `${PRETTY_INDENT}${label}: ${first}`, ...rest.map((line) => `${PRETTY_INDENT}${line}`)];
|
|
540
|
+
}
|
|
541
|
+
/** pretty 渲染:多行彩色 `[时间] LEVEL (name/pid): 消息` + 逐行字段。 */
|
|
542
|
+
function renderPrettyLine(record, ctx) {
|
|
543
|
+
const label = levelLabel(record["level"]);
|
|
544
|
+
const color = LEVEL_COLORS[label.toLowerCase()] ?? "";
|
|
545
|
+
const time = renderTime(record["time"], ctx.timestamp, false, ctx.timeOriginMs);
|
|
546
|
+
const msg = typeof record["msg"] === "string" ? record["msg"] : "";
|
|
547
|
+
const head = `[${time}] ${paint(color, label.toUpperCase(), ctx.useColor)} ${renderMeta(record)}:`;
|
|
548
|
+
const lines = msg === "" ? [head] : [`${head} ${paint(MESSAGE_COLOR, msg, ctx.useColor)}`];
|
|
549
|
+
for (const [key, value] of Object.entries(record)) if (!RESERVED_KEYS.has(key)) lines.push(...renderPrettyField(key, value, ctx.useColor));
|
|
550
|
+
return `${lines.join("\n")}\n`;
|
|
551
|
+
}
|
|
552
|
+
/** 创建控制台渲染流(pretty / single-line / json)。 */
|
|
455
553
|
function createConsoleFormatStream(opts) {
|
|
456
554
|
const out = opts.destination ?? process.stdout;
|
|
457
555
|
const ctx = {
|
|
458
556
|
timestamp: opts.timestamp,
|
|
459
557
|
timeOriginMs: performance.timeOrigin,
|
|
460
|
-
useColor: opts.format
|
|
558
|
+
useColor: opts.format !== "json" && opts.colorize
|
|
461
559
|
};
|
|
462
|
-
const render = opts.format === "json" ? renderJsonLine : renderSingleLine;
|
|
560
|
+
const render = opts.format === "pretty" ? renderPrettyLine : opts.format === "json" ? renderJsonLine : renderSingleLine;
|
|
463
561
|
return { write(line) {
|
|
464
562
|
let record;
|
|
465
563
|
try {
|
|
@@ -479,6 +577,7 @@ function createConsoleFormatStream(opts) {
|
|
|
479
577
|
* - 统一 level 控制(控制台与文件可分别设级,2026-10-25 日志可配置化)
|
|
480
578
|
* - 内置 redact(token / 票据等敏感字段不打日志),可追加
|
|
481
579
|
* - 无全局单例(ADR-015 推论):每进程实例化一份,由装配层持有
|
|
580
|
+
* - 三种控制台格式全部由 log-format 自渲染(2026-11-03 起不再依赖 pino-pretty)
|
|
482
581
|
*
|
|
483
582
|
* 时间源(2026-10-25 修复):QQNT 原生层会在 onRecvSysMsg 回调窗口内篡改进程
|
|
484
583
|
* Date(实测记录时间冻结为假值、回调外恢复),故时间戳统一取
|
|
@@ -492,33 +591,6 @@ const DEFAULT_REDACT_PATHS = [
|
|
|
492
591
|
"password",
|
|
493
592
|
"secret"
|
|
494
593
|
];
|
|
495
|
-
/** 从本模块位置解析 optional peer(dist/index.mjs 与 src/infra 深度不同,但都归 createRequire 处理)。 */
|
|
496
|
-
const requireFromHere = createRequire(import.meta.url);
|
|
497
|
-
/** undefined = 尚未探测;null = 未安装(降级 single-line 结构化输出)。 */
|
|
498
|
-
let prettyFactory;
|
|
499
|
-
/**
|
|
500
|
-
* 懒加载 pino-pretty(optional peerDependency,2026-11-03 依赖审计整改)。
|
|
501
|
-
*
|
|
502
|
-
* 为什么不用顶层 `import pinoPretty from "pino-pretty"`:kernel 被 koishi 适配器
|
|
503
|
-
* 或嵌入式宿主当库引用时不需要彩色终端渲染,但静态 import 会让「没装
|
|
504
|
-
* pino-pretty」直接变成模块加载期的 ERR_MODULE_NOT_FOUND。改为运行时 require +
|
|
505
|
-
* try/catch:宿主没装(或 pnpm 严格隔离下解析不到)就退化为 single-line 结构化
|
|
506
|
-
* 输出,CLI 侧因为自己依赖 pino-pretty,终端体验不变。
|
|
507
|
-
*
|
|
508
|
-
* 用 createRequire 而非动态 import():解析结果需要同步(createLogger 是同步
|
|
509
|
-
* API),且 pino-pretty 13 是 CJS 包,同步 require 最直接。
|
|
510
|
-
*/
|
|
511
|
-
function loadPrettyFactory() {
|
|
512
|
-
if (prettyFactory !== void 0) return prettyFactory;
|
|
513
|
-
try {
|
|
514
|
-
const mod = requireFromHere("pino-pretty");
|
|
515
|
-
const factory = typeof mod === "function" ? mod : mod.default;
|
|
516
|
-
prettyFactory = typeof factory === "function" ? factory : null;
|
|
517
|
-
} catch {
|
|
518
|
-
prettyFactory = null;
|
|
519
|
-
}
|
|
520
|
-
return prettyFactory;
|
|
521
|
-
}
|
|
522
594
|
/** 级别数值序(求多目的地最低级别用)。 */
|
|
523
595
|
const LEVEL_ORDER = [
|
|
524
596
|
"trace",
|
|
@@ -537,87 +609,73 @@ function minLevel(a, b) {
|
|
|
537
609
|
function wallMs() {
|
|
538
610
|
return performance.timeOrigin + performance.now();
|
|
539
611
|
}
|
|
540
|
-
/** 进程内相对秒标签(elapsed 模式,pretty 字符串时间路径用)。 */
|
|
541
|
-
function elapsedLabelNow() {
|
|
542
|
-
return `+${(performance.now() / 1e3).toFixed(3)}s`;
|
|
543
|
-
}
|
|
544
612
|
function toSingle(streams) {
|
|
545
613
|
const [only] = streams;
|
|
546
614
|
if (only === void 0) throw new KernelError("logger 内部错误:目的地列表为空", "UNKNOWN");
|
|
547
615
|
return only.stream;
|
|
548
616
|
}
|
|
549
|
-
/**
|
|
550
|
-
function
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
colorize,
|
|
556
|
-
...timestampMode === "local" ? { translateTime: "SYS:HH:MM:ss.l" } : {},
|
|
557
|
-
...timestampMode === "iso8601" ? { translateTime: "SYS:yyyy-mm-dd'T'HH:MM:ss.l Z" } : {},
|
|
558
|
-
singleLine: false,
|
|
617
|
+
/** 控制台目的地(console=false 返回 null)。 */
|
|
618
|
+
function buildConsoleTarget(opts, render, destination) {
|
|
619
|
+
if ((opts.console ?? true) !== true) return null;
|
|
620
|
+
return {
|
|
621
|
+
stream: createConsoleFormatStream({
|
|
622
|
+
...render,
|
|
559
623
|
destination
|
|
560
|
-
})
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
format: format === "pretty" ? "single-line" : format,
|
|
564
|
-
timestamp: timestampMode,
|
|
565
|
-
colorize,
|
|
566
|
-
destination
|
|
567
|
-
});
|
|
624
|
+
}),
|
|
625
|
+
level: opts.level ?? "info"
|
|
626
|
+
};
|
|
568
627
|
}
|
|
569
|
-
/**
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
const isTty = destination.isTTY === true;
|
|
575
|
-
const requested = opts.format ?? (isTty ? "pretty" : "single-line");
|
|
576
|
-
const format = requested === "pretty" && loadPrettyFactory() === null ? "single-line" : requested;
|
|
628
|
+
/** 文件目的地(未配置 file 返回 null;同步写入,父目录自动创建)。 */
|
|
629
|
+
function buildFileTarget(opts, level) {
|
|
630
|
+
const { file } = opts;
|
|
631
|
+
if (file === void 0) return null;
|
|
632
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
577
633
|
return {
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
634
|
+
stream: pino.destination({
|
|
635
|
+
dest: file,
|
|
636
|
+
sync: true
|
|
637
|
+
}),
|
|
638
|
+
level
|
|
582
639
|
};
|
|
583
640
|
}
|
|
641
|
+
/** 记录产生门槛 = 全部目的地中最低级别(multistream 再按各自级别分发过滤)。 */
|
|
642
|
+
function gateLevel(targets) {
|
|
643
|
+
let gate = "fatal";
|
|
644
|
+
for (const target of targets) gate = minLevel(gate, target.level);
|
|
645
|
+
return gate;
|
|
646
|
+
}
|
|
647
|
+
/** 单目的地直连(避免 multistream 包装),多目的地走 multistream。 */
|
|
648
|
+
function mergeTargets(targets) {
|
|
649
|
+
return targets.length === 1 ? toSingle(targets) : pino.multistream(targets);
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* 创建 pino logger:console(pretty/single-line/json)+ 可选文件,统一 level / redact。
|
|
653
|
+
*
|
|
654
|
+
* 文件目的地用同步写入(`sync: true`):日志量级下性能可接受,且进程退出不丢日志,
|
|
655
|
+
* 无需额外的 flush 步骤(对比异步 SonicBoom 的 flushSync 时序陷阱)。
|
|
656
|
+
* 文件目的地恒为 JSON 行(数值时间戳),格式/时间戳渲染仅作用于控制台目的地。
|
|
657
|
+
*/
|
|
584
658
|
function createLogger(opts = {}) {
|
|
585
659
|
const consoleLevel = opts.level ?? "info";
|
|
586
|
-
const
|
|
587
|
-
const
|
|
588
|
-
const
|
|
589
|
-
const
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
});
|
|
594
|
-
if (file)
|
|
595
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
596
|
-
streams.push({
|
|
597
|
-
stream: pino.destination({
|
|
598
|
-
dest: file,
|
|
599
|
-
sync: true
|
|
600
|
-
}),
|
|
601
|
-
level: fileLevel
|
|
602
|
-
});
|
|
603
|
-
}
|
|
604
|
-
if (streams.length === 0) throw new KernelError("logger 至少需要一个输出目标:console 或 file", "INVALID_PARAM");
|
|
605
|
-
let gate = "fatal";
|
|
606
|
-
for (const entry of streams) gate = minLevel(gate, entry.level);
|
|
607
|
-
const pinoTimestamp = render.format === "pretty" && render.timestampMode === "elapsed" ? () => `,"time":"${elapsedLabelNow()}"` : () => `,"time":${wallMs()}`;
|
|
660
|
+
const destination = opts.destination ?? process.stdout;
|
|
661
|
+
const isTty = destination.isTTY === true;
|
|
662
|
+
const format = opts.format ?? (isTty ? "pretty" : "single-line");
|
|
663
|
+
const targets = [buildConsoleTarget(opts, {
|
|
664
|
+
format,
|
|
665
|
+
timestamp: opts.timestamp ?? "local",
|
|
666
|
+
colorize: opts.colorize ?? (format === "pretty" && isTty)
|
|
667
|
+
}, destination), buildFileTarget(opts, opts.fileLevel ?? consoleLevel)].filter((target) => target !== null);
|
|
668
|
+
if (targets.length === 0) throw new KernelError("logger 至少需要一个输出目标:console 或 file", "INVALID_PARAM");
|
|
608
669
|
const pinoOptions = {
|
|
609
|
-
level:
|
|
670
|
+
level: gateLevel(targets),
|
|
610
671
|
redact: [...DEFAULT_REDACT_PATHS, ...opts.redact ?? []],
|
|
611
|
-
timestamp:
|
|
672
|
+
timestamp: () => `,"time":${wallMs()}`,
|
|
673
|
+
...opts.base === void 0 ? {} : { base: {
|
|
674
|
+
pid: process.pid,
|
|
675
|
+
...opts.base
|
|
676
|
+
} }
|
|
612
677
|
};
|
|
613
|
-
|
|
614
|
-
pid: process.pid,
|
|
615
|
-
...base
|
|
616
|
-
};
|
|
617
|
-
let stream;
|
|
618
|
-
if (streams.length === 1) stream = toSingle(streams);
|
|
619
|
-
else stream = pino.multistream(streams);
|
|
620
|
-
return pino(pinoOptions, stream);
|
|
678
|
+
return pino(pinoOptions, mergeTargets(targets));
|
|
621
679
|
}
|
|
622
680
|
// src/infra/paths.ts
|
|
623
681
|
/**
|
|
@@ -4058,6 +4116,51 @@ function systemInfo() {
|
|
|
4058
4116
|
}
|
|
4059
4117
|
/** 纯数字串(major.node 提取的 appid 判定)。 */
|
|
4060
4118
|
const DIGITS_ONLY_RE = /^\d+$/;
|
|
4119
|
+
/** major.node 内嵌 qua(如 `V1_LNX_NQ_3.2.35_54395_GW_B`)扫描正则。 */
|
|
4120
|
+
const QUA_RE = /V1_(?:WIN|LNX|MAC)_NQ_[A-Za-z0-9._-]+_GW_B/;
|
|
4121
|
+
/** 当前平台 → wrapper PlatformType(未知平台按 Windows 处理,保持旧行为)。 */
|
|
4122
|
+
function detectPlatformType() {
|
|
4123
|
+
switch (platform()) {
|
|
4124
|
+
case "linux": return PlatformType.KLINUX;
|
|
4125
|
+
case "darwin": return PlatformType.KMAC;
|
|
4126
|
+
default: return PlatformType.KWINDOWS;
|
|
4127
|
+
}
|
|
4128
|
+
}
|
|
4129
|
+
/** 平台对应的 qua 前缀(Linux 用 LNX,macOS 用 MAC)。 */
|
|
4130
|
+
function quaPrefix(platform) {
|
|
4131
|
+
if (platform === PlatformType.KLINUX) return "V1_LNX";
|
|
4132
|
+
if (platform === PlatformType.KMAC) return "V1_MAC";
|
|
4133
|
+
return "V1_WIN";
|
|
4134
|
+
}
|
|
4135
|
+
/**
|
|
4136
|
+
* 由客户端版本拼 qua。Windows 保持历史行为(连字符原样);
|
|
4137
|
+
* Linux/macOS 用 `_` 连接(实测 `V1_LNX_NQ_3.2.35_54395_GW_B`)。
|
|
4138
|
+
*/
|
|
4139
|
+
function buildQua(fullVersion, platform) {
|
|
4140
|
+
const version = platform === PlatformType.KWINDOWS ? fullVersion : fullVersion.replace("-", "_");
|
|
4141
|
+
return `${quaPrefix(platform)}_NQ_${version}_GW_B`;
|
|
4142
|
+
}
|
|
4143
|
+
/** 从 major.node 扫描 qua(找不到返回 null;读文件失败同样返回 null)。 */
|
|
4144
|
+
function parseQuaFromMajor(majorPath) {
|
|
4145
|
+
if (!existsSync(majorPath)) return null;
|
|
4146
|
+
let buf;
|
|
4147
|
+
try {
|
|
4148
|
+
buf = readFileSync(majorPath);
|
|
4149
|
+
} catch {
|
|
4150
|
+
return null;
|
|
4151
|
+
}
|
|
4152
|
+
const marker = Buffer.from("V1_", "latin1");
|
|
4153
|
+
let pos = 0;
|
|
4154
|
+
while (pos < buf.length) {
|
|
4155
|
+
const idx = buf.indexOf(marker, pos);
|
|
4156
|
+
if (idx === -1) return null;
|
|
4157
|
+
const slice = buf.subarray(idx, Math.min(idx + 80, buf.length)).toString("latin1");
|
|
4158
|
+
const matched = QUA_RE.exec(slice)?.[0];
|
|
4159
|
+
if (matched !== void 0) return matched;
|
|
4160
|
+
pos = idx + marker.length;
|
|
4161
|
+
}
|
|
4162
|
+
return null;
|
|
4163
|
+
}
|
|
4061
4164
|
/**
|
|
4062
4165
|
* 从 major.node 提取 appid(NapCat parseAppidFromMajorV2 的自研等价实现)。
|
|
4063
4166
|
* major.node 含 `QQAppId/` 标记后跟数字(腾讯工具链产物,实测确认)。
|
|
@@ -4098,21 +4201,21 @@ function readMarkerValue(buf, start) {
|
|
|
4098
4201
|
* majorPath 缺省或解析失败时抛 KernelError——不再静默回退过期 appid。
|
|
4099
4202
|
* majorPath 传 wrapper.node 同目录 major.node。
|
|
4100
4203
|
*/
|
|
4101
|
-
function resolveAppidQua(fullVersion, majorPath) {
|
|
4204
|
+
function resolveAppidQua(fullVersion, majorPath, platform = detectPlatformType()) {
|
|
4102
4205
|
const appid = majorPath !== void 0 ? parseAppidFromMajor(majorPath) : null;
|
|
4103
4206
|
if (appid === null) throw kernelError("无法从 major.node 解析 appid,请确认 wrapper.node/major.node 完整,或更新 qq-releases.json", "INVALID_STATE");
|
|
4104
4207
|
return {
|
|
4105
4208
|
appid,
|
|
4106
|
-
qua:
|
|
4209
|
+
qua: (majorPath !== void 0 ? parseQuaFromMajor(majorPath) : null) ?? buildQua(fullVersion, platform)
|
|
4107
4210
|
};
|
|
4108
4211
|
}
|
|
4109
4212
|
/** 生成 engine 桌面配置(wrapper 契约字段)。majorPath 可选(缺失/解析失败会抛错)。 */
|
|
4110
|
-
function buildEngineConfig(fullVersion, dataPathGlobal, majorPath) {
|
|
4213
|
+
function buildEngineConfig(fullVersion, dataPathGlobal, majorPath, platform = detectPlatformType()) {
|
|
4111
4214
|
const { osVersion } = systemInfo();
|
|
4112
|
-
const { qua } = resolveAppidQua(fullVersion, majorPath);
|
|
4215
|
+
const { qua } = resolveAppidQua(fullVersion, majorPath, platform);
|
|
4113
4216
|
return {
|
|
4114
4217
|
base_path_prefix: "",
|
|
4115
|
-
platform_type:
|
|
4218
|
+
platform_type: platform,
|
|
4116
4219
|
app_type: APP_TYPE_DESKTOP,
|
|
4117
4220
|
app_version: fullVersion,
|
|
4118
4221
|
os_version: osVersion,
|
|
@@ -4138,6 +4241,7 @@ function buildLoginConfig(appid, fullVersion, commonPath) {
|
|
|
4138
4241
|
/** 生成 session 初始化配置(登录成功后调用)。 */
|
|
4139
4242
|
function buildSessionConfig(options) {
|
|
4140
4243
|
const { appid, fullVersion, selfUin, selfUid, accountPath, downloadPath, machineGuid } = options;
|
|
4244
|
+
const platform = options.platform ?? detectPlatformType();
|
|
4141
4245
|
const { platVer, osVersion, devType } = systemInfo();
|
|
4142
4246
|
const deviceInfo = {
|
|
4143
4247
|
guid: machineGuid ?? "",
|
|
@@ -4160,7 +4264,7 @@ function buildSessionConfig(options) {
|
|
|
4160
4264
|
d2: "",
|
|
4161
4265
|
d2Key: "",
|
|
4162
4266
|
machineId: "",
|
|
4163
|
-
platform
|
|
4267
|
+
platform,
|
|
4164
4268
|
platVer,
|
|
4165
4269
|
appid,
|
|
4166
4270
|
rdeliveryConfig: {
|
|
@@ -4168,7 +4272,7 @@ function buildSessionConfig(options) {
|
|
|
4168
4272
|
systemId: 0,
|
|
4169
4273
|
appId: "",
|
|
4170
4274
|
logicEnvironment: "",
|
|
4171
|
-
platform
|
|
4275
|
+
platform,
|
|
4172
4276
|
language: "",
|
|
4173
4277
|
sdkVersion: "",
|
|
4174
4278
|
userId: "",
|
|
@@ -4210,16 +4314,28 @@ function readMachineGuid(loginService) {
|
|
|
4210
4314
|
* 本模块**不再**使用 koffi / vtable / 内存偏移——所有对象由 QQ 的 NAPI 层自动构建。
|
|
4211
4315
|
* 业务层拿到的都是真实 JS 对象:engine.initWithDeskTopConfig(config, adapter) 等。
|
|
4212
4316
|
*/
|
|
4213
|
-
/**
|
|
4317
|
+
/**
|
|
4318
|
+
* 默认 engine 配置(按平台探测)。
|
|
4319
|
+
*
|
|
4320
|
+
* 平台:`process.platform` → KLINUX/KMAC/KWINDOWS;qua 优先从 wrapper.node 同目录
|
|
4321
|
+
* major.node 扫描(`NAPUTO_WRAPPER_PATH` 由 loader 注入),找不到再按版本拼。
|
|
4322
|
+
* Linux 实测需要 `V1_LNX_NQ_3.2.35_54395_GW_B`;Windows 旧行为(qua 空)仅在
|
|
4323
|
+
* 拿不到版本/major.node 时保底。
|
|
4324
|
+
*/
|
|
4214
4325
|
function defaultEngineConfig(env, qqDataPath) {
|
|
4326
|
+
const platform = detectPlatformType();
|
|
4327
|
+
const fullVersion = env.qqVersion ?? "";
|
|
4328
|
+
const wrapperPath = process.env["NAPUTO_WRAPPER_PATH"] ?? "";
|
|
4329
|
+
const majorPath = wrapperPath !== "" ? join(dirname(wrapperPath), "major.node") : "";
|
|
4330
|
+
const qua = (majorPath !== "" ? parseQuaFromMajor(majorPath) : null) ?? (fullVersion !== "" ? buildQua(fullVersion, platform) : "");
|
|
4215
4331
|
return {
|
|
4216
4332
|
base_path_prefix: env.dataDir ?? "",
|
|
4217
|
-
platform_type:
|
|
4333
|
+
platform_type: platform,
|
|
4218
4334
|
app_type: 4,
|
|
4219
|
-
app_version:
|
|
4220
|
-
os_version: process.platform,
|
|
4221
|
-
use_xlog:
|
|
4222
|
-
qua
|
|
4335
|
+
app_version: fullVersion,
|
|
4336
|
+
os_version: version() || process.platform,
|
|
4337
|
+
use_xlog: platform !== PlatformType.KWINDOWS,
|
|
4338
|
+
qua,
|
|
4223
4339
|
global_path_config: { desktopGlobalPath: qqDataPath ?? env.dataDir ?? "" },
|
|
4224
4340
|
thumb_config: {
|
|
4225
4341
|
maxSide: 324,
|
|
@@ -4246,8 +4362,16 @@ function electronProcessType() {
|
|
|
4246
4362
|
* QQ 真实数据路径才能读到历史账号——cli 的 `.napuketto\default` 数据目录读不到
|
|
4247
4363
|
* (getLoginList 返回空 → 只能 QR 登录)。V1 主进程模式 QQ 自己 initConfig 过
|
|
4248
4364
|
* 正确路径,无需此解析。
|
|
4365
|
+
*
|
|
4366
|
+
* 平台分流(2026-11-09 Stage 1 E2E):Linux(KLINUX)自建宿主持有 QQ 数据,直接
|
|
4367
|
+
* 用数据根(`<数据根>/nt_qq`),不读 `$HOME`——否则换机器/换用户读不到历史账号,
|
|
4368
|
+
* 还会把 QQ 崩溃目录等写进用户主目录。Windows 保持官方 API + 默认位置兜底。
|
|
4249
4369
|
*/
|
|
4250
|
-
function resolveQqUserDataRoot(exports) {
|
|
4370
|
+
function resolveQqUserDataRoot(exports, opts = {}) {
|
|
4371
|
+
if ((opts.platform ?? detectPlatformType()) === PlatformType.KLINUX) {
|
|
4372
|
+
const dataRoot = opts.dataRoot ?? process.env["NAPUTO_DATA_ROOT"] ?? "";
|
|
4373
|
+
if (dataRoot !== "") return dataRoot;
|
|
4374
|
+
}
|
|
4251
4375
|
return extractUserDataRoot(exports) ?? join(homedir(), "Documents", "Tencent Files");
|
|
4252
4376
|
}
|
|
4253
4377
|
/** 从 QQ 官方 API 提取数据根(不可用返回 null,调用方回退默认)。 */
|
|
@@ -4385,7 +4509,7 @@ function finishSession(ctx, hasCaptured, isSelfHost, sessionConfig) {
|
|
|
4385
4509
|
/** engine 配置:显式覆盖优先,否则默认(含 QQ 数据根 global 路径解析)。 */
|
|
4386
4510
|
function resolveEngineConfig(ctx, env, engineConfig) {
|
|
4387
4511
|
if (engineConfig !== void 0) return engineConfig;
|
|
4388
|
-
return defaultEngineConfig(env ?? {}, resolveBootQqGlobalPath(ctx));
|
|
4512
|
+
return defaultEngineConfig(env ?? {}, resolveBootQqGlobalPath(ctx, env?.dataRoot));
|
|
4389
4513
|
}
|
|
4390
4514
|
/** 捕获 QQ 已 init 的 session(boot.cjs 拦截 `new` 窃取),返回是否捕获成功。 */
|
|
4391
4515
|
function captureSession(ctx, qqSession) {
|
|
@@ -4399,10 +4523,13 @@ function captureSession(ctx, qqSession) {
|
|
|
4399
4523
|
* 数据目录(数据根/nt_qq/global,HANDOVER-V6),否则登录数据读写错位
|
|
4400
4524
|
* (P2-1 实测 2026-08-06;getLoginList 空)。QQ 主进程(V1)QQ 自己已配置
|
|
4401
4525
|
* engine,无需解析。
|
|
4526
|
+
*
|
|
4527
|
+
* `dataRoot` 仅 Linux 生效(`resolveQqUserDataRoot` 平台分流):loader 由
|
|
4528
|
+
* `NAPUTO_DATA_ROOT` 注入,QQ 数据固定落 `<数据根>/nt_qq/global`。
|
|
4402
4529
|
*/
|
|
4403
|
-
function resolveBootQqGlobalPath(ctx) {
|
|
4530
|
+
function resolveBootQqGlobalPath(ctx, dataRoot) {
|
|
4404
4531
|
if (electronProcessType() === "browser") return;
|
|
4405
|
-
const root = resolveQqUserDataRoot(ctx.exports);
|
|
4532
|
+
const root = resolveQqUserDataRoot(ctx.exports, dataRoot !== void 0 && dataRoot !== "" ? { dataRoot } : {});
|
|
4406
4533
|
if (root === null) return;
|
|
4407
4534
|
return resolveQqGlobalPath(root);
|
|
4408
4535
|
}
|
|
@@ -4665,11 +4792,12 @@ function waitQrLoggedIn(session) {
|
|
|
4665
4792
|
/**
|
|
4666
4793
|
* loginService.initConfig 的 commonPath:
|
|
4667
4794
|
* worker/自建宿主(非 browser)优先 QQ 真实数据目录(数据根/nt_qq/global),
|
|
4668
|
-
* 否则回退账号目录。
|
|
4795
|
+
* 否则回退账号目录。Linux 下数据根即 Napuketto 数据根(`ctx.paths.root`),
|
|
4796
|
+
* Windows 由 QQ 官方 API 定位。
|
|
4669
4797
|
*/
|
|
4670
4798
|
function resolveCommonPath(ctx, wrapper) {
|
|
4671
4799
|
if (electronProcessType() !== "browser") {
|
|
4672
|
-
const root = resolveQqUserDataRoot(wrapper.exports);
|
|
4800
|
+
const root = resolveQqUserDataRoot(wrapper.exports, { dataRoot: ctx.paths.root });
|
|
4673
4801
|
if (root !== null) return resolveQqGlobalPath(root);
|
|
4674
4802
|
}
|
|
4675
4803
|
return ctx.paths.accountDir;
|