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.

50 lines
2.3 KiB

4 years ago
  1. 'use strict';
  2. var JSON3 = require('json3');
  3. // Some extra characters that Chrome gets wrong, and substitutes with
  4. // something else on the wire.
  5. // eslint-disable-next-line no-control-regex
  6. var extraEscapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g
  7. , extraLookup;
  8. // This may be quite slow, so let's delay until user actually uses bad
  9. // characters.
  10. var unrollLookup = function(escapable) {
  11. var i;
  12. var unrolled = {};
  13. var c = [];
  14. for (i = 0; i < 65536; i++) {
  15. c.push( String.fromCharCode(i) );
  16. }
  17. escapable.lastIndex = 0;
  18. c.join('').replace(escapable, function(a) {
  19. unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  20. return '';
  21. });
  22. escapable.lastIndex = 0;
  23. return unrolled;
  24. };
  25. // Quote string, also taking care of unicode characters that browsers
  26. // often break. Especially, take care of unicode surrogates:
  27. // http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates
  28. module.exports = {
  29. quote: function(string) {
  30. var quoted = JSON3.stringify(string);
  31. // In most cases this should be very fast and good enough.
  32. extraEscapable.lastIndex = 0;
  33. if (!extraEscapable.test(quoted)) {
  34. return quoted;
  35. }
  36. if (!extraLookup) {
  37. extraLookup = unrollLookup(extraEscapable);
  38. }
  39. return quoted.replace(extraEscapable, function(a) {
  40. return extraLookup[a];
  41. });
  42. }
  43. };