repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/nushell/debug.ts

Raw
File outline
import { closeSync, constants, fstatSync, openSync, writeSync } from "node:fs";

export type DebugLog = (
	event: string,
	details?: Record<string, unknown>,
) => void;

export function openDebugLog(
	path: string,
	onError: (message: string) => void,
): {
	log: DebugLog;
	close: () => void;
} {
	const fd = openSync(
		path,
		constants.O_WRONLY |
			constants.O_APPEND |
			constants.O_CREAT |
			(constants.O_NOFOLLOW ?? 0),
		0o600,
	);
	const stat = fstatSync(fd);
	if (
		!stat.isFile() ||
		(process.platform !== "win32" && (stat.mode & 0o077) !== 0)
	) {
		closeSync(fd);
		throw new Error(
			"Debug log must be a regular file accessible only to its owner",
		);
	}
	let open = true;
	let sequence = 0;
	const close = () => {
		if (!open) return;
		open = false;
		closeSync(fd);
	};
	return {
		log(event, details = {}) {
			if (!open) return;
			try {
				writeSync(
					fd,
					`${JSON.stringify({ ...details, timestamp: new Date().toISOString(), pid: process.pid, sequence: ++sequence, event })}\n`,
				);
			} catch (error) {
				close();
				onError(
					`Nushell debug logging stopped: ${error instanceof Error ? error.message : String(error)}`,
				);
			}
		},
		close,
	};
}