refactor(common): extract leaf utilities into @snowluma/common package
Phase 1 of the 4-package split called out in RoadMap #3. Moves the "infrastructure" leaves — files with zero business dependencies that @snowluma/bridge, @snowluma/core, and @snowluma/onebot all consume — into a dedicated workspace package. Mirrors what #4 (proto-defs) did for wire-protobuf definitions. Why --- - Cleaner layering: these were never bridge- or onebot-specific. Logger / hex codec / runtime config sit at the bottom of every module's import graph; giving them their own package makes that graph readable and prevents future leaks the other direction. - Sets up #3's bridge + onebot extractions: those need a clean leaf to depend on. Without this, every cross-package import would have to re-export through core, which defeats the split. - Mirrors @snowluma/proto-defs layout — per-file subpath exports (`@snowluma/common/logger`, `@snowluma/common/hex`, …) keep import sites unambiguous and let bundlers tree-shake aggressively. Layout ------ Moved (via `git mv` — history preserved): packages/core/src/utils/logger.ts → @snowluma/common/logger packages/core/src/utils/hex.ts → @snowluma/common/hex packages/core/src/utils/log-file-transport.ts → @snowluma/common/log-file-transport packages/core/src/utils/log-summary.ts → @snowluma/common/log-summary packages/core/src/protocol/packet-sender.ts → @snowluma/common/packet-sender packages/core/src/protocol/types.ts → @snowluma/common/protocol-types packages/core/src/common/runtime.ts → @snowluma/common/runtime Not moved (deferred to Phase 2): `packages/core/src/utils/event-format.ts` — it has reverse imports on `bridge/events`, `bridge/identity-service`, `onebot/message-store`, `onebot/types`. It moves into @snowluma/bridge in Phase 2, with the MessageStore parameter decoupled via a structural type so bridge doesn't end up depending on onebot. Changes ------- - New package `packages/common/` (package.json, tsconfig.json — no src/index.ts barrel, callers use the subpath exports directly to avoid pulling in `node:fs` when only the hex codec is needed). - 7 `.ts` files moved via `git mv`. - 50+ import sites rewritten via sed across `packages/core/src` and `packages/core/tests`. Old shapes (`../utils/logger`, `../../protocol/types`, `./common/runtime`, `../src/utils/hex`) all collapse to `@snowluma/common/<sub>`. - `@snowluma/core` depends on `@snowluma/common` (workspace:*). - `packages/core/src/{protocol,common}/` directories removed (empty). Verification ------------ - core typecheck: clean - common typecheck: clean - Full workspace `pnpm -r typecheck`: all 9 projects clean - core test suite: 552 passed / 552 total (pre-existing websocket-darwin-arm64.node addon failure unchanged — same baseline as the previous refactor commits) - Vite build with stubbed native binary: clean (143 modules, 2.84 MB bundle, 224 KB gzip — same size envelope as before) Note: `utils/event-format.ts` is the only file remaining under the old `utils/` namespace. It moves into @snowluma/bridge alongside the events / identity-service / packet-pipeline trio in Phase 2.
This commit is contained in:
64 files changed
+138
-65
No files matched your search
@@ -0,0 +1,35 @@
|
||||
const HEX_CHARS = '0123456789abcdef';
|
||||
const HEX_CHARS_UPPER = '0123456789ABCDEF';
|
||||
|
||||
export function toHex(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS[b >> 4];
|
||||
h += HEX_CHARS[b & 0xf];
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
export function toHexUpper(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
return data.length > limit ? `${head}...` : head;
|
||||
}
|
||||
|
||||
export function fromHex(hex: string): Buffer {
|
||||
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const DEFAULT_DIR = 'logs';
|
||||
const DEFAULT_MAX_MB = 50;
|
||||
const DEFAULT_RETAIN_DAYS = 7;
|
||||
const FILE_PREFIX = 'snowluma-';
|
||||
const FILE_SUFFIX = '.log';
|
||||
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
|
||||
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
|
||||
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
|
||||
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
|
||||
|
||||
function parsePositiveInt(v: string | undefined, dflt: number): number {
|
||||
if (!v) return dflt;
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : dflt;
|
||||
}
|
||||
|
||||
function todayString(d: Date = new Date()): string {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function dateOf(s: string): Date {
|
||||
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
|
||||
return new Date(y!, m! - 1, d!);
|
||||
}
|
||||
|
||||
function stripAnsi(line: string): string {
|
||||
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
|
||||
}
|
||||
|
||||
interface OpenFile {
|
||||
stream: fs.WriteStream;
|
||||
bytes: number;
|
||||
date: string;
|
||||
splitIndex: number;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one output directory: keeps at most one open WriteStream, handles
|
||||
* daily rollover, per-file size cap, and retention cleanup. The shared
|
||||
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
|
||||
*/
|
||||
class FileWriter {
|
||||
private disabled = false;
|
||||
private file: OpenFile | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly dir: string,
|
||||
private readonly maxBytes: number,
|
||||
private readonly retainDays: number,
|
||||
) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.disabled = true;
|
||||
console.error(
|
||||
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
get isDisabled(): boolean {
|
||||
return this.disabled;
|
||||
}
|
||||
|
||||
get currentPath(): string | null {
|
||||
return this.file?.path ?? null;
|
||||
}
|
||||
|
||||
write(data: string, bytes: number): void {
|
||||
if (this.disabled) return;
|
||||
const today = todayString();
|
||||
this.ensureForToday(today);
|
||||
if (!this.file) return;
|
||||
|
||||
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
|
||||
this.rotateBySize();
|
||||
if (!this.file) return;
|
||||
}
|
||||
|
||||
this.file.stream.write(data);
|
||||
this.file.bytes += bytes;
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
const f = this.file;
|
||||
this.file = null;
|
||||
if (!f) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
f.stream.end(() => resolve());
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureForToday(today: string): void {
|
||||
if (this.file && this.file.date === today) return;
|
||||
|
||||
if (this.file) {
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
this.file = null;
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
// Resume from the highest existing split index for today (so two
|
||||
// process starts on the same day share files / don't clobber).
|
||||
let idx = 0;
|
||||
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
|
||||
this.file = this.openFile(today, idx);
|
||||
}
|
||||
|
||||
private rotateBySize(): void {
|
||||
if (!this.file) return;
|
||||
const date = this.file.date;
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
let next = this.file.splitIndex + 1;
|
||||
while (fs.existsSync(this.pathFor(date, next))) next++;
|
||||
this.file = this.openFile(date, next);
|
||||
}
|
||||
|
||||
private openFile(date: string, splitIndex: number): OpenFile | null {
|
||||
const p = this.pathFor(date, splitIndex);
|
||||
try {
|
||||
let bytes = 0;
|
||||
try {
|
||||
bytes = fs.statSync(p).size;
|
||||
} catch {
|
||||
/* file doesn't exist yet */
|
||||
}
|
||||
const stream = fs.createWriteStream(p, { flags: 'a' });
|
||||
stream.on('error', (err) => {
|
||||
console.error(`[logger] file write error on ${p}: ${err.message}`);
|
||||
});
|
||||
return { stream, bytes, date, splitIndex, path: p };
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private pathFor(date: string, splitIndex: number): string {
|
||||
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
|
||||
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(this.dir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
|
||||
const cutoff = Date.now() - retainMs;
|
||||
for (const name of entries) {
|
||||
const m = FILE_RE.exec(name);
|
||||
if (!m) continue;
|
||||
const dateStr = m[1]!;
|
||||
if (dateOf(dateStr).getTime() < cutoff) {
|
||||
try {
|
||||
fs.unlinkSync(path.join(this.dir, name));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class FileTransport {
|
||||
private readonly dir: string;
|
||||
private readonly maxBytes: number;
|
||||
private readonly retainDays: number;
|
||||
private readonly enabled: boolean;
|
||||
private readonly perUinEnabled: boolean;
|
||||
private shared: FileWriter | null = null;
|
||||
private perUin = new Map<number, FileWriter>();
|
||||
|
||||
constructor() {
|
||||
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
|
||||
this.maxBytes =
|
||||
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
|
||||
this.retainDays = parsePositiveInt(
|
||||
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
DEFAULT_RETAIN_DAYS,
|
||||
);
|
||||
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
|
||||
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
|
||||
|
||||
if (this.enabled) {
|
||||
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
|
||||
this.shared = w.isDisabled ? null : w;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when no file output will happen (env disable or init failure). */
|
||||
get isDisabled(): boolean {
|
||||
return !this.shared;
|
||||
}
|
||||
|
||||
/** Current shared-file path (or null if disabled / not yet opened). */
|
||||
get currentPath(): string | null {
|
||||
return this.shared?.currentPath ?? null;
|
||||
}
|
||||
|
||||
/** Path of the per-UIN file for the given UIN, if open. */
|
||||
perUinPath(uin: number): string | null {
|
||||
return this.perUin.get(uin)?.currentPath ?? null;
|
||||
}
|
||||
|
||||
write(line: string, uin?: number): void {
|
||||
if (!this.shared) return;
|
||||
const data = stripAnsi(line) + '\n';
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
|
||||
this.shared.write(data, bytes);
|
||||
|
||||
if (uin !== undefined && this.perUinEnabled) {
|
||||
let w = this.perUin.get(uin);
|
||||
if (!w) {
|
||||
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
|
||||
if (w.isDisabled) return;
|
||||
this.perUin.set(uin, w);
|
||||
}
|
||||
w.write(data, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const closes: Promise<void>[] = [];
|
||||
if (this.shared) closes.push(this.shared.close());
|
||||
for (const w of this.perUin.values()) closes.push(w.close());
|
||||
this.shared = null;
|
||||
this.perUin.clear();
|
||||
await Promise.all(closes);
|
||||
}
|
||||
}
|
||||
|
||||
let singleton: FileTransport | null = null;
|
||||
|
||||
export function getFileTransport(): FileTransport {
|
||||
if (!singleton) singleton = new FileTransport();
|
||||
return singleton;
|
||||
}
|
||||
|
||||
/** Reset state between tests. Closes all active file handles. */
|
||||
export async function _resetFileTransportForTesting(): Promise<void> {
|
||||
if (singleton) await singleton.close();
|
||||
singleton = null;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
|
||||
function valueRepr(v: unknown): string {
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a params object as a single line for logging. Skips deep
|
||||
* traversal: nested objects collapse to `{...}`, arrays to `[len=N]`.
|
||||
* Strings are quoted; long ones are truncated with an ellipsis.
|
||||
*
|
||||
* Output is capped at MAX_TOTAL chars; on overflow the tail is
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v)}`;
|
||||
// +1 accounts for the separating space we'd insert when joining.
|
||||
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
|
||||
out.push('...');
|
||||
break;
|
||||
}
|
||||
out.push(entry);
|
||||
total += entry.length + (out.length > 1 ? 1 : 0);
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
};
|
||||
|
||||
const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
const logEntries: LogEntry[] = [];
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
}
|
||||
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
|
||||
// Only governs console + ring buffer + subscribers; the file
|
||||
// transport always sees debug-and-up regardless.
|
||||
let currentLevel: LogLevel = resolveMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the console / subscriber level at runtime. Invalid input is
|
||||
* a no-op (returns false). File transport is unaffected — it always
|
||||
* sees every level so post-mortems remain useful.
|
||||
*/
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
if (process.env.NO_COLOR === '1') return false;
|
||||
return Boolean(process.stdout.isTTY);
|
||||
}
|
||||
|
||||
function ansi(code: number, text: string): string {
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
}
|
||||
|
||||
function currentTime(): string {
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
const message = format(...args);
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
}
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber level filter. File output is debug-and-up always;
|
||||
// see log-file-transport.ts.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options, args);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
message,
|
||||
line,
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush and close the underlying log file. Call from shutdown hooks
|
||||
* (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal
|
||||
* buffer makes it to disk. Returns a promise that resolves once the OS
|
||||
* has finalized the write.
|
||||
*/
|
||||
export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number;[k: string]: unknown }) => Logger;
|
||||
}
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface SendPacketResult {
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer | null;
|
||||
}
|
||||
|
||||
export interface PacketSender {
|
||||
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface PacketInfo {
|
||||
pid: number;
|
||||
uin: string;
|
||||
packetType?: number;
|
||||
serviceCmd: string;
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
}
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
@@ -0,0 +1,113 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
};
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
let normalized: RuntimeConfig;
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
normalized = { ...DEFAULT_RUNTIME_CONFIG };
|
||||
} else {
|
||||
normalized = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
|
||||
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
|
||||
// pick a free port per-launch while CLI/Docker users continue to drive
|
||||
// it from runtime.json.
|
||||
const envPort = envPortOverride();
|
||||
if (envPort !== undefined) {
|
||||
normalized = { ...normalized, webuiPort: envPort };
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function envPortOverride(): number | undefined {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
if (!raw || typeof raw !== 'string') return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!isObject(parsed)) return null;
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
if (n > 0 && n <= 65535) return n;
|
||||
return fallback;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
if (port > 0 && port <= 65535) return port;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
Reference in new issue
Block a user