@dxos/util 0.4.10-main.fd4f2a3 → 0.4.10-main.fd8ea31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/json.ts CHANGED
@@ -12,6 +12,7 @@ import { arrayToBuffer } from './uint8array';
12
12
  export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
13
13
 
14
14
  const MAX_DEPTH = 5;
15
+ const LOG_MAX_DEPTH = 7;
15
16
 
16
17
  /**
17
18
  * JSON.stringify replacer.
@@ -75,6 +76,46 @@ export const jsonify = (value: any, depth = 0, visitedObjects = new WeakSet<any>
75
76
  }
76
77
  };
77
78
 
79
+ /**
80
+ * Recursively converts an object into a JSON-compatible object appropriate for logging.
81
+ */
82
+
83
+ // TODO(nf): use util.inspect/[util.inspect.custom] instead?
84
+ export const jsonlogify = (value: any, depth = 0, visitedObjects = new WeakSet<any>()): any => {
85
+ if (depth > LOG_MAX_DEPTH) {
86
+ return null;
87
+ } else if (typeof value === 'function') {
88
+ return null;
89
+ } else if (typeof value === 'object' && value !== null) {
90
+ if (visitedObjects.has(value)) {
91
+ return null;
92
+ }
93
+ visitedObjects.add(value);
94
+
95
+ try {
96
+ if (value instanceof Uint8Array) {
97
+ return arrayToBuffer(value).toString('hex');
98
+ } else if (Array.isArray(value)) {
99
+ return value.map((x) => jsonlogify(x, depth + 1, visitedObjects));
100
+ } else if (typeof value.toJSONL === 'function') {
101
+ return value.toJSONL();
102
+ } else if (typeof value.toJSON === 'function') {
103
+ return value.toJSON();
104
+ } else {
105
+ const res: any = {};
106
+ for (const key of Object.keys(value)) {
107
+ res[key] = jsonlogify(value[key], depth + 1, visitedObjects);
108
+ }
109
+ return res;
110
+ }
111
+ } finally {
112
+ visitedObjects.delete(value);
113
+ }
114
+ } else {
115
+ return value;
116
+ }
117
+ };
118
+
78
119
  export type JsonKeyOptions = {
79
120
  truncate?: boolean;
80
121
  humanize?: boolean;