serialize.js
9.88 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"use strict";
const xnv = require("xml-name-validator");
const attributeUtils = require("./attributes");
const { NAMESPACES, VOID_ELEMENTS, NODE_TYPES } = require("./constants");
const XML_CHAR = /^(\x09|\x0A|\x0D|[\x20-\uD7FF]|[\uE000-\uFFFD]|(?:[\uD800-\uDBFF][\uDC00-\uDFFF]))*$/u;
const PUBID_CHAR = /^(\x20|\x0D|\x0A|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%])*$/u;
function asciiCaseInsensitiveMatch(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; ++i) {
if ((a.charCodeAt(i) | 32) !== (b.charCodeAt(i) | 32)) {
return false;
}
}
return true;
}
function recordNamespaceInformation(element, map, prefixMap) {
let defaultNamespaceAttrValue = null;
for (let i = 0; i < element.attributes.length; ++i) {
const attr = element.attributes[i];
if (attr.namespaceURI === NAMESPACES.XMLNS) {
if (attr.prefix === null) {
defaultNamespaceAttrValue = attr.value;
continue;
}
let namespaceDefinition = attr.value;
if (namespaceDefinition === NAMESPACES.XML) {
continue;
}
// This is exactly the other way than the spec says, but that's intended.
// All the maps coalesce null to the empty string (explained in the
// spec), so instead of doing that every time, just do it once here.
if (namespaceDefinition === null) {
namespaceDefinition = "";
}
if (
namespaceDefinition in map &&
map[namespaceDefinition].includes(attr.localName)
) {
continue;
}
if (!(namespaceDefinition in map)) {
map[namespaceDefinition] = [];
}
map[namespaceDefinition].push(attr.localName);
prefixMap[attr.localName] = namespaceDefinition;
}
}
return defaultNamespaceAttrValue;
}
function serializeDocumentType(node, namespace, prefixMap, requireWellFormed) {
if (requireWellFormed && !PUBID_CHAR.test(node.publicId)) {
throw new Error("Failed to serialize XML: document type node publicId is not well-formed.");
}
if (
requireWellFormed &&
(!XML_CHAR.test(node.systemId) ||
(node.systemId.includes('"') && node.systemId.includes("'")))
) {
throw new Error("Failed to serialize XML: document type node systemId is not well-formed.");
}
let markup = `<!DOCTYPE ${node.name}`;
if (node.publicId !== "") {
markup += ` PUBLIC "${node.publicId}"`;
} else if (node.systemId !== "") {
markup += " SYSTEM";
}
if (node.systemId !== "") {
markup += ` "${node.systemId}"`;
}
return `${markup}>`;
}
function serializeProcessingInstruction(
node,
namespace,
prefixMap,
requireWellFormed
) {
if (
requireWellFormed &&
(node.target.includes(":") || asciiCaseInsensitiveMatch(node.target, "xml"))
) {
throw new Error("Failed to serialize XML: processing instruction node target is not well-formed.");
}
if (
requireWellFormed &&
(!XML_CHAR.test(node.data) || node.data.includes("?>"))
) {
throw new Error("Failed to serialize XML: processing instruction node data is not well-formed.");
}
return `<?${node.target} ${node.data}?>`;
}
function serializeDocument(
node,
namespace,
prefixMap,
requireWellFormed,
refs
) {
if (requireWellFormed && node.documentElement === null) {
throw new Error("Failed to serialize XML: document does not have a document element.");
}
let serializedDocument = "";
for (const child of node.childNodes) {
serializedDocument += xmlSerialization(
child,
namespace,
prefixMap,
requireWellFormed,
refs
);
}
return serializedDocument;
}
function serializeDocumentFragment(
node,
namespace,
prefixMap,
requireWellFormed,
refs
) {
let markup = "";
for (const child of node.childNodes) {
markup += xmlSerialization(
child,
namespace,
prefixMap,
requireWellFormed,
refs
);
}
return markup;
}
function serializeText(node, namespace, prefixMap, requireWellFormed) {
if (requireWellFormed && !XML_CHAR.test(node.data)) {
throw new Error("Failed to serialize XML: text node data is not well-formed.");
}
return node.data
.replace(/&/ug, "&")
.replace(/</ug, "<")
.replace(/>/ug, ">");
}
function serializeComment(node, namespace, prefixMap, requireWellFormed) {
if (requireWellFormed && !XML_CHAR.test(node.data)) {
throw new Error("Failed to serialize XML: comment node data is not well-formed.");
}
if (
requireWellFormed &&
(node.data.includes("--") || node.data.endsWith("-"))
) {
throw new Error("Failed to serialize XML: found hyphens in illegal places in comment node data.");
}
return `<!--${node.data}-->`;
}
function serializeElement(node, namespace, prefixMap, requireWellFormed, refs) {
if (
requireWellFormed &&
(node.localName.includes(":") || !xnv.name(node.localName))
) {
throw new Error("Failed to serialize XML: element node localName is not a valid XML name.");
}
let markup = "<";
let qualifiedName = "";
let skipEndTag = false;
let ignoreNamespaceDefinitionAttr = false;
const map = { ...prefixMap };
const localPrefixesMap = Object.create(null);
const localDefaultNamespace = recordNamespaceInformation(
node,
map,
localPrefixesMap
);
let inheritedNs = namespace;
const ns = node.namespaceURI;
if (inheritedNs === ns) {
if (localDefaultNamespace !== null) {
ignoreNamespaceDefinitionAttr = true;
}
if (ns === NAMESPACES.XML) {
qualifiedName = `xml:${node.localName}`;
} else {
qualifiedName = node.localName;
}
markup += qualifiedName;
} else {
let { prefix } = node;
let candidatePrefix = attributeUtils.preferredPrefixString(map, ns, prefix);
if (prefix === "xmlns") {
if (requireWellFormed) {
throw new Error("Failed to serialize XML: element nodes can't have a prefix of \"xmlns\".");
}
candidatePrefix = "xmlns";
}
if (candidatePrefix !== null) {
qualifiedName = `${candidatePrefix}:${node.localName}`;
if (
localDefaultNamespace !== null &&
localDefaultNamespace !== NAMESPACES.XML
) {
inheritedNs =
localDefaultNamespace === "" ? null : localDefaultNamespace;
}
markup += qualifiedName;
} else if (prefix !== null) {
if (prefix in localPrefixesMap) {
prefix = attributeUtils.generatePrefix(map, ns, refs.prefixIndex++);
}
if (map[ns]) {
map[ns].push(prefix);
} else {
map[ns] = [prefix];
}
qualifiedName = `${prefix}:${node.localName}`;
markup += `${qualifiedName} xmlns:${prefix}="${attributeUtils.serializeAttributeValue(ns, requireWellFormed)}"`;
if (localDefaultNamespace !== null) {
inheritedNs =
localDefaultNamespace === "" ? null : localDefaultNamespace;
}
} else if (localDefaultNamespace === null || localDefaultNamespace !== ns) {
ignoreNamespaceDefinitionAttr = true;
qualifiedName = node.localName;
inheritedNs = ns;
markup += `${qualifiedName} xmlns="${attributeUtils.serializeAttributeValue(ns, requireWellFormed)}"`;
} else {
qualifiedName = node.localName;
inheritedNs = ns;
markup += qualifiedName;
}
}
markup += attributeUtils.serializeAttributes(
node,
map,
localPrefixesMap,
ignoreNamespaceDefinitionAttr,
requireWellFormed,
refs
);
if (
ns === NAMESPACES.HTML &&
node.childNodes.length === 0 &&
VOID_ELEMENTS.has(node.localName)
) {
markup += " /";
skipEndTag = true;
} else if (ns !== NAMESPACES.HTML && node.childNodes.length === 0) {
markup += "/";
skipEndTag = true;
}
markup += ">";
if (skipEndTag) {
return markup;
}
if (ns === NAMESPACES.HTML && node.localName === "template") {
markup += xmlSerialization(
node.content,
inheritedNs,
map,
requireWellFormed,
refs
);
} else {
for (const child of node.childNodes) {
markup += xmlSerialization(
child,
inheritedNs,
map,
requireWellFormed,
refs
);
}
}
markup += `</${qualifiedName}>`;
return markup;
}
function serializeCDATASection(node) {
return `<![CDATA[${node.data}]]>`;
}
/**
* @param {{prefixIndex: number}} refs
*/
function xmlSerialization(node, namespace, prefixMap, requireWellFormed, refs) {
switch (node.nodeType) {
case NODE_TYPES.ELEMENT_NODE:
return serializeElement(
node,
namespace,
prefixMap,
requireWellFormed,
refs
);
case NODE_TYPES.DOCUMENT_NODE:
return serializeDocument(
node,
namespace,
prefixMap,
requireWellFormed,
refs
);
case NODE_TYPES.COMMENT_NODE:
return serializeComment(node, namespace, prefixMap, requireWellFormed);
case NODE_TYPES.TEXT_NODE:
return serializeText(node, namespace, prefixMap, requireWellFormed);
case NODE_TYPES.DOCUMENT_FRAGMENT_NODE:
return serializeDocumentFragment(
node,
namespace,
prefixMap,
requireWellFormed,
refs
);
case NODE_TYPES.DOCUMENT_TYPE_NODE:
return serializeDocumentType(
node,
namespace,
prefixMap,
requireWellFormed
);
case NODE_TYPES.PROCESSING_INSTRUCTION_NODE:
return serializeProcessingInstruction(
node,
namespace,
prefixMap,
requireWellFormed
);
case NODE_TYPES.ATTRIBUTE_NODE:
return "";
case NODE_TYPES.CDATA_SECTION_NODE:
return serializeCDATASection(node);
default:
throw new TypeError("Failed to serialize XML: only Nodes can be serialized.");
}
}
module.exports = (root, { requireWellFormed = false } = {}) => {
const namespacePrefixMap = Object.create(null);
namespacePrefixMap["http://www.w3.org/XML/1998/namespace"] = ["xml"];
return xmlSerialization(root, null, namespacePrefixMap, requireWellFormed, {
prefixIndex: 1
});
};