decode.js
2.2 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
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeHTML = exports.decodeHTMLStrict = exports.decodeXML = void 0;
var entities_json_1 = __importDefault(require("./maps/entities.json"));
var legacy_json_1 = __importDefault(require("./maps/legacy.json"));
var xml_json_1 = __importDefault(require("./maps/xml.json"));
var decode_codepoint_1 = __importDefault(require("./decode_codepoint"));
var strictEntityRe = /&(?:[a-zA-Z0-9]+|#[xX][\da-fA-F]+|#\d+);/g;
exports.decodeXML = getStrictDecoder(xml_json_1.default);
exports.decodeHTMLStrict = getStrictDecoder(entities_json_1.default);
function getStrictDecoder(map) {
var replace = getReplacer(map);
return function (str) { return String(str).replace(strictEntityRe, replace); };
}
var sorter = function (a, b) { return (a < b ? 1 : -1); };
exports.decodeHTML = (function () {
var legacy = Object.keys(legacy_json_1.default).sort(sorter);
var keys = Object.keys(entities_json_1.default).sort(sorter);
for (var i = 0, j = 0; i < keys.length; i++) {
if (legacy[j] === keys[i]) {
keys[i] += ";?";
j++;
}
else {
keys[i] += ";";
}
}
var re = new RegExp("&(?:" + keys.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g");
var replace = getReplacer(entities_json_1.default);
function replacer(str) {
if (str.substr(-1) !== ";")
str += ";";
return replace(str);
}
// TODO consider creating a merged map
return function (str) { return String(str).replace(re, replacer); };
})();
function getReplacer(map) {
return function replace(str) {
if (str.charAt(1) === "#") {
var secondChar = str.charAt(2);
if (secondChar === "X" || secondChar === "x") {
return decode_codepoint_1.default(parseInt(str.substr(3), 16));
}
return decode_codepoint_1.default(parseInt(str.substr(2), 10));
}
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
return map[str.slice(1, -1)] || str;
};
}