parse5-sax-parser 6.0.1 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,7 +16,7 @@
16
16
  <br>
17
17
 
18
18
  <p align="center">
19
- 📖 <a href="https://github.com/inikulin/parse5/tree/master/packages/parse5-sax-parser/docs/index.md"><b>Documentation</b></a> 📖
19
+ 📖 <a href="https://parse5.js.org/modules/parse5-sax-parser.html"><b>Documentation</b></a> 📖
20
20
  </p>
21
21
 
22
22
  ---
@@ -30,5 +30,5 @@
30
30
  </p>
31
31
 
32
32
  <p align="center">
33
- <a href="https://github.com/inikulin/parse5/tree/master/docs/version-history.md">Version history</a>
33
+ <a href="https://github.com/inikulin/parse5/releases">Changelog</a>
34
34
  </p>
@@ -0,0 +1,4 @@
1
+ import { Writable } from 'node:stream';
2
+ export declare class DevNullStream extends Writable {
3
+ _write(_chunk: string, _encoding: string, cb: () => void): void;
4
+ }
@@ -0,0 +1,6 @@
1
+ import { Writable } from 'node:stream';
2
+ export class DevNullStream extends Writable {
3
+ _write(_chunk, _encoding, cb) {
4
+ cb();
5
+ }
6
+ }
@@ -0,0 +1,153 @@
1
+ import { Transform } from 'node:stream';
2
+ import type { Tokenizer, TokenHandler, Token } from 'parse5';
3
+ import { ParserFeedbackSimulator } from './parser-feedback-simulator.js';
4
+ export interface SAXParserOptions {
5
+ /**
6
+ * Enables source code location information for tokens.
7
+ *
8
+ * When enabled, each token will have a `sourceCodeLocation` property.
9
+ */
10
+ sourceCodeLocationInfo?: boolean;
11
+ }
12
+ /**
13
+ * Streaming [SAX](https://en.wikipedia.org/wiki/Simple_API_for_XML)-style HTML parser.
14
+ * A [transform stream](https://nodejs.org/api/stream.html#stream_class_stream_transform) (which means you can pipe _through_ it, see example).
15
+ *
16
+ * @example
17
+ *
18
+ * ```js
19
+ * const SAXParser = require('parse5-sax-parser');
20
+ * const http = require('http');
21
+ * const fs = require('fs');
22
+ *
23
+ * const file = fs.createWriteStream('/home/google.com.html');
24
+ * const parser = new SAXParser();
25
+ *
26
+ * parser.on('text', text => {
27
+ * // Handle page text content
28
+ * ...
29
+ * });
30
+ *
31
+ * http.get('http://google.com', res => {
32
+ * // `SAXParser` is the `Transform` stream, which means you can pipe
33
+ * // through it. So, you can analyze the page content and, e.g., save it
34
+ * // to the file at the same time:
35
+ * res.pipe(parser).pipe(file);
36
+ * });
37
+ * ```
38
+ */
39
+ export declare class SAXParser extends Transform implements TokenHandler {
40
+ protected options: SAXParserOptions;
41
+ /** @internal */
42
+ protected parserFeedbackSimulator: ParserFeedbackSimulator;
43
+ private pendingText;
44
+ private lastChunkWritten;
45
+ private stopped;
46
+ protected tokenizer: Tokenizer;
47
+ /**
48
+ * @param options Parsing options.
49
+ */
50
+ constructor(options?: SAXParserOptions);
51
+ _transform(chunk: string, _encoding: string, callback: (error?: Error | null, data?: string) => void): void;
52
+ _final(callback: (error?: Error | null, data?: string) => void): void;
53
+ /**
54
+ * Stops parsing. Useful if you want the parser to stop consuming CPU time
55
+ * once you've obtained the desired info from the input stream. Doesn't
56
+ * prevent piping, so that data will flow through the parser as usual.
57
+ *
58
+ * @example
59
+ *
60
+ * ```js
61
+ * const SAXParser = require('parse5-sax-parser');
62
+ * const http = require('http');
63
+ * const fs = require('fs');
64
+ *
65
+ * const file = fs.createWriteStream('google.com.html');
66
+ * const parser = new SAXParser();
67
+ *
68
+ * parser.on('doctype', ({ name, publicId, systemId }) => {
69
+ * // Process doctype info and stop parsing
70
+ * ...
71
+ * parser.stop();
72
+ * });
73
+ *
74
+ * http.get('http://google.com', res => {
75
+ * // Despite the fact that parser.stop() was called whole
76
+ * // content of the page will be written to the file
77
+ * res.pipe(parser).pipe(file);
78
+ * });
79
+ * ```
80
+ */
81
+ stop(): void;
82
+ protected _transformChunk(chunk: string): string;
83
+ /** @internal */
84
+ onCharacter({ chars, location }: Token.CharacterToken): void;
85
+ /** @internal */
86
+ onWhitespaceCharacter(token: Token.CharacterToken): void;
87
+ /** @internal */
88
+ onNullCharacter(token: Token.CharacterToken): void;
89
+ /** @internal */
90
+ onEof(): void;
91
+ /** @internal */
92
+ onStartTag(token: Token.TagToken): void;
93
+ /** @internal */
94
+ onEndTag(token: Token.TagToken): void;
95
+ /** @internal */
96
+ onDoctype(token: Token.DoctypeToken): void;
97
+ /** @internal */
98
+ onComment(token: Token.CommentToken): void;
99
+ protected emitIfListenerExists(eventName: string, token: SaxToken): boolean;
100
+ protected _emitToken(eventName: string, token: SaxToken): void;
101
+ private _emitPendingText;
102
+ }
103
+ export interface SaxToken {
104
+ /** Source code location info. Available if location info is enabled via {@link SAXParserOptions}. */
105
+ sourceCodeLocation?: Token.Location | null;
106
+ }
107
+ export interface StartTag extends SaxToken {
108
+ /** Tag name */
109
+ tagName: string;
110
+ /** List of attributes */
111
+ attrs: Token.Attribute[];
112
+ /** Indicates if the tag is self-closing */
113
+ selfClosing: boolean;
114
+ }
115
+ export interface EndTag extends SaxToken {
116
+ /** Tag name */
117
+ tagName: string;
118
+ }
119
+ export interface Text extends SaxToken {
120
+ /** Text content. */
121
+ text: string;
122
+ }
123
+ export interface Comment extends SaxToken {
124
+ /** Comment text. */
125
+ text: string;
126
+ }
127
+ export interface Doctype extends SaxToken {
128
+ /** Document type name. */
129
+ name: string | null;
130
+ /** Document type public identifier. */
131
+ publicId: string | null;
132
+ /** Document type system identifier. */
133
+ systemId: string | null;
134
+ }
135
+ export interface SAXParser {
136
+ /** Raised when the parser encounters a start tag. */
137
+ on(event: 'startTag', listener: (startTag: StartTag) => void): this;
138
+ /** Raised when the parser encounters an end tag. */
139
+ on(event: 'endTag', listener: (endTag: EndTag) => void): this;
140
+ /** Raised when the parser encounters a comment. */
141
+ on(event: 'comment', listener: (comment: Comment) => void): this;
142
+ /** Raised when the parser encounters text content. */
143
+ on(event: 'text', listener: (text: Text) => void): this;
144
+ /** Raised when the parser encounters a [document type declaration](https://en.wikipedia.org/wiki/Document_type_declaration) */
145
+ on(event: 'doctype', listener: (doctype: Doctype) => void): this;
146
+ /**
147
+ * Base event handler.
148
+ *
149
+ * @param event Name of the event
150
+ * @param handler Event handler
151
+ */
152
+ on(event: string, handler: (...args: any[]) => void): this;
153
+ }
package/dist/index.js ADDED
@@ -0,0 +1,191 @@
1
+ import { Transform } from 'node:stream';
2
+ import { DevNullStream } from './dev-null-stream.js';
3
+ import { ParserFeedbackSimulator } from './parser-feedback-simulator.js';
4
+ /**
5
+ * Streaming [SAX](https://en.wikipedia.org/wiki/Simple_API_for_XML)-style HTML parser.
6
+ * A [transform stream](https://nodejs.org/api/stream.html#stream_class_stream_transform) (which means you can pipe _through_ it, see example).
7
+ *
8
+ * @example
9
+ *
10
+ * ```js
11
+ * const SAXParser = require('parse5-sax-parser');
12
+ * const http = require('http');
13
+ * const fs = require('fs');
14
+ *
15
+ * const file = fs.createWriteStream('/home/google.com.html');
16
+ * const parser = new SAXParser();
17
+ *
18
+ * parser.on('text', text => {
19
+ * // Handle page text content
20
+ * ...
21
+ * });
22
+ *
23
+ * http.get('http://google.com', res => {
24
+ * // `SAXParser` is the `Transform` stream, which means you can pipe
25
+ * // through it. So, you can analyze the page content and, e.g., save it
26
+ * // to the file at the same time:
27
+ * res.pipe(parser).pipe(file);
28
+ * });
29
+ * ```
30
+ */
31
+ export class SAXParser extends Transform {
32
+ /**
33
+ * @param options Parsing options.
34
+ */
35
+ constructor(options = {}) {
36
+ super({ encoding: 'utf8', decodeStrings: false });
37
+ this.pendingText = null;
38
+ this.lastChunkWritten = false;
39
+ this.stopped = false;
40
+ this.options = {
41
+ sourceCodeLocationInfo: false,
42
+ ...options,
43
+ };
44
+ this.parserFeedbackSimulator = new ParserFeedbackSimulator(this.options, this);
45
+ this.tokenizer = this.parserFeedbackSimulator.tokenizer;
46
+ // NOTE: always pipe the stream to the /dev/null stream to avoid
47
+ // the `highWaterMark` to be hit even if we don't have consumers.
48
+ // (see: https://github.com/inikulin/parse5/issues/97#issuecomment-171940774)
49
+ this.pipe(new DevNullStream());
50
+ }
51
+ //`Transform` implementation
52
+ _transform(chunk, _encoding, callback) {
53
+ if (typeof chunk !== 'string') {
54
+ throw new TypeError('Parser can work only with string streams.');
55
+ }
56
+ callback(null, this._transformChunk(chunk));
57
+ }
58
+ _final(callback) {
59
+ this.lastChunkWritten = true;
60
+ callback(null, this._transformChunk(''));
61
+ }
62
+ /**
63
+ * Stops parsing. Useful if you want the parser to stop consuming CPU time
64
+ * once you've obtained the desired info from the input stream. Doesn't
65
+ * prevent piping, so that data will flow through the parser as usual.
66
+ *
67
+ * @example
68
+ *
69
+ * ```js
70
+ * const SAXParser = require('parse5-sax-parser');
71
+ * const http = require('http');
72
+ * const fs = require('fs');
73
+ *
74
+ * const file = fs.createWriteStream('google.com.html');
75
+ * const parser = new SAXParser();
76
+ *
77
+ * parser.on('doctype', ({ name, publicId, systemId }) => {
78
+ * // Process doctype info and stop parsing
79
+ * ...
80
+ * parser.stop();
81
+ * });
82
+ *
83
+ * http.get('http://google.com', res => {
84
+ * // Despite the fact that parser.stop() was called whole
85
+ * // content of the page will be written to the file
86
+ * res.pipe(parser).pipe(file);
87
+ * });
88
+ * ```
89
+ */
90
+ stop() {
91
+ this.stopped = true;
92
+ this.tokenizer.pause();
93
+ }
94
+ //Internals
95
+ _transformChunk(chunk) {
96
+ if (!this.stopped) {
97
+ this.tokenizer.write(chunk, this.lastChunkWritten);
98
+ }
99
+ return chunk;
100
+ }
101
+ /** @internal */
102
+ onCharacter({ chars, location }) {
103
+ if (this.pendingText === null) {
104
+ this.pendingText = { text: chars, sourceCodeLocation: location };
105
+ }
106
+ else {
107
+ this.pendingText.text += chars;
108
+ if (location && this.pendingText.sourceCodeLocation) {
109
+ const { endLine, endCol, endOffset } = location;
110
+ this.pendingText.sourceCodeLocation = {
111
+ ...this.pendingText.sourceCodeLocation,
112
+ endLine,
113
+ endCol,
114
+ endOffset,
115
+ };
116
+ }
117
+ }
118
+ if (this.tokenizer.preprocessor.willDropParsedChunk()) {
119
+ this._emitPendingText();
120
+ }
121
+ }
122
+ /** @internal */
123
+ onWhitespaceCharacter(token) {
124
+ this.onCharacter(token);
125
+ }
126
+ /** @internal */
127
+ onNullCharacter(token) {
128
+ this.onCharacter(token);
129
+ }
130
+ /** @internal */
131
+ onEof() {
132
+ this._emitPendingText();
133
+ this.stopped = true;
134
+ }
135
+ /** @internal */
136
+ onStartTag(token) {
137
+ this._emitPendingText();
138
+ const startTag = {
139
+ tagName: token.tagName,
140
+ attrs: token.attrs,
141
+ selfClosing: token.selfClosing,
142
+ sourceCodeLocation: token.location,
143
+ };
144
+ this.emitIfListenerExists('startTag', startTag);
145
+ }
146
+ /** @internal */
147
+ onEndTag(token) {
148
+ this._emitPendingText();
149
+ const endTag = {
150
+ tagName: token.tagName,
151
+ sourceCodeLocation: token.location,
152
+ };
153
+ this.emitIfListenerExists('endTag', endTag);
154
+ }
155
+ /** @internal */
156
+ onDoctype(token) {
157
+ this._emitPendingText();
158
+ const doctype = {
159
+ name: token.name,
160
+ publicId: token.publicId,
161
+ systemId: token.systemId,
162
+ sourceCodeLocation: token.location,
163
+ };
164
+ this.emitIfListenerExists('doctype', doctype);
165
+ }
166
+ /** @internal */
167
+ onComment(token) {
168
+ this._emitPendingText();
169
+ const comment = {
170
+ text: token.data,
171
+ sourceCodeLocation: token.location,
172
+ };
173
+ this.emitIfListenerExists('comment', comment);
174
+ }
175
+ emitIfListenerExists(eventName, token) {
176
+ if (this.listenerCount(eventName) === 0) {
177
+ return false;
178
+ }
179
+ this._emitToken(eventName, token);
180
+ return true;
181
+ }
182
+ _emitToken(eventName, token) {
183
+ this.emit(eventName, token);
184
+ }
185
+ _emitPendingText() {
186
+ if (this.pendingText !== null) {
187
+ this.emitIfListenerExists('text', this.pendingText);
188
+ this.pendingText = null;
189
+ }
190
+ }
191
+ }
@@ -0,0 +1,31 @@
1
+ import { Tokenizer, type TokenizerOptions, type TokenHandler, Token } from 'parse5';
2
+ /**
3
+ * Simulates adjustments of the Tokenizer which are performed by the standard parser during tree construction.
4
+ */
5
+ export declare class ParserFeedbackSimulator implements TokenHandler {
6
+ private handler;
7
+ private namespaceStack;
8
+ inForeignContent: boolean;
9
+ skipNextNewLine: boolean;
10
+ tokenizer: Tokenizer;
11
+ constructor(options: TokenizerOptions, handler: TokenHandler);
12
+ /** @internal */
13
+ onNullCharacter(token: Token.CharacterToken): void;
14
+ /** @internal */
15
+ onWhitespaceCharacter(token: Token.CharacterToken): void;
16
+ /** @internal */
17
+ onCharacter(token: Token.CharacterToken): void;
18
+ /** @internal */
19
+ onComment(token: Token.CommentToken): void;
20
+ /** @internal */
21
+ onDoctype(token: Token.DoctypeToken): void;
22
+ /** @internal */
23
+ onEof(token: Token.EOFToken): void;
24
+ private _enterNamespace;
25
+ private _leaveCurrentNamespace;
26
+ private _ensureTokenizerMode;
27
+ /** @internal */
28
+ onStartTag(token: Token.TagToken): void;
29
+ /** @internal */
30
+ onEndTag(token: Token.TagToken): void;
31
+ }
@@ -0,0 +1,183 @@
1
+ import { Tokenizer, TokenizerMode, Token, foreignContent, html, } from 'parse5';
2
+ const $ = html.TAG_ID;
3
+ const REPLACEMENT_CHARACTER = '\uFFFD';
4
+ const LINE_FEED_CODE_POINT = 0x0a;
5
+ /**
6
+ * Simulates adjustments of the Tokenizer which are performed by the standard parser during tree construction.
7
+ */
8
+ export class ParserFeedbackSimulator {
9
+ constructor(options, handler) {
10
+ this.handler = handler;
11
+ this.namespaceStack = [];
12
+ this.inForeignContent = false;
13
+ this.skipNextNewLine = false;
14
+ this.tokenizer = new Tokenizer(options, this);
15
+ this._enterNamespace(html.NS.HTML);
16
+ }
17
+ /** @internal */
18
+ onNullCharacter(token) {
19
+ this.skipNextNewLine = false;
20
+ if (this.inForeignContent) {
21
+ this.handler.onCharacter({
22
+ type: Token.TokenType.CHARACTER,
23
+ chars: REPLACEMENT_CHARACTER,
24
+ location: token.location,
25
+ });
26
+ }
27
+ else {
28
+ this.handler.onNullCharacter(token);
29
+ }
30
+ }
31
+ /** @internal */
32
+ onWhitespaceCharacter(token) {
33
+ if (this.skipNextNewLine && token.chars.charCodeAt(0) === LINE_FEED_CODE_POINT) {
34
+ this.skipNextNewLine = false;
35
+ if (token.chars.length === 1) {
36
+ return;
37
+ }
38
+ token.chars = token.chars.substr(1);
39
+ }
40
+ this.handler.onWhitespaceCharacter(token);
41
+ }
42
+ /** @internal */
43
+ onCharacter(token) {
44
+ this.skipNextNewLine = false;
45
+ this.handler.onCharacter(token);
46
+ }
47
+ /** @internal */
48
+ onComment(token) {
49
+ this.skipNextNewLine = false;
50
+ this.handler.onComment(token);
51
+ }
52
+ /** @internal */
53
+ onDoctype(token) {
54
+ this.skipNextNewLine = false;
55
+ this.handler.onDoctype(token);
56
+ }
57
+ /** @internal */
58
+ onEof(token) {
59
+ this.skipNextNewLine = false;
60
+ this.handler.onEof(token);
61
+ }
62
+ //Namespace stack mutations
63
+ _enterNamespace(namespace) {
64
+ this.namespaceStack.unshift(namespace);
65
+ this.inForeignContent = namespace !== html.NS.HTML;
66
+ this.tokenizer.inForeignNode = this.inForeignContent;
67
+ }
68
+ _leaveCurrentNamespace() {
69
+ this.namespaceStack.shift();
70
+ this.inForeignContent = this.namespaceStack[0] !== html.NS.HTML;
71
+ this.tokenizer.inForeignNode = this.inForeignContent;
72
+ }
73
+ //Token handlers
74
+ _ensureTokenizerMode(tn) {
75
+ switch (tn) {
76
+ case $.TEXTAREA:
77
+ case $.TITLE: {
78
+ this.tokenizer.state = TokenizerMode.RCDATA;
79
+ break;
80
+ }
81
+ case $.PLAINTEXT: {
82
+ this.tokenizer.state = TokenizerMode.PLAINTEXT;
83
+ break;
84
+ }
85
+ case $.SCRIPT: {
86
+ this.tokenizer.state = TokenizerMode.SCRIPT_DATA;
87
+ break;
88
+ }
89
+ case $.STYLE:
90
+ case $.IFRAME:
91
+ case $.XMP:
92
+ case $.NOEMBED:
93
+ case $.NOFRAMES:
94
+ case $.NOSCRIPT: {
95
+ this.tokenizer.state = TokenizerMode.RAWTEXT;
96
+ break;
97
+ }
98
+ default:
99
+ // Do nothing
100
+ }
101
+ }
102
+ /** @internal */
103
+ onStartTag(token) {
104
+ let tn = token.tagID;
105
+ switch (tn) {
106
+ case $.SVG: {
107
+ this._enterNamespace(html.NS.SVG);
108
+ break;
109
+ }
110
+ case $.MATH: {
111
+ this._enterNamespace(html.NS.MATHML);
112
+ break;
113
+ }
114
+ default:
115
+ // Do nothing
116
+ }
117
+ if (this.inForeignContent) {
118
+ if (foreignContent.causesExit(token)) {
119
+ this._leaveCurrentNamespace();
120
+ }
121
+ else {
122
+ const currentNs = this.namespaceStack[0];
123
+ if (currentNs === html.NS.MATHML) {
124
+ foreignContent.adjustTokenMathMLAttrs(token);
125
+ }
126
+ else if (currentNs === html.NS.SVG) {
127
+ foreignContent.adjustTokenSVGTagName(token);
128
+ foreignContent.adjustTokenSVGAttrs(token);
129
+ }
130
+ foreignContent.adjustTokenXMLAttrs(token);
131
+ tn = token.tagID;
132
+ if (!token.selfClosing && foreignContent.isIntegrationPoint(tn, currentNs, token.attrs)) {
133
+ this._enterNamespace(html.NS.HTML);
134
+ }
135
+ }
136
+ }
137
+ else {
138
+ switch (tn) {
139
+ case $.PRE:
140
+ case $.TEXTAREA:
141
+ case $.LISTING: {
142
+ this.skipNextNewLine = true;
143
+ break;
144
+ }
145
+ case $.IMAGE: {
146
+ token.tagName = html.TAG_NAMES.IMG;
147
+ token.tagID = $.IMG;
148
+ break;
149
+ }
150
+ default:
151
+ // Do nothing
152
+ }
153
+ this._ensureTokenizerMode(tn);
154
+ }
155
+ this.handler.onStartTag(token);
156
+ }
157
+ /** @internal */
158
+ onEndTag(token) {
159
+ let tn = token.tagID;
160
+ if (!this.inForeignContent) {
161
+ const previousNs = this.namespaceStack[1];
162
+ if (previousNs === html.NS.SVG) {
163
+ const adjustedTagName = foreignContent.SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);
164
+ if (adjustedTagName) {
165
+ tn = html.getTagID(adjustedTagName);
166
+ }
167
+ }
168
+ //NOTE: check for exit from integration point
169
+ if (foreignContent.isIntegrationPoint(tn, previousNs, token.attrs)) {
170
+ this._leaveCurrentNamespace();
171
+ }
172
+ }
173
+ else if ((tn === $.SVG && this.namespaceStack[0] === html.NS.SVG) ||
174
+ (tn === $.MATH && this.namespaceStack[0] === html.NS.MATHML)) {
175
+ this._leaveCurrentNamespace();
176
+ }
177
+ // NOTE: adjust end tag name as well for consistency
178
+ if (this.namespaceStack[0] === html.NS.SVG) {
179
+ foreignContent.adjustTokenSVGTagName(token);
180
+ }
181
+ this.handler.onEndTag(token);
182
+ }
183
+ }
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "parse5-sax-parser",
3
+ "type": "module",
3
4
  "description": "Streaming SAX-style HTML parser.",
