forked from prettier/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser-parse5.js
More file actions
50 lines (45 loc) · 1.17 KB
/
Copy pathparser-parse5.js
File metadata and controls
50 lines (45 loc) · 1.17 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
"use strict";
// const createError = require("./parser-create-error");
function parse(text /*, parsers, opts*/) {
// Inline the require to avoid loading all the JS if we don't use it
const parse5 = require("parse5");
try {
const isFragment = !/^\s*<(!doctype|html|head|body)/i.test(text);
const ast = (isFragment ? parse5.parseFragment : parse5.parse)(text, {
treeAdapter: parse5.treeAdapters.htmlparser2,
locationInfo: true
});
return extendAst(ast);
} catch (error) {
// throw createError(error.message, {
// start: {
// line: error.locations[0].line,
// column: error.locations[0].column
// }
// } else {
throw error;
// }
}
}
function extendAst(ast) {
if (!ast || !ast.children) {
return ast;
}
for (const child of ast.children) {
extendAst(child);
if (child.attribs) {
child.attributes = convertAttribs(child.attribs);
}
}
return ast;
}
function convertAttribs(attribs) {
return Object.keys(attribs).map(attributeKey => {
return {
type: "attribute",
key: attributeKey,
value: attribs[attributeKey]
};
});
}
module.exports = parse;