import fs from 'fs'; import path from 'path'; export default function sigproRouter() { const virtualModuleId = 'virtual:sigpro-routes'; const resolvedVirtualModuleId = '\0' + virtualModuleId; function getFiles(dir) { let results = []; if (!fs.existsSync(dir)) return results; const list = fs.readdirSync(dir); list.forEach(file => { const fullPath = path.resolve(dir, file); const stat = fs.statSync(fullPath); if (stat && stat.isDirectory()) { results = results.concat(getFiles(fullPath)); } else if (file.endsWith('.js')) { results.push(fullPath); } }); return results; } return { name: 'sigpro-router', resolveId(id) { if (id === virtualModuleId) return resolvedVirtualModuleId; }, load(id) { if (id === resolvedVirtualModuleId) { const pagesDir = path.resolve(process.cwd(), 'src/pages'); let files = getFiles(pagesDir); files = files.sort((a, b) => { const aDyn = a.includes('['); const bDyn = b.includes('['); if (aDyn !== bDyn) return aDyn ? 1 : -1; return a.length - b.length; }); let imports = ''; let routeArray = 'export const routes = [\n'; console.log('\n🚀 [SigPro Router] Mapa de rutas generado:'); files.forEach((fullPath, i) => { const relativePath = path.relative(pagesDir, fullPath).replace(/\\/g, '/'); const fileName = relativePath.replace('.js', ''); const varName = `Page_${i}`; let urlPath = '/' + fileName.toLowerCase(); if (urlPath.endsWith('/index')) urlPath = urlPath.replace('/index', '') || '/'; const isDynamic = urlPath.includes('[') && urlPath.includes(']'); let finalPathValue = `'${urlPath}'`; let paramName = null; if (isDynamic) { // Extraemos el nombre del parámetro (ej: de [id] extraemos 'id') const match = urlPath.match(/\[([^\]]+)\]/); paramName = match ? match[1] : 'id'; // CORRECCIÓN: Usamos Grupos Nombrados de JS (?...) // Esto permite que el router haga path.match(regex).groups const regexStr = urlPath .replace(/\//g, '\\/') .replace(/\[([^\]]+)\]/, '(?<$1>[^/]+)'); // Reemplaza [id] por (?[^/]+) finalPathValue = `new RegExp("^${regexStr}$")`; } console.log(` ${isDynamic ? '🔗' : '📄'} ${urlPath.padEnd(20)} -> ${relativePath}`); imports += `import ${varName} from './src/pages/${relativePath}';\n`; routeArray += ` { path: ${finalPathValue}, component: ${varName}, isDynamic: ${isDynamic}, paramName: ${paramName ? `'${paramName}'` : 'null'} },\n`; }); routeArray += '];'; return `${imports}\n${routeArray}`; } } }; }