4
- "version": "6.0.1",
5
+ "version": "8.0.0",
5
6
  "author": "Ivan Nikulin <ifaaan@gmail.com> (https://github.com/inikulin)",
6
7
  "contributors": "https://github.com/inikulin/parse5/graphs/contributors",
7
- "homepage": "https://github.com/inikulin/parse5",
8
+ "homepage": "https://parse5.js.org",
9
+ "funding": "https://github.com/inikulin/parse5?sponsor=1",
8
10
  "keywords": [
9
11
  "parse5",
10
12
  "parser",
@@ -13,16 +15,23 @@
13
15
  "SAX"
14
16
  ],
15
17
  "license": "MIT",
16
- "main": "./lib/index.js",
18
+ "main": "dist/index.js",
19
+ "module": "dist/index.js",
20
+ "types": "dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
17
26
  "dependencies": {
18
- "parse5": "^6.0.1"
27
+ "parse5": "^8.0.0"
19
28
  },
20
29
  "repository": {
21
30
  "type": "git",
22
31
  "url": "git://github.com/inikulin/parse5.git"
23
32
  },
24
33
  "files": [
25
- "lib"
26
- ],
27
- "gitHead": "37227a3429584903cbd1799dade995266fc2dbe6"
34
+ "dist/**/*.js",
35
+ "dist/**/*.d.ts"
36
+ ]
28
37
  }
