-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
36 lines (35 loc) · 1.1 KB
/
index.ts
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
import { encode } from "he";
import * as sanitizeXMLCharacters from "sanitize-xml-string";
export default html;
export type HTML = string;
export function html(
template: TemplateStringsArray,
...substitutions: (string | string[])[]
): HTML {
const templatePartsSanitized = template.map((templatePart) =>
sanitizeXMLCharacters.sanitize(templatePart)
);
const substitutionsSanitized = [
...substitutions.map((substitution) =>
(Array.isArray(substitution) ? substitution : [substitution]).map(
(substitutionPart) =>
sanitizeXMLCharacters.sanitize(String(substitutionPart))
)
),
[],
];
const buffer = new Array<string>();
for (const index of templatePartsSanitized.keys()) {
let templatePart = templatePartsSanitized[index];
let substitution = substitutionsSanitized[index];
if (templatePart.endsWith("$")) {
templatePart = templatePart.slice(0, -1);
} else {
substitution = substitution.map((substitutionPart) =>
encode(substitutionPart)
);
}
buffer.push(templatePart, ...substitution);
}
return buffer.join("");
}