happy-dom 9.10.8 → 9.11.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.

Potentially problematic release.


This version of happy-dom might be problematic. Click here for more details.

Files changed (64) hide show
  1. package/lib/config/PlainTextElements.d.ts +4 -1
  2. package/lib/config/PlainTextElements.d.ts.map +1 -1
  3. package/lib/config/PlainTextElements.js +4 -1
  4. package/lib/config/PlainTextElements.js.map +1 -1
  5. package/lib/config/UnnestableElements.d.ts +18 -1
  6. package/lib/config/UnnestableElements.d.ts.map +1 -1
  7. package/lib/config/UnnestableElements.js +18 -18
  8. package/lib/config/UnnestableElements.js.map +1 -1
  9. package/lib/config/VoidElements.d.ts +16 -1
  10. package/lib/config/VoidElements.d.ts.map +1 -1
  11. package/lib/config/VoidElements.js +16 -17
  12. package/lib/config/VoidElements.js.map +1 -1
  13. package/lib/dom-parser/DOMParser.js +2 -2
  14. package/lib/dom-parser/DOMParser.js.map +1 -1
  15. package/lib/fetch/Request.d.ts +7 -0
  16. package/lib/fetch/Request.d.ts.map +1 -1
  17. package/lib/fetch/Request.js +25 -0
  18. package/lib/fetch/Request.js.map +1 -1
  19. package/lib/fetch/types/IRequest.d.ts +7 -0
  20. package/lib/fetch/types/IRequest.d.ts.map +1 -1
  21. package/lib/nodes/document/Document.d.ts.map +1 -1
  22. package/lib/nodes/document/Document.js +19 -18
  23. package/lib/nodes/document/Document.js.map +1 -1
  24. package/lib/nodes/element/Element.d.ts.map +1 -1
  25. package/lib/nodes/element/Element.js +1 -3
  26. package/lib/nodes/element/Element.js.map +1 -1
  27. package/lib/nodes/html-template-element/HTMLTemplateElement.d.ts.map +1 -1
  28. package/lib/nodes/html-template-element/HTMLTemplateElement.js +2 -4
  29. package/lib/nodes/html-template-element/HTMLTemplateElement.js.map +1 -1
  30. package/lib/nodes/parent-node/ParentNodeUtility.d.ts +3 -3
  31. package/lib/nodes/parent-node/ParentNodeUtility.d.ts.map +1 -1
  32. package/lib/nodes/parent-node/ParentNodeUtility.js +1 -4
  33. package/lib/nodes/parent-node/ParentNodeUtility.js.map +1 -1
  34. package/lib/nodes/shadow-root/ShadowRoot.d.ts.map +1 -1
  35. package/lib/nodes/shadow-root/ShadowRoot.js +1 -3
  36. package/lib/nodes/shadow-root/ShadowRoot.js.map +1 -1
  37. package/lib/range/Range.js.map +1 -1
  38. package/lib/xml-parser/XMLParser.d.ts +14 -38
  39. package/lib/xml-parser/XMLParser.d.ts.map +1 -1
  40. package/lib/xml-parser/XMLParser.js +222 -200
  41. package/lib/xml-parser/XMLParser.js.map +1 -1
  42. package/lib/xml-serializer/XMLSerializer.d.ts.map +1 -1
  43. package/lib/xml-serializer/XMLSerializer.js +11 -7
  44. package/lib/xml-serializer/XMLSerializer.js.map +1 -1
  45. package/package.json +1 -1
  46. package/src/config/PlainTextElements.ts +4 -1
  47. package/src/config/UnnestableElements.ts +18 -18
  48. package/src/config/VoidElements.ts +16 -17
  49. package/src/dom-parser/DOMParser.ts +2 -2
  50. package/src/fetch/Request.ts +34 -0
  51. package/src/fetch/types/IRequest.ts +8 -0
  52. package/src/nodes/document/Document.ts +19 -18
  53. package/src/nodes/element/Element.ts +1 -3
  54. package/src/nodes/html-template-element/HTMLTemplateElement.ts +2 -4
  55. package/src/nodes/parent-node/ParentNodeUtility.ts +13 -11
  56. package/src/nodes/shadow-root/ShadowRoot.ts +1 -3
  57. package/src/range/Range.ts +1 -1
  58. package/src/xml-parser/XMLParser.ts +280 -226
  59. package/src/xml-serializer/XMLSerializer.ts +12 -7
  60. package/lib/config/ChildLessElements.d.ts +0 -3
  61. package/lib/config/ChildLessElements.d.ts.map +0 -1
  62. package/lib/config/ChildLessElements.js +0 -4
  63. package/lib/config/ChildLessElements.js.map +0 -1
  64. package/src/config/ChildLessElements.ts +0 -1
