1 import colors from "picocolors"
2
3 type LoggerOptions = {
4 file?: string | string[]
5 error?: any
6 }
7
8 function getTimestamp(): string {
9 const now = new Date()
10 return now.toLocaleTimeString("en-US", { hour12: true })
11 }
12
13 function getPrefix(type: "warn" | "info" | "error") {
14 const timestamp = colors.dim(getTimestamp())
15 const typeColor =
16 type === "warn"
17 ? colors.yellow
18 : type === "info"
19 ? colors.green
20 : colors.red
21
22 const prefix = typeColor("[@medusajs/admin-vite-plugin]")
23
24 return `${timestamp} ${prefix}`
25 }
26
27 function getFile(options: LoggerOptions): string {
28 if (!options.file) {
29 return ""
30 }
31
32 const value = Array.isArray(options.file)
33 ? options.file.map((f) => f).join(", ")
34 : options.file
35
36 return colors.dim(`${value}`)
37 }
38
39 function formatError(error: any): string {
40 if (error instanceof Error) {
41 return colors.red(`${error.name}: ${error.message}\n${error.stack}`)
42 } else if (typeof error === "object") {
43 return colors.red(JSON.stringify(error, null, 2))
44 } else {
45 return colors.red(String(error))
46 }
47 }
48
49 const logger = {
50 warn(msg: string, options: LoggerOptions = {}) {
51 console.warn(`${getPrefix("warn")} ${msg} ${getFile(options)}`)
52 },
53 info(msg: string, options: LoggerOptions = {}) {
54 console.info(`${getPrefix("info")} ${msg} ${getFile(options)}`)
55 },
56 error(msg: string, options: LoggerOptions = {}) {
57 console.error(`${getPrefix("error")} ${msg} ${getFile(options)}`)
58 if (options.error) {
59 console.error(formatError(options.error))
60 }
61 },
62 }
63
64 export { logger }