All files / src/lib client-log.ts

64.28% Statements 27/42
58.06% Branches 18/31
61.53% Functions 8/13
64.28% Lines 27/42

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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140                                        16x   16x   16x       5x 5x                         17x 6x 6x   17x 11x 11x 11x           11x         1x                     50x     50x                 50x 7x   43x 1x         16x   42x     1x               7x 2x   5x         16x                                                    
// Logging in the browser. Lines are buffered and sent to the Worker
// (POST /api/log), which writes them into the same logs as the server's, with
// the same trace id (src/lib/trace.ts). Same rules as server logging: event
// names are `<capability>.<what_happened>`, no personal data.
 
import { isNetworkError } from './network-error'
import { browserTraceId } from './trace'
 
export type ClientLogLevel = 'info' | 'warn' | 'error'
export type ClientLogFields = Record<string, string | number | boolean>
 
export interface ClientLogEvent {
  level: ClientLogLevel
  event: string
  time: string
  path: string
  fields?: ClientLogFields
  error?: { name: string; message: string; stack?: string }
}
 
export const CLIENT_LOG_URL = '/api/log'
/** The most events one request carries; the server refuses more. */
export const CLIENT_LOG_BATCH = 20
 
const buffer: ClientLogEvent[] = []
let timer: ReturnType<typeof setTimeout> | undefined
 
function errorInfo(error: unknown): ClientLogEvent['error'] {
  Eif (error instanceof Error) {
    return {
      name: error.name,
      message: error.message.slice(0, 500),
      ...(error.stack === undefined
        ? {}
        : { stack: error.stack.slice(0, 4000) }),
    }
  }
  return { name: 'Error', message: String(error).slice(0, 500) }
}
 
/** Sends what is buffered; `beacon` survives the page being closed. */
export function flushClientLog(options: { beacon?: boolean } = {}): void {
  if (timer !== undefined) {
    clearTimeout(timer)
    timer = undefined
  }
  while (buffer.length > 0) {
    const events = buffer.splice(0, CLIENT_LOG_BATCH)
    const body = JSON.stringify({ traceId: browserTraceId(), events })
    Iif (options.beacon === true && typeof navigator.sendBeacon === 'function') {
      navigator.sendBeacon(
        CLIENT_LOG_URL,
        new Blob([body], { type: 'application/json' }),
      )
    } else {
      void fetch(CLIENT_LOG_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body,
        keepalive: true,
      }).catch(() => undefined)
    }
  }
}
 
function add(
  level: ClientLogLevel,
  event: string,
  fields?: ClientLogFields,
  error?: unknown,
) {
  Iif (typeof window === 'undefined') {
    return
  }
  buffer.push({
    level,
    event,
    time: new Date().toISOString(),
    // The path only: query strings may carry personal data.
    path: window.location.pathname,
    ...(fields === undefined ? {} : { fields }),
    ...(error === undefined ? {} : { error: errorInfo(error) }),
  })
  if (level === 'error' || buffer.length >= CLIENT_LOG_BATCH) {
    flushClientLog()
  } else {
    timer ??= setTimeout(() => {
      flushClientLog()
    }, 5000)
  }
}
 
export const clientLog = {
  info: (event: string, fields?: ClientLogFields) => {
    add('info', event, fields)
  },
  warn: (event: string, fields?: ClientLogFields) => {
    add('warn', event, fields)
  },
  /**
   * A failure someone should look at. A connection failure (the request
   * never reached the server) is sent as a warning with `network: true`
   * instead, so it doesn't raise an alert.
   */
  error: (event: string, fields?: ClientLogFields, error?: unknown) => {
    if (isNetworkError(error)) {
      add('warn', event, { ...fields, network: true }, error)
    } else {
      add('error', event, fields, error)
    }
  },
}
 
let installed = false
 
/**
 * Logs uncaught errors and unhandled rejections, and sends what is buffered
 * when the page is hidden or closed. Called once from the root route.
 */
export function installClientLogging(): void {
  if (installed || typeof window === 'undefined') {
    return
  }
  installed = true
  window.addEventListener('error', (e) => {
    clientLog.error('app.uncaught_error', {}, e.error ?? e.message)
  })
  window.addEventListener('unhandledrejection', (e) => {
    clientLog.error('app.unhandled_rejection', {}, e.reason)
  })
  window.addEventListener('pagehide', () => {
    flushClientLog({ beacon: true })
  })
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
      flushClientLog({ beacon: true })
    }
  })
}