-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathextractors.js
64 lines (54 loc) · 1.55 KB
/
extractors.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
'use strict';
/**
* Extracts all the {{...}} and {{{...}}} from the text
* and replaces them with ==HANDLEBARS_ID_<num>==.
*
* This is used so the markdown parser doesn't see the
* content of the handlebars and much it up.
*
* @param {string} content
* @returns {content: string, handlebars: *}
*/
function extractHandlebars(content) {
// Yes, this is 💩 but I don't really want to write a parser.
const escapeHtmlRE = /\{\{#escapehtml\}\}[\s\S]*?\{\{\/escapehtml\}\}/g;
const tripleRE = /\{\{\{[\s\S]*?\}\}\}/g;
const doubleRE = /\{\{[\s\S]*?\}\}/g;
let numExtractions = 0;
const handlebars = {
};
function saveHandlebar(match) {
const id = `==HANDLEBARS_ID_${++numExtractions}==`;
handlebars[id] = match;
return id;
}
content = content.replace(escapeHtmlRE, saveHandlebar);
content = content.replace(tripleRE, saveHandlebar);
content = content.replace(doubleRE, saveHandlebar);
return {
content,
handlebars,
};
}
/**
* Reinserts the previously extracted handlebars
* @param {*} handlebars returned from extractHandlebars
* @param {string} content
* @returns {string}
*/
function insertHandlebars(handlebars, content) {
const handlebarRE = /==HANDLEBARS_ID_\d+==/g;
function restoreHandlebar(match) {
const value = handlebars[match];
if (value === undefined) {
throw new Error(`no match restoring handlebar for: ${match}`);
}
return value;
}
content = content.replace(handlebarRE, restoreHandlebar);
return content;
}
module.exports = {
extractHandlebars,
insertHandlebars,
};