All files / utils/converter stringify.ts

86.95% Statements 80/92
90.58% Branches 77/85
100% Functions 4/4
86.51% Lines 77/89

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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 26130x                                                                                                                                               30x               1348x   1348x 2762x 2762x               2254x     508x 134x 134x   4x       374x 30x 30x 30x           344x 6x 6x 6x               338x 7x 7x 7x               331x 4x 4x           327x 2x     325x 15x   310x   310x 21x 21x 8x 8x 8x     21x 841x                 289x 289x 98x     191x 185x 185x 185x 2x     183x 4x 4x 4x 4x 106x 106x     4x 4x 4x   4x     183x 183x 563x   180x           9x                 1348x 1348x 1348x   1131x               167x     50x 50x   4x       4x 4x 4x                         1348x 1348x 1348x          
import { exhaustiveCheck } from '../common/exhaustive-check.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). Use a negative number to disable the depth limit.
   */
  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;
 
  /**
   * Maximum number of array elements to show before truncating (default: 100) Use a negative number to disable the
   * array element limit.
   */
  readonly maxArrayElements?: number;
 
  /**
   * Maximum number of object properties to show before truncating (default: 50) Use a negative number to disable the
   * object property limit.
   */
  readonly maxProperties?: number;
};
 
/**
 * 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
 * import { stringify } from 'emitnlog/utils';
 * const str = stringify({ key: 'value' });
 * ```
 *
 * @example With options
 *
 * ```ts
 * import { stringify } from 'emitnlog/utils';
 *
 * // 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 => {
  const {
    includeStack = false,
    pretty = false,
    maxDepth = 5,
    useLocale = false,
    maxArrayElements = 100,
    maxProperties = 50,
  } = options || {};
 
  const prepare = (val: unknown, depth = 0, seen = new WeakSet()): unknown => {
    const type = typeof val;
    switch (type) {
      case 'string':
      case 'number':
      case 'bigint':
      case 'boolean':
      case 'undefined':
      case 'symbol':
      case 'function':
        return val;
 
      case 'object': {
        if (val instanceof Date) {
          try {
            return useLocale ? val.toLocaleString() : val.toISOString();
          } catch {
            return '[Invalid Date]';
          }
        }
 
        if (val instanceof Error) {
          try {
            const message = val.message || val.name || '[unknown error]';
            return includeStack && val.stack ? `${message}\n${val.stack}` : message;
          } catch {
            return '[Invalid Error]';
          }
        }
 
        if (val instanceof Map) {
          Eif (maxDepth < 0 || depth < maxDepth) {
            try {
              return prepare(Object.fromEntries(val), depth + 1, seen);
            } catch {
              // ignore
            }
          }
          return `Map(${val.size})`;
        }
 
        if (val instanceof Set) {
          Eif (maxDepth < 0 || depth < maxDepth) {
            try {
              return prepare(Array.from(val), depth + 1, seen);
            } catch {
              // ignore
            }
          }
          return `Set(${val.size})`;
        }
 
        if (val instanceof RegExp) {
          try {
            return val.toString();
          } catch {
            return '[RegExp]';
          }
        }
 
        if (!val) {
          return val;
        }
 
        if (seen.has(val)) {
          return '[Circular Reference]';
        }
        seen.add(val);
 
        if (Array.isArray(val)) {
          Eif (maxDepth < 0 || depth < maxDepth) {
            if (maxArrayElements >= 0 && val.length > maxArrayElements) {
              const truncatedArray = val.slice(0, maxArrayElements);
              truncatedArray.push(`...(${val.length - maxArrayElements})`);
              val = truncatedArray;
            }
 
            try {
              return (val as unknown[]).map((item) => prepare(item, depth + 1, seen));
            } catch {
              // ignore
            }
          }
          return `Array(${(val as unknown[]).length})`;
        }
 
        // eslint-disable-next-line @typescript-eslint/no-base-to-string
        const stringValue = String(val);
        if (stringValue !== '[object Object]') {
          return stringValue;
        }
 
        if (maxDepth < 0 || depth < maxDepth) {
          try {
            let keys = Object.keys(val);
            if (!keys.length) {
              return '{}';
            }
 
            if (maxProperties >= 0 && keys.length > maxProperties) {
              const originalLength = keys.length;
              keys = keys.slice(0, maxProperties);
              const truncatedObj: Record<string, unknown> = {};
              for (let i = 0; i < maxProperties; i++) {
                const key = keys[i];
                truncatedObj[key] = (val as Record<string, unknown>)[key];
              }
 
              const truncatedKey = `...(${originalLength - maxProperties})`;
              keys.push(truncatedKey);
              truncatedObj[truncatedKey] = '...';
 
              val = truncatedObj;
            }
 
            const result: Record<string, unknown> = {};
            for (const key of keys) {
              result[key] = prepare((val as Record<string, unknown>)[key], depth + 1, seen);
            }
            return result;
          } catch {
            // ignore
          }
        }
 
        return '[object Object]';
      }
 
      default:
        exhaustiveCheck(type);
        return val;
    }
  };
 
  const convert = (val: unknown): string => {
    const type = typeof val;
    switch (type) {
      case 'string':
        return val as string;
 
      case 'number':
      case 'bigint':
      case 'boolean':
      case 'undefined':
      case 'symbol':
      case 'function':
        return String(val);
 
      case 'object': {
        try {
          return pretty ? JSON.stringify(val, undefined, 2) : JSON.stringify(val);
        } catch {
          Iif (Array.isArray(val)) {
            return `Array(${val.length})`;
          }
 
          try {
            const keys = Object.keys(val as object);
            return `{${keys.join(', ')}}`;
          } catch {
            return String(val);
          }
        }
      }
 
      default:
        exhaustiveCheck(type);
        return String(val);
    }
  };
 
  try {
    const converted = prepare(value);
    return convert(converted);
  } catch {
    return '[Stringify Error]';
  }
};