Skip to content
Merged
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@knighted/jsx",
"version": "1.9.1",
"version": "1.9.2",
"description": "Runtime JSX tagged template that renders DOM or React trees anywhere with or without a build step.",
"keywords": [
"jsx runtime",
Expand Down
107 changes: 87 additions & 20 deletions src/transpile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,8 @@ type StripEdit = {
replacement?: string
}

const MAX_TYPESCRIPT_STRIP_PASSES = 5

const hasStringProperty = <K extends string>(
value: unknown,
key: K,
Expand Down Expand Up @@ -486,6 +488,67 @@ const applyStripEdits = (magic: MagicString, edits: StripEdit[]) => {
return changed
}

const stripTypeScriptSyntax = (
source: string,
sourceType: TranspileSourceType,
): TranspileJsxSourceResult => {
let currentCode = source
let changed = false
let reachedStripPassLimit = true

for (let pass = 0; pass < MAX_TYPESCRIPT_STRIP_PASSES; pass += 1) {
const parsed = parseSync(
'transpile-jsx-source.tsx',
currentCode,
createModuleParserOptions(sourceType),
)
const error = parsed.errors[0]
if (error) {
throw new Error(formatParserError(error))
}

const edits = collectTypeScriptStripEdits(currentCode, parsed.program)
if (!edits.length) {
reachedStripPassLimit = false
break
}

const magic = new MagicString(currentCode)
const passChanged = applyStripEdits(magic, edits)
if (!passChanged) {
reachedStripPassLimit = false
break
}

currentCode = magic.toString()
changed = true
}

if (reachedStripPassLimit) {
const parsed = parseSync(
'transpile-jsx-source.tsx',
currentCode,
createModuleParserOptions(sourceType),
)
const error = parsed.errors[0]
if (error) {
throw new Error(formatParserError(error))
}

const remainingEdits = collectTypeScriptStripEdits(currentCode, parsed.program)
if (remainingEdits.length) {
throw new Error(
`[jsx] TypeScript strip did not converge after ${MAX_TYPESCRIPT_STRIP_PASSES} passes (${remainingEdits.length} removable TypeScript nodes remain).`,
)
}
}

return {
code: currentCode,
changed,
}
}

export function transpileJsxSource(
source: string,
options: TranspileJsxSourceOptions = {},
Expand All @@ -506,32 +569,36 @@ export function transpileJsxSource(
throw new Error(formatParserError(firstError))
}

const magic = new MagicString(source)
const stripChanged =
typescriptMode === 'strip'
? applyStripEdits(magic, collectTypeScriptStripEdits(source, parsed.program))
: false

const jsxRoots = collectRootJsxNodes(parsed.program)
if (!jsxRoots.length) {
const jsxMagic = new MagicString(source)

if (jsxRoots.length) {
const builder = new SourceJsxReactBuilder(
source,
createElementRef,
fragmentRef,
typescriptMode === 'strip',
)

jsxRoots.sort(compareByRangeStartDesc).forEach(node => {
jsxMagic.overwrite(node.range[0], node.range[1], builder.compile(node))
})
}

const jsxCode = jsxRoots.length ? jsxMagic.toString() : source
const jsxChanged = jsxRoots.length > 0

if (typescriptMode !== 'strip') {
return {
code: stripChanged ? magic.toString() : source,
changed: stripChanged,
code: jsxCode,
changed: jsxChanged,
}
}

const builder = new SourceJsxReactBuilder(
source,
createElementRef,
fragmentRef,
typescriptMode === 'strip',
)
jsxRoots.sort(compareByRangeStartDesc).forEach(node => {
magic.overwrite(node.range[0], node.range[1], builder.compile(node))
})
const stripResult = stripTypeScriptSyntax(jsxCode, sourceType)

return {
code: magic.toString(),
changed: true,
code: stripResult.code,
changed: jsxChanged || stripResult.changed,
}
}
32 changes: 32 additions & 0 deletions test/transpile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,4 +248,36 @@ const beta = (right as B)
expect(result.code).not.toContain(' as A')
expect(result.code).not.toContain(' as B')
})

it('strips chained TS casts around JSX expressions', () => {
const input = `
const node = (<Checkbox checked={true} /> as unknown as HTMLElement)
`

const result = transpileJsxSource(input, {
sourceType: 'script',
typescript: 'strip',
})

expect(result.changed).toBe(true)
expect(result.code).toContain(
'const node = (React.createElement(Checkbox, { "checked": true }))',
)
expect(result.code).not.toContain(' as unknown')
expect(result.code).not.toContain(' as HTMLElement')
expect(() => new Function(result.code)).not.toThrow()
})

it('throws a clear error when strip mode does not converge', () => {
const input = `
const node = ((((((value as A) as B) as C) as D) as E) as F)
`

expect(() =>
transpileJsxSource(input, {
sourceType: 'script',
typescript: 'strip',
}),
).toThrow(/TypeScript strip did not converge after 5 passes/)
})
})
Loading