Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(NODE-5040): add color to BSON inspect #635

Merged
merged 17 commits into from
Oct 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 10 additions & 15 deletions src/binary.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isAnyArrayBuffer, isUint8Array } from './parser/utils';
import { type InspectFn, defaultInspect, isAnyArrayBuffer, isUint8Array } from './parser/utils';
import type { EJSONOptions } from './extended_json';
import { BSONError } from './error';
import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants';
Expand Down Expand Up @@ -263,14 +263,12 @@ export class Binary extends BSONValue {
return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
return `Binary.createFromBase64("${base64}", ${this.sub_type})`;
const base64Arg = inspect(base64, options);
const subTypeArg = inspect(this.sub_type, options);
return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
}
}

Expand Down Expand Up @@ -463,13 +461,10 @@ export class UUID extends Binary {
* Converts to a string representation of this Id.
*
* @returns return the 36 character hex string representation.
* @internal
*
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new UUID("${this.toHexString()}")`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
return `new UUID(${inspect(this.toHexString(), options)})`;
}
}
17 changes: 15 additions & 2 deletions src/bson_value.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BSON_MAJOR_VERSION } from './constants';
import { type InspectFn } from './parser/utils';

/** @public */
export abstract class BSONValue {
Expand All @@ -10,8 +11,20 @@ export abstract class BSONValue {
return BSON_MAJOR_VERSION;
}

/** @public */
public abstract inspect(): string;
[Symbol.for('nodejs.util.inspect.custom')](
W-A-James marked this conversation as resolved.
Show resolved Hide resolved
depth?: number,
options?: unknown,
inspect?: InspectFn
): string {
return this.inspect(depth, options, inspect);
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* @public
* Prints a human-readable string of BSON value information
* If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
*/
public abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;

/** @internal */
abstract toExtendedJSON(): unknown;
Expand Down
20 changes: 10 additions & 10 deletions src/code.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Document } from './bson';
import { BSONValue } from './bson_value';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface CodeExtended {
Expand Down Expand Up @@ -55,15 +56,14 @@ export class Code extends BSONValue {
return new Code(doc.$code, doc.$scope);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
const codeJson = this.toJSON();
return `new Code(${JSON.stringify(String(codeJson.code))}${
codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''
})`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
let parametersString = inspect(this.code, options);
const multiLineFn = parametersString.includes('\n');
if (this.scope != null) {
parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
}
const endingNewline = multiLineFn && this.scope === null;
return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
}
}
24 changes: 13 additions & 11 deletions src/db_ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Document } from './bson';
import { BSONValue } from './bson_value';
import type { EJSONOptions } from './extended_json';
import type { ObjectId } from './objectid';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface DBRefLike {
Expand Down Expand Up @@ -111,17 +112,18 @@ export class DBRef extends BSONValue {
return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;

const args = [
inspect(this.namespace, options),
inspect(this.oid, options),
...(this.db ? [inspect(this.db, options)] : []),
...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
];

args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];

inspect(): string {
// NOTE: if OID is an ObjectId class it will just print the oid string.
const oid =
this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
addaleax marked this conversation as resolved.
Show resolved Hide resolved
return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${
this.db ? `, "${this.db}"` : ''
})`;
return `new DBRef(${args.join(', ')})`;
}
}
13 changes: 5 additions & 8 deletions src/decimal128.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import { Long } from './long';
import { isUint8Array } from './parser/utils';
import { type InspectFn, defaultInspect, isUint8Array } from './parser/utils';
import { ByteUtils } from './utils/byte_utils';

