decode.js 2.2 KB

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