diff --git a/loader/typescript.loader.js b/loader/typescript.loader.js index fda26e7..d46fce1 100644 --- a/loader/typescript.loader.js +++ b/loader/typescript.loader.js @@ -1,3 +1,4 @@ +import { isUtf8 } from 'node:buffer' import { readFile } from 'node:fs/promises' import { stripTypeScriptTypes } from 'node:module' // 22.13.0+ import { fileURLToPath } from 'node:url' @@ -13,20 +14,25 @@ function shouldProcessUrl(s) { } } -const { URL, Buffer } = globalThis +// amaro < 1.2 writes blanks of the same UTF-8 length, 1.2+ writes spaces +const blanks = new Set([' ', '\u00A0', '\u2002', '\uFEFF']) + +const { URL } = globalThis export async function load(url, context, nextLoad) { if (shouldProcessUrl(url)) { const sourceBuf = await readFile(new URL(url)) - const source = sourceBuf.toString('utf8') + if (!isUtf8(sourceBuf)) throw new Error('invalid utf-8') + const decoded = sourceBuf.toString('utf8') + // Node drops a byte order mark when reading a module, and so does stripping + const source = decoded.startsWith('\uFEFF') ? decoded.slice(1) : decoded const transformed = stripTypeScriptTypes(source, { mode: 'strip' }) - const transformedBuf = Buffer.from(transformed) - if (sourceBuf.length !== transformedBuf.length) throw new Error('length mismatch') + if (source.length !== transformed.length) throw new Error('length mismatch') // eslint-disable-next-line unicorn/no-for-loop - for (let i = 0; i < transformedBuf.length; i++) { - // should match either the source buffer or spaces or semicolon: https://github.com/swc-project/swc/issues/9331 - const val = transformedBuf[i] - if (val !== sourceBuf[i] && val !== 0x20 && val !== 0x3b) throw new Error('result mismatch') + for (let i = 0; i < transformed.length; i++) { + // should match either the source or blanks or semicolon: https://github.com/swc-project/swc/issues/9331 + const val = transformed[i] + if (val !== source[i] && !blanks.has(val) && val !== ';') throw new Error('result mismatch') } return { format: 'module', source: transformed, shortCircuit: true } diff --git a/tests/typescript.test.ts b/tests/typescript.test.ts index 55a97b8..7667afc 100644 --- a/tests/typescript.test.ts +++ b/tests/typescript.test.ts @@ -21,4 +21,9 @@ describe('typescript', () => { test('sum works', () => { expect(sum(20, 22)).toBe(42) }) + + test('non-ASCII in stripped types', () => { + const greet = (name: 'Grüße' | '你好' | '😀'): string => name + expect(greet('你好')).toBe('你好') + }) })