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.

67 lines
2.4 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 xml_json_1 = __importDefault(require("./maps/xml.json"));
  7. var inverseXML = getInverseObj(xml_json_1.default);
  8. var xmlReplacer = getInverseReplacer(inverseXML);
  9. exports.encodeXML = getInverse(inverseXML, xmlReplacer);
  10. var entities_json_1 = __importDefault(require("./maps/entities.json"));
  11. var inverseHTML = getInverseObj(entities_json_1.default);
  12. var htmlReplacer = getInverseReplacer(inverseHTML);
  13. exports.encodeHTML = getInverse(inverseHTML, htmlReplacer);
  14. function getInverseObj(obj) {
  15. return Object.keys(obj)
  16. .sort()
  17. .reduce(function (inverse, name) {
  18. inverse[obj[name]] = "&" + name + ";";
  19. return inverse;
  20. }, {});
  21. }
  22. function getInverseReplacer(inverse) {
  23. var single = [];
  24. var multiple = [];
  25. Object.keys(inverse).forEach(function (k) {
  26. return k.length === 1
  27. ? // Add value to single array
  28. single.push("\\" + k)
  29. : // Add value to multiple array
  30. multiple.push(k);
  31. });
  32. //TODO add ranges
  33. multiple.unshift("[" + single.join("") + "]");
  34. return new RegExp(multiple.join("|"), "g");
  35. }
  36. var reNonASCII = /[^\0-\x7F]/g;
  37. var reAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  38. function singleCharReplacer(c) {
  39. return "&#x" + c
  40. .charCodeAt(0)
  41. .toString(16)
  42. .toUpperCase() + ";";
  43. }
  44. // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any
  45. function astralReplacer(c, _) {
  46. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  47. var high = c.charCodeAt(0);
  48. var low = c.charCodeAt(1);
  49. var codePoint = (high - 0xd800) * 0x400 + low - 0xdc00 + 0x10000;
  50. return "&#x" + codePoint.toString(16).toUpperCase() + ";";
  51. }
  52. function getInverse(inverse, re) {
  53. return function (data) {
  54. return data
  55. .replace(re, function (name) { return inverse[name]; })
  56. .replace(reAstralSymbols, astralReplacer)
  57. .replace(reNonASCII, singleCharReplacer);
  58. };
  59. }
  60. var reXmlChars = getInverseReplacer(inverseXML);
  61. function escape(data) {
  62. return data
  63. .replace(reXmlChars, singleCharReplacer)
  64. .replace(reAstralSymbols, astralReplacer)
  65. .replace(reNonASCII, singleCharReplacer);
  66. }
  67. exports.escape = escape;