You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.1 KiB

4 years ago
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. var entities_json_1 = __importDefault(require("./maps/entities.json"));
  7. var legacy_json_1 = __importDefault(require("./maps/legacy.json"));
  8. var xml_json_1 = __importDefault(require("./maps/xml.json"));
  9. var decode_codepoint_1 = __importDefault(require("./decode_codepoint"));
  10. exports.decodeXML = getStrictDecoder(xml_json_1.default);
  11. exports.decodeHTMLStrict = getStrictDecoder(entities_json_1.default);
  12. function getStrictDecoder(map) {
  13. var keys = Object.keys(map).join("|");
  14. var replace = getReplacer(map);
  15. keys += "|#[xX][\\da-fA-F]+|#\\d+";
  16. var re = new RegExp("&(?:" + keys + ");", "g");
  17. return function (str) { return String(str).replace(re, replace); };
  18. }
  19. var sorter = function (a, b) { return (a < b ? 1 : -1); };
  20. exports.decodeHTML = (function () {
  21. var legacy = Object.keys(legacy_json_1.default).sort(sorter);
  22. var keys = Object.keys(entities_json_1.default).sort(sorter);
  23. for (var i = 0, j = 0; i < keys.length; i++) {
  24. if (legacy[j] === keys[i]) {
  25. keys[i] += ";?";
  26. j++;
  27. }
  28. else {
  29. keys[i] += ";";
  30. }
  31. }
  32. var re = new RegExp("&(?:" + keys.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g");
  33. var replace = getReplacer(entities_json_1.default);
  34. function replacer(str) {
  35. if (str.substr(-1) !== ";")
  36. str += ";";
  37. return replace(str);
  38. }
  39. //TODO consider creating a merged map
  40. return function (str) {
  41. return String(str).replace(re, replacer);
  42. };
  43. })();
  44. function getReplacer(map) {
  45. return function replace(str) {
  46. if (str.charAt(1) === "#") {
  47. if (str.charAt(2) === "X" || str.charAt(2) === "x") {
  48. return decode_codepoint_1.default(parseInt(str.substr(3), 16));
  49. }
  50. return decode_codepoint_1.default(parseInt(str.substr(2), 10));
  51. }
  52. return map[str.slice(1, -1)];
  53. };
  54. }