summaryrefslogtreecommitdiff
path: root/modules/esm/console.js
blob: 9b57f97bb127d0162a1a197fdc2c7f95320af7e8 (plain)
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2021 Evan Welsh <contact@evanwelsh.com>

import GLib from 'gi://GLib';

const NativeConsole = import.meta.importSync('_consoleNative');

const DEFAULT_LOG_DOMAIN = 'Gjs-Console';

// A line-by-line implementation of https://console.spec.whatwg.org/.

// 2.2.1. Formatting specifiers
// https://console.spec.whatwg.org/#formatting-specifiers
//
// %s - string
// %d or %i - integer
// %f - float
// %o - "optimal" object formatting
// %O - "generic" object formatting
// %c - "CSS" formatting (unimplemented by GJS)

/**
 * A simple regex to capture formatting specifiers
 */
const specifierTest = /%(d|i|s|f|o|O|c)/;

/**
 * @param {string} str a string to check for format specifiers like %s or %i
 * @returns {boolean}
 */
function hasFormatSpecifiers(str) {
    return specifierTest.test(str);
}

/**
 * @param {any} item an item to format
 */
function formatGenerically(item) {
    return JSON.stringify(item, null, 4);
}

/**
 * @param {any} item an item to format
 * @returns {string}
 */
function formatOptimally(item) {
    // Handle optimal error formatting.
    if (item instanceof Error) {
        return `${item.toString()}${item.stack ? '\n' : ''}${item.stack
            ?.split('\n')
            // Pad each stacktrace line.
            .map(line => line.padStart(2, ' '))
            .join('\n')}`;
    }

    // TODO: Enhance 'optimal' formatting.
    // There is a current work on a better object formatter for GJS in
    // https://gitlab.gnome.org/GNOME/gjs/-/merge_requests/587
    return JSON.stringify(item, null, 4);
}

/**
 * Implementation of the WHATWG Console object.
 */
class Console {
    #groupIndentation = '';
    #countLabels = {};
    #timeLabels = {};
    #logDomain = DEFAULT_LOG_DOMAIN;

    get [Symbol.toStringTag]() {
        return 'Console';
    }

    // 1.1 Logging functions
    // https://console.spec.whatwg.org/#logging

    /**
     * Logs a critical message if the condition is not truthy.
     * {@see console.error()} for additional information.
     *
     * @param {boolean} condition a boolean condition which, if false, causes
     *   the log to print
     * @param  {...any} data formatting substitutions, if applicable
     * @returns {void}
     */
    assert(condition, ...data) {
        if (condition)
            return;

        const message = 'Assertion failed';

        if (data.length === 0)
            data.push(message);

        if (typeof data[0] !== 'string') {
            data.unshift(message);
        } else {
            const first = data.shift();
            data.unshift(`${message}: ${first}`);
        }
        this.#logger('assert', data);
    }

    /**
     * Resets grouping and clears the terminal on systems supporting ANSI
     * terminal control sequences.
     *
     * In file-based stdout or systems which do not support clearing,
     * console.clear() has no visual effect.
     *
     * @returns {void}
     */
    clear() {
        this.#groupIndentation = '';
        NativeConsole.clearTerminal();
    }

    /**
     * Logs a message with severity equal to {@see GLib.LogLevelFlags.DEBUG}.
     *
     * @param  {...any} data formatting substitutions, if applicable
     */
    debug(...data) {
        this.#logger('debug', data);
    }

    /**
     * Logs a message with severity equal to {@see GLib.LogLevelFlags.CRITICAL}.
     * Does not use {@see GLib.LogLevelFlags.ERROR} to avoid asserting and
     * forcibly shutting down the application.
     *
     * @param  {...any} data formatting substitutions, if applicable
     */
    error(...data) {
        this.#logger('error', data);
    }

    /**
     * Logs a message with severity equal to {@see GLib.LogLevelFlags.INFO}.
     *
     * @param  {...any} data formatting substitutions, if applicable
     */
    info(...data) {
        this.#logger('info', data);
    }

    /**
     * Logs a message with severity equal to {@see GLib.LogLevelFlags.MESSAGE}.
     *
     * @param  {...any} data formatting substitutions, if applicable
     */
    log(...data) {
        this.#logger('log', data);
    }

    // 1.1.7 table(tabularData, properties)
    table(tabularData, _properties) {
        this.log(tabularData);
    }

