replaceDirectChaiUsage.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // @ts-check
  2. /**
  3. * @param {import('jscodeshift').FileInfo} file
  4. * @param {import('jscodeshift').API} api
  5. */
  6. module.exports = function transformer(file, api) {
  7. const j = api.jscodeshift
  8. const root = j(file.source)
  9. const chaiImportCollection = root.find(j.ImportDeclaration, {
  10. source: {
  11. value: 'chai',
  12. },
  13. })
  14. if (chaiImportCollection.length === 0) {
  15. return root.toSource()
  16. }
  17. const chaiImport = chaiImportCollection.get(0).node
  18. const chaiSpecifiers = chaiImport.specifiers
  19. if (!chaiSpecifiers || chaiSpecifiers.length === 0) {
  20. return root.toSource()
  21. }
  22. const vitestImportCollection = root.find(j.ImportDeclaration, {
  23. source: {
  24. value: 'vitest',
  25. },
  26. })
  27. if (vitestImportCollection.length > 0) {
  28. const vitestImport = vitestImportCollection.get(0).node
  29. const existingVitestSpecifierNames = new Set(
  30. vitestImport.specifiers.map(specifier => specifier.imported.name)
  31. )
  32. const newSpecifiers = chaiSpecifiers.filter(
  33. specifier => !existingVitestSpecifierNames.has(specifier.imported.name)
  34. )
  35. if (newSpecifiers.length > 0) {
  36. vitestImport.specifiers.push(...newSpecifiers)
  37. }
  38. chaiImportCollection.remove()
  39. } else {
  40. chaiImport.source.value = 'vitest'
  41. }
  42. return root.toSource({ quote: 'single' })
  43. }