All files / src/utils/converter stringify.ts

89.77% Statements 158/176
88.77% Branches 87/98
100% Functions 4/4
89.77% Lines 158/176

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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 3111x                                                                                                                                                                                                               1x 844x 844x 844x 844x 844x 844x 844x 844x   844x 2294x 2294x 2294x 2294x 2294x 2294x 2294x 2294x 2294x 1714x   2294x 580x 264x 264x 264x 4x 4x 264x   462x 44x 44x 44x 44x     44x   445x 7x 6x 6x 6x     6x 1x 1x   445x 8x 7x 7x 7x     7x 1x 1x   445x 4x 4x 4x     4x   445x 3x 3x   445x 16x 16x 234x   445x 24x 23x 9x 9x 8x 8x 9x 9x   23x 23x 23x     23x 1x 1x     210x 445x 5x 5x   580x 199x 199x 199x 4x 4x   195x 596x 596x 596x   199x 8x 8x   8x 8x 120x 120x 120x 120x 2x 2x 2x 2x 120x   8x 6x 6x 6x 8x 8x   187x 198x 476x 476x 476x   4x 476x 187x 198x     199x   6x 6x   2294x     2294x 2294x   844x 844x 844x 844x 547x   844x 844x 844x 844x 844x 844x 236x   844x 61x 61x 61x 4x       4x 4x 4x 4x     4x 61x   844x     844x 844x   844x 844x 844x 844x     844x  
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. Use a negative number to disable the depth limit.
   *
   * @default 5
   */
  readonly maxDepth?: number;
 
  /**
   * When true, uses `toLocaleString()` instead of `toISOString()` to format dates using the local locale instead of the
   * default ISO format.
   *
   * @default false
   */
  readonly useLocale?: boolean;
 
  /**
   * Maximum number of array elements to show before truncating. Use a negative number to disable the array element
   * limit.
   *
   * @default 100
   */
  readonly maxArrayElements?: number;
 
  /**
   * When true, excludes the array truncation element.
   *
   * By default, stringify adds a truncation element like `'...(4)'` to indicate that an array has been truncated due to
   * the `maxArrayElements` option.
   *
   * @default false
   */
  readonly excludeArrayTruncationElement?: boolean;
 
  /**
   * Maximum number of object properties to show before truncating. Use a negative number to disable the object property
   * limit.
   *
   * @default 50
   */
  readonly maxProperties?: number;
 
  /**
   * When true, excludes the object truncation property.
   *
   * By default, stringify adds a truncation property like `'...(4)':'...'` to indicate that an object has been
   * truncated due to the `maxProperties` option.
   *
   * @default false
   */
  readonly excludeObjectTruncationProperty?: 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
 * 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) {
          if (maxDepth < 0 || depth < maxDepth) {
            try {
              return prepare(Object.fromEntries(val), depth + 1, seen);
            } catch {
              // ignore
            }
          }
          return `Map(${val.size})`;
        }
 
        if (val instanceof Set) {
          if (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)) {
          if (maxDepth < 0 || depth < maxDepth) {
            if (maxArrayElements >= 0 && val.length > maxArrayElements) {
              const truncatedArray = val.slice(0, maxArrayElements);
              if (!options?.excludeArrayTruncationElement) {
                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 {
            const keys = Object.keys(val);
            if (!keys.length) {
              return {};
            }
 
            const prepareValue = (key: string) => {
              const v = (val as Record<string, unknown>)[key];
              return prepare(v, depth + 1, seen);
            };
 
            if (maxProperties >= 0 && keys.length > maxProperties) {
              const length = keys.length;
              const truncatedObj: Record<string, unknown> = {};
 
              let max = maxProperties;
              for (let i = 0; i < max; i++) {
                const key = keys[i];
                try {
                  truncatedObj[key] = prepareValue(key);
                } catch {
                  if (max < length) {
                    max++;
                  }
                }
              }
 
              if (length > max && !options?.excludeObjectTruncationProperty) {
                const truncatedKey = `...(${length - max})`;
                truncatedObj[truncatedKey] = '...';
              }
              return truncatedObj;
            }
 
            const result: Record<string, unknown> = {};
            for (const key of keys) {
              try {
                result[key] = prepareValue(key);
              } catch {
                // ignore
              }
            }
            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 {
          if (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]';
  }
};