migrate-barrel-imports 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +5 -6
- package/package.json +1 -1
package/dist/index.js
CHANGED
@@ -1,7 +1,6 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import{Command as e}from"commander";import
|
3
|
-
Processing file: ${
|
4
|
-
Total exports found: ${
|
5
|
-
Processing file: ${e}`);let p=
|
6
|
-
Processing package: ${
|
7
|
-
Warning: ${a.errors} errors encountered during processing`)}let v={targetPath:".",ignoreSourceFiles:[],ignoreTargetFiles:[],includeExtension:!1};async function D(){let o=new e;o.name("migrate-barrel-imports").description("CLI tool to migrate barrel files imports to direct imports").argument("<source-path>",'Glob pattern for source packages containing barrel files (e.g. "libs/*")').argument("[target-path]","Path to the directory where imports should be migrated (default: current directory)").option("--ignore-source-files <patterns>","Comma-separated list of file patterns to ignore in source directory").option("--ignore-target-files <patterns>","Comma-separated list of file patterns to ignore in target directory").option("--no-extension","Exclude js|jsx|ts|tsx|mjs|cjs file extensions from import statements").allowUnknownOption(!1).parse(process.argv);let s=o.args;s[0]||(console.error("Error: source-path is required"),process.exit(1));let r=s[0],t=s[1]||v.targetPath,i=o.opts();await N({sourcePath:r,targetPath:t,ignoreSourceFiles:i.ignoreSourceFiles?i.ignoreSourceFiles.split(","):v.ignoreSourceFiles,ignoreTargetFiles:i.ignoreTargetFiles?i.ignoreTargetFiles.split(","):v.ignoreTargetFiles,includeExtension:!1!==i.extension||v.includeExtension})}(async()=>{await D()})();
|
2
|
+
import{Command as e}from"commander";import{readFileSync as o,writeFileSync as t}from"node:fs";import s from"node:path";import r from"@babel/generator";import{parse as i}from"@babel/parser";import a from"@babel/traverse";import{isVariableDeclaration as n,isIdentifier as l,isFunctionDeclaration as c,isTSEnumDeclaration as p,isTSInterfaceDeclaration as u,isTSTypeAliasDeclaration as d,isClassDeclaration as g,isExportSpecifier as f,isImportSpecifier as m,isImportDefaultSpecifier as h,isImportNamespaceSpecifier as x,importDeclaration as F,importSpecifier as $,stringLiteral as k}from"@babel/types";import S from"fast-glob";import y from"micromatch";let E=r.default||r,w=a.default||a,P={sourceType:"module",plugins:["typescript","jsx","decorators-legacy","classProperties","classPrivateProperties","classPrivateMethods","exportDefaultFrom","exportNamespaceFrom","functionBind","functionSent","dynamicImport","nullishCoalescingOperator","optionalChaining","objectRestSpread","asyncGenerators","doExpressions","importMeta","logicalAssignment","moduleBlocks","moduleStringNames","numericSeparator","partialApplication","privateIn","throwExpressions","topLevelAwait"]};async function b(e){try{let t=o(e,"utf-8"),s=i(t,P),r=!1;return w(s,{ExportNamedDeclaration(e){e.node.source&&(r=!0)},ExportDefaultDeclaration(){}}),r}catch(o){return console.error(`Error checking if ${e} is a barrel file:`,o),!1}}async function j({packagePath:e,ignoreSourceFiles:t=[],stats:r}){let a=[],m=new Set,h={};console.log(`Scanning for TypeScript and JavaScript files in: ${e}`);let x=await S("**/*.{ts,tsx,js,jsx}",{cwd:e,ignore:["**/node_modules/**","**/dist/**","**/build/**"]});for(let o of(console.log(`Found ${x.length} files`),x)){let t=s.join(e,o);await b(t)&&(m.add(o),console.log(`Identified barrel file: ${o}`))}for(let m of x){let x=t.some(e=>y.isMatch(m,e));x&&(console.log(`File matches ignore pattern but will be preserved: ${m}`),r&&r.sourceFilesSkipped++);let F=s.join(e,m);console.log(`
|
3
|
+
Processing file: ${m}`);let $=o(F,"utf-8");try{let e=i($,P),o=[],t={},r={},k=[];w(e,{ExportNamedDeclaration(e){if(e.node.source){let s=e.node.source.value;if(s.includes("node_modules")||!s.startsWith(".")){e.node.specifiers.forEach(e=>{if(f(e)){let i=e.exported,a=l(i)?i.name:i.value;t[a]=s,o.push(a),r[a]=m,h[a]||(h[a]=[]),h[a].push(m)}});return}}if(e.node.declaration){var i;let t=(i=e.node.declaration)?n(i)?i.declarations.map(e=>l(e.id)?e.id.name:null).filter(e=>null!==e):c(i)&&i.id||p(i)||u(i)||d(i)||g(i)&&i.id?[i.id.name]:[]:[];t.length>0&&(o.push(...t),t.forEach(e=>{r[e]=m,h[e]||(h[e]=[]),h[e].push(m)}))}let a=e.node.specifiers.map(o=>{if(f(o)){let t=o.exported,i=l(t)?t.name:t.value;if(e.node.source){let o=e.node.source.value;if(o.startsWith(".")){let e=s.join(s.dirname(m),o);r[i]=e.replace(/\.[^/.]+$/,""),h[i]||(h[i]=[]),h[i].push(m)}}return i}return null}).filter(e=>null!==e);a.length>0&&(o.push(...a),a.forEach(e=>{r[e]||(r[e]=m)}))},ExportDefaultDeclaration(e){let t=e.node.declaration,s=l(t)?t.name:c(t)&&t.id||g(t)&&t.id?t.id.name:"default";o.push(s),r[s]=m,"default"!==s&&k.push(s)}}),(o.length>0||Object.keys(t).length>0)&&(a.push({source:m,exports:o,isIgnored:x,...Object.keys(t).length>0&&{reExports:t},...Object.keys(r).length>0&&{exportSources:r},...k.length>0&&{defaultExportNames:k},...await b(F)&&{isBarrelFile:!0},...Object.keys(h).length>0&&{exportFiles:h}}),o.length>0&&console.log(`Found exports ${o.join(", ")} in ${m}`))}catch(e){console.error(`Error parsing ${m}:`,e)}}return console.log(`
|
4
|
+
Total exports found: ${a.length}`),console.log(`Barrel files found: ${m.size}`),a}async function v({packageName:e,targetPath:t,stats:s}){try{let s=new Set,r=await S(["**/*.{ts,tsx,js,jsx}"],{cwd:t,absolute:!0,ignore:["**/node_modules/**","**/dist/**","**/build/**"],followSymbolicLinks:!1});for(let t of(console.log(`Found ${r.length} files to scan`),r))try{let r=o(t,"utf-8"),a=i(r,P);w(a,{ImportDeclaration(o){let r=o.node.source.value;(r===e||r.startsWith(`${e}/`))&&s.add(t)}})}catch(e){console.error(`Error processing file ${t}:`,e)}let a=Array.from(s);if(a.length>0)for(let o of(console.log(`Found total of ${a.length} files with imports from ${e}`),console.log("Files found:"),a))console.log(` ${o}`);else console.log(`No files found importing from ${e}`);return a}catch(e){return console.error("Error finding imports:",e),[]}}async function D({filePath:e,packageName:s,exports:r,includeExtension:a=!0,warnings:n,stats:c}){console.log(`
|
5
|
+
Processing file: ${e}`);let p=o(e,"utf-8"),u=!1;try{let o=i(p,P),n=[];w(o,{ImportDeclaration(e){e.node.source.value.startsWith(s)&&n.push(e.node)}});let d=new Map,g=[];for(let e of n)for(let o of(e.source.value,e.specifiers))if(m(o)){let e=o.imported,t=l(e)?e.name:e.value,i=r.find(e=>e.exports.includes(t));if(i){if(i.isIgnored){g.push(o);continue}if(i.reExports?.[t]){let e=i.reExports[t];if(!e.startsWith(".")){d.has(e)||d.set(e,[]),d.get(e)?.push({local:o.local,imported:o.imported}),u=!0;continue}}if("src/index.ts"===i.source&&i.exports.includes(t)&&!i.reExports?.[t]){if(i.defaultExportNames?.includes(t)){d.has(s)||d.set(s,[]),d.get(s)?.push({local:o.local,imported:o.imported}),u=!0;continue}if("default"!==t){let e=a?`${s}/${i.source}`:`${s}/${i.source.replace(/\.[^/.]+$/,"")}`;d.has(e)||d.set(e,[]),d.get(e)?.push({local:o.local,imported:o.imported}),u=!0;continue}}let e=i.exportFiles?.[t]||[],r=e[0];if(e.length>1){let o=e.filter(e=>!e.includes(".stories.")&&!e.includes(".test.")&&!e.includes(".spec.")&&!e.includes(".stories/")&&!e.includes(".test/")&&!e.includes(".spec/"));o.length>0&&(r=o[0])}if(r){let e=a?`${s}/${r}`:`${s}/${r.replace(/\.[^/.]+$/,"")}`,i=o.local.name!==t,n=Array.from(d.values()).some(e=>e.some(e=>e.imported&&l(e.imported)&&e.imported.name===t));i&&n||(d.has(e)||d.set(e,[]),d.get(e)?.push({local:o.local,imported:o.imported}),u=!0);continue}g.push(o)}else(h(o)||x(o))&&g.push(o)}w(o,{ImportDeclaration(e){e.node.source.value.startsWith(s)&&e.remove()}});let f=[];for(let[e,o]of d)o.length>0&&(f.push(F(o.map(({local:e,imported:o})=>$(e,o)),k(e))),c&&(c.importsMigrated+=o.length));if(g.length>0&&f.push(F(g,k(s))),f.length>0&&(o.program.body.unshift(...f),u=!0),u){let s=E(o,{retainLines:!0,retainFunctionParens:!0},p).code;t(e,s),console.log(`Writing changes to ${e}`),c&&c.importsUpdated++}else c&&c.noChangesNeeded++}catch(o){console.error(`Error updating imports in ${e}:`,o)}}async function T(e){let{sourcePath:o,targetPath:t,includeExtension:s=!0}=e,r={sourcePackagesFound:0,sourcePackagesProcessed:0,sourcePackagesSkipped:0,sourceFilesFound:0,sourceFilesWithExports:0,sourceFilesSkipped:0,exportsFound:0,targetFilesFound:0,targetFilesProcessed:0,importsUpdated:0,noChangesNeeded:0,targetFilesSkipped:0,importsMigrated:0},i=[];try{let e=await I(o);for(let o of(r.sourcePackagesFound=e.length,e)){console.log(`
|
6
|
+
Processing package: ${o}`);let e=await j({packagePath:o,stats:r});r.exportsFound=e.reduce((e,o)=>e+o.exports.length,0),r.sourceFilesWithExports=e.length;let a=await N(o),n=await v({packageName:a,targetPath:t,stats:r});for(let o of(r.targetFilesFound=n.length,n))r.targetFilesProcessed++,await D({filePath:o,packageName:a,exports:e,includeExtension:s,warnings:i,stats:r});r.sourcePackagesProcessed++}console.log("\nMigration Summary"),console.log(`Source packages found: ${r.sourcePackagesFound}`),console.log(`Source packages processed: ${r.sourcePackagesProcessed}`),console.log(`Source packages skipped: ${r.sourcePackagesSkipped}`),console.log(`Source files found: ${r.sourceFilesFound}`),console.log(`Source files with exports: ${r.sourceFilesWithExports}`),console.log(`Source files skipped: ${r.sourceFilesSkipped}`),console.log(`Exports found: ${r.exportsFound}`),console.log(`Target files found: ${r.targetFilesFound}`),console.log(`Target files processed: ${r.targetFilesProcessed}`),console.log(`Target files with imports updated: ${r.importsUpdated}`),console.log(`Target files with no changes needed: ${r.noChangesNeeded}`),console.log(`Target files skipped: ${r.targetFilesSkipped}`),console.log(`Total imports migrated: ${r.importsMigrated}`),i.length>0&&(console.log("\nWarnings:"),i.forEach(e=>console.log(` - ${e}`)))}catch(e){throw console.error("Error during migration:",e),e}}async function N(e){return JSON.parse(o(s.join(e,"package.json"),"utf-8")).name}async function I(e){let o=s.isAbsolute(e)?s.resolve(e):s.join(process.cwd(),e);console.log(`Looking for source packages in: ${o}`);let t=await S("{package.json,**/package.json}",{cwd:o,ignore:["**/node_modules/**","**/dist/**","**/build/**"],absolute:!0});return console.log(`Found ${t.length} package.json files:`),t.forEach(e=>console.log(` - ${e}`)),t.map(s.dirname)}let W={targetPath:".",ignoreSourceFiles:[],ignoreTargetFiles:[],includeExtension:!1};async function C(){let o=new e;o.name("migrate-barrel-imports").description("CLI tool to migrate barrel files imports to direct imports").argument("<source-path>",'Glob pattern for source packages containing barrel files (e.g. "libs/*")').argument("[target-path]","Path to the directory where imports should be migrated (default: current directory)").option("--ignore-source-files <patterns>","Comma-separated list of file patterns to ignore in source directory").option("--ignore-target-files <patterns>","Comma-separated list of file patterns to ignore in target directory").option("--no-extension","Exclude js|jsx|ts|tsx|mjs|cjs file extensions from import statements").allowUnknownOption(!1).parse(process.argv);let t=o.args;t[0]||(console.error("Error: source-path is required"),process.exit(1));let s=t[0],r=t[1]||W.targetPath,i=o.opts();await T({sourcePath:s,targetPath:r,ignoreSourceFiles:i.ignoreSourceFiles?i.ignoreSourceFiles.split(","):W.ignoreSourceFiles,ignoreTargetFiles:i.ignoreTargetFiles?i.ignoreTargetFiles.split(","):W.ignoreTargetFiles,includeExtension:!1!==i.extension||W.includeExtension})}(async()=>{await C()})();
|