UNPKG

cmte

Version:

Design by Committee™ except it's just you and LLMs

86 lines (70 loc) 2.41 kB
import { transformFileSync } from '@babel/core'; import { parse } from '@babel/parser'; import traverse from '@babel/traverse'; import generate from '@babel/generator'; import * as t from '@babel/types'; import { glob } from 'glob'; import * as fs from 'fs'; import * as path from 'path'; async function getAllTypeScriptFiles() { return glob('src/**/*.{ts,tsx}'); } async function convertToJs(file) { // Phase 1: TypeScript → JavaScript conversion const result = transformFileSync(file, { presets: ['@babel/preset-typescript'], plugins: [ // Add plugins to handle specific TypeScript features ['@babel/plugin-transform-typescript', { allowNamespaces: true }] ] }); // Phase 2: Fix any remaining syntax issues const ast = parse(result.code, { sourceType: 'module', plugins: ['jsx'] // if needed }); traverse(ast, { // Fix specific patterns by working with the AST ImportDeclaration(path) { // Fix import paths const source = path.get('source'); if (source.isStringLiteral() && source.node.value.startsWith('.')) { source.node.value = source.node.value.replace(/\.tsx?$/, '.js'); } }, // Add more visitors as needed }); // Generate clean JavaScript return generate(ast).code; } async function processFile(file) { try { console.log(`Converting ${file}...`); const jsCode = await convertToJs(file); // Create the new file path, changing .ts/.tsx to .js/.jsx const newPath = file.replace(/\.tsx?$/, (ext) => ext === '.ts' ? '.js' : '.jsx'); // Ensure the directory exists await fs.promises.mkdir(path.dirname(newPath), { recursive: true }); // Write the converted code await fs.promises.writeFile(newPath, jsCode); console.log(`Successfully converted ${file} to ${newPath}`); } catch (error) { console.error(`Error converting ${file}:`, error); } } async function main() { try { const files = await getAllTypeScriptFiles(); console.log(`Found ${files.length} TypeScript files to convert`); for (const file of files) { await processFile(file); } console.log('Conversion complete! Running cleanup script...'); // Run the cleanup script await import('./convert-to-js.js'); } catch (error) { console.error('Error during conversion:', error); process.exit(1); } } main();