forked from inikulin/parse5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
307 lines (269 loc) · 9.04 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { Transform } from 'node:stream';
import type { Tokenizer, TokenHandler } from 'parse5/dist/tokenizer/index.js';
import type {
Attribute,
Location,
TagToken,
CommentToken,
DoctypeToken,
CharacterToken,
} from 'parse5/dist/common/token.js';
import { DevNullStream } from './dev-null-stream.js';
import { ParserFeedbackSimulator } from './parser-feedback-simulator.js';
export interface SAXParserOptions {
/**
* Enables source code location information for the tokens.
* When enabled, each token will have `sourceCodeLocation` property.
*/
sourceCodeLocationInfo?: boolean;
}
/**
* Streaming [SAX](https://en.wikipedia.org/wiki/Simple_API_for_XML)-style HTML parser.
* A [transform stream](https://nodejs.org/api/stream.html#stream_class_stream_transform) (which means you can pipe _through_ it, see example).
*
* @example
*
* ```js
* const SAXParser = require('parse5-sax-parser');
* const http = require('http');
* const fs = require('fs');
*
* const file = fs.createWriteStream('/home/google.com.html');
* const parser = new SAXParser();
*
* parser.on('text', text => {
* // Handle page text content
* ...
* });
*
* http.get('http://google.com', res => {
* // SAXParser is the Transform stream, which means you can pipe
* // through it. So, you can analyze page content and, e.g., save it
* // to the file at the same time:
* res.pipe(parser).pipe(file);
* });
* ```
*/
export class SAXParser extends Transform implements TokenHandler {
protected options: SAXParserOptions;
protected parserFeedbackSimulator: ParserFeedbackSimulator;
private pendingText: Text | null = null;
private lastChunkWritten = false;
private stopped = false;
protected tokenizer: Tokenizer;
/**
* @param options Parsing options.
*/
constructor(options: SAXParserOptions = {}) {
super({ encoding: 'utf8', decodeStrings: false });
this.options = {
sourceCodeLocationInfo: false,
...options,
};
this.parserFeedbackSimulator = new ParserFeedbackSimulator(this.options, this);
this.tokenizer = this.parserFeedbackSimulator.tokenizer;
// NOTE: always pipe stream to the /dev/null stream to avoid
// `highWaterMark` hit even if we don't have consumers.
// (see: https://github.com/inikulin/parse5/issues/97#issuecomment-171940774)
this.pipe(new DevNullStream());
}
//TransformStream implementation
override _transform(
chunk: string,
_encoding: string,
callback: (error?: Error | null, data?: string) => void
): void {
if (typeof chunk !== 'string') {
throw new TypeError('Parser can work only with string streams.');
}
callback(null, this._transformChunk(chunk));
}
override _final(callback: (error?: Error | null, data?: string) => void): void {
this.lastChunkWritten = true;
callback(null, this._transformChunk(''));
}
/**
* Stops parsing. Useful if you want the parser to stop consuming CPU time
* once you've obtained the desired info from the input stream. Doesn't
* prevent piping, so that data will flow through the parser as usual.
*
* @example
*
* ```js
* const SAXParser = require('parse5-sax-parser');
* const http = require('http');
* const fs = require('fs');
*
* const file = fs.createWriteStream('google.com.html');
* const parser = new SAXParser();
*
* parser.on('doctype', ({ name, publicId, systemId }) => {
* // Process doctype info and stop parsing
* ...
* parser.stop();
* });
*
* http.get('http://google.com', res => {
* // Despite the fact that parser.stop() was called whole
* // content of the page will be written to the file
* res.pipe(parser).pipe(file);
* });
* ```
*/
public stop(): void {
this.stopped = true;
}
//Internals
protected _transformChunk(chunk: string): string {
if (!this.stopped) {
this.tokenizer.write(chunk, this.lastChunkWritten);
this._runParsingLoop();
}
return chunk;
}
private _runParsingLoop(): void {
while (!this.stopped && this.tokenizer.active) {
this.tokenizer.getNextToken();
}
}
/** @internal */
onCharacter({ chars, location }: CharacterToken): void {
if (this.pendingText === null) {
this.pendingText = { text: chars, sourceCodeLocation: location };
} else {
this.pendingText.text += chars;
if (location && this.pendingText.sourceCodeLocation) {
const { endLine, endCol, endOffset } = location;
this.pendingText.sourceCodeLocation = {
...this.pendingText.sourceCodeLocation,
endLine,
endCol,
endOffset,
};
}
}
if (this.tokenizer.preprocessor.willDropParsedChunk()) {
this._emitPendingText();
}
}
/** @internal */
onWhitespaceCharacter(token: CharacterToken): void {
this.onCharacter(token);
}
/** @internal */
onNullCharacter(token: CharacterToken): void {
this.onCharacter(token);
}
/** @internal */
onEof(): void {
this._emitPendingText();
this.stopped = true;
}
/** @internal */
onStartTag(token: TagToken): void {
this._emitPendingText();
const startTag: StartTag = {
tagName: token.tagName,
attrs: token.attrs,
selfClosing: token.selfClosing,
sourceCodeLocation: token.location,
};
this.emitIfListenerExists('startTag', startTag);
}
/** @internal */
onEndTag(token: TagToken): void {
this._emitPendingText();
const endTag: EndTag = {
tagName: token.tagName,
sourceCodeLocation: token.location,
};
this.emitIfListenerExists('endTag', endTag);
}
/** @internal */
onDoctype(token: DoctypeToken): void {
this._emitPendingText();
const doctype: Doctype = {
name: token.name,
publicId: token.publicId,
systemId: token.systemId,
sourceCodeLocation: token.location,
};
this.emitIfListenerExists('doctype', doctype);
}
/** @internal */
onComment(token: CommentToken): void {
this._emitPendingText();
const comment: Comment = {
text: token.data,
sourceCodeLocation: token.location,
};
this.emitIfListenerExists('comment', comment);
}
protected emitIfListenerExists(eventName: string, token: SaxToken): boolean {
if (this.listenerCount(eventName) === 0) {
return false;
}
this._emitToken(eventName, token);
return true;
}
protected _emitToken(eventName: string, token: SaxToken): void {
this.emit(eventName, token);
}
private _emitPendingText(): void {
if (this.pendingText !== null) {
this.emitIfListenerExists('text', this.pendingText);
this.pendingText = null;
}
}
}
export interface SaxToken {
/** Source code location info. Available if location info is enabled via {@link SAXParserOptions}. */
sourceCodeLocation?: Location | null;
}
export interface StartTag extends SaxToken {
/** Tag name */
tagName: string;
/** List of attributes */
attrs: Attribute[];
/** Indicates if the tag is self-closing */
selfClosing: boolean;
}
export interface EndTag extends SaxToken {
/** Tag name */
tagName: string;
}
export interface Text extends SaxToken {
/** Text content. */
text: string;
}
export interface Comment extends SaxToken {
/** Comment text. */
text: string;
}
export interface Doctype extends SaxToken {
/** Document type name. */
name: string | null;
/** Document type public identifier. */
publicId: string | null;
/** Document type system identifier. */
systemId: string | null;
}
export interface SAXParser {
/** Raised when the parser encounters a start tag. */
on(event: 'startTag', listener: (startTag: StartTag) => void): this;
/** Raised when parser encounters an end tag. */
on(event: 'endTag', listener: (endTag: EndTag) => void): this;
/** Raised when parser encounters a comment. */
on(event: 'comment', listener: (comment: Comment) => void): this;
/** Raised when parser encounters text content. */
on(event: 'text', listener: (text: Text) => void): this;
/** Raised when parser encounters a [document type declaration](https://en.wikipedia.org/wiki/Document_type_declaration) */
on(event: 'doctype', listener: (doctype: Doctype) => void): this;
/**
* Base event handler.
*
* @param event Name of the event
* @param handler Event handler
*/
on(event: string, handler: (...args: any[]) => void): this;
}