esm-check-migration.mjs 7.1 KB

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