-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
XMLParser.ts
executable file
·249 lines (220 loc) · 8 KB
/
XMLParser.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
import Node from '../nodes/node/Node';
import Element from '../nodes/element/Element';
import IDocument from '../nodes/document/IDocument';
import VoidElements from '../config/VoidElements';
import UnnestableElements from '../config/UnnestableElements';
import ChildLessElements from '../config/ChildLessElements';
import { decode } from 'he';
import NamespaceURI from '../config/NamespaceURI';
import HTMLScriptElement from '../nodes/html-script-element/HTMLScriptElement';
import INode from '../nodes/node/INode';
import IElement from '../nodes/element/IElement';
import HTMLLinkElement from '../nodes/html-link-element/HTMLLinkElement';
import IDocumentFragment from '../nodes/document-fragment/IDocumentFragment';
const MARKUP_REGEXP = /<(\/?)([a-z][-.0-9_a-z]*)\s*([^<>]*?)(\/?)>/gi;
const COMMENT_REGEXP = /<!--(.*?)-->|<([!?])([^>]*)>/gi;
const DOCUMENT_TYPE_ATTRIBUTE_REGEXP = /"([^"]+)"/gm;
const ATTRIBUTE_REGEXP = /([^\s=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))/gms;
/**
* XML parser.
*/
export default class XMLParser {
/**
* Parses XML/HTML and returns a root element.
*
* @param document Document.
* @param data HTML data.
* @param [evaluateScripts = false] Set to "true" to enable script execution.
* @returns Root element.
*/
public static parse(
document: IDocument,
data: string,
evaluateScripts = false
): IDocumentFragment {
const root = document.createDocumentFragment();
const stack: Array<IElement | IDocumentFragment> = [root];
const markupRegexp = new RegExp(MARKUP_REGEXP, 'gi');
let parent: IDocumentFragment | IElement = root;
let parentUnnestableTagName = null;
let lastTextIndex = 0;
let match: RegExpExecArray;
while ((match = markupRegexp.exec(data))) {
const tagName = match[2].toLowerCase();
const isStartTag = !match[1];
if (parent && match.index !== lastTextIndex) {
const text = data.substring(lastTextIndex, match.index);
this.appendTextAndCommentNodes(document, parent, text);
}
if (isStartTag) {
const namespaceURI =
tagName === 'svg'
? NamespaceURI.svg
: (<IElement>parent).namespaceURI || NamespaceURI.html;
const newElement = document.createElementNS(namespaceURI, tagName);
// Scripts are not allowed to be executed when they are parsed using innerHTML, outerHTML, replaceWith() etc.
// However, they are allowed to be executed when document.write() is used.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
if (tagName === 'script') {
(<HTMLScriptElement>newElement)._evaluateScript = evaluateScripts;
}
// An assumption that the same rule should be applied for the HTMLLinkElement is made here.
if (tagName === 'link') {
(<HTMLLinkElement>newElement)._evaluateCSS = evaluateScripts;
}
this.setAttributes(newElement, match[3]);
if (!match[4] && !VoidElements.includes(tagName)) {
// Some elements are not allowed to be nested (e.g. "<a><a></a></a>" is not allowed.).
// Therefore we will auto-close the tag.
if (parentUnnestableTagName === tagName) {
stack.pop();
parent = <Element>parent.parentNode || root;
}
parent = <Element>parent.appendChild(newElement);
parentUnnestableTagName = this.getUnnestableTagName(parent);
stack.push(parent);
} else {
parent.appendChild(newElement);
}
lastTextIndex = markupRegexp.lastIndex;
// Tags which contain non-parsed content
// For example: <script> JavaScript should not be parsed
if (ChildLessElements.includes(tagName)) {
let childLessMatch = null;
while ((childLessMatch = markupRegexp.exec(data))) {
if (childLessMatch[2] === match[2] && childLessMatch[1]) {
markupRegexp.lastIndex -= childLessMatch[0].length;
break;
}
}
}
} else {
stack.pop();
parent = stack[stack.length - 1] || root;
parentUnnestableTagName = this.getUnnestableTagName(parent);
lastTextIndex = markupRegexp.lastIndex;
}
}
// Text after last element
if ((!match && data.length > 0) || (match && lastTextIndex !== match.index)) {
const text = data.substring(lastTextIndex);
this.appendTextAndCommentNodes(document, parent || root, text);
}
return root;
}
/**
* Returns a tag name if element is unnestable.
*
* @param element Element.
* @returns Tag name if element is unnestable.
*/
private static getUnnestableTagName(element: IElement | IDocumentFragment): string {
const tagName = (<IElement>element).tagName ? (<IElement>element).tagName.toLowerCase() : null;
return tagName && UnnestableElements.includes(tagName) ? tagName : null;
}
/**
* Appends text and comment nodes.
*
* @param document Document.
* @param node Node.
* @param text Text to search in.
*/
private static appendTextAndCommentNodes(document: IDocument, node: INode, text: string): void {
for (const innerNode of this.getTextAndCommentNodes(document, text)) {
node.appendChild(innerNode);
}
}
/**
* Returns text and comment nodes from a text.
*
* @param document Document.
* @param text Text to search in.
* @returns Nodes.
*/
private static getTextAndCommentNodes(document: IDocument, text: string): Node[] {
const nodes = [];
const commentRegExp = new RegExp(COMMENT_REGEXP, 'gms');
let hasDocumentType = false;
let lastIndex = 0;
let match;
while ((match = commentRegExp.exec(text))) {
if (match.index > 0 && lastIndex !== match.index) {
const textNode = document.createTextNode(text.substring(lastIndex, match.index));
nodes.push(textNode);
}
if (match[3] && match[3].toUpperCase().startsWith('DOCTYPE')) {
const docTypeSplit = match[3].split(' ');
if (docTypeSplit.length > 1) {
const docTypeString = docTypeSplit.slice(1).join(' ');
const attributes = [];
const attributeRegExp = new RegExp(DOCUMENT_TYPE_ATTRIBUTE_REGEXP, 'gm');
const isPublic = docTypeString.includes('PUBLIC');
let attributeMatch;
while ((attributeMatch = attributeRegExp.exec(docTypeString))) {
attributes.push(attributeMatch[1]);
}
const publicId = isPublic ? attributes[0] || '' : '';
const systemId = isPublic ? attributes[1] || '' : attributes[0] || '';
const documentTypeNode = document.implementation.createDocumentType(
docTypeSplit[1],
publicId,
systemId
);
nodes.push(documentTypeNode);
hasDocumentType = true;
}
} else {
const comment = match[1] ? match[1] : match[2] === '?' ? '?' + match[3] : match[3];
const commentNode = document.createComment(comment);
nodes.push(commentNode);
lastIndex = match.index + match[0].length;
}
}
if (!hasDocumentType && lastIndex < text.length) {
const textNode = document.createTextNode(text.substring(lastIndex));
nodes.push(textNode);
}
return nodes;
}
/**
* Sets raw attributes.
*
* @param element Element.
* @param attributesString Raw attributes.
*/
private static setAttributes(element: IElement, attributesString: string): void {
const attributes = attributesString.trim();
if (attributes) {
const regExp = new RegExp(ATTRIBUTE_REGEXP, 'gi');
let match: RegExpExecArray;
// Attributes with value
while ((match = regExp.exec(attributes))) {
if (match[1]) {
const value = decode(match[2] || match[3] || match[4] || '');
const name = this._getAttributeName(element.namespaceURI, match[1]);
const namespaceURI = element.tagName === 'SVG' && name === 'xmlns' ? value : null;
element.setAttributeNS(namespaceURI, name, value);
}
}
// Attributes with no value
for (const name of attributes.replace(ATTRIBUTE_REGEXP, '').trim().split(' ')) {
if (name) {
element.setAttributeNS(null, this._getAttributeName(element.namespaceURI, name), '');
}
}
}
}
/**
* Returns attribute name.
*
* @param namespaceURI Namespace URI.
* @param name Name.
* @returns Attribute name based on namespace.
*/
private static _getAttributeName(namespaceURI: string, name: string): string {
if (namespaceURI === NamespaceURI.svg) {
return name;
}
return name.toLowerCase();
}
}