From 8543592e93d77a635cd3e81e488d25fd034de9c2 Mon Sep 17 00:00:00 2001 From: Wahid Rizka Fathurrohman Date: Sat, 5 Sep 2026 02:42:35 +0700 Subject: [PATCH] fix: count string-level appends and prepends in isEmpty isEmpty() only walked the chunks, so it ignored the string-level intro and outro that plain prepend() and append() write to. A source whose only output came from append() or prepend() was reported as empty even though toString() returned that content. isEmpty() now checks intro and outro as well, the same way toString(), generateMap() and lastChar() already do, while still disregarding whitespace. --- src/MagicString.ts | 5 +++++ test/MagicString.test.ts | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/MagicString.ts b/src/MagicString.ts index 753eb13d..7536d83b 100644 --- a/src/MagicString.ts +++ b/src/MagicString.ts @@ -1043,6 +1043,9 @@ export default class MagicString { * Returns true if the resulting source is empty (disregarding white space). */ isEmpty(): boolean { + // mirrors toString(): the string-level intro and outro bookend the chunks + if (this.intro.length && this.intro.trim()) + return false let chunk: Chunk | null = this.firstChunk while (chunk) { if ( @@ -1054,6 +1057,8 @@ export default class MagicString { } chunk = chunk.next } + if (this.outro.length && this.outro.trim()) + return false return true } diff --git a/test/MagicString.test.ts b/test/MagicString.test.ts index dea8f2d3..71c86541 100644 --- a/test/MagicString.test.ts +++ b/test/MagicString.test.ts @@ -1882,6 +1882,22 @@ describe('magicString', () => { assert.equal(s.isEmpty(), true) }) + + it('should count content appended or prepended to the string', () => { + assert.equal(new MagicString('').append('X').isEmpty(), false) + assert.equal(new MagicString('').prepend('Y').isEmpty(), false) + + const s = new MagicString('abc') + s.remove(0, 3) + s.append('!') + assert.equal(s.toString(), '!') + assert.equal(s.isEmpty(), false) + }) + + it('should still disregard whitespace appended or prepended to the string', () => { + const s = new MagicString('').prepend(' ').append(' ') + assert.equal(s.isEmpty(), true) + }) }) describe('length', () => {