    /**
     * @param  {...any} data formatting substitutions, if applicable
     * @returns {void}
     */
    trace(...data) {
        if (data.length === 0)
            data = ['Trace'];

        this.#logger('trace', data);
    }

    /**
     * Logs a message with severity equal to {@see GLib.LogLevelFlags.WARNING}.
     *
     * @param  {...any} data formatting substitutions, if applicable
     * @returns {void}
     */
    warn(...data) {
        this.#logger('warn', data);
    }

    /**
     * @param {object} item an item to format generically
     * @param {never} [options] any additional options for the formatter. Unused
     *   in our implementation.
     */
    dir(item, options) {
        const object = formatGenerically(item);
        this.#printer('dir', [object], options);
    }

    /**
     * @param  {...any} data formatting substitutions, if applicable
     * @returns {void}
     */
    dirxml(...data) {
        this.log(...data);
    }

    // 1.2 Counting functions
    // https://console.spec.whatwg.org/#counting

    /**
     * Logs how many times console.count(label) has been called with a given
     * label.
     * {@see console.countReset()} for resetting a count.
     *
     * @param  {string} label unique identifier for this action
     * @returns {void}
     */
    count(label) {
        this.#countLabels[label] ??= 0;
        const count = ++this.#countLabels[label];
        const concat = `${label}: ${count}`;

        this.#logger('count', [concat]);
    }

    /**
     * @param  {string} label the unique label to reset the count for
     * @returns {void}
     */
    countReset(label) {
        const count = this.#countLabels[label];
        if (typeof count !== 'number')
            this.#printer('reportWarning', [`No count found for label: '${label}'.`]);
        else
            this.#countLabels[label] = 0;
    }

    // 1.3 Grouping functions
    // https://console.spec.whatwg.org/#grouping

    /**
     * @param  {...any} data formatting substitutions, if applicable
     * @returns {void}
     */
    group(...data) {
        this.#logger('group', data);
        this.#groupIndentation += '  ';
    }

    /**
     * Alias for console.group()
     *
     * @param  {...any} data formatting substitutions, if applicable
     * @returns {void}
     */
    groupCollapsed(...data) {
        // We can't 'collapse' output in a terminal, so we alias to
        // group()
        this.group(...data);
    }

    /**
     * @returns {void}
     */
    groupEnd() {
        this.#groupIndentation = this.#groupIndentation.slice(0, -2);
    }

    // 1.4 Timing functions
    // https://console.spec.whatwg.org/#timing

    /**
     * @param {string} label unique identifier for this action, pass to
     *   console.timeEnd() to complete
     * @returns {void}
     */
    time(label) {
        this.#timeLabels[label] = imports.gi.GLib.get_monotonic_time();
    }

