Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

console: fix console names #33524

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
281 changes: 151 additions & 130 deletions lib/internal/console/constructor.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
// the prototype so that users extending the Console can override them
// from the prototype chain of the subclass.
this[key] = this[key].bind(this);
ObjectDefineProperty(this[key], 'name', {
value: key
});
}

this[kBindStreamsEager](stdout, stderr);
Expand All @@ -155,68 +158,156 @@ ObjectDefineProperty(Console, SymbolHasInstance, {
}
});

// Eager version for the Console constructor
Console.prototype[kBindStreamsEager] = function(stdout, stderr) {
ObjectDefineProperties(this, {
'_stdout': { ...consolePropAttributes, value: stdout },
'_stderr': { ...consolePropAttributes, value: stderr }
});
};
const kColorInspectOptions = { colors: true };
const kNoColorInspectOptions = {};

// Lazily load the stdout and stderr from an object so we don't
// create the stdio streams when they are not even accessed
Console.prototype[kBindStreamsLazy] = function(object) {
let stdout;
let stderr;
ObjectDefineProperties(this, {
'_stdout': {
enumerable: false,
configurable: true,
get() {
if (!stdout) stdout = object.stdout;
return stdout;
},
set(value) { stdout = value; }
},
'_stderr': {
enumerable: false,
configurable: true,
get() {
if (!stderr) { stderr = object.stderr; }
return stderr;
},
set(value) { stderr = value; }
ObjectDefineProperties(Console.prototype, {
[kBindStreamsEager]: {
...consolePropAttributes,
// Eager version for the Console constructor
value: function(stdout, stderr) {
ObjectDefineProperties(this, {
'_stdout': { ...consolePropAttributes, value: stdout },
'_stderr': { ...consolePropAttributes, value: stderr }
});
}
});
};
},
[kBindStreamsLazy]: {
...consolePropAttributes,
// Lazily load the stdout and stderr from an object so we don't
// create the stdio streams when they are not even accessed
value: function(object) {
let stdout;
let stderr;
ObjectDefineProperties(this, {
'_stdout': {
enumerable: false,
configurable: true,
get() {
if (!stdout) stdout = object.stdout;
return stdout;
},
set(value) { stdout = value; }
},
'_stderr': {
enumerable: false,
configurable: true,
get() {
if (!stderr) { stderr = object.stderr; }
return stderr;
},
set(value) { stderr = value; }
}
});
}
},
[kBindProperties]: {
...consolePropAttributes,
value: function(ignoreErrors, colorMode, groupIndentation = 2) {
ObjectDefineProperties(this, {
'_stdoutErrorHandler': {
...consolePropAttributes,
value: createWriteErrorHandler(this, kUseStdout)
},
'_stderrErrorHandler': {
...consolePropAttributes,
value: createWriteErrorHandler(this, kUseStderr)
},
'_ignoreErrors': {
...consolePropAttributes,
value: Boolean(ignoreErrors)
},
'_times': { ...consolePropAttributes, value: new Map() },
// Corresponds to https://console.spec.whatwg.org/#count-map
[kCounts]: { ...consolePropAttributes, value: new Map() },
[kColorMode]: { ...consolePropAttributes, value: colorMode },
[kIsConsole]: { ...consolePropAttributes, value: true },
[kGroupIndent]: { ...consolePropAttributes, value: '' },
[kGroupIndentationWidth]: {
...consolePropAttributes,
value: groupIndentation
},
});
}
},
[kWriteToConsole]: {
...consolePropAttributes,
value: function(streamSymbol, string) {
const ignoreErrors = this._ignoreErrors;
const groupIndent = this[kGroupIndent];

const useStdout = streamSymbol === kUseStdout;
const stream = useStdout ? this._stdout : this._stderr;
const errorHandler = useStdout ?
this._stdoutErrorHandler : this._stderrErrorHandler;

if (groupIndent.length !== 0) {
if (string.includes('\n')) {
string = string.replace(/\n/g, `\n${groupIndent}`);
}
string = groupIndent + string;
}
string += '\n';

if (ignoreErrors === false) return stream.write(string);

// There may be an error occurring synchronously (e.g. for files or TTYs
// on POSIX systems) or asynchronously (e.g. pipes on POSIX systems), so
// handle both situations.
try {
// Add and later remove a noop error handler to catch synchronous
// errors.
if (stream.listenerCount('error') === 0)
stream.once('error', noop);

stream.write(string, errorHandler);
} catch (e) {
// Console is a debugging utility, so it swallowing errors is not
// desirable even in edge cases such as low stack space.
if (isStackOverflowError(e))
throw e;
// Sorry, there's no proper way to pass along the error here.
} finally {
stream.removeListener('error', noop);
}
}
},
[kGetInspectOptions]: {
...consolePropAttributes,
value: function(stream) {
let color = this[kColorMode];
if (color === 'auto') {
color = stream.isTTY && (
typeof stream.getColorDepth === 'function' ?
stream.getColorDepth() > 2 : true);
}

Console.prototype[kBindProperties] = function(ignoreErrors, colorMode,
groupIndentation = 2) {
ObjectDefineProperties(this, {
'_stdoutErrorHandler': {
...consolePropAttributes,
value: createWriteErrorHandler(this, kUseStdout)
},
'_stderrErrorHandler': {
...consolePropAttributes,
value: createWriteErrorHandler(this, kUseStderr)
},
'_ignoreErrors': {
...consolePropAttributes,
value: Boolean(ignoreErrors)
},
'_times': { ...consolePropAttributes, value: new Map() },
// Corresponds to https://console.spec.whatwg.org/#count-map
[kCounts]: { ...consolePropAttributes, value: new Map() },
[kColorMode]: { ...consolePropAttributes, value: colorMode },
[kIsConsole]: { ...consolePropAttributes, value: true },
[kGroupIndent]: { ...consolePropAttributes, value: '' },
[kGroupIndentationWidth]: {
...consolePropAttributes,
value: groupIndentation
},
});
};
const options = optionsMap.get(this);
if (options) {
if (options.colors === undefined) {
options.colors = color;
}
return options;
}

return color ? kColorInspectOptions : kNoColorInspectOptions;
}
},
[kFormatForStdout]: {
...consolePropAttributes,
value: function(args) {
const opts = this[kGetInspectOptions](this._stdout);
return formatWithOptions(opts, ...args);
}
},
[kFormatForStderr]: {
...consolePropAttributes,
value: function(args) {
const opts = this[kGetInspectOptions](this._stderr);
return formatWithOptions(opts, ...args);
}
},
});

// Make a function that can serve as the callback passed to `stream.write()`.
function createWriteErrorHandler(instance, streamSymbol) {
Expand All @@ -239,76 +330,6 @@ function createWriteErrorHandler(instance, streamSymbol) {
};
}

Console.prototype[kWriteToConsole] = function(streamSymbol, string) {
const ignoreErrors = this._ignoreErrors;
const groupIndent = this[kGroupIndent];

const useStdout = streamSymbol === kUseStdout;
const stream = useStdout ? this._stdout : this._stderr;
const errorHandler = useStdout ?
this._stdoutErrorHandler : this._stderrErrorHandler;

if (groupIndent.length !== 0) {
if (string.includes('\n')) {
string = string.replace(/\n/g, `\n${groupIndent}`);
}
string = groupIndent + string;
}
string += '\n';

if (ignoreErrors === false) return stream.write(string);

// There may be an error occurring synchronously (e.g. for files or TTYs
// on POSIX systems) or asynchronously (e.g. pipes on POSIX systems), so
// handle both situations.
try {
// Add and later remove a noop error handler to catch synchronous errors.
if (stream.listenerCount('error') === 0)
stream.once('error', noop);

stream.write(string, errorHandler);
} catch (e) {
// Console is a debugging utility, so it swallowing errors is not desirable
// even in edge cases such as low stack space.
if (isStackOverflowError(e))
throw e;
// Sorry, there's no proper way to pass along the error here.
} finally {
stream.removeListener('error', noop);
}
};

const kColorInspectOptions = { colors: true };
const kNoColorInspectOptions = {};
Console.prototype[kGetInspectOptions] = function(stream) {
let color = this[kColorMode];
if (color === 'auto') {
color = stream.isTTY && (
typeof stream.getColorDepth === 'function' ?
stream.getColorDepth() > 2 : true);
}

const options = optionsMap.get(this);
if (options) {
if (options.colors === undefined) {
options.colors = color;
}
return options;
}

return color ? kColorInspectOptions : kNoColorInspectOptions;
};

Console.prototype[kFormatForStdout] = function(args) {
const opts = this[kGetInspectOptions](this._stdout);
return formatWithOptions(opts, ...args);
};

Console.prototype[kFormatForStderr] = function(args) {
const opts = this[kGetInspectOptions](this._stderr);
return formatWithOptions(opts, ...args);
};

const consoleMethods = {
log(...args) {
this[kWriteToConsole](kUseStdout, this[kFormatForStdout](args));
Expand Down Expand Up @@ -492,7 +513,7 @@ const consoleMethods = {
if (setIter)
tabularData = previewEntries(tabularData);

const setlike = setIter || (mapIter && !isKeyValue) || isSet(tabularData);
const setlike = setIter || mapIter || isSet(tabularData);
if (setlike) {
const values = [];
let length = 0;
Expand Down
2 changes: 2 additions & 0 deletions lib/internal/console/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ for (const prop of ReflectOwnKeys(Console.prototype)) {
if (prop === 'constructor') { continue; }
const desc = ReflectGetOwnPropertyDescriptor(Console.prototype, prop);
if (typeof desc.value === 'function') { // fix the receiver
const name = desc.value.name;
desc.value = desc.value.bind(globalConsole);
ReflectDefineProperty(desc.value, 'name', { value: name });
}
ReflectDefineProperty(globalConsole, prop, desc);
}
Expand Down
4 changes: 4 additions & 0 deletions lib/internal/util/inspector.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const {
ObjectDefineProperty,
ObjectKeys,
} = primordials;

Expand Down Expand Up @@ -42,6 +43,9 @@ function wrapConsole(consoleFromNode, consoleFromVM) {
consoleFromNode[key] = consoleCall.bind(consoleFromNode,
consoleFromVM[key],
consoleFromNode[key]);
ObjectDefineProperty(consoleFromNode[key], 'name', {
value: key
});
} else {
// Add additional console APIs from the inspector
consoleFromNode[key] = consoleFromVM[key];
Expand Down
27 changes: 25 additions & 2 deletions test/parallel/test-console-methods.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict';
require('../common');

// This test ensures that console methods
// cannot be invoked as constructors
// This test ensures that console methods cannot be invoked as constructors and
// that their name is always correct.

const assert = require('assert');

Expand Down Expand Up @@ -32,7 +32,30 @@ const methods = [
'groupCollapsed',
];

const alternateNames = {
debug: 'log',
info: 'log',
dirxml: 'log',
error: 'warn',
groupCollapsed: 'group'
};

function assertEqualName(method) {
try {
assert.strictEqual(console[method].name, method);
} catch {
assert.strictEqual(console[method].name, alternateNames[method]);
}
try {
assert.strictEqual(newInstance[method].name, method);
} catch {
assert.strictEqual(newInstance[method].name, alternateNames[method]);
}
}

for (const method of methods) {
assertEqualName(method);

assert.throws(() => new console[method](), err);
assert.throws(() => new newInstance[method](), err);
assert.throws(() => Reflect.construct({}, [], console[method]), err);
Expand Down
Loading