All files / src/dev-server logger.ts

61.11% Statements 22/36
30.76% Branches 4/13
11.11% Functions 1/9
56.66% Lines 17/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 702x 2x 2x     2x   2x           2x               2x 2x           2x     2x   2x       2x   8x                                 2x     2x     2x         2x    
import fp from "fastify-plugin";
import dateTime from "./date-time.js";
import { bold, blue, dim, yellow, red, cyan, green } from "femtocolor";
 
/* eslint-disable @typescript-eslint/no-var-requires */
const ms = require("ms") as (val: number, options?: object) => string;
const colorOptions = (
  require("femtocolor") as { options: { enabled: boolean } }
).options;
/* eslint-enable @typescript-eslint/no-var-requires */
 
// femtocolor requires process.env.TERM (POSIX) to enable colors; Windows terminals don't set it.
// Fall back to Node's own color-depth check, which handles Windows Terminal via WT_SESSION.
Iif (
  !colorOptions.enabled &&
  process.stdout.isTTY &&
  process.stdout.hasColors()
) {
  colorOptions.enabled = true;
}
 
const EOL = "\n";
const colorCodes: Record<number, (s: string) => string> = {
  5: red,
  4: yellow,
  3: cyan,
  2: green,
};
const getColor = (status: number) =>
  colorCodes[Math.trunc(status / 100)] ?? ((s: string) => s);
 
export const header = blue("⚡︎dev-server");
 
const log = (msg: string): void => {
  process.stdout.write(`[${dateTime()}] ${msg}` + EOL);
};
 
export const responseLogger = fp(
  async (server: any, { silent = false }: { silent?: boolean } = {}) => {
    Eif (silent) return;
    const logResponse = async (req: any, reply: any) => {
      const status: number = reply.statusCode;
      const c = getColor(status);
      const timing = ms(Math.round(reply.elapsedTime)) || "";
      log(
        bold(c(req.method)) +
          " " +
          req.url +
          c(" • ") +
          dim(status + " • " + timing),
      );
    };
    server.addHook("onResponse", logResponse);
  },
);
 
export const logDir = (dir: string): void =>
  log(header + " serving " + bold(dir));
 
export const logSpa = (spaFile: string): void =>
  log(header + " using fallback file " + bold(spaFile));
 
export const logProxy = (from: string, to: string): void =>
  log(
    header + " proxying from " + bold(yellow(from)) + " to " + bold(yellow(to)),
  );
 
export const logListening = (host: string, port: number): void =>
  log(header + " listening on " + bold(green(`http://${host}:${port}`)));