Skip to content

Commit

Permalink
fix: Avoid polynomial regexp in stringifyString
Browse files Browse the repository at this point in the history
As reported by CodeQL, though unrelated to the rest of the PR
  • Loading branch information
eemeli committed Feb 14, 2023
1 parent 2489810 commit 8407300
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/stringify/stringifyString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,15 @@ function quotedString(value: string, ctx: StringifyContext) {
return qs(value, ctx)
}

// The negative lookbehind avoids a polynomial search,
// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind
let blockEndNewlines: RegExp
try {
blockEndNewlines = new RegExp('(^|(?<!\n))\n+(?!\n|$)', 'g')
} catch {
blockEndNewlines = /\n+(?!\n|$)/g
}

function blockString(
{ comment, type, value }: StringifyScalar,
ctx: StringifyContext,
Expand Down Expand Up @@ -211,7 +220,7 @@ function blockString(
if (end) {
value = value.slice(0, -end.length)
if (end[end.length - 1] === '\n') end = end.slice(0, -1)
end = end.replace(/\n+(?!\n|$)/g, `$&${indent}`)
end = end.replace(blockEndNewlines, `$&${indent}`)
}

// determine indent indicator from whitespace at value start
Expand Down

0 comments on commit 8407300

Please sign in to comment.