Skip to content

Commit

Permalink
fix: support deep ternary injection (#293)
Browse files Browse the repository at this point in the history
  • Loading branch information
martaradziszewska authored Nov 9, 2023
1 parent 46f84f7 commit 189da45
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,9 @@ async function detectImports (code: string | MagicString, ctx: UnimportContext,
}
// Remove property, but keep `case x:` and `? x :`
const end = strippedCode[i.index! + i[0].length]
if (end === ':' && !['?', 'case'].includes(i[1].trim())) {
// also keeps deep ternary like `true ? false ? a : b : c`
const before = strippedCode[i.index! - 1]
if (end === ':' && !['?', 'case'].includes(i[1].trim()) && before !== ':') {
return null
}
const name = i[2]
Expand Down
15 changes: 15 additions & 0 deletions test/inject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,19 @@ import { baz } from 'baz'
import { baz } from 'baz'"
`)
})

test('deep ternary inject', async () => {
const { injectImports } = createUnimport({
imports: [
{ name: 'A', from: 'test-id' },
{ name: 'B', from: 'test-id' },
{ name: 'C', from: 'test-id' }
]
})
expect((await injectImports('const result = true ? false ? A : B : C')).code)
.toMatchInlineSnapshot(`
"import { A, B, C } from 'test-id';
const result = true ? false ? A : B : C"
`)
})
})

0 comments on commit 189da45

Please sign in to comment.