/
debug.ts
286 lines (242 loc) · 6.56 KB
/
debug.ts
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
const { noColor, env } = Deno;
import { ms } from "https://raw.githubusercontent.com/denolib/ms/master/ms.ts";
import format from "./format.ts";
import { coerce, selectColor, regexpToNamespace } from "./utils.ts";
interface DebugInstance {
(log: string | Error, ...args: any[]): void;
namespace: string;
enabled: boolean;
color: number;
destroy: () => boolean;
extend: (namespace: string, delimiter?: string) => DebugInstance;
log?: Function;
}
interface DebugModule {
(namespace: string): DebugInstance;
enable: (namespaces: any) => void;
disable: () => string;
enabled: (namespace: string) => boolean;
names: RegExp[];
skips: RegExp[];
formatters: Formatters;
log: Function;
}
interface Formatters {
[key: string]: (value: any) => string;
}
/**
* Active `debug` instances.
*/
let instances: DebugInstance[] = [];
/**
* The currently active debug mode names, and names to skip.
*/
let names: RegExp[] = [];
let skips: RegExp[] = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
let formatters: Formatters = {};
/**
* Create a debugger with the given `namespace`.
*/
function createDebug(namespace: string): DebugInstance {
let prevTime: number;
let debug: DebugInstance;
// @ts-ignore-next-line
debug = function (log: string | Error, ...args: any[]) {
// Skip if debugger is disabled
if (!debug.enabled) {
return;
}
const self = debug;
log = coerce(log);
if (typeof log !== "string") {
// Anything else let's inspect with %O
args.unshift(log);
log = "%O";
}
// Set `diff` timestamp
const currTime = Number(Date.now());
// Difference in miliseconds
const diff = currTime - (prevTime || currTime);
prevTime = currTime;
// Apply all custom formatters to our arguments
const customFormattedArgs = applyFormatters.call(self, log, ...args);
const { namespace, color } = self;
// Format the string before logging
const formattedArgs = formatArgs(
{ namespace, color, diff },
customFormattedArgs,
);
// Use a custom logger if defined
// If not, we use the default logger
const logFn = self.log || debugModule.log;
// Finally, log
logFn.apply(self, formattedArgs);
return;
};
debug.namespace = namespace;
debug.color = selectColor(namespace);
debug.enabled = enabled(namespace);
debug.destroy = destroy;
debug.extend = extend;
instances.push(debug);
return debug;
}
function destroy(this: DebugInstance) {
if (instances.includes(this)) {
this.enabled = false;
instances = instances.filter((instance) => instance !== this);
return true;
}
return false;
}
/**
* const server = debug('server');
* const serverHttp = server.extend('http') // server:http
* const serverHttpReq = serverHttp.extend('req', '-') // server:http-req
*/
function extend(
this: DebugInstance,
subNamespace: string,
delimiter: string = ":",
) {
const newNamespace = `${this.namespace}${delimiter}${subNamespace}`;
const newDebug = createDebug(newNamespace);
// Pass down the custom logger
newDebug.log = this.log;
return newDebug;
}
function applyFormatters(this: DebugInstance, fmt: string, ...args: any[]) {
let index = 0;
const newFmt = fmt.replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === "%%") {
return match;
}
const formatter = formatters[format];
if (typeof formatter === "function") {
const value = args[index];
// Remove the argument we used in the custom formatter
args = [...args.slice(0, index), ...args.slice(index + 1)];
return formatter.call(this, value);
}
index++;
return match;
});
// Return the update fmt string and updated args
return [newFmt, ...args];
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*/
export function enabled(namespace: string): boolean {
if (namespace[namespace.length - 1] === "*") {
return true;
}
for (const skip of skips) {
if (skip.test(namespace)) {
return false;
}
}
for (const name of names) {
if (name.test(namespace)) {
return true;
}
}
return false;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*/
export function enable(namespaces: any) {
updateNamespacesEnv(namespaces);
// Resets enabled and disable namespaces
names = [];
skips = [];
// Splits on comma
// Loops through the passed namespaces
// And groups them in enabled and disabled lists
(typeof namespaces === "string" ? namespaces : "")
.split(/[\s,]+/)
// Ignore empty strings
.filter(Boolean)
.map((namespace) => namespace.replace(/\*/g, ".*?"))
.forEach((ns) => {
// If a namespace starts with `-`, we should disable that namespace
if (ns[0] === "-") {
skips.push(new RegExp("^" + ns.slice(1) + "$"));
} else {
names.push(new RegExp("^" + ns + "$"));
}
});
instances.forEach((instance) => {
instance.enabled = enabled(instance.namespace);
});
}
interface FormatArgsOptions {
namespace: string;
color: number;
diff: number;
}
function formatArgs(
{ namespace, color, diff }: FormatArgsOptions,
args: any[],
): any[] {
const colorCode = "\u001B[3" + (color < 8 ? color : "8;5;" + color);
const prefix = noColor
? ` ${namespace} `
: ` ${colorCode};1m${namespace} \u001B[0m`;
// Add a prefix on every line
args[0] = args[0]
.split("\n")
.map((line: string) => `${prefix}${line}`)
.join("\n");
const lastArg = noColor
? `+${ms(diff)}`
: `${colorCode}m+${ms(diff)}${"\u001B[0m"}`;
return [...args, lastArg];
}
/**
* Disable debug output.
*/
export function disable(): string {
const namespaces = [
...names.map(regexpToNamespace),
...skips.map(regexpToNamespace).map((namespace) => `-${namespace}`),
].join(",");
enable("");
return namespaces;
}
/**
* Save `namespaces` to env.
*/
function updateNamespacesEnv(namespaces: string): void {
if (namespaces) {
env.toObject().DEBUG = namespaces;
} else {
delete env.toObject().DEBUG;
}
}
// Default logger
function log(...args: any[]): void {
const result = format(...args);
console.log(result);
}
// Exports
const debugModule: DebugModule = Object.assign(createDebug, {
enable,
disable,
enabled,
names,
skips,
formatters,
log,
});
// Enable namespaces passed from env
enable(env.toObject().DEBUG);
export default debugModule;