UNPKG

2.85 kBJavaScriptView Raw
1import * as symbol from './symbol.js'
2import * as time from './time.js'
3import * as env from './environment.js'
4import * as func from './function.js'
5import * as json from './json.js'
6
7export const BOLD = symbol.create()
8export const UNBOLD = symbol.create()
9export const BLUE = symbol.create()
10export const GREY = symbol.create()
11export const GREEN = symbol.create()
12export const RED = symbol.create()
13export const PURPLE = symbol.create()
14export const ORANGE = symbol.create()
15export const UNCOLOR = symbol.create()
16
17/* c8 ignore start */
18/**
19 * @param {Array<undefined|string|Symbol|Object|number|function():any>} args
20 * @return {Array<string|object|number>}
21 */
22export const computeNoColorLoggingArgs = args => {
23 if (args.length === 1 && args[0]?.constructor === Function) {
24 args = /** @type {Array<string|Symbol|Object|number>} */ (/** @type {[function]} */ (args)[0]())
25 }
26 const strBuilder = []
27 const logArgs = []
28 // try with formatting until we find something unsupported
29 let i = 0
30 for (; i < args.length; i++) {
31 const arg = args[i]
32 if (arg === undefined) {
33 strBuilder.push('undefined')
34 } else if (arg.constructor === String || arg.constructor === Number) {
35 strBuilder.push(arg)
36 } else if (arg.constructor === Object) {
37 logArgs.push(JSON.stringify(arg))
38 }
39 }
40 return logArgs
41}
42/* c8 ignore stop */
43
44const loggingColors = [GREEN, PURPLE, ORANGE, BLUE]
45let nextColor = 0
46let lastLoggingTime = time.getUnixTime()
47
48/* c8 ignore start */
49/**
50 * @param {function(...any):void} _print
51 * @param {string} moduleName
52 * @return {function(...any):void}
53 */
54export const createModuleLogger = (_print, moduleName) => {
55 const color = loggingColors[nextColor]
56 const debugRegexVar = env.getVariable('log')
57 const doLogging = debugRegexVar !== null &&
58 (debugRegexVar === '*' || debugRegexVar === 'true' ||
59 new RegExp(debugRegexVar, 'gi').test(moduleName))
60 nextColor = (nextColor + 1) % loggingColors.length
61 moduleName += ': '
62 return !doLogging
63 ? func.nop
64 : (...args) => {
65 if (args.length === 1 && args[0]?.constructor === Function) {
66 args = args[0]()
67 }
68 const timeNow = time.getUnixTime()
69 const timeDiff = timeNow - lastLoggingTime
70 lastLoggingTime = timeNow
71 _print(
72 color,
73 moduleName,
74 UNCOLOR,
75 ...args.map((arg) => {
76 if (arg != null && arg.constructor === Uint8Array) {
77 arg = Array.from(arg)
78 }
79 const t = typeof arg
80 switch (t) {
81 case 'string':
82 case 'symbol':
83 return arg
84 default: {
85 return json.stringify(arg)
86 }
87 }
88 }),
89 color,
90 ' +' + timeDiff + 'ms'
91 )
92 }
93}
94/* c8 ignore stop */