@@ -1,25 +1,59 @@
1
- import Node from '../nodes/node/Node';
2
- import Element from '../nodes/element/Element';
3
1
  import IDocument from '../nodes/document/IDocument';
4
2
  import VoidElements from '../config/VoidElements';
5
3
  import UnnestableElements from '../config/UnnestableElements';
6
- import ChildLessElements from '../config/ChildLessElements';
7
- import { decode } from 'he';
8
4
  import NamespaceURI from '../config/NamespaceURI';
9
5
  import HTMLScriptElement from '../nodes/html-script-element/HTMLScriptElement';
10
- import INode from '../nodes/node/INode';
11
6
  import IElement from '../nodes/element/IElement';
12
7
  import HTMLLinkElement from '../nodes/html-link-element/HTMLLinkElement';
13
- import IDocumentFragment from '../nodes/document-fragment/IDocumentFragment';
14
8
  import PlainTextElements from '../config/PlainTextElements';
9
+ import IDocumentType from '../nodes/document-type/IDocumentType';
10
+ import INode from '../nodes/node/INode';
11
+ import IDocumentFragment from '../nodes/document-fragment/IDocumentFragment';
12
+ import { decode } from 'he';
13
+
14
+ /**
15
+ * Markup RegExp.
16
+ *
17
+ * Group 1: Beginning of start tag (e.g. "div" in "<div").
18
+ * Group 2: End tag (e.g. "div" in "</div>").
19
+ * Group 3: Comment with ending "--" (e.g. " Comment 1 " in "<!-- Comment 1 -->").
20
+ * Group 4: Comment without ending "--" (e.g. " Comment 1 " in "<!-- Comment 1 >").
21
+ * Group 5: Exclamation mark comment (e.g. "DOCTYPE html" in "<!DOCTYPE html>").
22
+ * Group 6: Processing instruction (e.g. "xml version="1.0"?" in "<?xml version="1.0"?>").
23
+ * Group 7: End of self closing start tag (e.g. "/>" in "<img/>").
24
+ * Group 8: End of start tag (e.g. ">" in "<div>").
25
+ */
26
+ const MARKUP_REGEXP =
27
+ /<([a-zA-Z0-9-]+)|<\/([a-zA-Z0-9-]+)>|<!--([^-]+)-->|<!--([^>]+)>|<!([^>]+)>|<\?([^>]+)>|(\/>)|(>)/gm;
28
+
29
+ /**
30
+ * Attribute RegExp.
31
+ *
32
+ * Group 1: Attribute name when the attribute has a value using double apostrophe (e.g. "name" in "<div name="value">").
33
+ * Group 2: Attribute apostrophe value using double apostrophe (e.g. "value" in "<div name="value">").
34
+ * Group 3: Attribute value when the attribute has a value using double apostrophe (e.g. "value" in "<div name="value">").
35
+ * Group 4: Attribute apostrophe when the attribute has a value using double apostrophe (e.g. "value" in "<div name="value">").
36
+ * Group 5: Attribute name when the attribute has a value using single apostrophe (e.g. "name" in "<div name='value'>").
37
+ * Group 6: Attribute apostrophe when the attribute has a value using single apostrophe (e.g. "name" in "<div name='value'>").
38
+ * Group 7: Attribute value when the attribute has a value using single apostrophe (e.g. "value" in "<div name='value'>").
39
+ * Group 8: Attribute apostrophe when the attribute has a value using single apostrophe (e.g. "name" in "<div name='value'>").
40
+ * Group 9: Attribute name when the attribute has no value (e.g. "disabled" in "<div disabled>").
41
+ */
42
+ const ATTRIBUTE_REGEXP =
43
+ /\s*([a-zA-Z0-9-_:]+) *= *("{0,1})([^"]*)("{0,1})|\s*([a-zA-Z0-9-_:]+) *= *('{0,1})([^']*)('{0,1})|\s*([a-zA-Z0-9-_:]+)/gm;
44
+
45
+ enum MarkupReadStateEnum {
46
+ startOrEndTag = 'startOrEndTag',
47
+ insideStartTag = 'insideStartTag',
48
+ plainTextContent = 'plainTextContent'
49
+ }
15
50
 
16
- const CONDITION_COMMENT_REGEXP =
17
- /<!(--)?\[if (!|le|lt|lte|gt|gte|\(.*\)|&|\|| |IE|WindowsEdition|Contoso|true|false|\d+\.?(\d+)?|)*\]>/gi;
18
- const CONDITION_COMMENT_END_REGEXP = /<!\[endif\](--)?>/gi;
19
- const MARKUP_REGEXP = /<(\/?)([a-z][-.0-9_a-z]*)\s*([^<>]*?)(\/?)>/gi;
20
- const COMMENT_REGEXP = /<!--(.*?)-->|<([!?])([^>]*)>/gi;
51
+ /**
52
+ * Document type attribute RegExp.
53
+ *
54
+ * Group 1: Attribute value.
55
+ */
21
56
  const DOCUMENT_TYPE_ATTRIBUTE_REGEXP = /"([^"]+)"/gm;
