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

[devtools] allow non-coercible objects in formatConsoleArgumentsToSingleString #31444

Merged
merged 1 commit into from
Nov 10, 2024
Merged
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
6 changes: 6 additions & 0 deletions packages/react-devtools-shared/src/__tests__/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ describe('utils', () => {
'Symbol(abc) 123',
);
});

it('should gracefully handle objects with no prototype', () => {
expect(
formatConsoleArgumentsToSingleString('%o', Object.create(null)),
).toEqual('%o [object Object]');
});
});

describe('formatWithStyles', () => {
Expand Down
17 changes: 15 additions & 2 deletions packages/react-devtools-shared/src/backend/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,19 @@ export function serializeToString(data: any): string {
);
}

function safeToString(val: any): string {
try {
return String(val);
} catch (err) {
if (typeof val === 'object') {
// An object with no prototype and no `[Symbol.toPrimitive]()`, `toString()`, and `valueOf()` methods would throw.
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion
return '[object Object]';
}
throw err;
}
}

// based on https://github.com/tmpfs/format-util/blob/0e62d430efb0a1c51448709abd3e2406c14d8401/format.js#L1
// based on https://developer.mozilla.org/en-US/docs/Web/API/console#Using_string_substitutions
// Implements s, d, i and f placeholders
Expand All @@ -176,7 +189,7 @@ export function formatConsoleArgumentsToSingleString(
): string {
const args = inputArgs.slice();

let formatted: string = String(maybeMessage);
let formatted: string = safeToString(maybeMessage);

// If the first argument is a string, check for substitutions.
if (typeof maybeMessage === 'string') {
Expand Down Expand Up @@ -211,7 +224,7 @@ export function formatConsoleArgumentsToSingleString(
// Arguments that remain after formatting.
if (args.length) {
for (let i = 0; i < args.length; i++) {
formatted += ' ' + String(args[i]);
formatted += ' ' + safeToString(args[i]);
}
}

Expand Down
Loading