Files
overleaf-cep/services/web/transform/cjs-to-esm/codemods/fixMissingJsImports.mjs
Andrew Rumble eda1bd697f Merge pull request #27958 from overleaf/ar-change-esm-codemod-to-use-vitest-and-general-refactor
[web] change esm codemod to use vitest and general refactor

GitOrigin-RevId: 7f8c699b160ee0b7ff991d6284cb126165694c4f
2025-09-17 08:04:57 +00:00

55 lines
1.3 KiB
JavaScript

import path from 'node:path'
import fs from 'node:fs'
/**
* @param {import('jscodeshift').FileInfo} file
* @param {import('jscodeshift').API} api
*/
module.exports = function transformer(file, api) {
const j = api.jscodeshift
const root = j(file.source)
let hasChanges = false
const considerExtensionReplacement = nodePath => {
const source = nodePath.value.source
if (
!source ||
typeof source.value !== 'string' ||
!source.value.endsWith('.js')
) {
return
}
const importPath = source.value
const currentDirectory = path.dirname(file.path)
const jsPath = path.resolve(currentDirectory, importPath)
if (fs.existsSync(jsPath)) {
return
}
const mjsImportPath = importPath.replace(/\.js$/, '.mjs')
const mjsPath = path.resolve(currentDirectory, mjsImportPath)
if (fs.existsSync(mjsPath)) {
j(nodePath).get('source').replace(j.literal(mjsImportPath))
hasChanges = true
}
}
const declarationTypes = [
j.ImportDeclaration,
j.ExportNamedDeclaration,
j.ExportAllDeclaration,
]
declarationTypes.forEach(type => {
root
.find(type, { source: s => s !== null })
.forEach(considerExtensionReplacement)
})
return hasChanges ? root.toSource({ quote: 'single' }) : null
}