Skip to content

Commit

Permalink
Improve isEsmId
Browse files Browse the repository at this point in the history
  • Loading branch information
jdalton committed Oct 17, 2024
1 parent 2f236ba commit 9a7073f
Showing 1 changed file with 33 additions and 24 deletions.
57 changes: 33 additions & 24 deletions scripts/utils/packages.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,37 +70,46 @@ function isEsmId(id_, parentId_) {
}
const parentId = parentId_ ? resolveId(parentId_) : undefined
const resolvedId = resolveId(id_, parentId)
let result = false
if (resolvedId.endsWith('.mjs')) {
result = true
} else if (
!resolvedId.endsWith('.cjs') &&
!resolvedId.endsWith('.json') &&
!resolvedId.endsWith('.ts')
return true
}
if (
resolvedId.endsWith('.cjs') ||
resolvedId.endsWith('.json') ||
resolvedId.endsWith('.ts')
) {
let filepath
if (path.isAbsolute(resolvedId)) {
filepath = resolvedId
} else if (parentId && isRelative(resolvedId)) {
filepath = path.join(path.dirname(parentId), resolvedId)
}
if (filepath) {
const pkgJsonPath = findUpSync('package.json', {
cwd: path.dirname(resolvedId)
})
if (pkgJsonPath && require(pkgJsonPath)?.type === 'module') {
return false
}
let filepath
if (path.isAbsolute(resolvedId)) {
filepath = resolvedId
} else if (parentId && isRelative(resolvedId)) {
filepath = path.join(path.dirname(parentId), resolvedId)
}
if (filepath) {
const pkgJsonPath = findUpSync('package.json', {
cwd: path.dirname(resolvedId)
})
if (pkgJsonPath) {
const pkgJson = require(pkgJsonPath)
const { exports: entryExports } = pkgJson
if (
pkgJson.type === 'module' &&
!entryExports?.require &&
!entryExports?.node?.default?.endsWith('.cjs')
) {
return true
}
try {
new vm.Script(fs.readFileSync(resolvedId, 'utf8'))
} catch (e) {
if (e instanceof SyntaxError) {
result = true
}
}
try {
new vm.Script(fs.readFileSync(resolvedId, 'utf8'))
} catch (e) {
if (e instanceof SyntaxError) {
return true
}
}
}
return result
return false
}

function normalizeId(id) {
Expand Down

0 comments on commit 9a7073f

Please sign in to comment.