    /**
     * Logs the time since the last call to console.time(label) where label is
     * the same.
     *
     * @param {string} label unique identifier for this action, pass to
     *   console.timeEnd() to complete
     * @param {...any} data string substitutions, if applicable
     * @returns {void}
     */
    timeLog(label, ...data) {
        const startTime = this.#timeLabels[label];

        if (typeof startTime !== 'number') {
            this.#printer('reportWarning', [
                `No time log found for label: '${label}'.`,
            ]);
        } else {
            const durationMs = (imports.gi.GLib.get_monotonic_time() - startTime) / 1000;
            const concat = `${label}: ${durationMs.toFixed(3)} ms`;
            data.unshift(concat);

            this.#printer('timeLog', data);
        }
    }

    /**
     * Logs the time since the last call to console.time(label) and completes
     * the action.
     * Call console.time(label) again to re-measure.
     *
     * @param {string} label unique identifier for this action
     * @returns {void}
     */
    timeEnd(label) {
        const startTime = this.#timeLabels[label];

        if (typeof startTime !== 'number') {
            this.#printer('reportWarning', [
                `No time log found for label: '${label}'.`,
            ]);
        } else {
            delete this.#timeLabels[label];

            const durationMs = (imports.gi.GLib.get_monotonic_time() - startTime) / 1000;
            const concat = `${label}: ${durationMs.toFixed(3)} ms`;

            this.#printer('timeEnd', [concat]);
        }
    }

    // Non-standard functions which are de-facto standards.
    // Similar to Node, we define these as no-ops for now.

    /**
     * @deprecated Not implemented in GJS
     *
     * @param {string} _label unique identifier for this action, pass to
     *   console.profileEnd to complete
     * @returns {void}
     */
    profile(_label) {}

    /**
     * @deprecated Not implemented in GJS
     *
     * @param {string} _label unique identifier for this action
     * @returns {void}
     */
    profileEnd(_label) {}

    /**
     * @deprecated Not implemented in GJS
     *
     * @param {string} _label unique identifier for this action
     * @returns {void}
     */
    timeStamp(_label) {}

    // GJS-specific extensions for integrating with GLib structured logging

    /**
     * @param {string} logDomain the GLib log domain this Console should print
     *   with. Defaults to 'Gjs-Console'.
     * @returns {void}
     */
    setLogDomain(logDomain) {
        this.#logDomain = String(logDomain);
    }

    /**
     * @returns {string}
     */
    get logDomain() {
        return this.#logDomain;
    }

    // 2. Supporting abstract operations
    // https://console.spec.whatwg.org/#supporting-ops

    /**
     * 2.1. Logger
     * https://console.spec.whatwg.org/#logger
     *
     * Conditionally applies formatting based on the inputted arguments,
     * and prints at the provided severity (logLevel)
     *
     * @param {string} logLevel the severity (log level) the args should be
     *   emitted with
     * @param {unknown[]} args the arguments to pass to the printer
     * @returns {void}
     */
    #logger(logLevel, args) {
        if (args.length === 0)
            return;

        const [first, ...rest] = args;

        if (rest.length === 0) {
            this.#printer(logLevel, [first]);
            return undefined;
        }

        // If first does not contain any format specifiers, don't call Formatter
        if (typeof first !== 'string' || !hasFormatSpecifiers(first)) {
            this.#printer(logLevel, args);
            return undefined;
        }

        // Otherwise, perform print the result of Formatter.
        this.#printer(logLevel, this.#formatter([first, ...rest]));

        return undefined;
    }

    /**
     * 2.2. Formatter
     * https://console.spec.whatwg.org/#formatter
     *
     * @param {[string, ...any[]]} args an array of format strings followed by
     *   their arguments
     */
    #formatter(args) {
        // The initial formatting string is the first arg
        let target = args[0];

        if (args.length === 1)
            return target;

        const current = args[1];

        // Find the index of the first format specifier.
        const specifierIndex = specifierTest.exec(target).index;
        const specifier = target.slice(specifierIndex, specifierIndex + 2);
        let converted = null;
        switch (specifier) {
        case '%s':
            converted = String(current);
            break;
        case '%d':
        case '%i':
            if (typeof current === 'symbol')
                converted = Number.NaN;
            else
                converted = parseInt(current, 10);
            break;
        case '%f':
            if (typeof current === 'symbol')
                converted = Number.NaN;
            else
                converted = parseFloat(current);
            break;
        case '%o':
            converted = formatOptimally(current);
            break;
        case '%O':
            converted = formatGenerically(current);
            break;
        case '%c':
            converted = '';
            break;
        }
        // If any of the previous steps set converted, replace the specifier in
        // target with the converted value.
        if (converted !== null) {
            target =
                target.slice(0, specifierIndex) +
                converted +
                target.slice(specifierIndex + 2);
        }

        /**
         * Create the next format input...
         *
         * @type {[string, ...any[]]}
         */
        const result = [target, ...args.slice(2)];

        if (!hasFormatSpecifiers(target))
            return result;

        if (result.length === 1)
            return result;

        return this.#formatter(result);
    }

    /**
     * @typedef {object} PrinterOptions
     * @param {Array.<string[]>} [stackTrace] an error stacktrace to append
     * @param {Record<string, any>} [fields] fields to include in the structured
     *   logging call
     */

    /**
     * 2.3. Printer
     * https://console.spec.whatwg.org/#printer
     *
     * This implementation of Printer maps WHATWG log severity to
     * {@see GLib.LogLevelFlags} and outputs using GLib structured logging.
     *
     * @param {string} logLevel the log level (log tag) the args should be
     *   emitted with
     * @param {unknown[]} args the arguments to print, either a format string
     *   with replacement args or multiple strings
     * @param {PrinterOptions} [options] additional options for the
     *   printer
     * @returns {void}
     */
    #printer(logLevel, args, options) {
        const GLib = imports.gi.GLib;
        let severity;

        switch (logLevel) {
        case 'log':
        case 'dir':
        case 'dirxml':
        case 'trace':
        case 'group':
        case 'groupCollapsed':
        case 'timeLog':
        case 'timeEnd':
            severity = GLib.LogLevelFlags.LEVEL_MESSAGE;
            break;
        case 'debug':
            severity = GLib.LogLevelFlags.LEVEL_DEBUG;
            break;
        case 'count':
        case 'info':
            severity = GLib.LogLevelFlags.LEVEL_INFO;
            break;
        case 'warn':
        case 'countReset':
        case 'reportWarning':
            severity = GLib.LogLevelFlags.LEVEL_WARNING;
            break;
        case 'error':
        case 'assert':
            severity = GLib.LogLevelFlags.LEVEL_CRITICAL;
            break;
        default:
            severity = GLib.LogLevelFlags.LEVEL_MESSAGE;
        }

        const output = args
            .map(a => {
                if (a === null)
                    return 'null';
                else if (typeof a === 'object')
                    return formatOptimally(a);
                else if (typeof a === 'function')
                    return a.toString();
                else if (typeof a === 'undefined')
                    return 'undefined';
                else if (typeof a === 'bigint')
                    return `${a}n`;
                else
                    return String(a);
            })
            .join(' ');

        let formattedOutput = this.#groupIndentation + output;
        const extraFields = {};

        let stackTrace = options?.stackTrace;
        if (!stackTrace &&
            (logLevel === 'trace' || severity <= GLib.LogLevelFlags.LEVEL_WARNING)) {
            stackTrace = new Error().stack;
            const currentFile = stackTrace.match(/^[^@]*@(.*):\d+:\d+$/m)?.at(1);
            const index = stackTrace.lastIndexOf(currentFile) + currentFile.length;

            stackTrace = stackTrace.substring(index).split('\n');
            // Remove the remainder of the first line
            stackTrace.shift();
        }

        if (logLevel === 'trace') {
            if (stackTrace?.length) {
                formattedOutput += `\n${stackTrace.map(s =>
                    `${this.#groupIndentation}${s}`).join('\n')}`;
            } else {
                formattedOutput +=
                    `\n${this.#groupIndentation}No trace available`;
            }
        }

        if (stackTrace?.length) {
            const [stackLine] = stackTrace;
            const match = stackLine.match(/^([^@]*)@(.*):(\d+):\d+$/);

            if (match) {
                const [_, func, file, line] = match;

                if (func)
                    extraFields.CODE_FUNC = func;
                if (file)
                    extraFields.CODE_FILE = file;
                if (line)
                    extraFields.CODE_LINE = line;
            }
        }

        GLib.log_structured(this.#logDomain, severity, {
            MESSAGE: formattedOutput,
            ...extraFields,
            ...options?.fields ?? {},
        });
    }
}