22
- const ATTRIBUTE_REGEXP = /([^\s=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))/gms;
23
57
 
24
58
  /**
25
59
  * XML parser.
@@ -29,121 +63,233 @@ export default class XMLParser {
29
63
  * Parses XML/HTML and returns a root element.
30
64
  *
31
65
  * @param document Document.
32
- * @param data HTML data.
33
- * @param [evaluateScripts = false] Set to "true" to enable script execution.
34
- * @returns Root element.
66
+ * @param xml XML/HTML string.
67
+ * @param [options] Options.
68
+ * @param [options.rootNode] Node to append elements to. Otherwise a new DocumentFragment is created.
69
+ * @param [options.evaluateScripts = false] Set to "true" to enable script execution.
70
+ * @returns Root node.
35
71
  */
36
72
  public static parse(
37
73
  document: IDocument,
38
- data: string,
39
- evaluateScripts = false
40
- ): IDocumentFragment {
41
- const root = document.createDocumentFragment();
42
- const stack: Array<IElement | IDocumentFragment> = [root];
43
- const markupRegexp = new RegExp(MARKUP_REGEXP, 'gi');
44
- let parent: IDocumentFragment | IElement = root;
45
- let parentTagName = null;
46
- let parentUnnestableTagName = null;
47
- let lastTextIndex = 0;
74
+ xml: string,
75
+ options?: { rootNode?: IElement | IDocumentFragment | IDocument; evaluateScripts?: boolean }
76
+ ): IElement | IDocumentFragment | IDocument {
77
+ const root = options && options.rootNode ? options.rootNode : document.createDocumentFragment();
78
+ const stack: INode[] = [root];
79
+ const markupRegexp = new RegExp(MARKUP_REGEXP, 'gm');
80
+ const { evaluateScripts = false } = options || {};
81
+ const unnestableTagNames: string[] = [];
82
+ let currentNode: INode | null = root;
48
83
  let match: RegExpExecArray;
84
+ let plainTextTagName: string | null = null;
85
+ let readState: MarkupReadStateEnum = MarkupReadStateEnum.startOrEndTag;
86
+ let startTagIndex = 0;
87
+ let lastIndex = 0;
49
88
 
50
- if (data !== null && data !== undefined) {
51
- data = String(data);
52
-
53
- while ((match = markupRegexp.exec(data))) {
54
- const tagName = match[2].toLowerCase();
55
- const isStartTag = !match[1];
56
-
57
- if (parent && match.index !== lastTextIndex) {
58
- const text = data.substring(lastTextIndex, match.index);
59
- if (parentTagName && PlainTextElements.includes(parentTagName)) {
60
- parent.appendChild(document.createTextNode(text));
61
- } else {
62
- let condCommMatch;
63
- let condCommEndMatch;
64
- const condCommRegexp = new RegExp(CONDITION_COMMENT_REGEXP, 'gi');
65
- const condCommEndRegexp = new RegExp(CONDITION_COMMENT_END_REGEXP, 'gi');
66
- // @Refer: https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/?redirectedfrom=MSDN
89
+ if (xml !== null && xml !== undefined) {
90
+ xml = String(xml);
91
+
92
+ while ((match = markupRegexp.exec(xml))) {
93
+ switch (readState) {
94
+ case MarkupReadStateEnum.startOrEndTag:
67
95
  if (
68
- isStartTag &&
69
- (condCommMatch = condCommRegexp.exec(text)) &&
70
- condCommMatch[0] &&
71
- (condCommEndMatch = condCommEndRegexp.exec(data.substring(markupRegexp.lastIndex))) &&
72
- condCommEndMatch[0]
96
+ match.index !== lastIndex &&
97
+ (match[1] || match[2] || match[3] || match[4] || match[5] || match[6])
98
+ ) {
99
+ // Plain text between tags.
100
+
101
+ currentNode.appendChild(
102
+ document.createTextNode(xml.substring(lastIndex, match.index))
103
+ );
104
+ }
105
+
106
+ if (match[1]) {
107
+ // Start tag.
108
+
109
+ const tagName = match[1].toUpperCase();
110
+
111
+ // Some elements are not allowed to be nested (e.g. "<a><a></a></a>" is not allowed.).
112
+ // Therefore we need to auto-close the tag, so that it become valid (e.g. "<a></a><a></a>").
113
+ const unnestableTagNameIndex = unnestableTagNames.indexOf(tagName);
114
+ if (unnestableTagNameIndex !== -1) {
115
+ unnestableTagNames.splice(unnestableTagNameIndex, 1);
116
+ while (currentNode !== root) {
117
+ if ((<IElement>currentNode).tagName === tagName) {
118
+ stack.pop();
119
+ currentNode = stack[stack.length - 1] || root;
120
+ break;
121
+ }
122
+ stack.pop();
123
+ currentNode = stack[stack.length - 1] || root;
124
+ }
125
+ }
126
+
127
+ // NamespaceURI is inherited from the parent element.
128
+ // It should default to SVG for SVG elements.
129
+ const namespaceURI =
130
+ tagName === 'SVG'
131
+ ? NamespaceURI.svg
132
+ : (<IElement>currentNode).namespaceURI || NamespaceURI.html;
133
+ const newElement = document.createElementNS(namespaceURI, tagName);
134
+
135
+ currentNode.appendChild(newElement);
136
+ currentNode = newElement;
137
+ stack.push(currentNode);
138
+ readState = MarkupReadStateEnum.insideStartTag;
139
+ startTagIndex = markupRegexp.lastIndex;
140
+ } else if (match[2]) {
141
+ // End tag.
142
+
143
+ if (match[2].toUpperCase() === (<IElement>currentNode).tagName) {
144
+ // Some elements are not allowed to be nested (e.g. "<a><a></a></a>" is not allowed.).
145
+ // Therefore we need to auto-close the tag, so that it become valid (e.g. "<a></a><a></a>").
146
+ const unnestableTagNameIndex = unnestableTagNames.indexOf(
147
+ (<IElement>currentNode).tagName
148
+ );
149
+ if (unnestableTagNameIndex !== -1) {
150
+ unnestableTagNames.splice(unnestableTagNameIndex, 1);
151
+ }
152
+
153
+ stack.pop();
154
+ currentNode = stack[stack.length - 1] || root;
155
+ }
156
+ } else if (
157
+ match[3] ||
158
+ match[4] ||
159
+ (match[6] && (<IElement>currentNode).namespaceURI === NamespaceURI.html)
73
160
  ) {
74
- markupRegexp.lastIndex += condCommEndRegexp.lastIndex;
75
- continue;
161
+ // Comment.
162
+
163
+ currentNode.appendChild(
164
+ document.createComment((match[6] ? '?' : '') + (match[3] || match[4] || match[6]))
165
+ );
166
+ } else if (match[5]) {
167
+ // Exclamation mark comment (usually <!DOCTYPE>).
168
+
169
+ currentNode.appendChild(
170
+ this.getDocumentTypeNode(document, match[5]) || document.createComment(match[5])
171
+ );
172
+ } else if (match[6]) {
173
+ // Processing instruction (not supported by HTML).
174
+ // TODO: Add support for processing instructions.
76
175
  } else {
77
- this.appendTextAndCommentNodes(document, parent, text);
176
+ // Plain text between tags, including the match as it is not a valid start or end tag.
177
+
178
+ currentNode.appendChild(
179
+ document.createTextNode(xml.substring(lastIndex, markupRegexp.lastIndex))
180
+ );
78
181
  }
79
- }
80
- }
81
182
 
82
- if (isStartTag) {
83
- const namespaceURI =
84
- tagName === 'svg'
85
- ? NamespaceURI.svg
86
- : (<IElement>parent).namespaceURI || NamespaceURI.html;
87
- const newElement = document.createElementNS(namespaceURI, tagName);
88
-
89
- // Scripts are not allowed to be executed when they are parsed using innerHTML, outerHTML, replaceWith() etc.
90
- // However, they are allowed to be executed when document.write() is used.
91
- // See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
92
- if (tagName === 'script') {
93
- (<HTMLScriptElement>newElement)._evaluateScript = evaluateScripts;
94
- }
95
-
96
- // An assumption that the same rule should be applied for the HTMLLinkElement is made here.
97
- if (tagName === 'link') {
98
- (<HTMLLinkElement>newElement)._evaluateCSS = evaluateScripts;
99
- }
100
-
101
- this.setAttributes(newElement, match[3]);
102
-
103
- if (!match[4] && !VoidElements.includes(tagName)) {
104
- // Some elements are not allowed to be nested (e.g. "<a><a></a></a>" is not allowed.).
105
- // Therefore we will auto-close the tag.
106
- if (parentUnnestableTagName === tagName) {
107
- stack.pop();
108
- parent = <Element>parent.parentNode || root;
183
+ break;
184
+ case MarkupReadStateEnum.insideStartTag:
185
+ // End of start tag
186
+ if (match[7] || match[8]) {
187
+ // End of start tag.
188
+
189
+ // Attribute name and value.
190
+
191
+ const attributeString = xml.substring(startTagIndex, match.index);
192
+ let hasAttributeStringEnded = true;
193
+
194
+ if (!!attributeString) {
195
+ const attributeRegexp = new RegExp(ATTRIBUTE_REGEXP, 'gm');
196
+ let attributeMatch: RegExpExecArray;
197
+
198
+ while ((attributeMatch = attributeRegexp.exec(attributeString))) {
199
+ if (
200
+ (attributeMatch[1] && attributeMatch[2] === attributeMatch[4]) ||
201
+ (attributeMatch[5] && attributeMatch[6] === attributeMatch[8]) ||
202
+ attributeMatch[9]
203
+ ) {
204
+ // Valid attribute name and value.
205
+
206
+ const name = attributeMatch[1] || attributeMatch[5] || attributeMatch[9] || '';
207
+ const rawValue = attributeMatch[3] || attributeMatch[7] || '';
208
+ const value = rawValue ? decode(rawValue) : '';
209
+ const namespaceURI =
210
+ (<IElement>currentNode).tagName === 'SVG' && name === 'xmlns' ? value : null;
211
+
212
+ (<IElement>currentNode).setAttributeNS(namespaceURI, name, value);
213
+
214
+ startTagIndex += attributeMatch[0].length;
215
+ } else if (!attributeMatch[4] && !attributeMatch[8]) {
216
+ // End attribute apostrophe is missing (e.g. "attr='value" or 'attr="value').
217
+
218
+ hasAttributeStringEnded = false;
219
+ break;
220
+ }
221
+ }
222
+ }
223
+
224
+ // We need to check if the attribute string is read completely.
225
+ // The attribute string can potentially contain "/>" or ">".
226
+ if (hasAttributeStringEnded) {
227
+ // Checks if the tag is a self closing tag (ends with "/>") or void element.
228
+ // When it is a self closing tag or void element it should be closed immediately.
229
+ // Self closing tags are not allowed in the HTML namespace, but the parser should still allow it for void elements.
230
+ // Self closing tags is supported in the SVG namespace.
231
+ if (
232
+ VoidElements[(<IElement>currentNode).tagName] ||
233
+ (match[7] && (<IElement>currentNode).namespaceURI === NamespaceURI.svg)
234
+ ) {
235
+ stack.pop();
236
+ currentNode = stack[stack.length - 1] || root;
237
+ readState = MarkupReadStateEnum.startOrEndTag;
238
+ } else {
239
+ // Plain text elements such as <script> and <style> should only contain text.
240
+ plainTextTagName = PlainTextElements[(<IElement>currentNode).tagName]
241
+ ? (<IElement>currentNode).tagName
242
+ : null;
243
+
244
+ readState = !!plainTextTagName
245
+ ? MarkupReadStateEnum.plainTextContent
246
+ : MarkupReadStateEnum.startOrEndTag;
247
+
248
+ if (UnnestableElements[(<IElement>currentNode).tagName]) {
249
+ unnestableTagNames.push((<IElement>currentNode).tagName);
250
+ }
251
+ }
252
+
253
+ startTagIndex = markupRegexp.lastIndex;
254
+ }
109
255
  }
110
256
 
111
- parent = <Element>parent.appendChild(newElement);
112
- parentTagName = tagName;
113
- parentUnnestableTagName = this.getUnnestableTagName(parent);
114
- stack.push(parent);
115
- } else {
116
- parent.appendChild(newElement);
117
- }
118
- lastTextIndex = markupRegexp.lastIndex;
119
-
120
- // Tags which contain non-parsed content
121
- // For example: <script> JavaScript should not be parsed
122
- if (ChildLessElements.includes(tagName)) {
123
- let childLessMatch = null;
124
- while ((childLessMatch = markupRegexp.exec(data))) {
125
- if (childLessMatch[2].toLowerCase() === tagName && childLessMatch[1]) {
126
- markupRegexp.lastIndex -= childLessMatch[0].length;
127
- break;
257
+ break;
258
+ case MarkupReadStateEnum.plainTextContent:
259
+ if (match[2] && match[2].toUpperCase() === plainTextTagName) {
260
+ // End of plain text tag.
261
+
262
+ // Scripts are not allowed to be executed when they are parsed using innerHTML, outerHTML, replaceWith() etc.
263
+ // However, they are allowed to be executed when document.write() is used.
264
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
265
+ if (plainTextTagName === 'SCRIPT') {
266
+ (<HTMLScriptElement>currentNode)._evaluateScript = evaluateScripts;
267
+ } else if (plainTextTagName === 'LINK') {
268
+ // An assumption that the same rule should be applied for the HTMLLinkElement is made here.
269
+ (<HTMLLinkElement>currentNode)._evaluateCSS = evaluateScripts;
128
270
  }
271
+
272
+ // Plain text elements such as <script> and <style> should only contain text.
273
+ currentNode.appendChild(
274
+ document.createTextNode(xml.substring(startTagIndex, match.index))
275
+ );
276
+
277
+ stack.pop();
278
+ currentNode = stack[stack.length - 1] || root;
279
+ plainTextTagName = null;
280
+ readState = MarkupReadStateEnum.startOrEndTag;
129
281
  }
130
- }
131
- } else {
132
- stack.pop();
133
- parent = stack[stack.length - 1] || root;
134
- parentTagName = (<IElement>parent).tagName
135
- ? (<IElement>parent).tagName.toLowerCase()
136
- : null;
137
- parentUnnestableTagName = this.getUnnestableTagName(parent);
138
-
139
- lastTextIndex = markupRegexp.lastIndex;
282
+
283
+ break;
140
284
  }
285
+
286
+ lastIndex = markupRegexp.lastIndex;
141
287
  }
142
288
 
143
- // Text after last element
144
- if ((!match && data.length > 0) || (match && lastTextIndex !== match.index)) {
145
- const text = data.substring(lastTextIndex);
146
- this.appendTextAndCommentNodes(document, parent || root, text);
289
+ if (lastIndex !== xml.length) {
290
+ // Plain text after tags.
291
+
292
+ currentNode.appendChild(document.createTextNode(xml.substring(lastIndex)));
147
293
  }
148
294
  }
149
295
 
@@ -151,132 +297,40 @@ export default class XMLParser {
151
297
  }
152
298
 
153
299
  /**
154
- * Returns a tag name if element is unnestable.
155
- *
156
- * @param element Element.
157
- * @returns Tag name if element is unnestable.
158
- */
159
- private static getUnnestableTagName(element: IElement | IDocumentFragment): string {
160
- const tagName = (<IElement>element).tagName ? (<IElement>element).tagName.toLowerCase() : null;
161
- return tagName && UnnestableElements.includes(tagName) ? tagName : null;
162
- }
163
-
164
- /**
165
- * Appends text and comment nodes.
300
+ * Returns document type node.
166
301
  *
167
302
  * @param document Document.
168
- * @param node Node.
169
- * @param text Text to search in.
303
+ * @param value Value.
304
+ * @returns Document type node.
170
305
  */
171
- private static appendTextAndCommentNodes(document: IDocument, node: INode, text: string): void {
172
- for (const innerNode of this.getTextAndCommentNodes(document, text)) {
173
- node.appendChild(innerNode);
306
+ private static getDocumentTypeNode(document: IDocument, value: string): IDocumentType {
307
+ if (!value.toUpperCase().startsWith('DOCTYPE')) {
308
+ return null;
174
309
  }
175
- }
176
310
 
177
- /**
178
- * Returns text and comment nodes from a text.
179
- *
180
- * @param document Document.
181
- * @param text Text to search in.
182
- * @returns Nodes.
183
- */
184
- private static getTextAndCommentNodes(document: IDocument, text: string): Node[] {
185
- const nodes = [];
186
- const commentRegExp = new RegExp(COMMENT_REGEXP, 'gms');
187
- let hasDocumentType = false;
188
- let lastIndex = 0;
189
- let match;
311
+ const docTypeSplit = value.split(' ');
190
312
 
191
- while ((match = commentRegExp.exec(text))) {
192
- if (match.index > 0 && lastIndex !== match.index) {
193
- const textNode = document.createTextNode(text.substring(lastIndex, match.index));
194
- nodes.push(textNode);
195
- }
196
- if (match[3] && match[3].toUpperCase().startsWith('DOCTYPE')) {
197
- const docTypeSplit = match[3].split(' ');
198
-
199
- if (docTypeSplit.length > 1) {
200
- const docTypeString = docTypeSplit.slice(1).join(' ');
201
- const attributes = [];
202
- const attributeRegExp = new RegExp(DOCUMENT_TYPE_ATTRIBUTE_REGEXP, 'gm');
203
- const isPublic = docTypeString.includes('PUBLIC');
204
- let attributeMatch;
205
-
206
- while ((attributeMatch = attributeRegExp.exec(docTypeString))) {
207
- attributes.push(attributeMatch[1]);
208
- }
209
-
210
- const publicId = isPublic ? attributes[0] || '' : '';
211
- const systemId = isPublic ? attributes[1] || '' : attributes[0] || '';
212
-
213
- const documentTypeNode = document.implementation.createDocumentType(
214
- docTypeSplit[1],
215
- publicId,
216
- systemId
217
- );
218
-
219
- nodes.push(documentTypeNode);
220
- hasDocumentType = true;
221
- }
222
- } else {
223
- const comment = match[1] ? match[1] : match[2] === '?' ? '?' + match[3] : match[3];
224
- const commentNode = document.createComment(comment);
225
- nodes.push(commentNode);
226
- lastIndex = match.index + match[0].length;
227
- }
313
+ if (docTypeSplit.length <= 1) {
314
+ return null;
228
315
  }
229
316
 
230
- if (!hasDocumentType && lastIndex < text.length) {
231
- const textNode = document.createTextNode(text.substring(lastIndex));
232
- nodes.push(textNode);
233
- }
317
+ const docTypeString = docTypeSplit.slice(1).join(' ');
318
+ const attributes = [];
319
+ const attributeRegExp = new RegExp(DOCUMENT_TYPE_ATTRIBUTE_REGEXP, 'gm');
320
+ const isPublic = docTypeString.toUpperCase().includes('PUBLIC');
321
+ let attributeMatch;
234
322
 
235
- return nodes;
236
- }
237
-
238
- /**
239
- * Sets raw attributes.
240
- *
241
- * @param element Element.
242
- * @param attributesString Raw attributes.
243
- */
244
- private static setAttributes(element: IElement, attributesString: string): void {
245
- const attributes = attributesString.trim();
246
- if (attributes) {
247
- const regExp = new RegExp(ATTRIBUTE_REGEXP, 'gi');
248
- let match: RegExpExecArray;
249
-
250
- // Attributes with value
251
- while ((match = regExp.exec(attributes))) {
252
- if (match[1]) {
253
- const value = decode(match[2] || match[3] || match[4] || '');
254
- const name = this._getAttributeName(element.namespaceURI, match[1]);
255
- const namespaceURI = element.tagName === 'SVG' && name === 'xmlns' ? value : null;
256
- element.setAttributeNS(namespaceURI, name, value);
257
- }
258
- }
259
-
260
- // Attributes with no value
261
- for (const name of attributes.replace(ATTRIBUTE_REGEXP, '').trim().split(' ')) {
262
- if (name) {
263
- element.setAttribute(this._getAttributeName(element.namespaceURI, name), '');
264
- }
265
- }
323
+ while ((attributeMatch = attributeRegExp.exec(docTypeString))) {
324
+ attributes.push(attributeMatch[1]);
266
325
  }
267
- }
268
326
 
269
- /**
270
- * Returns attribute name.
271
- *
272
- * @param namespaceURI Namespace URI.
273
- * @param name Name.
274
- * @returns Attribute name based on namespace.
275
- */
276
- private static _getAttributeName(namespaceURI: string, name: string): string {
277
- if (namespaceURI === NamespaceURI.svg) {
278
- return name;
279
- }
280
- return name.toLowerCase();
327
+ const publicId = isPublic ? attributes[0] || '' : '';
328
+ const systemId = isPublic ? attributes[1] || '' : attributes[0] || '';
329
+
330
+ return document.implementation.createDocumentType(
331
+ docTypeSplit[1].toLowerCase(),
332
+ publicId,
333
+ systemId
334
+ );
281
335
  }
282
336
  }
@@ -6,6 +6,8 @@ import { escape } from 'he';
6
6
  import INode from '../nodes/node/INode';
7
7
  import IElement from '../nodes/element/IElement';
8
8
  import IHTMLTemplateElement from '../nodes/html-template-element/IHTMLTemplateElement';
9
+ import NodeTypeEnum from '../nodes/node/NodeTypeEnum';
10
+ import IProcessingInstruction from '../nodes/processing-instruction/IProcessingInstruction';
9
11
 
10
12
  /**
11
13
  * Utility for converting an element to string.
@@ -21,16 +23,16 @@ export default class XMLSerializer {
21
23
  */
22
24
  public serializeToString(root: INode, options?: { includeShadowRoots?: boolean }): string {
23
25
  switch (root.nodeType) {
24
- case Node.ELEMENT_NODE:
26
+ case NodeTypeEnum.elementNode:
25
27
  const element = <Element>root;
26
28
  const tagName = element.tagName.toLowerCase();
27
29
 
28
- if (VoidElements.includes(tagName)) {
30
+ if (VoidElements[element.tagName]) {
29
31
  return `<${tagName}${this._getAttributes(element)}>`;
30
32
  }
31
33
 
32
34
  const childNodes =
33
- element.tagName === 'TEMPLATE'
35
+ tagName === 'template'
34
36
  ? (<IHTMLTemplateElement>root).content.childNodes
35
37
  : root.childNodes;
36
38
  let innerHTML = '';
@@ -57,11 +59,14 @@ export default class XMLSerializer {
57
59
  html += this.serializeToString(node, options);
58
60
  }
59
61
  return html;
60
- case Node.COMMENT_NODE:
62
+ case NodeTypeEnum.commentNode:
61
63
  return `<!--${root.textContent}-->`;
62
- case Node.TEXT_NODE:
63
- return root['textContent'];
64
- case Node.DOCUMENT_TYPE_NODE:
64
+ case NodeTypeEnum.processingInstructionNode:
65
+ // TODO: Add support for processing instructions.
66
+ return `<!--?${(<IProcessingInstruction>root).target} ${root.textContent}?-->`;
67
+ case NodeTypeEnum.textNode:
68
+ return root.textContent;
69
+ case NodeTypeEnum.documentTypeNode:
65
70
  const doctype = <DocumentType>root;
66
71
  const identifier = doctype.publicId ? ' PUBLIC' : doctype.systemId ? ' SYSTEM' : '';
67
72
  const publicId = doctype.publicId ? ` "${doctype.publicId}"` : '';
@@ -1,3 +0,0 @@
1
- declare const _default: string[];
2
- export default _default;
3
- //# sourceMappingURL=ChildLessElements.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChildLessElements.d.ts","sourceRoot":"","sources":["../../src/config/ChildLessElements.ts"],"names":[],"mappings":";AAAA,wBAAmC"}
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = ['style', 'script'];
4
- //# sourceMappingURL=ChildLessElements.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChildLessElements.js","sourceRoot":"","sources":["../../src/config/ChildLessElements.ts"],"names":[],"mappings":";;AAAA,kBAAe,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC"}
@@ -1 +0,0 @@
1
- export default ['style', 'script'];