quote.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. /**
  4. * Match all characters that need to be escaped in a string. Modified from
  5. * source to match single quotes instead of double.
  6. *
  7. * Source: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
  8. */
  9. const ESCAPABLE = /[\\\'\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  10. /**
  11. * Map of characters to escape characters.
  12. */
  13. const META_CHARS = new Map([
  14. ["\b", "\\b"],
  15. ["\t", "\\t"],
  16. ["\n", "\\n"],
  17. ["\f", "\\f"],
  18. ["\r", "\\r"],
  19. ["'", "\\'"],
  20. ['"', '\\"'],
  21. ["\\", "\\\\"]
  22. ]);
  23. /**
  24. * Escape any character into its literal JavaScript string.
  25. *
  26. * @param {string} char
  27. * @return {string}
  28. */
  29. function escapeChar(char) {
  30. return (META_CHARS.get(char) ||
  31. `\\u${`0000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  32. }
  33. /**
  34. * Quote a string.
  35. */
  36. function quoteString(str) {
  37. return `'${str.replace(ESCAPABLE, escapeChar)}'`;
  38. }
  39. exports.quoteString = quoteString;
  40. /**
  41. * JavaScript reserved keywords.
  42. */
  43. const RESERVED_WORDS = new Set(("break else new var case finally return void catch for switch while " +
  44. "continue function this with default if throw delete in try " +
  45. "do instanceof typeof abstract enum int short boolean export " +
  46. "interface static byte extends long super char final native synchronized " +
  47. "class float package throws const goto private transient debugger " +
  48. "implements protected volatile double import public let yield").split(" "));
  49. /**
  50. * Test for valid JavaScript identifier.
  51. */
  52. exports.IS_VALID_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
  53. /**
  54. * Check if a variable name is valid.
  55. */
  56. function isValidVariableName(name) {
  57. return (typeof name === "string" &&
  58. !RESERVED_WORDS.has(name) &&
  59. exports.IS_VALID_IDENTIFIER.test(name));
  60. }
  61. exports.isValidVariableName = isValidVariableName;
  62. /**
  63. * Quote JavaScript key access.
  64. */
  65. function quoteKey(key, next) {
  66. return isValidVariableName(key) ? key : next(key);
  67. }
  68. exports.quoteKey = quoteKey;
  69. /**
  70. * Serialize the path to a string.
  71. */
  72. function stringifyPath(path, next) {
  73. let result = "";
  74. for (const key of path) {
  75. if (isValidVariableName(key)) {
  76. result += `.${key}`;
  77. }
  78. else {
  79. result += `[${next(key)}]`;
  80. }
  81. }
  82. return result;
  83. }
  84. exports.stringifyPath = stringifyPath;
  85. //# sourceMappingURL=quote.js.map