export type Level = "DEBUG" | "INFO" | "WARN" | "ERROR";export type LogLine = { timestamp: string; level: Level; module?: string; message: string; fields: Record<string, string>;};export type LogParseFailure = { kind: "empty_line" } | { kind: "bad_timestamp" } | { kind: "bad_level"; level: string };export class LogParseError extends Error { declare readonly kind: LogParseFailure["kind"]; declare readonly level?: string; constructor(failure: LogParseFailure) { super(failure.kind); Object.assign(this, failure); }}const LEVELS: readonly string[] = ["DEBUG", "INFO", "WARN", "ERROR"];const FIELD = /^([a-z_][a-z0-9_]*)=(.+)$/;const validTimestamp = (t: string): boolean => { const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/.exec(t); if (!m) return false; const [y, mo, d, hh, mm, ss] = m.slice(1).map(Number); if (mo < 1 || mo > 12 || hh > 23 || mm > 59 || ss > 59 || d < 1) return false; const leap = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0; const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1]; return d <= days;};/** Throws LogParseError when the line cannot be parsed. */export function parseLogLine(line: string): LogLine { const tokens = line.split(" ").filter((t) => t !== ""); if (tokens.length === 0) throw new LogParseError({ kind: "empty_line" }); const timestamp = tokens[0]; if (!validTimestamp(timestamp)) throw new LogParseError({ kind: "bad_timestamp" }); const level = tokens.length > 1 ? tokens[1] : ""; if (!LEVELS.includes(level)) throw new LogParseError({ kind: "bad_level", level }); let start = 2; let module: string | undefined; const maybeModule = tokens[2]; if (maybeModule !== undefined && maybeModule.length > 2 && maybeModule.startsWith("[") && maybeModule.endsWith("]")) { module = maybeModule.slice(1, -1); start = 3; } let end = tokens.length; while (end > start && FIELD.test(tokens[end - 1])) end -= 1; const entries: Array<[string, string]> = []; for (const tok of tokens.slice(end)) { const eq = tok.indexOf("="); entries.push([tok.slice(0, eq), tok.slice(eq + 1)]); } const result: LogLine = { timestamp, level: level as Level, message: tokens.slice(start, end).join(" "), fields: Object.fromEntries(entries), }; if (module !== undefined) result.module = module; return result;}