From 98b5d5754be86e7ffc6b0470be14f5f8677b3857 Mon Sep 17 00:00:00 2001 From: Anton Golub Date: Sun, 23 Feb 2025 15:43:14 +0300 Subject: [PATCH] feat: define `Symbol.toPrimitive` --- .size-limit.json | 4 ++-- src/core.ts | 12 ++++++++++-- test/core.test.js | 10 ++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/.size-limit.json b/.size-limit.json index 2f6ce22ddd..5772945e1a 100644 --- a/.size-limit.json +++ b/.size-limit.json @@ -9,14 +9,14 @@ { "name": "zx/index", "path": "build/*.{js,cjs}", - "limit": "811 kB", + "limit": "812 kB", "brotli": false, "gzip": false }, { "name": "dts libdefs", "path": "build/*.d.ts", - "limit": "38.7 kB", + "limit": "39 kB", "brotli": false, "gzip": false }, diff --git a/src/core.ts b/src/core.ts index bf85e68b57..4f56666469 100644 --- a/src/core.ts +++ b/src/core.ts @@ -485,10 +485,14 @@ export class ProcessPromise extends Promise { return this._stage } - get [Symbol.toStringTag]() { + get [Symbol.toStringTag](): string { return 'ProcessPromise' } + [Symbol.toPrimitive](): string { + return this.toString() + } + // Configurators stdio( stdin: IOType, @@ -728,10 +732,14 @@ export class ProcessOutput extends Error { return this._dto.duration } - get [Symbol.toStringTag]() { + get [Symbol.toStringTag](): string { return 'ProcessOutput' } + [Symbol.toPrimitive](): string { + return this.valueOf() + } + toString(): string { return this.stdall } diff --git a/test/core.test.js b/test/core.test.js index fee4148dcb..1146998e49 100644 --- a/test/core.test.js +++ b/test/core.test.js @@ -423,6 +423,9 @@ describe('core', () => { assert.ok(p.signal instanceof AbortSignal) assert.equal(p.output, null) assert.equal(Object.prototype.toString.call(p), '[object ProcessPromise]') + assert.equal('' + p, '[object ProcessPromise]') + assert.equal(`${p}`, '[object ProcessPromise]') + assert.equal(+p, NaN) await p assert.ok(p.output instanceof ProcessOutput) @@ -1103,6 +1106,13 @@ describe('core', () => { assert.equal(Object.prototype.toString.call(o), '[object ProcessOutput]') }) + test('[Symbol.toPrimitive]', () => { + const o = new ProcessOutput(-1, 'SIGTERM', '', '', 'foo\n', 'msg', 20) + assert.equal('' + o, 'foo') + assert.equal(`${o}`, 'foo') + assert.equal(+o, NaN) + }) + test('toString()', async () => { const o = new ProcessOutput(null, null, '', '', 'foo\n') assert.equal(o.toString(), 'foo\n')