utils.cjs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. 'use strict';
  2. function isIterable(value) {
  3. return (
  4. typeof value === 'object' &&
  5. value !== null &&
  6. (
  7. typeof value[Symbol.iterator] === 'function' ||
  8. typeof value[Symbol.asyncIterator] === 'function'
  9. )
  10. );
  11. }
  12. function replaceValue(holder, key, value, replacer) {
  13. if (value && typeof value.toJSON === 'function') {
  14. value = value.toJSON();
  15. }
  16. if (replacer !== null) {
  17. value = replacer.call(holder, String(key), value);
  18. }
  19. switch (typeof value) {
  20. case 'function':
  21. case 'symbol':
  22. value = undefined;
  23. break;
  24. case 'object':
  25. if (value !== null) {
  26. const cls = value.constructor;
  27. if (cls === String || cls === Number || cls === Boolean) {
  28. value = value.valueOf();
  29. }
  30. }
  31. break;
  32. }
  33. return value;
  34. }
  35. function normalizeReplacer(replacer) {
  36. if (typeof replacer === 'function') {
  37. return replacer;
  38. }
  39. if (Array.isArray(replacer)) {
  40. const allowlist = new Set(replacer
  41. .map(item => {
  42. const cls = item && item.constructor;
  43. return cls === String || cls === Number ? String(item) : null;
  44. })
  45. .filter(item => typeof item === 'string')
  46. );
  47. return [...allowlist];
  48. }
  49. return null;
  50. }
  51. function normalizeSpace(space) {
  52. if (typeof space === 'number') {
  53. if (!Number.isFinite(space) || space < 1) {
  54. return false;
  55. }
  56. return ' '.repeat(Math.min(space, 10));
  57. }
  58. if (typeof space === 'string') {
  59. return space.slice(0, 10) || false;
  60. }
  61. return false;
  62. }
  63. function normalizeStringifyOptions(optionsOrReplacer, space) {
  64. if (optionsOrReplacer === null || Array.isArray(optionsOrReplacer) || typeof optionsOrReplacer !== 'object') {
  65. optionsOrReplacer = {
  66. replacer: optionsOrReplacer,
  67. space
  68. };
  69. }
  70. let replacer = normalizeReplacer(optionsOrReplacer.replacer);
  71. let getKeys = Object.keys;
  72. if (Array.isArray(replacer)) {
  73. const allowlist = replacer;
  74. getKeys = () => allowlist;
  75. replacer = null;
  76. }
  77. return {
  78. ...optionsOrReplacer,
  79. replacer,
  80. getKeys,
  81. space: normalizeSpace(optionsOrReplacer.space)
  82. };
  83. }
  84. exports.isIterable = isIterable;
  85. exports.normalizeReplacer = normalizeReplacer;
  86. exports.normalizeSpace = normalizeSpace;
  87. exports.normalizeStringifyOptions = normalizeStringifyOptions;
  88. exports.replaceValue = replaceValue;