Skip to content

Commit

Permalink
fix(findExports): disable tokenizer if parsing fails (resolves #64)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 3, 2022
1 parent 83e30de commit 4ed5c61
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
14 changes: 11 additions & 3 deletions src/analyze.ts
Expand Up @@ -130,14 +130,14 @@ export function findExports (code: string): ESMExport[] {
if (!exports.length) {
return []
}
const exportLocations = _getExportLocations(code)
if (!exportLocations.length) {
const exportLocations = _tryGetExportLocations(code)
if (exportLocations && !exportLocations.length) {
return []
}

return exports.filter((exp, index, exports) => {
// Filter false positive export matches
if (!_isExportStatement(exportLocations, exp)) {
if (exportLocations && !_isExportStatement(exportLocations, exp)) {
return false
}
// Prevent multiple exports of same function, only keep latest iteration of signatures
Expand Down Expand Up @@ -168,6 +168,14 @@ function _isExportStatement (exportsLocation: TokenLocation[], exp: ESMExport) {
return exportsLocation.some(location => exp.start <= location.start && exp.end >= location.end)
}

function _tryGetExportLocations (code: string) {
try {
return _getExportLocations(code)
} catch (err) {
return null
}
}

function _getExportLocations (code: string) {
const tokens = tokenizer(code, {
ecmaVersion: 'latest',
Expand Down
4 changes: 3 additions & 1 deletion test/exports.test.ts
Expand Up @@ -15,7 +15,9 @@ describe('findExports', () => {
'export const $foo = () => {}': { type: 'declaration', names: ['$foo'] },
'export { foo as default }': { type: 'default', name: 'default', names: ['default'] },
'export * from "./other"': { type: 'star', specifier: './other' },
'export * as foo from "./other"': { type: 'star', specifier: './other', name: 'foo' }
'export * as foo from "./other"': { type: 'star', specifier: './other', name: 'foo' },
// eslint-disable-next-line no-template-curly-in-string
'const a = `<div${JSON.stringify({ class: 42 })}>`;\nexport default true;': { type: 'default', name: 'default', names: ['default'] }
}

for (const [input, test] of Object.entries(tests)) {
Expand Down

0 comments on commit 4ed5c61

Please sign in to comment.