Skip to content

Commit b287ce4

Browse files
committed
fix: enhance string serialization with well-formed check
1 parent 43b2dd7 commit b287ce4

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

lib/serializer.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,13 @@ module.exports = class Serializer {
9595

9696
if (len === 0) {
9797
return '""'
98-
} else if (len < 42) {
98+
}
99+
100+
if (!str.isWellFormed()) {
101+
return JSON.stringify(str)
102+
}
103+
104+
if (len < 42) {
99105
// magically escape strings for json
100106
// relying on their charCodeAt
101107
// everything below 32 needs JSON.stringify()
@@ -114,13 +120,13 @@ module.exports = class Serializer {
114120
last === -1 && (last = 0)
115121
result += str.slice(last, i) + '\\'
116122
last = i
117-
} else if (point < 32 || (point >= 0xD800 && point <= 0xDFFF)) {
123+
} else if (point < 32) {
118124
// The current character is non-printable characters or a surrogate.
119125
return JSON.stringify(str)
120126
}
121127
}
122128
return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"')
123-
} else if (len < 5000 && str.isWellFormed() && ASCII_ESCAPE.test(str) === false) {
129+
} else if (len < 5000 && ASCII_ESCAPE.test(str) === false) {
124130
// Only use the regular expression for shorter input. The overhead is otherwise too much.
125131
return '"' + str + '"'
126132
} else {

0 commit comments

Comments
 (0)