esm-check-migration.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import fs from 'node:fs'
  2. import path from 'node:path'
  3. import minimist from 'minimist'
  4. const APP_CODE_PATH = ['app', 'modules', 'scripts', 'test']
  5. // These have already been converted but don't have a `.mjs` extension
  6. const converted = new Set([
  7. 'scripts/ukamf/check-certs.js',
  8. 'scripts/ukamf/check-idp-metadata.js',
  9. 'scripts/ukamf/metadata-processor.js',
  10. 'scripts/ukamf/ukamf-db.js',
  11. 'scripts/ukamf/ukamf-entity.js',
  12. 'scripts/translations/checkCoverage.js',
  13. 'scripts/translations/checkSanitizeOptions.js',
  14. 'scripts/translations/checkVariables.js',
  15. 'scripts/translations/cleanupUnusedLocales.js',
  16. 'scripts/translations/config.js',
  17. 'scripts/translations/download.js',
  18. 'scripts/translations/insertHTMLFragments.js',
  19. 'scripts/translations/replaceLinkFragments.js',
  20. 'scripts/translations/sanitize.js',
  21. 'scripts/translations/transformLocales.js',
  22. 'scripts/translations/translateLocales.js',
  23. 'scripts/translations/upload.js',
  24. 'scripts/translations/uploadNonEnglish.js',
  25. 'scripts/translations/utils.js',
  26. ])
  27. // These files are not to be converted (e.g. they use CommonJS features that are not available in ES Modules)
  28. const excluded = new Set([
  29. 'modules/server-ce-scripts/scripts/create-user.js', // must be CJS for backwards compatibility
  30. 'test/acceptance/config/settings.test.saas.js', // must be CJS for @overleaf/settings module
  31. 'test/acceptance/config/settings.test.server-pro.js', // must be CJS for @overleaf/settings module
  32. 'app/src/infrastructure/PackageVersions.js', // required by webpack
  33. ])
  34. function fileIsESM(file) {
  35. const relativePath = file.replace(process.cwd() + '/', '')
  36. return file.endsWith('.mjs') || converted.has(relativePath)
  37. }
  38. function fileCanBeConvertedToESM(file) {
  39. const relativePath = file.replace(process.cwd() + '/', '')
  40. if (fileIsESM(relativePath)) {
  41. return false
  42. }
  43. return !excluded.has(relativePath)
  44. }
  45. const {
  46. _: args,
  47. files,
  48. help,
  49. json,
  50. } = minimist(process.argv.slice(2), {
  51. boolean: ['files', 'help', 'json'],
  52. alias: {
  53. files: 'f',
  54. help: 'h',
  55. json: 'j',
  56. },
  57. default: {
  58. files: false,
  59. help: false,
  60. json: false,
  61. },
  62. })
  63. const paths = args.length > 0 ? args : APP_CODE_PATH
  64. function usage() {
  65. console.error(`Usage: node check-esm-migration.js [OPTS...] dir1 dir2
  66. node check-esm-migration.js file
  67. Usage with directories
  68. ----------------------
  69. When the arguments are a list of directories it prints the status of ES Modules migration within those directories.
  70. When no directory is provided, it checks app/ and modules/, which represent the entire codebase.
  71. With the --files (-f) option, it prints the list of JS files that:
  72. - Are not migrated to ESM
  73. - Are not required by any file that is not migrated yet to ESM (in the entire codebase)
  74. These files should be the most immediate candidates to be migrated.
  75. WARNING: please note that this script only looks up literals in require() statements, so paths
  76. built dynamically (such as those in infrastructure/Modules.js) are not being taken into account.
  77. Usage with a JS file
  78. --------------------
  79. When the argument is a JS file, the script outputs the files that depend on this file that have not been converted
  80. yet to ES Modules.
  81. The files in the list must to be converted to ES Modules before converting the JS file.
  82. Example:
  83. node scrips/check-esm-migration.js --files modules/admin-panel
  84. node scrips/check-esm-migration.js app/src/router.js
  85. Options:
  86. --files Prints the files that are not imported by app code via CommonJS
  87. --json Prints the result in JSON format, including the list of files from --files
  88. --help Prints this help
  89. `)
  90. }
  91. function resolveImportPaths(dir, file) {
  92. const absolutePath = path.resolve(dir, file)
  93. if (fs.existsSync(absolutePath)) {
  94. return absolutePath
  95. } else if (fs.existsSync(absolutePath + '.js')) {
  96. return absolutePath + '.js'
  97. } else if (fs.existsSync(absolutePath + '.mjs')) {
  98. return absolutePath + '.mjs'
  99. } else {
  100. return null
  101. }
  102. }
  103. function collectJsFiles(dir, files = []) {
  104. const items = fs.readdirSync(dir)
  105. items.forEach(item => {
  106. const fullPath = path.join(dir, item)
  107. const stat = fs.statSync(fullPath)
  108. if (stat.isDirectory()) {
  109. const basename = path.basename(fullPath)
  110. // skipping directories from search
  111. if (!['frontend', 'node_modules'].includes(basename)) {
  112. collectJsFiles(fullPath, files)
  113. }
  114. } else if (
  115. stat.isFile() &&
  116. (fullPath.endsWith('.js') || fullPath.endsWith('.mjs'))
  117. ) {
  118. files.push(fullPath)
  119. }
  120. })
  121. return files
  122. }
  123. function extractImports(filePath) {
  124. const fileContent = fs.readFileSync(filePath, 'utf-8')
  125. // not 100% compliant (string escaping, etc.) but does the work here
  126. const contentWithoutComments = fileContent.replace(
  127. /\/\/.*|\/\*[\s\S]*?\*\//g,
  128. ''
  129. )
  130. const requireRegex = /require\s*\(\s*['"](.+?)['"]\s*\)/g
  131. const dependencies = []
  132. while (true) {
  133. const match = requireRegex.exec(contentWithoutComments)
  134. if (!match) {
  135. break
  136. }
  137. dependencies.push(match[1])
  138. }
  139. // build absolute path for the imported file
  140. return dependencies
  141. .map(depPath => resolveImportPaths(path.dirname(filePath), depPath))
  142. .filter(path => path !== null)
  143. }
  144. // Main function to process a list of directories and create the Map of dependencies
  145. function findJSAndImports(directories) {
  146. const fileDependenciesMap = new Map()
  147. directories.forEach(dir => {
  148. if (fs.existsSync(dir)) {
  149. const jsFiles = collectJsFiles(dir)
  150. jsFiles.forEach(filePath => {
  151. const imports = extractImports(filePath)
  152. fileDependenciesMap.set(filePath, imports)
  153. })
  154. } else {
  155. console.error(`Directory not found: ${dir}`)
  156. process.exit(1)
  157. }
  158. })
  159. return fileDependenciesMap
  160. }
  161. function printDirectoriesReport(allFilesAndImports) {
  162. // collect all files that are imported via CommonJS in the entire backend codebase
  163. const filesImportedViaCjs = new Set()
  164. allFilesAndImports.forEach((imports, file) => {
  165. if (!fileIsESM(file)) {
  166. imports.forEach(imprt => filesImportedViaCjs.add(imprt))
  167. }
  168. })
  169. // collect js files from the selected paths
  170. const selectedFiles = Array.from(
  171. findJSAndImports(paths.map(dir => path.resolve(dir))).keys()
  172. ).filter(file => !file.endsWith('settings.test.js'))
  173. const nonMigratedFiles = selectedFiles.filter(fileCanBeConvertedToESM)
  174. const migratedFileCount = selectedFiles.filter(fileIsESM).length
  175. // collect files in the selected paths that are not imported via CommonJs in the entire backend codebase
  176. const filesNotImportedViaCjs = nonMigratedFiles.filter(
  177. file => !filesImportedViaCjs.has(file)
  178. )
  179. if (json) {
  180. console.log(
  181. JSON.stringify(
  182. {
  183. fileCount: selectedFiles.length,
  184. migratedFileCount,
  185. filesNotImportedViaCjs,
  186. },
  187. null,
  188. 2
  189. )
  190. )
  191. } else {
  192. console.log(`Found ${selectedFiles.length} files in ${paths}:
  193. - ${migratedFileCount} have been migrated to ES Modules (progress=${((migratedFileCount / selectedFiles.length) * 100).toFixed(2)}%)
  194. - ${filesNotImportedViaCjs.length} are ready to migrate (these are not imported via CommonJS in the entire codebase)
  195. `)
  196. if (files) {
  197. console.log(`Files that are ready to migrate:`)
  198. filesNotImportedViaCjs.forEach(file =>
  199. console.log(` - ${file.replace(process.cwd() + '/', '')}`)
  200. )
  201. }
  202. }
  203. }
  204. function printFileReport(allFilesAndImports) {
  205. const filePath = path.resolve(paths[0])
  206. if (fileIsESM(filePath)) {
  207. console.log(`${filePath} is already migrated to ESM`)
  208. return
  209. }
  210. const filePathWithoutExtension = filePath.replace('.js', '')
  211. const importingFiles = []
  212. allFilesAndImports.forEach((imports, file) => {
  213. if (fileIsESM(file)) {
  214. return
  215. }
  216. if (
  217. imports.some(
  218. imprt => imprt === filePath || imprt === filePathWithoutExtension
  219. )
  220. ) {
  221. importingFiles.push(file)
  222. }
  223. })
  224. if (json) {
  225. console.log(
  226. JSON.stringify(
  227. {
  228. importingFiles,
  229. },
  230. null,
  231. 2
  232. )
  233. )
  234. } else {
  235. console.log(`${filePath} is required by ${importingFiles.length} CJS file`)
  236. importingFiles.forEach(file =>
  237. console.log(` - ${file.replace(process.cwd() + '/', '')}`)
  238. )
  239. }
  240. }
  241. function main() {
  242. if (help) {
  243. usage()
  244. process.exit(0)
  245. }
  246. // collect all the js files in the entire backend codebase (app/ + modules/) with its imports
  247. const allFilesAndImports = findJSAndImports(
  248. APP_CODE_PATH.map(dir => path.resolve(dir))
  249. )
  250. const entryPoint = fs.existsSync('app.js') ? 'app.js' : 'app.mjs'
  251. allFilesAndImports.set(path.resolve(entryPoint), extractImports(entryPoint))
  252. const isFileReport = fs.statSync(paths[0]).isFile()
  253. if (isFileReport) {
  254. printFileReport(allFilesAndImports)
  255. } else {
  256. printDirectoriesReport(allFilesAndImports)
  257. }
  258. }
  259. main()