From 7fd83e5c5aa574553778ef45392cc63e962cb81d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 14 Oct 2026 04:10:52 +0000 Subject: [PATCH] fix: fall back when inferred encoding is unknown to iconv MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit jschardet 4 can report codec names iconv-lite does not implement (ISO-2022-JP, low-confidence cp500, …). Passing those through to iconv.decode crashes HTML pipelines that have no charset hint. Skip unsupported inferred names so getEncoding uses the target encoding. Declared unknown charsets still throw. --- index.js | 7 +++++-- test/index.js | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 4178a63..b7ede2e 100644 --- a/index.js +++ b/index.js @@ -12,7 +12,10 @@ const ICONV_ALIASES = { const inferredEncoding = content => { const detected = jschardet.detect(content) - return detected && detected.encoding + const encoding = detected && toIconvName(detected.encoding) + // jschardet 4 can name codecs iconv-lite does not ship (ISO-2022-JP, cp500, …). + // Skip those so the caller falls back to the target encoding instead of throwing. + if (encoding && iconv.encodingExists(encoding)) return encoding } const toIconvName = encoding => { @@ -27,7 +30,7 @@ module.exports = targetEncoding => { const getEncoding = (content, contentType) => toIconvName(charset({ 'content-type': contentType }, content)) || - toIconvName(inferredEncoding(content)) || + inferredEncoding(content) || targetEncoding return (buffer, contentType) => { diff --git a/test/index.js b/test/index.js index f94fa02..518c404 100644 --- a/test/index.js +++ b/test/index.js @@ -47,3 +47,25 @@ test('throws when the declared charset is unknown to iconv', t => { const error = t.throws(() => toUTF8(buffer, 'text/html; charset=iso-2022-jp')) t.true(error.message.includes('iso-2022-jp')) }) + +test('falls back when inferred encoding is unknown to iconv', t => { + // ISO-2022-JP ESC sequences: jschardet is confident; iconv-lite has no codec. + const buffer = Buffer.concat([ + Buffer.from(''), + Buffer.from([0x1b, 0x24, 0x42, 0x46, 0x7c, 0x4b, 0x5c, 0x38, 0x6c, 0x1b, 0x28, 0x42]), + Buffer.from('') + ]) + const output = toUTF8(buffer, 'text/html') + t.true(output.includes('')) + t.true(output.includes('')) +}) + +test('falls back when jschardet guesses an unsupported encoding', t => { + const iconv = require('iconv-lite') + const buffer = iconv.encode( + '' + 'あ'.repeat(200) + '', + 'EUC-JP' + ) + const output = toUTF8(buffer, 'text/html') + t.true(output.includes('')) +})