-
Notifications
You must be signed in to change notification settings - Fork 72
/
console.js
343 lines (308 loc) · 11.4 KB
/
console.js
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// @ts-check
// To ensure that this module operates without special privilege, it should
// not reference the free variable `console` except for its own internal
// debugging purposes in the declaration of `internalDebugConsole`, which is
// normally commented out.
import { defineProperty, freeze, fromEntries } from '../commons.js';
import './types.js';
import './internal-types.js';
// For our internal debugging purposes, uncomment
// const internalDebugConsole = console;
// The whitelists of console methods, from:
// Whatwg "living standard" https://console.spec.whatwg.org/
// Node https://nodejs.org/dist/latest-v14.x/docs/api/console.html
// MDN https://developer.mozilla.org/en-US/docs/Web/API/Console_API
// TypeScript https://openstapps.gitlab.io/projectmanagement/interfaces/_node_modules__types_node_globals_d_.console.html
// Chrome https://developers.google.com/web/tools/chrome-devtools/console/api
// All console level methods have parameters (fmt?, ...args)
// where the argument sequence `fmt?, ...args` formats args according to
// fmt if fmt is a format string. Otherwise, it just renders them all as values
// separated by spaces.
// https://console.spec.whatwg.org/#formatter
// https://nodejs.org/docs/latest/api/util.html#util_util_format_format_args
// For the causal console, all occurrences of `fmt, ...args` or `...args` by
// itself must check for the presence of an error to ask the
// `loggedErrorHandler` to handle.
// In theory we should do a deep inspection to detect for example an array
// containing an error. We currently do not detect these and may never.
/** @type {readonly [keyof VirtualConsole, LogSeverity | undefined][]} */
const consoleLevelMethods = freeze([
['debug', 'debug'], // (fmt?, ...args) verbose level on Chrome
['log', 'log'], // (fmt?, ...args) info level on Chrome
['info', 'info'], // (fmt?, ...args)
['warn', 'warn'], // (fmt?, ...args)
['error', 'error'], // (fmt?, ...args)
['trace', 'log'], // (fmt?, ...args)
['dirxml', 'log'], // (fmt?, ...args)
['group', 'log'], // (fmt?, ...args)
['groupCollapsed', 'log'], // (fmt?, ...args)
]);
/** @type {readonly [keyof VirtualConsole, LogSeverity | undefined][]} */
const consoleOtherMethods = freeze([
['assert', 'error'], // (value, fmt?, ...args)
['timeLog', 'log'], // (label?, ...args) no fmt string
// Insensitive to whether any argument is an error. All arguments can pass
// thru to baseConsole as is.
['clear', undefined], // ()
['count', 'info'], // (label?)
['countReset', undefined], // (label?)
['dir', 'log'], // (item, options?)
['groupEnd', 'log'], // ()
// In theory tabular data may be or contain an error. However, we currently
// do not detect these and may never.
['table', 'log'], // (tabularData, properties?)
['time', 'info'], // (label?)
['timeEnd', 'info'], // (label?)
// Node Inspector only, MDN, and TypeScript, but not whatwg
['profile', undefined], // (label?)
['profileEnd', undefined], // (label?)
['timeStamp', undefined], // (label?)
]);
/** @type {readonly [keyof VirtualConsole, LogSeverity | undefined][]} */
export const consoleWhitelist = freeze([
...consoleLevelMethods,
...consoleOtherMethods,
]);
/**
* consoleOmittedProperties is currently unused. I record and maintain it here
* with the intention that it be treated like the `false` entries in the main
* SES whitelist: that seeing these on the original console is expected, but
* seeing anything else that's outside the whitelist is surprising and should
* provide a diagnostic.
*
* const consoleOmittedProperties = freeze([
* 'memory', // Chrome
* 'exception', // FF, MDN
* '_ignoreErrors', // Node
* '_stderr', // Node
* '_stderrErrorHandler', // Node
* '_stdout', // Node
* '_stdoutErrorHandler', // Node
* '_times', // Node
* 'context', // Chrome, Node
* 'record', // Safari
* 'recordEnd', // Safari
*
* 'screenshot', // Safari
* // Symbols
* '@@toStringTag', // Chrome: "Object", Safari: "Console"
* // A variety of other symbols also seen on Node
* ]);
*/
// /////////////////////////////////////////////////////////////////////////////
/** @type {MakeLoggingConsoleKit} */
const makeLoggingConsoleKit = () => {
// Not frozen!
let logArray = [];
const loggingConsole = fromEntries(
consoleWhitelist.map(([name, _]) => {
// Use an arrow function so that it doesn't come with its own name in
// its printed form. Instead, we're hoping that tooling uses only
// the `.name` property set below.
const method = (...args) => {
logArray.push([name, ...args]);
};
defineProperty(method, 'name', { value: name });
return [name, freeze(method)];
}),
);
freeze(loggingConsole);
const takeLog = () => {
const result = freeze(logArray);
logArray = [];
return result;
};
freeze(takeLog);
const typedLoggingConsole = /** @type {VirtualConsole} */ (loggingConsole);
return freeze({ loggingConsole: typedLoggingConsole, takeLog });
};
freeze(makeLoggingConsoleKit);
export { makeLoggingConsoleKit };
// /////////////////////////////////////////////////////////////////////////////
/** @type {ErrorInfo} */
const ErrorInfo = {
NOTE: 'ERROR_NOTE:',
MESSAGE: 'ERROR_MESSAGE:',
};
freeze(ErrorInfo);
/**
* The error annotations are sent to the baseConsole by calling some level
* method. The 'debug' level seems best, because the Chrome console classifies
* `debug` as verbose and does not show it by default. But we keep it symbolic
* so we can change our mind. (On Node, `debug`, `log`, and `info` are aliases
* for the same function and so will behave the same there.)
*/
export const BASE_CONSOLE_LEVEL = 'debug';
/** @type {MakeCausalConsole} */
const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
const {
getStackString,
takeMessageLogArgs,
takeNoteLogArgsArray,
} = loggedErrorHandler;
// by "tagged", we mean first sent to the baseConsole as an argument in a
// console level method call, in which it is shown with an identifying tag
// number. We number the errors according to the order in
// which they were first logged to the baseConsole, starting at 1.
let numErrorsTagged = 0;
/** @type WeakMap<Error, number> */
const errorTagOrder = new WeakMap();
/**
* @param {Error} err
* @returns {string}
*/
const tagError = err => {
let errNum;
if (errorTagOrder.has(err)) {
errNum = errorTagOrder.get(err);
} else {
numErrorsTagged += 1;
errorTagOrder.set(err, numErrorsTagged);
errNum = numErrorsTagged;
}
return `${err.name}#${errNum}`;
};
const extractErrorArgs = (logArgs, subErrorsSink) => {
const argTags = logArgs.map(arg => {
if (arg instanceof Error) {
subErrorsSink.push(arg);
return `(${tagError(arg)})`;
}
return arg;
});
return argTags;
};
/**
* @param {Error} error
* @param {ErrorInfoKind} kind
* @param {readonly any[]} logArgs
* @param {Array<Error>} subErrorsSink
*/
const logErrorInfo = (error, kind, logArgs, subErrorsSink) => {
const errorTag = tagError(error);
const errorName =
kind === ErrorInfo.MESSAGE ? `${errorTag}:` : `${errorTag} ${kind}`;
const argTags = extractErrorArgs(logArgs, subErrorsSink);
baseConsole[BASE_CONSOLE_LEVEL](errorName, ...argTags);
};
/**
* Logs the `subErrors` within a group named `label`.
*
* @param {string | undefined} optTag
* @param {Error[]} subErrors
* @returns {void}
*/
const logSubErrors = (optTag = undefined, subErrors) => {
if (subErrors.length >= 1) {
let label;
if (subErrors.length === 1) {
label = `Nested error`;
} else {
label = `Nested ${subErrors.length} errors`;
}
if (optTag !== undefined) {
label = `${label} under ${optTag}`;
}
baseConsole.group(label);
try {
for (const subError of subErrors) {
// eslint-disable-next-line no-use-before-define
logError(subError);
}
} finally {
baseConsole.groupEnd();
}
}
};
const errorsLogged = new WeakSet();
/** @type {NoteCallback} */
const noteCallback = (error, noteLogArgs) => {
const subErrors = [];
// Annotation arrived after the error has already been logged,
// so just log the annotation immediately, rather than remembering it.
logErrorInfo(error, ErrorInfo.NOTE, noteLogArgs, subErrors);
logSubErrors(tagError(error), subErrors);
};
const logError = error => {
if (errorsLogged.has(error)) {
return;
}
const errorTag = tagError(error);
errorsLogged.add(error);
const subErrors = [];
const messageLogArgs = takeMessageLogArgs(error);
const noteLogArgsArray = takeNoteLogArgsArray(error, noteCallback);
// Show the error's most informative error message
if (messageLogArgs === undefined) {
// If there is no message log args, then just show the message that
// the error itself carries.
baseConsole[BASE_CONSOLE_LEVEL](`${errorTag}:`, error.message);
} else {
// If there is one, we take it to be strictly more informative than the
// message string carried by the error, so show it *instead*.
logErrorInfo(error, ErrorInfo.MESSAGE, messageLogArgs, subErrors);
}
// After the message but before any other annotations, show the stack.
let stackString = getStackString(error);
if (
typeof stackString === 'string' &&
stackString.length >= 1 &&
!stackString.endsWith('\n')
) {
stackString += '\n';
}
baseConsole[BASE_CONSOLE_LEVEL]('', stackString);
// Show the other annotations on error
for (const noteLogArgs of noteLogArgsArray) {
logErrorInfo(error, ErrorInfo.NOTE, noteLogArgs, subErrors);
}
// explain all the errors seen in the messages already emitted.
logSubErrors(errorTag, subErrors);
};
const levelMethods = consoleLevelMethods.map(([level, _]) => {
const levelMethod = (...logArgs) => {
const subErrors = [];
const argTags = extractErrorArgs(logArgs, subErrors);
// @ts-ignore
baseConsole[level](...argTags);
logSubErrors(undefined, subErrors);
};
defineProperty(levelMethod, 'name', { value: level });
return [level, freeze(levelMethod)];
});
const otherMethodNames = consoleOtherMethods.filter(
([name, _]) => name in baseConsole,
);
const otherMethods = otherMethodNames.map(([name, _]) => {
const otherMethod = (...args) => {
// @ts-ignore
baseConsole[name](...args);
return undefined;
};
defineProperty(otherMethod, 'name', { value: name });
return [name, freeze(otherMethod)];
});
const causalConsole = fromEntries([...levelMethods, ...otherMethods]);
return freeze(causalConsole);
};
freeze(makeCausalConsole);
export { makeCausalConsole };
// /////////////////////////////////////////////////////////////////////////////
/** @type {FilterConsole} */
const filterConsole = (baseConsole, filter, _topic = undefined) => {
// TODO do something with optional topic string
const whilelist = consoleWhitelist.filter(([name, _]) => name in baseConsole);
const methods = whilelist.map(([name, severity]) => {
const method = (...args) => {
if (severity === undefined || filter.canLog(severity)) {
// @ts-ignore
baseConsole[name](...args);
}
};
return [name, freeze(method)];
});
const filteringConsole = fromEntries(methods);
return freeze(filteringConsole);
};
freeze(filterConsole);
export { filterConsole };