Skip to content
Open
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
22 changes: 14 additions & 8 deletions loader/typescript.loader.js
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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 }
Expand Down
5 changes: 5 additions & 0 deletions tests/typescript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('你好')
})
})
Loading