-
Notifications
You must be signed in to change notification settings - Fork 20
/
parse.js
80 lines (69 loc) · 1.7 KB
/
parse.js
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
const get = require('lodash.get');
const set = require('lodash.set');
const parser = require('posthtml-parser');
/**
* Parse file content (html) and categorize it by tag and type
*
* @param {string} content
* @returns {object}
*/
module.exports.default = function (content) {
let output = {};
const nodes = parser(content);
nodes.forEach((node) => {
if (typeof node == 'object' && isCorrectTag(node)) {
append(output, [node.tag, getType(node)], getContent(node));
}
});
return output;
}
/**
* Add property of given path to the object
*
* @param {object} object
* @param {array} path
* @param {string} value
*/
function append(object, path, value) {
set(object, path, get(object, path, '') + `\r\n${value}`);
}
/**
* Get code content of given tag (node)
* @param {object} node
* @returns {string}
*/
function getContent(node) {
return (node.content || []).join(' ');
}
/**
* Get tag type property
* @param {object} node
* @returns {string}
*/
function getType(node) {
const tagLoaders = {
script: 'javascript',
style: 'text/css'
};
if(typeof node.attrs == 'undefined' || typeof node.attrs.type == 'undefined')
return tagLoaders[node.tag];
return node.attrs.type;
}
/**
* Verify tag is either `script` or `style`
*
* @param {object} node
* @returns {boolean}
*/
function isCorrectTag(node) {
return node.tag === 'script' || node.tag === 'style';
}
/*
* Export private functions for testing purposes
*/
if (process.env.NODE_ENV === 'test') {
module.exports.append = append;
module.exports.getContent = getContent;
module.exports.getType = getType;
module.exports.isCorrectTag = isCorrectTag;
}