All files / utils/converter stringify.ts

86.11% Statements 62/72
78.94% Branches 60/76
100% Functions 3/3
85.71% Lines 60/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 19829x                                                                                                                 29x 1262x 1262x   1262x 1262x 1262x       1262x 2x     1260x 2x     1258x 127x 127x   2x       1131x 30x 30x     1101x 3x 3x 3x 3x         1x     1098x 3x 3x 3x 3x         1x     1095x 1x 1x           1094x   1094x 1094x 1094x             968x       126x       126x 28x   28x 28x 484x 484x   457x 224x 2x   222x   222x 1x     1x     454x           28x   8x       8x 8x 8x           98x                     1262x            
import { isNotNullable } from '../common/is-not-nullable.ts';
 
/**
 * Options for the stringify function
 */
export type StringifyOptions = {
  /**
   * Whether to include stack traces for errors (default: false)
   */
  readonly includeStack?: boolean;
 
  /**
   * Whether to prettify the output with indentation (default: false)
   */
  readonly pretty?: boolean;
 
  /**
   * Maximum depth for recursive object serialization (default: 5)
   */
  readonly maxDepth?: number;
 
  /**
   * Format dates using the local locale instead of ISO format (default: false) When true, uses `toLocaleString()`
   * instead of `toISOString()`
   */
  readonly useLocale?: boolean;
};
 
/**
 * Converts a given value into a string representation that is appropriate for log events. This function is guaranteed
 * to never throw an error, making it safe for logging contexts.
 *
 * @example Simple usage
 *
 * ```ts
 * const str = stringify({ key: 'value' });
 * ```
 *
 * @example With options
 *
 * ```ts
 * // Include stack trace for errors
 * const error = new Error('Something went wrong');
 * const strWithStack = stringify(error, { includeStack: true });
 *
 * // Pretty format objects
 * const strPretty = stringify(complexObject, { pretty: true });
 *
 * // Format dates using locale
 * const date = new Date();
 * const localDate = stringify(date, { useLocale: true });
 * ```
 *
 * @param {unknown} value - The value to convert into a string.
 * @param {StringifyOptions} [options] - Optional configuration for stringification.
 * @returns {string} The string representation of the value.
 */
export const stringify = (value: unknown, options?: StringifyOptions): string => {
  try {
    const { includeStack = false, pretty = false, maxDepth = 5, useLocale = false } = options || {};
 
    const stringifyInternal = (val: unknown, depth = 0): string => {
      try {
        Iif (depth > maxDepth && typeof val === 'object' && isNotNullable(val)) {
          return Array.isArray(val) ? `Array(${val.length})` : '[object Object]';
        }
 
        if (val === undefined) {
          return 'undefined';
        }
 
        if (val === null) {
          return 'null';
        }
 
        if (val instanceof Date) {
          try {
            return useLocale ? val.toLocaleString() : val.toISOString().replace('T', ' ').slice(0, -1);
          } catch {
            return '[Invalid Date]';
          }
        }
 
        if (val instanceof Error) {
          const message = val.message || val.name || '[unknown error]';
          return includeStack && val.stack ? `${message}\n${val.stack}` : message;
        }
 
        if (val instanceof Map) {
          Eif (depth < maxDepth) {
            try {
              const entries: unknown = Object.fromEntries(val);
              return pretty ? JSON.stringify(entries, undefined, 2) : JSON.stringify(entries);
            } catch {
              // ignore
            }
          }
          return `Map(${val.size})`;
        }
 
        if (val instanceof Set) {
          Eif (depth < maxDepth) {
            try {
              const array = Array.from(val);
              return pretty ? JSON.stringify(array, undefined, 2) : JSON.stringify(array);
            } catch {
              // ignore
            }
          }
          return `Set(${val.size})`;
        }
 
        if (val instanceof RegExp) {
          try {
            return val.toString();
          } catch {
            return '[RegExp]';
          }
        }
 
        try {
          // eslint-disable-next-line @typescript-eslint/no-base-to-string
          const stringValue = String(val);
          const type = typeof val;
          switch (type) {
            case 'boolean':
            case 'number':
            case 'string':
            case 'bigint':
            case 'symbol':
            case 'function':
              return stringValue;
 
            default: {
              // Handle objects (including arrays)
              Iif (depth >= maxDepth) {
                return Array.isArray(val) ? `Array(${val.length})` : '[object Object]';
              }
 
              if (stringValue === '[object Object]' || Array.isArray(val)) {
                try {
                  // For depth limiting and circular references
                  const seen = new WeakSet();
                  const replacer = (key: string, val2: unknown) => {
                    try {
                      if (key === '') return val2;
 
                      if (typeof val2 === 'object' && isNotNullable(val2)) {
                        if (seen.has(val2)) {
                          return '[Circular]';
                        }
                        seen.add(val2);
 
                        if (depth + 1 >= maxDepth) {
                          Iif (Array.isArray(val2)) {
                            return `Array(${val2.length})`;
                          }
                          return '[object Object]';
                        }
                      }
                      return val2;
                    } catch {
                      return '[Error in replacer]';
                    }
                  };
 
                  return pretty ? JSON.stringify(val, replacer, 2) : JSON.stringify(val, replacer);
                } catch {
                  Iif (Array.isArray(val)) {
                    return `Array(${val.length})`;
                  }
 
                  try {
                    const keys = Object.keys(val as object);
                    return `{${keys.join(', ')}}`;
                  } catch {
                    return stringValue;
                  }
                }
              }
              return stringValue;
            }
          }
        } catch {
          return '[Non-stringifiable value]';
        }
      } catch {
        return '[Stringify error]';
      }
    };
 
    return stringifyInternal(value);
  } catch {
    // Absolute last resort fallback
    return '[Stringify fatal error]';
  }
};