Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 61 lines · 2.4 KiB · at eb4a6ea

import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable } from "@tsus/runtime/boundary";export type Level = "DEBUG" | "INFO" | "WARN" | "ERROR";export type LogLine = {  timestamp: string;  level: Level;  module: Option<string>;  message: string;  fields: Record<string, string>;};export type LogParseError = { kind: "empty_line" } | { kind: "bad_timestamp" } | { kind: "bad_level"; level: string };const LEVELS: readonly Level[] = ["DEBUG", "INFO", "WARN", "ERROR"];const FIELD = /^([a-z_][a-z0-9_]*)=(.+)$/;const daysIn = (y: number, mo: number): number => {  const leap = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1];};const validParts = (parts: number[]): boolean => {  const [y, mo, d, hh, mm, ss] = parts;  return mo >= 1 && mo <= 12 && hh <= 23 && mm <= 59 && ss <= 59 && d >= 1 && d <= daysIn(y, mo);};const validTimestamp = (t: string): boolean =>  fromNullable(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/.exec(t))    .map((m) => validParts(m.slice(1).map(Number)))    .unwrapOr(false);const moduleOf = (tok: Option<string>): Option<string> =>  tok.andThen((t) => (t.length > 2 && t.startsWith("[") && t.endsWith("]") ? Some(t.slice(1, -1)) : None));const build = (tokens: string[], level: Level): LogLine => {  const module = moduleOf(fromNullable(tokens[2]));  const start = module.isSome() ? 3 : 2;  let end = tokens.length;  while (end > start && FIELD.test(tokens[end - 1])) {    end -= 1;  }  const entries = tokens.slice(end).map((tok): [string, string] => [tok.slice(0, tok.indexOf("=")), tok.slice(tok.indexOf("=") + 1)]);  return { timestamp: tokens[0], level, module, message: tokens.slice(start, end).join(" "), fields: Object.fromEntries(entries) };};const toLevel = (text: string): Option<Level> => fromNullable(LEVELS.find((l) => l === text));export const parseLogLine = (line: string): Result<LogLine, LogParseError> => {  const tokens = line.split(" ").filter((t) => t !== "");  const level = fromNullable(tokens[1]).unwrapOr("");  return tokens.length === 0    ? Err({ kind: "empty_line" })    : !validTimestamp(tokens[0])      ? Err({ kind: "bad_timestamp" })      : match (toLevel(level)) {          Some(known) => Ok(build(tokens, known)),          None => Err({ kind: "bad_level", level }),        };};