@@ -1,11 +0,0 @@
1
- 'use strict';
2
-
3
- const { Writable } = require('stream');
4
-
5
- class DevNullStream extends Writable {
6
- _write(chunk, encoding, cb) {
7
- cb();
8
- }
9
- }
10
-
11
- module.exports = DevNullStream;
package/lib/index.js DELETED
@@ -1,166 +0,0 @@
1
- 'use strict';
2
-
3
- const { Transform } = require('stream');
4
- const Tokenizer = require('parse5/lib/tokenizer');
5
- const LocationInfoTokenizerMixin = require('parse5/lib/extensions/location-info/tokenizer-mixin');
6
- const Mixin = require('parse5/lib/utils/mixin');
7
- const mergeOptions = require('parse5/lib/utils/merge-options');
8
- const DevNullStream = require('./dev-null-stream');
9
- const ParserFeedbackSimulator = require('./parser-feedback-simulator');
10
-
11
- const DEFAULT_OPTIONS = {
12
- sourceCodeLocationInfo: false
13
- };
14
-
15
- class SAXParser extends Transform {
16
- constructor(options) {
17
- super({ encoding: 'utf8', decodeStrings: false });
18
-
19
- this.options = mergeOptions(DEFAULT_OPTIONS, options);
20
-
21
- this.tokenizer = new Tokenizer(options);
22
- this.locInfoMixin = null;
23
-
24
- if (this.options.sourceCodeLocationInfo) {
25
- this.locInfoMixin = Mixin.install(this.tokenizer, LocationInfoTokenizerMixin);
26
- }
27
-
28
- this.parserFeedbackSimulator = new ParserFeedbackSimulator(this.tokenizer);
29
-
30
- this.pendingText = null;
31
-
32
- this.lastChunkWritten = false;
33
- this.stopped = false;
34
-
35
- // NOTE: always pipe stream to the /dev/null stream to avoid
36
- // `highWaterMark` hit even if we don't have consumers.
37
- // (see: https://github.com/inikulin/parse5/issues/97#issuecomment-171940774)
38
- this.pipe(new DevNullStream());
39
- }
40
-
41
- //TransformStream implementation
42
- _transform(chunk, encoding, callback) {
43
- if (typeof chunk !== 'string') {
44
- throw new TypeError('Parser can work only with string streams.');
45
- }
46
-
47
- callback(null, this._transformChunk(chunk));
48
- }
49
-
50
- _final(callback) {
51
- this.lastChunkWritten = true;
52
- callback(null, this._transformChunk(''));
53
- }
54
-
55
- stop() {
56
- this.stopped = true;
57
- }
58
-
59
- //Internals
60
- _transformChunk(chunk) {
61
- if (!this.stopped) {
62
- this.tokenizer.write(chunk, this.lastChunkWritten);
63
- this._runParsingLoop();
64
- }
65
- return chunk;
66
- }
67
-
68
- _runParsingLoop() {
69
- let token = null;
70
-
71
- do {
72
- token = this.parserFeedbackSimulator.getNextToken();
73
-
74
- if (token.type === Tokenizer.HIBERNATION_TOKEN) {
75
- break;
76
- }
77
-
78
- if (
79
- token.type === Tokenizer.CHARACTER_TOKEN ||
80
- token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN ||
81
- token.type === Tokenizer.NULL_CHARACTER_TOKEN
82
- ) {
83
- if (this.pendingText === null) {
84
- token.type = Tokenizer.CHARACTER_TOKEN;
85
- this.pendingText = token;
86
- } else {
87
- this.pendingText.chars += token.chars;
88
-
89
- if (this.options.sourceCodeLocationInfo) {
90
- const { endLine, endCol, endOffset } = token.location;
91
- Object.assign(this.pendingText.location, {
92
- endLine,
93
- endCol,
94
- endOffset
95
- });
96
- }
97
- }
98
- } else {
99
- this._emitPendingText();
100
- this._handleToken(token);
101
- }
102
- } while (!this.stopped && token.type !== Tokenizer.EOF_TOKEN);
103
- }
104
-
105
- _handleToken(token) {
106
- if (token.type === Tokenizer.EOF_TOKEN) {
107
- return true;
108
- }
109
-
110
- const { eventName, reshapeToken } = TOKEN_EMISSION_HELPERS[token.type];
111
-
112
- if (this.listenerCount(eventName) === 0) {
113
- return false;
114
- }
115
-
116
- this._emitToken(eventName, reshapeToken(token));
117
-
118
- return true;
119
- }
120
-
121
- _emitToken(eventName, token) {
122
- this.emit(eventName, token);
123
- }
124
-
125
- _emitPendingText() {
126
- if (this.pendingText !== null) {
127
- this._handleToken(this.pendingText);
128
- this.pendingText = null;
129
- }
130
- }
131
- }
132
-
133
- const TOKEN_EMISSION_HELPERS = {
134
- [Tokenizer.START_TAG_TOKEN]: {
135
- eventName: 'startTag',
136
- reshapeToken: origToken => ({
137
- tagName: origToken.tagName,
138
- attrs: origToken.attrs,
139
- selfClosing: origToken.selfClosing,
140
- sourceCodeLocation: origToken.location
141
- })
142
- },
143
- [Tokenizer.END_TAG_TOKEN]: {
144
- eventName: 'endTag',
145
- reshapeToken: origToken => ({ tagName: origToken.tagName, sourceCodeLocation: origToken.location })
146
- },
147
- [Tokenizer.COMMENT_TOKEN]: {
148
- eventName: 'comment',
149
- reshapeToken: origToken => ({ text: origToken.data, sourceCodeLocation: origToken.location })
150
- },
151
- [Tokenizer.DOCTYPE_TOKEN]: {
152
- eventName: 'doctype',
153
- reshapeToken: origToken => ({
154
- name: origToken.name,
155
- publicId: origToken.publicId,
156
- systemId: origToken.systemId,
157
- sourceCodeLocation: origToken.location
158
- })
159
- },
160
- [Tokenizer.CHARACTER_TOKEN]: {
161
- eventName: 'text',
162
- reshapeToken: origToken => ({ text: origToken.chars, sourceCodeLocation: origToken.location })
163
- }
164
- };
165
-
166
- module.exports = SAXParser;
@@ -1,159 +0,0 @@
1
- 'use strict';
2
-
3
- const Tokenizer = require('parse5/lib/tokenizer');
4
- const foreignContent = require('parse5/lib/common/foreign-content');
5
- const unicode = require('parse5/lib/common/unicode');
6
- const HTML = require('parse5/lib/common/html');
7
-
8
- //Aliases
9
- const $ = HTML.TAG_NAMES;
10
- const NS = HTML.NAMESPACES;
11
-
12
- //ParserFeedbackSimulator
13
- //Simulates adjustment of the Tokenizer which performed by standard parser during tree construction.
14
- class ParserFeedbackSimulator {
15
- constructor(tokenizer) {
16
- this.tokenizer = tokenizer;
17
-
18
- this.namespaceStack = [];
19
- this.namespaceStackTop = -1;
20
- this._enterNamespace(NS.HTML);
21
- }
22
-
23
- getNextToken() {
24
- const token = this.tokenizer.getNextToken();
25
-
26
- if (token.type === Tokenizer.START_TAG_TOKEN) {
27
- this._handleStartTagToken(token);
28
- } else if (token.type === Tokenizer.END_TAG_TOKEN) {
29
- this._handleEndTagToken(token);
30
- } else if (token.type === Tokenizer.NULL_CHARACTER_TOKEN && this.inForeignContent) {
31
- token.type = Tokenizer.CHARACTER_TOKEN;
32
- token.chars = unicode.REPLACEMENT_CHARACTER;
33
- } else if (this.skipNextNewLine) {
34
- if (token.type !== Tokenizer.HIBERNATION_TOKEN) {
35
- this.skipNextNewLine = false;
36
- }
37
-
38
- if (token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN && token.chars[0] === '\n') {
39
- if (token.chars.length === 1) {
40
- return this.getNextToken();
41
- }
42
-
43
- token.chars = token.chars.substr(1);
44
- }
45
- }
46
-
47
- return token;
48
- }
49
-
50
- //Namespace stack mutations
51
- _enterNamespace(namespace) {
52
- this.namespaceStackTop++;
53
- this.namespaceStack.push(namespace);
54
-
55
- this.inForeignContent = namespace !== NS.HTML;
56
- this.currentNamespace = namespace;
57
- this.tokenizer.allowCDATA = this.inForeignContent;
58
- }
59
-
60
- _leaveCurrentNamespace() {
61
- this.namespaceStackTop--;
62
- this.namespaceStack.pop();
63
-
64
- this.currentNamespace = this.namespaceStack[this.namespaceStackTop];
65
- this.inForeignContent = this.currentNamespace !== NS.HTML;
66
- this.tokenizer.allowCDATA = this.inForeignContent;
67
- }
68
-
69
- //Token handlers
70
- _ensureTokenizerMode(tn) {
71
- if (tn === $.TEXTAREA || tn === $.TITLE) {
72
- this.tokenizer.state = Tokenizer.MODE.RCDATA;
73
- } else if (tn === $.PLAINTEXT) {
74
- this.tokenizer.state = Tokenizer.MODE.PLAINTEXT;
75
- } else if (tn === $.SCRIPT) {
76
- this.tokenizer.state = Tokenizer.MODE.SCRIPT_DATA;
77
- } else if (
78
- tn === $.STYLE ||
79
- tn === $.IFRAME ||
80
- tn === $.XMP ||
81
- tn === $.NOEMBED ||
82
- tn === $.NOFRAMES ||
83
- tn === $.NOSCRIPT
84
- ) {
85
- this.tokenizer.state = Tokenizer.MODE.RAWTEXT;
86
- }
87
- }
88
-
89
- _handleStartTagToken(token) {
90
- let tn = token.tagName;
91
-
92
- if (tn === $.SVG) {
93
- this._enterNamespace(NS.SVG);
94
- } else if (tn === $.MATH) {
95
- this._enterNamespace(NS.MATHML);
96
- }
97
-
98
- if (this.inForeignContent) {
99
- if (foreignContent.causesExit(token)) {
100
- this._leaveCurrentNamespace();
101
- return;
102
- }
103
-
104
- const currentNs = this.currentNamespace;
105
-
106
- if (currentNs === NS.MATHML) {
107
- foreignContent.adjustTokenMathMLAttrs(token);
108
- } else if (currentNs === NS.SVG) {
109
- foreignContent.adjustTokenSVGTagName(token);
110
- foreignContent.adjustTokenSVGAttrs(token);
111
- }
112
-
113
- foreignContent.adjustTokenXMLAttrs(token);
114
-
115
- tn = token.tagName;
116
-
117
- if (!token.selfClosing && foreignContent.isIntegrationPoint(tn, currentNs, token.attrs)) {
118
- this._enterNamespace(NS.HTML);
119
- }
120
- } else {
121
- if (tn === $.PRE || tn === $.TEXTAREA || tn === $.LISTING) {
122
- this.skipNextNewLine = true;
123
- } else if (tn === $.IMAGE) {
124
- token.tagName = $.IMG;
125
- }
126
-
127
- this._ensureTokenizerMode(tn);
128
- }
129
- }
130
-
131
- _handleEndTagToken(token) {
132
- let tn = token.tagName;
133
-
134
- if (!this.inForeignContent) {
135
- const previousNs = this.namespaceStack[this.namespaceStackTop - 1];
136
-
137
- if (previousNs === NS.SVG && foreignContent.SVG_TAG_NAMES_ADJUSTMENT_MAP[tn]) {
138
- tn = foreignContent.SVG_TAG_NAMES_ADJUSTMENT_MAP[tn];
139
- }
140
-
141
- //NOTE: check for exit from integration point
142
- if (foreignContent.isIntegrationPoint(tn, previousNs, token.attrs)) {
143
- this._leaveCurrentNamespace();
144
- }
145
- } else if (
146
- (tn === $.SVG && this.currentNamespace === NS.SVG) ||
147
- (tn === $.MATH && this.currentNamespace === NS.MATHML)
148
- ) {
149
- this._leaveCurrentNamespace();
150
- }
151
-
152
- // NOTE: adjust end tag name as well for consistency
153
- if (this.currentNamespace === NS.SVG) {
154
- foreignContent.adjustTokenSVGTagName(token);
155
- }
156
- }
157
- }
158
-
159
- module.exports = ParserFeedbackSimulator;