const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
Expand Down Expand Up @@ -847,12 +847,9 @@ export class Decimal128 extends BSONValue {
return Decimal128.fromString(doc.$numberDecimal);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new Decimal128("${this.toString()}")`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
const d128string = inspect(this.toString(), options);
return `new Decimal128(${d128string})`;
}
}
12 changes: 4 additions & 8 deletions src/double.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BSONValue } from './bson_value';
import type { EJSONOptions } from './extended_json';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface DoubleExtended {
Expand Down Expand Up @@ -71,13 +72,8 @@ export class Double extends BSONValue {
return options && options.relaxed ? doubleValue : new Double(doubleValue);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
const eJSON = this.toExtendedJSON() as DoubleExtended;
return `new Double(${eJSON.$numberDouble})`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
return `new Double(${inspect(this.value, options)})`;
}
}
11 changes: 4 additions & 7 deletions src/int_32.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BSONValue } from './bson_value';
import type { EJSONOptions } from './extended_json';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface Int32Extended {
Expand Down Expand Up @@ -59,12 +60,8 @@ export class Int32 extends BSONValue {
return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new Int32(${this.valueOf()})`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
return `new Int32(${inspect(this.value, options)})`;
}
}
13 changes: 6 additions & 7 deletions src/long.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import type { EJSONOptions } from './extended_json';
import { type InspectFn, defaultInspect } from './parser/utils';
import type { Timestamp } from './timestamp';

interface LongWASMHelpers {
Expand Down Expand Up @@ -1056,12 +1057,10 @@ export class Long extends BSONValue {
return longResult;
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
const longVal = inspect(this.toString(), options);
const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
return `new Long(${longVal}${unsignedVal})`;
}
}
5 changes: 0 additions & 5 deletions src/max_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@ export class MaxKey extends BSONValue {
return new MaxKey();
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return 'new MaxKey()';
}
Expand Down
5 changes: 0 additions & 5 deletions src/min_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@ export class MinKey extends BSONValue {
return new MinKey();
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return 'new MinKey()';
}
Expand Down
11 changes: 4 additions & 7 deletions src/objectid.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import { type InspectFn, defaultInspect } from './parser/utils';
import { BSONDataView, ByteUtils } from './utils/byte_utils';

// Regular expression that checks for hex value
Expand Down Expand Up @@ -294,13 +295,9 @@ export class ObjectId extends BSONValue {
* Converts to a string representation of this Id.
*
* @returns return the 24 character hex string representation.
* @internal
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new ObjectId("${this.toHexString()}")`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
return `new ObjectId(${inspect(this.toHexString(), options)})`;
}
}
27 changes: 27 additions & 0 deletions src/parser/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,30 @@ export function isMap(d: unknown): d is Map<unknown, unknown> {
export function isDate(d: unknown): d is Date {
return Object.prototype.toString.call(d) === '[object Date]';
}

export type InspectFn = (x: unknown, options?: unknown) => string;
export function defaultInspect(x: unknown, _options?: unknown): string {
return JSON.stringify(x, (k: string, v: unknown) => {
if (typeof v === 'bigint') {
return { $numberLong: `${v}` };
} else if (isMap(v)) {
return Object.fromEntries(v);
}
return v;
});
}

/** @internal */
type StylizeFunction = (x: string, style: string) => string;
/** @internal */
export function getStylizeFunction(options?: unknown): StylizeFunction | undefined {
const stylizeExists =
options != null &&
typeof options === 'object' &&
'stylize' in options &&
typeof options.stylize === 'function';

if (stylizeExists) {
return options.stylize as StylizeFunction;
}
}
14 changes: 7 additions & 7 deletions src/regexp.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import type { EJSONOptions } from './extended_json';
import { type InspectFn, defaultInspect, getStylizeFunction } from './parser/utils';

function alphabetize(str: string): string {
return str.split('').sort().join('');
Expand Down Expand Up @@ -103,12 +104,11 @@ export class BSONRegExp extends BSONValue {
throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
const stylize = getStylizeFunction(options) ?? (v => v);
inspect ??= defaultInspect;
const pattern = stylize(inspect(this.pattern), 'regexp');
const flags = stylize(inspect(this.options), 'regexp');
return `new BSONRegExp(${pattern}, ${flags})`;
}
}
11 changes: 4 additions & 7 deletions src/symbol.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BSONValue } from './bson_value';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface BSONSymbolExtended {
Expand Down Expand Up @@ -33,10 +34,6 @@ export class BSONSymbol extends BSONValue {
return this.value;
}

inspect(): string {
return `new BSONSymbol(${JSON.stringify(this.value)})`;
}

toJSON(): string {
return this.value;
}
Expand All @@ -51,8 +48,8 @@ export class BSONSymbol extends BSONValue {
return new BSONSymbol(doc.$symbol);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
return `new BSONSymbol(${inspect(this.value, options)})`;
}
}
Loading