Skip to content

Commit ac2f60d

Browse files
fb55claude
andcommitted
fix(sax-parser): flush completed text at chunk boundaries
A long run of text made the stream keep its whole pending text token and its input. `Tokenizer#flushCurrentCharacterToken` (internal) emits the pending text when the preprocessor is about to drop a parsed chunk, in every state without an unfinished token, and SAX calls it after each write. The text ends where `getCharacterTokenEndOffset()` puts it, before a pending CDATA end delimiter, character reference or `<` in script data, and `Preprocessor#dropParsedChunk(keep)` keeps only those code units, so the retained input is bounded by a chunk plus the longest such construct. An empty character token follows the flush, so the source range of CDATA delimiters or a tag discarded at EOF stays intact; SAX skips empty tokens, and as a character token rather than one of the flushed type it adds no replacement character in foreign content. The feedback simulator clears its skip-first-newline flag on any flushed text. The cases assert the flushed text before the input ends, exact source ranges across 16 KiB chunks, also when every chunk ends in a delimiter or reference, a bounded buffer and offset, raw forwarding across a split unknown reference, a surrogate pair at a chunk end, the `<pre>` newline, an unfinished tag after a flush, and a single replacement character after flushed null characters. Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 98a4bb3 commit ac2f60d

7 files changed

Lines changed: 190 additions & 6 deletions

File tree

‎packages/parse5-html-rewriting-stream/test/rewriting-stream.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,3 +403,39 @@ describe('RewritingStream', () => {
403403
})(),
404404
);
405405
});
406+
407+
it.each([
408+
['plain text', 'a'.repeat(16_384)],
409+
['a split unknown character reference', `${'a'.repeat(16_381)}&no`],
410+
])('flushes long text while retaining exact raw source and locations: %s', async (_label, chunk) => {
411+
const rewriter = new RewritingStream();
412+
let raw = '';
413+
let end = 0;
414+
rewriter.on('text', (token, source) => {
415+
assert.equal(token.sourceCodeLocation!.startOffset, end);
416+
end = token.sourceCodeLocation!.endOffset;
417+
raw += source;
418+
rewriter.emitRaw(source);
419+
});
420+
for (let i = 0; i < 16; i++) rewriter.write(chunk);
421+
assert.isAbove(raw.length, chunk.length * 12);
422+
rewriter.end();
423+
await finished(rewriter);
424+
assert.equal(raw, chunk.repeat(16));
425+
assert.equal(end, raw.length);
426+
});
427+
428+
it('excludes a discarded EOF tag from raw text after a flush', async () => {
429+
const rewriter = new RewritingStream();
430+
let raw = '';
431+
rewriter.on('text', (_token, source) => {
432+
raw += source;
433+
});
434+
const text = 'a'.repeat(70_000);
435+
rewriter.write(text);
436+
// The text is flushed before the end of the input.
437+
assert.equal(raw, text);
438+
rewriter.end('<unfinished');
439+
await finished(rewriter);
440+
assert.equal(raw, text);
441+
});

