UNPKG

2.04 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.inspectAny = void 0;
4const js_lib_1 = require("@naturalcycles/js-lib");
5const util_1 = require("util");
6/**
7 * Transforms ANY to human-readable string (via util.inspect mainly).
8 * Safe (no error throwing).
9 *
10 * Correclty prints Errors, AppErrors, ErrorObjects: error.message + \n + inspect(error.data)
11 *
12 * Enforces max length (default to 10_000, pass 0 to skip it).
13 *
14 * Logs numbers as-is, e.g: `6`.
15 * Logs strings as-is (without single quotes around, unlike default util.inspect behavior).
16 * Otherwise - just uses util.inspect() with reasonable defaults.
17 *
18 * Returns 'empty_string' if empty string is passed.
19 * Returns 'undefined' if undefined is passed (default util.inspect behavior).
20 */
21function inspectAny(obj, opt = {}) {
22 let s;
23 if (obj instanceof Error) {
24 // Stack includes message
25 s = (!opt.noErrorStack && obj.stack) || [obj?.name, obj.message].filter(Boolean).join(': ');
26 if (obj instanceof js_lib_1.AppError) {
27 s = [s, Object.keys(obj.data).length > 0 && inspectAny(obj.data, opt)]
28 .filter(Boolean)
29 .join('\n');
30 }
31 else if (typeof obj.code === 'string') {
32 s = obj.code + '\n' + s;
33 }
34 }
35 else if (js_lib_1._isErrorObject(obj)) {
36 s = [obj.message, Object.keys(obj.data).length > 0 && inspectAny(obj.data, opt)]
37 .filter(Boolean)
38 .join('\n');
39 }
40 else if (typeof obj === 'string') {
41 s = obj.trim() || 'empty_string';
42 }
43 else {
44 s = util_1.inspect(obj, {
45 breakLength: 80,
46 depth: 6,
47 ...opt,
48 });
49 }
50 // todo: think about maybe removing it in favor of maxStringLength/maxArrayLength built-in options
51 // Handle maxLen
52 if (opt.maxLen && s.length > opt.maxLen) {
53 s = s.slice(0, opt.maxLen) + `... ${Math.ceil(s.length / 1024)} KB message truncated`;
54 }
55 return s;
56}
57exports.inspectAny = inspectAny;