From f4f424deca9b7ee242165ca0d13fa34651f163af Mon Sep 17 00:00:00 2001 From: Phillip Barta Date: Mon, 6 Jul 2026 19:50:45 +0200 Subject: [PATCH] perf(json): avoid first-char regex for direct JSON bodies Skip the RFC 7159 whitespace scan when strict JSON bodies start directly with `{` or `[`. This avoids regex execution on the common valid path while preserving strict-mode handling for leading whitespace and primitive values. Update the first non-whitespace regex to match end-of-string so whitespace-only bodies return `undefined` without relying on a failed match/backtracking path. --- lib/types/json.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/types/json.js b/lib/types/json.js index 14ca3e49..cb636fbc 100644 --- a/lib/types/json.js +++ b/lib/types/json.js @@ -23,7 +23,7 @@ const { normalizeOptions } = require('../utils') module.exports = json /** - * RegExp to match the first non-space in a string. + * RegExp to match the first non-whitespace character in a string. * * Allowed whitespace is defined in RFC 7159: * @@ -33,7 +33,7 @@ module.exports = json * %x0A / ; Line feed or New line * %x0D ) ; Carriage return */ -const FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex +const FIRST_NON_WHITESPACE_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d]|$)/ // eslint-disable-line no-control-regex const JSON_SYNTAX_CHAR = '#' const JSON_SYNTAX_REGEXP = /#+/g @@ -80,10 +80,12 @@ function createJsonParser (options) { return {} } - const first = firstchar(body) - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) + if (body[0] !== '{' && body[0] !== '[') { + const first = firstNonWhitespaceChar(body) + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } } try { @@ -152,12 +154,10 @@ function createStrictSyntaxError (str, char) { * @returns {string|undefined} * @private */ -function firstchar (str) { - const match = FIRST_CHAR_REGEXP.exec(str) +function firstNonWhitespaceChar (str) { + const match = FIRST_NON_WHITESPACE_REGEXP.exec(str) - return match - ? match[1] - : undefined + return match && match[1] ? match[1] : undefined } /**