index.cjs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
  3. const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
  4. const JsonSigRx = /^["{[]|^-?[0-9][0-9.]{0,14}$/;
  5. function jsonParseTransform(key, value) {
  6. if (key === "__proto__" || key === "constructor") {
  7. return;
  8. }
  9. return value;
  10. }
  11. function destr(val) {
  12. if (typeof val !== "string") {
  13. return val;
  14. }
  15. const _lval = val.toLowerCase();
  16. if (_lval === "true") {
  17. return true;
  18. }
  19. if (_lval === "false") {
  20. return false;
  21. }
  22. if (_lval === "null") {
  23. return null;
  24. }
  25. if (_lval === "nan") {
  26. return NaN;
  27. }
  28. if (_lval === "infinity") {
  29. return Infinity;
  30. }
  31. if (_lval === "undefined") {
  32. return void 0;
  33. }
  34. if (!JsonSigRx.test(val)) {
  35. return val;
  36. }
  37. try {
  38. if (suspectProtoRx.test(val) || suspectConstructorRx.test(val)) {
  39. return JSON.parse(val, jsonParseTransform);
  40. }
  41. return JSON.parse(val);
  42. } catch (_e) {
  43. return val;
  44. }
  45. }
  46. module.exports = destr;