Sohaib
2023-08-15 232652149a287054df7e7c5136dafd3f55a79bf0
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
import chalk from "chalk"
import process from "process"
import { isMainThread } from "workerpool"
 
const rootFile = /.*at file:/
export function trace(msg: string, err: Error) {
  const stack = err.stack
 
  const lines: string[] = []
 
  lines.push("")
  lines.push(
    "\n" +
      chalk.bgRed.black.bold(" ERROR ") +
      "\n" +
      chalk.red(` ${msg}`) +
      (err.message.length > 0 ? `: ${err.message}` : ""),
  )
 
  if (!stack) {
    return
  }
 
  let reachedEndOfLegibleTrace = false
  for (const line of stack.split("\n").slice(1)) {
    if (reachedEndOfLegibleTrace) {
      break
    }
 
    if (!line.includes("node_modules")) {
      lines.push(` ${line}`)
      if (rootFile.test(line)) {
        reachedEndOfLegibleTrace = true
      }
    }
  }
 
  const traceMsg = lines.join("\n")
  if (!isMainThread) {
    // gather lines and throw
    throw new Error(traceMsg)
  } else {
    // print and exit
    console.error(traceMsg)
    process.exit(1)
  }
}