const console = new Console();

/**
 * @param {string} domain set the GLib log domain for the global console object.
 */
function setConsoleLogDomain(domain) {
    console.setLogDomain(domain);
}

/**
 * @returns {string}
 */
function getConsoleLogDomain() {
    return console.logDomain;
}

/**
 * For historical web-compatibility reasons, the namespace object for
 * console must have {} as its [[Prototype]].
 *
 * @type {Omit<Console, 'setLogDomain' | 'logDomain'>}
 */
const globalConsole = Object.create({});

const propertyNames =
    /** @type {['constructor', ...Array<string & keyof Console>]} */
    // eslint-disable-next-line no-extra-parens
    (Object.getOwnPropertyNames(Console.prototype));
const propertyDescriptors = Object.getOwnPropertyDescriptors(Console.prototype);
for (const key of propertyNames) {
    if (key === 'constructor')
        continue;

    // This non-standard function shouldn't be included.
    if (key === 'setLogDomain')
        continue;

    const descriptor = propertyDescriptors[key];
    if (typeof descriptor.value !== 'function')
        continue;

    Object.defineProperty(globalConsole, key, {
        ...descriptor,
        value: descriptor.value.bind(console),
    });
}
Object.defineProperties(globalConsole, {
    [Symbol.toStringTag]: {
        configurable: false,
        enumerable: true,
        get() {
            return 'console';
        },
    },
});
Object.freeze(globalConsole);

Object.defineProperty(globalThis, 'console', {
    configurable: false,
    enumerable: true,
    writable: false,
    value: globalConsole,
});

export {
    getConsoleLogDomain,
    setConsoleLogDomain,
    DEFAULT_LOG_DOMAIN
};

export default {
    getConsoleLogDomain,
    setConsoleLogDomain,
    DEFAULT_LOG_DOMAIN,
};