‎packages/parse5-sax-parser/lib/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,12 +123,17 @@ export class SAXParser extends Transform implements TokenHandler {
123123
protected _transformChunk(chunk: string): string {
124124
if (!this.stopped) {
125125
this.tokenizer.write(chunk, this.lastChunkWritten);
126+
this.tokenizer.flushCurrentCharacterToken();
126127
}
127128
return chunk;
128129
}
129130

130131
/** @internal */
131132
onCharacter({ chars, location }: Token.CharacterToken): void {
133+
// After a chunk-boundary flush the tokenizer continues with an empty text token, which arrives here without
134+
// characters. It is dropped unless its source range covers something (CDATA delimiters, a tag dropped at
135+
// EOF), which the rewriting stream still has to forward.
136+
if (chars.length === 0 && (!location || location.startOffset === location.endOffset)) return;
132137
if (this.pendingText === null) {
133138
this.pendingText = { text: chars, sourceCodeLocation: location };
134139
} else {

‎packages/parse5-sax-parser/lib/parser-feedback-simulator.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,9 @@ export class ParserFeedbackSimulator implements TokenHandler {
4747

4848
/** @internal */
4949
onWhitespaceCharacter(token: Token.CharacterToken): void {
50-
if (this.skipNextNewLine && token.chars.charCodeAt(0) === LINE_FEED_CODE_POINT) {
51-
this.skipNextNewLine = false;
52-
50+
const { skipNextNewLine } = this;
51+
this.skipNextNewLine = false;
52+
if (skipNextNewLine && token.chars.charCodeAt(0) === LINE_FEED_CODE_POINT) {
5353
if (token.chars.length === 1) {
5454
return;
5555
}

‎packages/parse5-sax-parser/test/sax-parser.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,84 @@ describe('SAX parser', () => {
155155
assert.strictEqual(foundText, true);
156156
});
157157
});
158+
159+
it.each([
160+
['data', '', 'a'.repeat(16_384)],
161+
['style', '<style>', 'a'.repeat(16_384)],
162+
['script', '<script>', 'a'.repeat(16_384)],
163+
['textarea', '<textarea>', 'a'.repeat(16_384)],
164+
['plaintext', '<plaintext>', 'a'.repeat(16_384)],
165+
['chunks ending in a surrogate pair', '', `${'a'.repeat(16_382)}\u{1F600}`],
166+
])('flushes uninterrupted text before EOF: %s', async (_label, prefix, chunk) => {
167+
const parser = new SAXParser({ sourceCodeLocationInfo: true });
168+
const input = prefix + chunk.repeat(16);
169+
let text = '';
170+
let end = prefix.length;
171+
parser.on('text', (token) => {
172+
assert.equal(token.sourceCodeLocation!.startOffset, end);
173+
end = token.sourceCodeLocation!.endOffset;
174+
assert.equal(token.sourceCodeLocation!.endCol, end + 1);
175+
text += token.text;
176+
});
177+
parser.write(prefix);
178+
for (let i = 0; i < 16; i++) parser.write(chunk);
179+
assert.isAtLeast(text.length, chunk.length * 12);
180+
parser.end();
181+
await finished(parser);
182+
assert.equal(text, chunk.repeat(16));
183+
assert.equal(end, input.length);
184+
});
185+
186+
it.each([
187+
['a CDATA end delimiter', '<svg><![CDATA[', `${'a'.repeat(16_382)}]]`],
188+
['a character reference', '', `${'a'.repeat(16_380)}&not`],
189+
['a less-than sign in escaped script data', '<script><!--', `${'a'.repeat(16_383)}<`],
190+
['an ambiguous ampersand', '&q', 'a'.repeat(16_384)],
191+
])('flushes text before EOF when every chunk ends in %s', async (_label, prefix, chunk) => {
192+
const parser = new SAXParser({ sourceCodeLocationInfo: true });
193+
const input = prefix + chunk.repeat(16);
194+
let length = 0;
195+
let end = -1;
196+
parser.on('text', ({ text, sourceCodeLocation }) => {
197+
const { startOffset, endOffset, endCol } = sourceCodeLocation!;
198+
if (end !== -1) assert.equal(startOffset, end);
199+
// Each event covers exactly the source of its text, without the delimiter or reference that follows.
200+
assert.equal(text, input.slice(startOffset, endOffset).replace('<![CDATA[', '').replaceAll('&not', '¬'));
201+
assert.equal(endCol, endOffset + 1);
202+
end = endOffset;
203+
length += text.length;
204+
});
205+
parser.write(prefix);
206+
for (let i = 0; i < 16; i++) parser.write(chunk);
207+
assert.isAtLeast(length, chunk.length * 12);
208+
parser.end();
209+
await finished(parser);
210+
assert.equal(end, input.length);
211+
});
212+
213+
it('adds no replacement character after flushed null characters in foreign content', async () => {
214+
const parser = new SAXParser();
215+
let actual = '';
216+
parser.on('text', (token) => {
217+
actual += token.text;
218+
});
219+
parser.write(`<svg>${'\0'.repeat(70_000)}`);
220+
parser.end('x');
221+
await finished(parser);
222+
// The null-character token becomes one replacement character; the empty token that follows the flush adds none.
223+
assert.equal(actual, '\uFFFDx');
224+
});
225+
226+
it('only skips the first newline after pre, even when whitespace is flushed', async () => {
227+
const parser = new SAXParser();
228+
let text = '';
229+
parser.on('text', (token) => {
230+
text += token.text;
231+
});
232+
parser.write(`<pre>${' '.repeat(70_000)}`);
233+
// The whitespace is flushed before the newline arrives.
234+
assert.equal(text.length, 70_000);
235+
parser.end('\ntext');
236+
await finished(parser);
237+
assert.equal(text, `${' '.repeat(70_000)}\ntext`);
238+
});

‎packages/parse5/lib/tokenizer/index.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,32 @@ describe('Tokenizer methods', () => {
269269
tokenizer.write('>', true);
270270
});
271271

272+
it.each([
273+
['a CDATA end delimiter', '<![CDATA[', 'aaaaaa]]'],
274+
['a character reference', '', 'aaaa&not'],
275+
])('drops the flushed input when every chunk ends in %s', (_label, prefix, chunk) => {
276+
const tokenizer = new Tokenizer(tokenizerOpts, {
277+
onCharacter: noop,
278+
onWhitespaceCharacter: noop,
279+
onNullCharacter: noop,
280+
onComment: noop,
281+
onDoctype: noop,
282+
onStartTag: noop,
283+
onEndTag: noop,
284+
onEof: noop,
285+
});
286+
tokenizer.inForeignNode = true;
287+
tokenizer.preprocessor.bufferWaterline = 8;
288+
tokenizer.write(prefix, false);
289+
for (let i = 0; i < 1000; i++) {
290+
tokenizer.write(chunk, false);
291+
tokenizer.flushCurrentCharacterToken();
292+
assert.isBelow(tokenizer.preprocessor.html.length, 3 * chunk.length);
293+
// The current code point keeps its offset after the drop.
294+
assert.equal(tokenizer.preprocessor.offset, prefix.length + (i + 1) * chunk.length - 1);
295+
}
296+
});
297+
272298
it('should pause and resume', () => {
273299
let count = 0;
274300
const tokenizer = new Tokenizer(tokenizerOpts, {

‎packages/parse5/lib/tokenizer/index.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,38 @@ export class Tokenizer {
460460
this._runParsingLoop();
461461
}
462462

463+
/** @internal Flush completed streaming text without splitting an unfinished token. */
464+
public flushCurrentCharacterToken(): void {
465+
// Only completed text is flushed: an unfinished token stays intact, including a doctype that has no token yet.
466+
if (
467+
this.paused ||
468+
this.active ||
469+
!this.currentCharacterToken ||
470+
this.currentToken ||
471+
this.state === State.DOCTYPE ||
472+
this.state === State.BEFORE_DOCTYPE_NAME ||
473+
!this.preprocessor.willDropParsedChunk()
474+
) {
475+
return;
476+
}
477+
478+
// The last `pending` code units, a delimiter or character reference, are not text yet and stay buffered. They
479+
// are ASCII, so they hold no preprocessing gap and no line break that the dropped gap history would have to keep.
480+
const pending =
481+
this.preprocessor.droppedBufferSize + this.preprocessor.pos + 1 - this.getCharacterTokenEndOffset();
482+
// Hibernation left us before the next code point (possibly an incomplete surrogate).
483+
this.preprocessor.advance();
484+
this.currentLocation = this.getCurrentLocation(pending);
485+
this.preprocessor.retreat(1);
486+
this._emitCurrentCharacterToken(this.currentLocation);
487+
// Keep a source range for CDATA delimiters or a later tag discarded at EOF. An empty null-character token
488+
// would become a replacement character in foreign content.
489+
this._createCharacterToken(TokenType.CHARACTER);
490+
this.preprocessor.dropParsedChunk(Math.max(pending - 1, 0));
491+
// Keep `entityStartPos` valid for a pending character reference.
492+
this.entityStartPos = this.preprocessor.pos + 1 - pending;
493+
}
494+
463495
//Hibernation
464496
protected _ensureHibernation(): boolean {
465497
if (this.preprocessor.endOfChunkHit) {

‎packages/parse5/lib/tokenizer/preprocessor.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,17 +109,21 @@ export class Preprocessor {
109109
return this.pos > this.bufferWaterline;
110110
}
111111

112-
public dropParsedChunk(): void {
112+
/**
113+
* Drop the parsed input, except for the current code point and the `keep` code units before it. The gap history is
114+
* reset, so the kept units must contain no preprocessing gap.
115+
*/
116+
public dropParsedChunk(keep = 0): void {
113117
if (this.willDropParsedChunk()) {
114118
// Retain the entire current code point, including both units of a surrogate pair.
115-
const droppedSize = this.offset - this.droppedBufferSize;
119+
const droppedSize = this.offset - this.droppedBufferSize - keep;
116120
this.html = this.html.substring(droppedSize);
117121
this.lineStartPos -= droppedSize;
118122
this.droppedBufferSize += droppedSize;
119123
this.pos -= droppedSize;
120124
this.lastGapPos = -2;
121125
this.gapStack.length = 0;
122-
if (this.pos > 0) this._addGap();
126+
if (this.pos > keep) this._addGap();
123127
}
124128
}
125129

0 commit comments

Comments
 (0)