versacompiler 2.1.0 → 2.3.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.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/dist/compiler/compile.js +2520 -25
  3. package/dist/compiler/error-reporter.js +467 -38
  4. package/dist/compiler/linter.js +72 -1
  5. package/dist/compiler/minify.js +272 -1
  6. package/dist/compiler/minifyTemplate.js +230 -1
  7. package/dist/compiler/module-resolution-optimizer.js +888 -1
  8. package/dist/compiler/parser.js +336 -1
  9. package/dist/compiler/performance-monitor.js +204 -56
  10. package/dist/compiler/tailwindcss.js +39 -1
  11. package/dist/compiler/transform-optimizer.js +392 -1
  12. package/dist/compiler/transformTStoJS.js +16 -1
  13. package/dist/compiler/transforms.js +554 -1
  14. package/dist/compiler/typescript-compiler.js +172 -2
  15. package/dist/compiler/typescript-error-parser.js +281 -10
  16. package/dist/compiler/typescript-manager.js +304 -2
  17. package/dist/compiler/typescript-sync-validator.js +295 -31
  18. package/dist/compiler/typescript-worker-pool.js +936 -1
  19. package/dist/compiler/typescript-worker-thread.cjs +466 -22
  20. package/dist/compiler/typescript-worker.js +339 -1
  21. package/dist/compiler/vuejs.js +396 -37
  22. package/dist/hrm/VueHRM.js +359 -1
  23. package/dist/hrm/errorScreen.js +83 -1
  24. package/dist/hrm/getInstanciaVue.js +313 -1
  25. package/dist/hrm/initHRM.js +586 -1
  26. package/dist/main.js +353 -7
  27. package/dist/servicios/browserSync.js +589 -2
  28. package/dist/servicios/file-watcher.js +425 -4
  29. package/dist/servicios/logger.js +63 -3
  30. package/dist/servicios/readConfig.js +399 -53
  31. package/dist/utils/excluded-modules.js +37 -1
  32. package/dist/utils/module-resolver.js +552 -1
  33. package/dist/utils/promptUser.js +48 -2
  34. package/dist/utils/proxyValidator.js +68 -1
  35. package/dist/utils/resolve-bin.js +58 -1
  36. package/dist/utils/utils.js +21 -1
  37. package/dist/utils/vue-types-setup.js +435 -241
  38. package/dist/wrappers/eslint-node.js +1 -1
  39. package/dist/wrappers/oxlint-node.js +122 -1
  40. package/dist/wrappers/tailwind-node.js +94 -1
  41. package/package.json +109 -104
@@ -1 +1,888 @@
1
- import{createHash as e}from"node:crypto";import{existsSync as i,readFileSync as a,readdirSync as o,statSync as s}from"node:fs";import{dirname as c,join as l,relative as u}from"node:path";import{cwd as d,env as f}from"node:process";import{logger as p}from"../servicios/logger.js";import{EXCLUDED_MODULES as m}from"../utils/excluded-modules.js";export class ModuleResolutionOptimizer{static instance;moduleIndex=new Map;resolutionCache=new Map;cacheOrder=[];aliasIndex=[];nodeModulesCache=new Map;metrics={totalResolutions:0,cacheHits:0,cacheMisses:0,averageResolveTime:0,indexLookups:0,filesystemAccess:0,aliasMatches:0};maxCacheSize=500;cacheMaxAge=300*1e3;indexRefreshInterval=600*1e3;excludedModules=m;lastIndexUpdate=0;constructor(){this.initializeIndexes(),this.setupPeriodicRefresh()}static getInstance(){return ModuleResolutionOptimizer.instance||(ModuleResolutionOptimizer.instance=new ModuleResolutionOptimizer),ModuleResolutionOptimizer.instance}initializeIndexes(){let e=performance.now();try{this.buildModuleIndex(),this.buildAliasIndex(),this.lastIndexUpdate=Date.now();let i=performance.now()-e;f.VERBOSE===`true`&&(p.info(`🚀 Índices de resolución construidos en ${i.toFixed(2)}ms`),p.info(`📦 ${this.moduleIndex.size} módulos indexados`),p.info(`🔗 ${this.aliasIndex.length} alias indexados`))}catch(e){p.error(`Error inicializando índices de resolución:`,e)}}buildModuleIndex(){let e=l(d(),`node_modules`);if(i(e))try{let i=this.discoverModules(e);for(let e of i)this.moduleIndex.set(e.name,{fullPath:e.fullPath,entryPoint:e.entryPoint,packageJson:e.packageJson,isESM:e.isESM,hasExports:e.hasExports,optimizedEntry:e.optimizedEntry,lastModified:e.lastModified});f.VERBOSE===`true`&&p.info(`📚 Índice de módulos construido: ${this.moduleIndex.size} entradas`)}catch(e){p.error(`Error construyendo índice de módulos:`,e)}}discoverModules(e){let i=[];try{let a=o(e);this.metrics.filesystemAccess++;for(let s of a){let a=l(e,s);try{if(s.startsWith(`/dist/examples`)){let e=o(a);this.metrics.filesystemAccess++;for(let o of e){let e=l(a,o),c=this.analyzeModule(`${s}/${o}`,e);c&&i.push(c)}}else{let e=this.analyzeModule(s,a);e&&i.push(e)}}catch{continue}}}catch(e){p.error(`Error descubriendo módulos:`,e)}return i}analyzeModule(e,o){try{let c=l(o,`package.json`);if(!i(c))return null;let u=s(c);this.metrics.filesystemAccess++;let d=JSON.parse(a(c,`utf-8`));this.metrics.filesystemAccess++;let f=d.type===`module`,p=!!d.exports,m=this.determineOptimalEntryPoint(d),h;return m&&(h=this.findOptimalESMVersion(o,m)),{name:e,fullPath:o,entryPoint:m||`index.js`,packageJson:d,isESM:f,hasExports:p,optimizedEntry:h,lastModified:u.mtime.getTime()}}catch{return null}}determineOptimalEntryPoint(e){let i=null;if(e.module)i=e.module;else if(e.exports){if(typeof e.exports==`string`)i=e.exports;else if(e.exports[`.`]){let a=e.exports[`.`];typeof a==`string`?i=a:typeof a==`object`&&(i=a.import||a.browser||a.default)}}else i=e.browser&&typeof e.browser==`string`?e.browser:e.main||null;return i&&(i=this.validateAndOptimizeEntryPoint(i,e)),i}validateAndOptimizeEntryPoint(e,i){let a=f.isProd===`true`,o=e.toLowerCase();if(!a&&(o.includes(`.min.`)||o.includes(`.prod.`))){let a=this.findDevelopmentAlternatives(e,i);if(a)return a}if(o.includes(`runtime`)&&!o.includes(`browser`)){let a=this.findBrowserAlternative(e,i);if(a)return a}return e}findDevelopmentAlternatives(e,i){let a=e.replace(`.min.`,`.`).replace(`.prod.`,`.`);if(i.exports&&typeof i.exports==`object`){let e=i.exports[`.`];if(e&&typeof e==`object`){let i=[e.development,e.import,e.browser,e.default].filter(Boolean);for(let e of i)if(typeof e==`string`&&!e.includes(`.min.`)&&!e.includes(`.prod.`))return e}}if(i.browser&&typeof i.browser==`object`){for(let e of Object.values(i.browser))if(typeof e==`string`&&!e.includes(`.min.`)&&!e.includes(`.prod.`)&&(e.includes(`browser`)||e.includes(`esm`)))return e}return a===e?null:a}findBrowserAlternative(e,i){if(i.exports&&typeof i.exports==`object`){let e=i.exports[`.`];if(e&&typeof e==`object`){let i=Object.keys(e).filter(e=>e.includes(`browser`)&&(e.includes(`esm`)||e.includes(`module`)));if(i.length>0){let a=i[0];if(a&&typeof e[a]==`string`)return e[a]}if(e.browser&&typeof e.browser==`string`)return e.browser}}let a=e.replace(/\.[^/.]+$/,``),o=[a.replace(`runtime`,`esm-browser`),a.replace(`runtime`,`browser`),a.replace(`runtime.esm-bundler`,`esm-browser`),e.replace(`runtime`,`esm-browser`),e.replace(`runtime`,`browser`)];return e.includes(`vue.runtime.esm-bundler`)&&o.unshift(`dist/vue.esm-browser.js`,`dist/vue.browser.esm.js`),o.find(i=>i!==e)||null}findOptimalESMVersion(e,a){let s=c(a),u=(a.split(`/`).pop()||``).replace(/\.[^/.]+$/,``),d=l(e,s);if(i(d))try{let e=o(d);this.metrics.filesystemAccess++;let i=[`${u}.esm-browser.js`,`${u}.esm.js`,`${u}.module.js`,`${u}.browser.js`];for(let a of i)if(e.includes(a))return l(s,a)}catch{}}buildAliasIndex(){if(f.PATH_ALIAS)try{let e=JSON.parse(f.PATH_ALIAS);this.aliasIndex=[];for(let[i,a]of Object.entries(e)){let e=i.replace(`/*`,``),o=e.length;this.aliasIndex.push({pattern:e,target:Array.isArray(a)?a:[a],regex:RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}(?=/|$)`),priority:o})}this.aliasIndex.sort((e,i)=>i.priority-e.priority),f.VERBOSE===`true`&&p.info(`🔗 Índice de alias construido: ${this.aliasIndex.length} patrones`)}catch(e){p.error(`Error construyendo índice de alias:`,e)}}async resolveModule(e,i){let a=performance.now();if(this.metrics.totalResolutions++,this.excludedModules.has(e))return{path:null,cached:!1,resolveTime:performance.now()-a};let o=this.createCacheKey(e,i),s=this.getFromCache(o);if(s!==void 0)return this.metrics.cacheHits++,{path:s,cached:!0,resolveTime:performance.now()-a,fromCache:!0};this.metrics.cacheMisses++;let c=null;try{c=e.includes(`/`)?await this.resolveSubPath(e):this.resolveFromIndex(e),c||(c=this.fallbackResolve(e)),c&&(c=this.getNodeModulesRelativePath(c))}catch(i){f.VERBOSE===`true`&&p.warn(`Error resolviendo ${e}:`,i)}this.setCache(o,c);let l=performance.now()-a;return this.updateMetrics(l),{path:c,cached:!1,resolveTime:l}}resolveFromIndex(e){this.metrics.indexLookups++;let i=this.moduleIndex.get(e);if(!i)return null;let a=i.optimizedEntry||i.entryPoint;return l(i.fullPath,a)}async resolveSubPath(e){let[a,...o]=e.split(`/`),s=o.join(`/`);if(!a)return null;this.metrics.indexLookups++;let c=this.moduleIndex.get(a);if(!c)return null;if(c.hasExports&&c.packageJson.exports){let e=`./${s}`,i=c.packageJson.exports[e];if(i){if(typeof i==`string`)return l(c.fullPath,i);if(typeof i==`object`){let e=i.import||i.default;if(typeof e==`string`)return l(c.fullPath,e)}}}let u=l(c.fullPath,s);if(i(u))return this.metrics.filesystemAccess++,u;for(let e of[`.mjs`,`.js`,`.cjs`]){let a=u+e;if(i(a))return this.metrics.filesystemAccess++,a}return null}fallbackResolve(e){let o=l(d(),`node_modules`,e),s=l(o,`package.json`);if(!i(s))return this.metrics.filesystemAccess++,null;try{let e=JSON.parse(a(s,`utf-8`));this.metrics.filesystemAccess++;let c=l(o,this.determineOptimalEntryPoint(e)||`index.js`);if(i(c))return this.metrics.filesystemAccess++,c}catch{}return null}findMatchingAlias(e){this.metrics.aliasMatches++;for(let i of this.aliasIndex)if(i.regex.test(e))return i;return null}resolveAlias(e){let i=this.findMatchingAlias(e);if(!i||!f.PATH_DIST)return null;let a=e.replace(i.pattern,``),o=i.target[0];if(!o)return null;let s,c=f.PATH_DIST.replace(`./`,``);if(a===``&&!o.includes(`*`))if(o.startsWith(`/`))s=l(`/`,c,o.substring(1));else{let e=o.replace(`./`,``);s=e.startsWith(`src/`)?l(`/`,c,e.replace(`src/`,``)):l(`/`,c,e)}else if(o.startsWith(`/`)){let e=o.substring(1).replace(`/*`,``);s=(e===`src`||e.startsWith(`src/`),l(`/`,c,a))}else{let e=o.replace(`./`,``).replace(`/*`,``);s=e===c?l(`/`,c,a):e.startsWith(c+`/`)?l(`/`,e,a):e.startsWith(`src/`)?l(`/`,c,e.replace(`src/`,``),a):[`examples`,`src`,`app`,`lib`].includes(e)?l(`/`,c,a):l(`/`,c,e,a)}return s.replace(/\\/g,`/`)}getFromCache(e){let i=this.resolutionCache.get(e);if(i){if(Date.now()-i.timestamp>this.cacheMaxAge){this.resolutionCache.delete(e),this.cacheOrder=this.cacheOrder.filter(i=>i!==e);return}return i.hits++,this.cacheOrder=this.cacheOrder.filter(i=>i!==e),this.cacheOrder.push(e),i.result}}setCache(e,i){if(this.resolutionCache.size>=this.maxCacheSize){let e=this.cacheOrder.shift();e&&this.resolutionCache.delete(e)}this.resolutionCache.set(e,{result:i,timestamp:Date.now(),hits:0}),this.cacheOrder.push(e)}createCacheKey(i,a){let o=e(`md5`);return o.update(i),a&&o.update(a),o.digest(`hex`)}getNodeModulesRelativePath(e){let i=e.indexOf(`node_modules`);if(i!==-1)return`/`+e.substring(i).replace(/\\/g,`/`);let a=u(d(),e).replace(/\\/g,`/`);return a.startsWith(`/`)?a:`/`+a}updateMetrics(e){this.metrics.averageResolveTime=(this.metrics.averageResolveTime*(this.metrics.totalResolutions-1)+e)/this.metrics.totalResolutions}setupPeriodicRefresh(){setInterval(()=>{Date.now()-this.lastIndexUpdate>this.indexRefreshInterval&&(f.VERBOSE===`true`&&p.info(`🔄 Actualizando índices de resolución de módulos`),this.refreshIndexes())},this.indexRefreshInterval)}refreshIndexes(){try{let e=this.moduleIndex.size;this.buildModuleIndex(),this.buildAliasIndex(),this.lastIndexUpdate=Date.now(),f.VERBOSE===`true`&&p.info(`📚 Índices actualizados: ${e} → ${this.moduleIndex.size} módulos`)}catch(e){p.error(`Error actualizando índices:`,e)}}clearExpiredCache(){let e=Date.now(),i=[];for(let[a,o]of this.resolutionCache.entries())e-o.timestamp>this.cacheMaxAge&&i.push(a);for(let e of i)this.resolutionCache.delete(e),this.cacheOrder=this.cacheOrder.filter(i=>i!==e);f.VERBOSE===`true`&&i.length>0&&p.info(`🧹 Limpiado caché expirado: ${i.length} entradas`)}getMetrics(){return{...this.metrics,cacheSize:this.resolutionCache.size,moduleIndexSize:this.moduleIndex.size,aliasIndexSize:this.aliasIndex.length,cacheHitRate:this.metrics.totalResolutions>0?this.metrics.cacheHits/this.metrics.totalResolutions*100:0}}resetMetrics(){this.metrics={totalResolutions:0,cacheHits:0,cacheMisses:0,averageResolveTime:0,indexLookups:0,filesystemAccess:0,aliasMatches:0}}forceRefresh(){this.initializeIndexes(),this.resolutionCache.clear(),this.cacheOrder=[],f.VERBOSE===`true`&&p.info(`🔄 Índices de resolución reconstruidos forzosamente`)}cleanup(){this.moduleIndex.clear(),this.resolutionCache.clear(),this.cacheOrder=[],this.aliasIndex=[],this.nodeModulesCache.clear(),f.VERBOSE===`true`&&p.info(`🧹 Sistema de resolución de módulos limpiado`)}}export async function getOptimizedModulePath(e,i){return(await ModuleResolutionOptimizer.getInstance().resolveModule(e,i)).path}export function getOptimizedAliasPath(e){return ModuleResolutionOptimizer.getInstance().resolveAlias(e)}export function getModuleResolutionMetrics(){return ModuleResolutionOptimizer.getInstance().getMetrics()}
1
+ /**
2
+ * Module Resolution Optimizer
3
+ *
4
+ * Optimiza la resolución de módulos mediante:
5
+ * - Sistema de indexación O(1) para búsquedas de módulos
6
+ * - Caché LRU para resoluciones repetidas
7
+ * - Indexación de alias para búsquedas rápidas
8
+ * - Batch processing para múltiples resoluciones
9
+ * - Monitoreo de performance y métricas
10
+ */
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
13
+ import { dirname, join, relative } from 'node:path';
14
+ import { cwd, env } from 'node:process';
15
+ import { logger } from '../servicios/logger.js';
16
+ import { EXCLUDED_MODULES } from '../utils/excluded-modules.js';
17
+ /**
18
+ * Sistema de optimización de resolución de módulos
19
+ * Implementa indexación, caché y búsquedas O(1)
20
+ */
21
+ export class ModuleResolutionOptimizer {
22
+ static instance;
23
+ // Índice principal de módulos para búsquedas O(1)
24
+ moduleIndex = new Map();
25
+ // Caché LRU para resoluciones repetidas
26
+ resolutionCache = new Map();
27
+ cacheOrder = [];
28
+ // Índice de alias optimizado
29
+ aliasIndex = [];
30
+ // Caché de rutas de node_modules descubiertas
31
+ nodeModulesCache = new Map();
32
+ // Métricas de rendimiento
33
+ metrics = {
34
+ totalResolutions: 0,
35
+ cacheHits: 0,
36
+ cacheMisses: 0,
37
+ averageResolveTime: 0,
38
+ indexLookups: 0,
39
+ filesystemAccess: 0,
40
+ aliasMatches: 0,
41
+ };
42
+ // Configuración
43
+ maxCacheSize = 500;
44
+ cacheMaxAge = 5 * 60 * 1000; // 5 minutos
45
+ indexRefreshInterval = 10 * 60 * 1000; // 10 minutos // Lista de módulos excluidos - usar la lista centralizada
46
+ excludedModules = EXCLUDED_MODULES;
47
+ lastIndexUpdate = 0;
48
+ constructor() {
49
+ this.initializeIndexes();
50
+ this.setupPeriodicRefresh();
51
+ }
52
+ static getInstance() {
53
+ if (!ModuleResolutionOptimizer.instance) {
54
+ ModuleResolutionOptimizer.instance =
55
+ new ModuleResolutionOptimizer();
56
+ }
57
+ return ModuleResolutionOptimizer.instance;
58
+ }
59
+ /**
60
+ * Resetea la instancia del singleton (útil para tests)
61
+ */
62
+ static resetInstance() {
63
+ ModuleResolutionOptimizer.instance = null;
64
+ }
65
+ /**
66
+ * Inicializa los índices de módulos y alias
67
+ */
68
+ initializeIndexes() {
69
+ const startTime = performance.now();
70
+ try {
71
+ this.buildModuleIndex();
72
+ this.buildAliasIndex();
73
+ this.lastIndexUpdate = Date.now();
74
+ const indexTime = performance.now() - startTime;
75
+ if (env.VERBOSE === 'true') {
76
+ logger.info(`🚀 Índices de resolución construidos en ${indexTime.toFixed(2)}ms`);
77
+ logger.info(`📦 ${this.moduleIndex.size} módulos indexados`);
78
+ logger.info(`🔗 ${this.aliasIndex.length} alias indexados`);
79
+ }
80
+ }
81
+ catch (error) {
82
+ logger.error('Error inicializando índices de resolución:', error);
83
+ }
84
+ }
85
+ /**
86
+ * Construye el índice principal de módulos para búsquedas O(1)
87
+ */
88
+ buildModuleIndex() {
89
+ const nodeModulesPath = join(cwd(), 'node_modules');
90
+ if (!existsSync(nodeModulesPath)) {
91
+ return;
92
+ }
93
+ try {
94
+ const modules = this.discoverModules(nodeModulesPath);
95
+ for (const moduleData of modules) {
96
+ this.moduleIndex.set(moduleData.name, {
97
+ fullPath: moduleData.fullPath,
98
+ entryPoint: moduleData.entryPoint,
99
+ packageJson: moduleData.packageJson,
100
+ isESM: moduleData.isESM,
101
+ hasExports: moduleData.hasExports,
102
+ optimizedEntry: moduleData.optimizedEntry,
103
+ lastModified: moduleData.lastModified,
104
+ });
105
+ }
106
+ if (env.VERBOSE === 'true') {
107
+ logger.info(`📚 Índice de módulos construido: ${this.moduleIndex.size} entradas`);
108
+ }
109
+ }
110
+ catch (error) {
111
+ logger.error('Error construyendo índice de módulos:', error);
112
+ }
113
+ }
114
+ /**
115
+ * Descubre módulos disponibles en node_modules con información optimizada
116
+ */
117
+ discoverModules(nodeModulesPath) {
118
+ const modules = [];
119
+ try {
120
+ const entries = readdirSync(nodeModulesPath);
121
+ this.metrics.filesystemAccess++;
122
+ for (const entry of entries) {
123
+ const modulePath = join(nodeModulesPath, entry);
124
+ try {
125
+ if (entry.startsWith('/dist/examples')) {
126
+ // Scoped packages
127
+ const scopedModules = readdirSync(modulePath);
128
+ this.metrics.filesystemAccess++;
129
+ for (const scopedModule of scopedModules) {
130
+ const scopedPath = join(modulePath, scopedModule);
131
+ const moduleData = this.analyzeModule(`${entry}/${scopedModule}`, scopedPath);
132
+ if (moduleData) {
133
+ modules.push(moduleData);
134
+ }
135
+ }
136
+ }
137
+ else {
138
+ // Regular packages
139
+ const moduleData = this.analyzeModule(entry, modulePath);
140
+ if (moduleData) {
141
+ modules.push(moduleData);
142
+ }
143
+ }
144
+ }
145
+ catch {
146
+ // Ignorar módulos que no se puedan analizar
147
+ continue;
148
+ }
149
+ }
150
+ }
151
+ catch (error) {
152
+ logger.error('Error descubriendo módulos:', error);
153
+ }
154
+ return modules;
155
+ }
156
+ /**
157
+ * Analiza un módulo individual y extrae información relevante
158
+ */
159
+ analyzeModule(name, modulePath) {
160
+ try {
161
+ const packageJsonPath = join(modulePath, 'package.json');
162
+ if (!existsSync(packageJsonPath)) {
163
+ return null;
164
+ }
165
+ const stats = statSync(packageJsonPath);
166
+ this.metrics.filesystemAccess++;
167
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
168
+ this.metrics.filesystemAccess++;
169
+ const isESM = packageJson.type === 'module';
170
+ const hasExports = !!packageJson.exports; // Determinar entry point optimizado
171
+ const entryPoint = this.determineOptimalEntryPoint(packageJson);
172
+ let optimizedEntry;
173
+ // Buscar versión ESM/browser optimizada
174
+ if (entryPoint) {
175
+ optimizedEntry = this.findOptimalESMVersion(modulePath, entryPoint);
176
+ }
177
+ return {
178
+ name,
179
+ fullPath: modulePath,
180
+ entryPoint: entryPoint || 'index.js',
181
+ packageJson,
182
+ isESM,
183
+ hasExports,
184
+ optimizedEntry,
185
+ lastModified: stats.mtime.getTime(),
186
+ };
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ } /**
192
+ * Determina el entry point óptimo basado en package.json
193
+ */
194
+ determineOptimalEntryPoint(packageJson) {
195
+ // Prioridad: module > exports > browser > main
196
+ let entryPoint = null;
197
+ if (packageJson.module) {
198
+ entryPoint = packageJson.module;
199
+ }
200
+ else if (packageJson.exports) {
201
+ if (typeof packageJson.exports === 'string') {
202
+ entryPoint = packageJson.exports;
203
+ }
204
+ else if (packageJson.exports['.']) {
205
+ const dotExport = packageJson.exports['.'];
206
+ if (typeof dotExport === 'string') {
207
+ entryPoint = dotExport;
208
+ }
209
+ else if (typeof dotExport === 'object') {
210
+ entryPoint =
211
+ dotExport.import ||
212
+ dotExport.browser ||
213
+ dotExport.default;
214
+ }
215
+ }
216
+ }
217
+ else if (packageJson.browser &&
218
+ typeof packageJson.browser === 'string') {
219
+ entryPoint = packageJson.browser;
220
+ }
221
+ else {
222
+ entryPoint = packageJson.main || null;
223
+ }
224
+ // ✨ NUEVA VALIDACIÓN POST-RESOLUCIÓN
225
+ // Verificar si el archivo resuelto cumple con criterios de desarrollo
226
+ if (entryPoint) {
227
+ entryPoint = this.validateAndOptimizeEntryPoint(entryPoint, packageJson);
228
+ }
229
+ return entryPoint;
230
+ }
231
+ /**
232
+ * ✨ NUEVA FUNCIÓN: Valida y optimiza el entry point basado en criterios de desarrollo
233
+ */
234
+ validateAndOptimizeEntryPoint(entryPoint, packageJson) {
235
+ const isProd = env.isProd === 'true';
236
+ const fileName = entryPoint.toLowerCase();
237
+ // Si estamos en desarrollo, evitar archivos .min o .prod
238
+ if (!isProd &&
239
+ (fileName.includes('.min.') || fileName.includes('.prod.'))) {
240
+ // Buscar alternativas mejores en el package.json
241
+ const alternatives = this.findDevelopmentAlternatives(entryPoint, packageJson);
242
+ if (alternatives) {
243
+ return alternatives;
244
+ }
245
+ }
246
+ // Priorizar versiones browser y esm para mejor compatibilidad
247
+ if (fileName.includes('runtime') && !fileName.includes('browser')) {
248
+ const browserAlternative = this.findBrowserAlternative(entryPoint, packageJson);
249
+ if (browserAlternative) {
250
+ return browserAlternative;
251
+ }
252
+ }
253
+ return entryPoint;
254
+ } /**
255
+ * ✨ NUEVA FUNCIÓN: Busca alternativas de desarrollo (no minificadas)
256
+ */
257
+ findDevelopmentAlternatives(entryPoint, packageJson) {
258
+ // Crear versión de desarrollo basada en el entry point actual
259
+ const devVersion = entryPoint
260
+ .replace('.min.', '.')
261
+ .replace('.prod.', '.');
262
+ // Si hay exports, buscar en diferentes condiciones
263
+ if (packageJson.exports && typeof packageJson.exports === 'object') {
264
+ const dotExport = packageJson.exports['.'];
265
+ if (dotExport && typeof dotExport === 'object') {
266
+ // Buscar versiones development, import, browser
267
+ const candidates = [
268
+ dotExport.development,
269
+ dotExport.import,
270
+ dotExport.browser,
271
+ dotExport.default,
272
+ ].filter(Boolean);
273
+ for (const candidate of candidates) {
274
+ if (typeof candidate === 'string' &&
275
+ !candidate.includes('.min.') &&
276
+ !candidate.includes('.prod.')) {
277
+ return candidate;
278
+ }
279
+ }
280
+ }
281
+ } // Si browser field es un objeto, buscar alternativas
282
+ if (packageJson.browser && typeof packageJson.browser === 'object') {
283
+ for (const value of Object.values(packageJson.browser)) {
284
+ if (typeof value === 'string' &&
285
+ !value.includes('.min.') &&
286
+ !value.includes('.prod.') &&
287
+ (value.includes('browser') || value.includes('esm'))) {
288
+ return value;
289
+ }
290
+ }
291
+ }
292
+ return devVersion !== entryPoint ? devVersion : null;
293
+ }
294
+ /**
295
+ * ✨ NUEVA FUNCIÓN: Busca alternativas browser para versiones runtime
296
+ */
297
+ findBrowserAlternative(entryPoint, packageJson) {
298
+ // Primero intentar con exports
299
+ if (packageJson.exports && typeof packageJson.exports === 'object') {
300
+ const dotExport = packageJson.exports['.'];
301
+ if (dotExport && typeof dotExport === 'object') {
302
+ // Buscar specific browser+esm combinations
303
+ const browserKeys = Object.keys(dotExport).filter(key => key.includes('browser') &&
304
+ (key.includes('esm') || key.includes('module')));
305
+ if (browserKeys.length > 0) {
306
+ const firstBrowserKey = browserKeys[0];
307
+ if (firstBrowserKey &&
308
+ typeof dotExport[firstBrowserKey] === 'string') {
309
+ return dotExport[firstBrowserKey];
310
+ }
311
+ }
312
+ // Fallback a browser general
313
+ if (dotExport.browser &&
314
+ typeof dotExport.browser === 'string') {
315
+ return dotExport.browser;
316
+ }
317
+ }
318
+ }
319
+ // Buscar en directorio dist versiones browser
320
+ const baseName = entryPoint.replace(/\.[^/.]+$/, '');
321
+ const browserCandidates = [
322
+ baseName.replace('runtime', 'esm-browser'),
323
+ baseName.replace('runtime', 'browser'),
324
+ baseName.replace('runtime.esm-bundler', 'esm-browser'),
325
+ entryPoint.replace('runtime', 'esm-browser'),
326
+ entryPoint.replace('runtime', 'browser'),
327
+ ];
328
+ // Para Vue específicamente
329
+ if (entryPoint.includes('vue.runtime.esm-bundler')) {
330
+ browserCandidates.unshift('dist/vue.esm-browser.js', 'dist/vue.browser.esm.js');
331
+ }
332
+ return (browserCandidates.find(candidate => candidate !== entryPoint) ||
333
+ null);
334
+ }
335
+ /**
336
+ * Busca versión ESM/browser optimizada (simplificada del module-resolver)
337
+ */
338
+ findOptimalESMVersion(moduleDir, entryPoint) {
339
+ const dir = dirname(entryPoint);
340
+ const baseName = entryPoint.split('/').pop() || '';
341
+ const nameWithoutExt = baseName.replace(/\.[^/.]+$/, '');
342
+ // Determinar el nombre base sin sufijos como .runtime, .bundler, etc.
343
+ // Por ejemplo: vue.runtime.esm-bundler -> vue
344
+ const coreBaseName = nameWithoutExt.split('.')[0];
345
+ const searchDir = join(moduleDir, dir);
346
+ if (!existsSync(searchDir)) {
347
+ return undefined;
348
+ }
349
+ try {
350
+ const files = readdirSync(searchDir);
351
+ this.metrics.filesystemAccess++;
352
+ // ✨ Patrones de prioridad dinámicos según modo producción
353
+ const patterns = env.isPROD === 'true'
354
+ ? [
355
+ // 🏭 MODO PRODUCCIÓN: Priorizar versiones optimizadas
356
+ // Primero intentar con el nombre exacto
357
+ `${nameWithoutExt}.esm-browser.prod.js`,
358
+ `${nameWithoutExt}.esm-browser.min.js`,
359
+ // Luego con el nombre base (para casos como vue.runtime.esm-bundler -> vue.esm-browser.prod.js)
360
+ `${coreBaseName}.esm-browser.prod.js`,
361
+ `${coreBaseName}.esm-browser.min.js`,
362
+ `${coreBaseName}.runtime.esm-browser.prod.js`,
363
+ `${coreBaseName}.runtime.esm-browser.min.js`,
364
+ // Otros patrones ESM optimizados
365
+ `${nameWithoutExt}.esm.prod.js`,
366
+ `${nameWithoutExt}.esm.min.js`,
367
+ `${nameWithoutExt}.module.prod.js`,
368
+ `${nameWithoutExt}.module.min.js`,
369
+ `${nameWithoutExt}.browser.prod.js`,
370
+ `${nameWithoutExt}.browser.min.js`,
371
+ // Fallback a versiones de desarrollo
372
+ `${coreBaseName}.esm-browser.js`,
373
+ `${coreBaseName}.runtime.esm-browser.js`,
374
+ `${nameWithoutExt}.esm-browser.js`,
375
+ `${nameWithoutExt}.esm.js`,
376
+ `${nameWithoutExt}.module.js`,
377
+ `${nameWithoutExt}.browser.js`,
378
+ ]
379
+ : [
380
+ // 🔧 MODO DESARROLLO: Priorizar versiones sin minificar
381
+ // Primero con nombre exacto
382
+ `${nameWithoutExt}.esm-browser.js`,
383
+ // Luego con nombre base
384
+ `${coreBaseName}.esm-browser.js`,
385
+ `${coreBaseName}.runtime.esm-browser.js`,
386
+ // Otros patrones ESM
387
+ `${nameWithoutExt}.esm.js`,
388
+ `${nameWithoutExt}.module.js`,
389
+ `${nameWithoutExt}.browser.js`,
390
+ // Fallback a versiones de producción si no hay desarrollo
391
+ `${coreBaseName}.esm-browser.prod.js`,
392
+ `${coreBaseName}.runtime.esm-browser.prod.js`,
393
+ `${nameWithoutExt}.esm-browser.prod.js`,
394
+ `${nameWithoutExt}.esm.prod.js`,
395
+ ];
396
+ for (const pattern of patterns) {
397
+ if (files.includes(pattern)) {
398
+ if (env.VERBOSE === 'true') {
399
+ const mode = env.isPROD === 'true' ? '🏭 PROD' : '🔧 DEV';
400
+ logger.info(`${mode} Versión optimizada encontrada (${coreBaseName}): ${join(dir, pattern)}`);
401
+ }
402
+ return join(dir, pattern);
403
+ }
404
+ }
405
+ }
406
+ catch {
407
+ // Ignorar errores de filesystem
408
+ }
409
+ return undefined;
410
+ }
411
+ /**
412
+ * Construye el índice de alias optimizado para búsquedas rápidas
413
+ */
414
+ buildAliasIndex() {
415
+ if (!env.PATH_ALIAS) {
416
+ return;
417
+ }
418
+ try {
419
+ const pathAlias = JSON.parse(env.PATH_ALIAS);
420
+ this.aliasIndex = [];
421
+ // Convertir alias a índice con prioridad
422
+ for (const [alias, target] of Object.entries(pathAlias)) {
423
+ const pattern = alias.replace('/*', '');
424
+ const priority = pattern.length; // Patrones más largos tienen prioridad
425
+ // El regex debe coincidir con el patrón al inicio, seguido de cualquier cosa o fin de cadena
426
+ // Por ejemplo, para "@/" debe coincidir con "@/cualquier-cosa" o solo "@/"
427
+ this.aliasIndex.push({
428
+ pattern,
429
+ target: Array.isArray(target) ? target : [target],
430
+ regex: new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`),
431
+ priority,
432
+ });
433
+ }
434
+ // Ordenar por prioridad (patrones más largos primero)
435
+ this.aliasIndex.sort((a, b) => b.priority - a.priority);
436
+ if (env.VERBOSE === 'true') {
437
+ logger.info(`🔗 Índice de alias construido: ${this.aliasIndex.length} patrones`);
438
+ }
439
+ }
440
+ catch (error) {
441
+ logger.error('Error construyendo índice de alias:', error);
442
+ }
443
+ }
444
+ /**
445
+ * Resuelve un módulo utilizando el sistema optimizado
446
+ */
447
+ async resolveModule(moduleName, fromFile) {
448
+ const startTime = performance.now();
449
+ this.metrics.totalResolutions++;
450
+ // Verificar si está excluido
451
+ if (this.excludedModules.has(moduleName)) {
452
+ return {
453
+ path: null,
454
+ cached: false,
455
+ resolveTime: performance.now() - startTime,
456
+ };
457
+ }
458
+ // Crear clave de caché
459
+ const cacheKey = this.createCacheKey(moduleName, fromFile);
460
+ // Verificar caché
461
+ const cached = this.getFromCache(cacheKey);
462
+ if (cached !== undefined) {
463
+ this.metrics.cacheHits++;
464
+ return {
465
+ path: cached,
466
+ cached: true,
467
+ resolveTime: performance.now() - startTime,
468
+ fromCache: true,
469
+ };
470
+ }
471
+ this.metrics.cacheMisses++;
472
+ // Resolver módulo
473
+ let resolvedPath = null;
474
+ try {
475
+ // 1. Verificar si es subpath de módulo (ej: 'vue/dist/vue.esm-bundler')
476
+ if (moduleName.includes('/')) {
477
+ resolvedPath = await this.resolveSubPath(moduleName);
478
+ }
479
+ else {
480
+ // 2. Búsqueda O(1) en el índice
481
+ resolvedPath = this.resolveFromIndex(moduleName);
482
+ }
483
+ // 3. Si no se encuentra en índice, intentar resolución tradicional
484
+ if (!resolvedPath) {
485
+ resolvedPath = this.fallbackResolve(moduleName);
486
+ }
487
+ // Convertir a ruta relativa desde node_modules
488
+ if (resolvedPath) {
489
+ resolvedPath = this.getNodeModulesRelativePath(resolvedPath);
490
+ }
491
+ }
492
+ catch (error) {
493
+ if (env.VERBOSE === 'true') {
494
+ logger.warn(`Error resolviendo ${moduleName}:`, error);
495
+ }
496
+ }
497
+ // Guardar en caché
498
+ this.setCache(cacheKey, resolvedPath);
499
+ const resolveTime = performance.now() - startTime;
500
+ this.updateMetrics(resolveTime);
501
+ return {
502
+ path: resolvedPath,
503
+ cached: false,
504
+ resolveTime,
505
+ };
506
+ }
507
+ /**
508
+ * Busca módulo en el índice (O(1))
509
+ */
510
+ resolveFromIndex(moduleName) {
511
+ this.metrics.indexLookups++;
512
+ const moduleInfo = this.moduleIndex.get(moduleName);
513
+ if (!moduleInfo) {
514
+ return null;
515
+ }
516
+ // Usar versión optimizada si está disponible
517
+ const entryPoint = moduleInfo.optimizedEntry || moduleInfo.entryPoint;
518
+ return join(moduleInfo.fullPath, entryPoint);
519
+ }
520
+ /**
521
+ * Resuelve subpaths de módulos (ej: 'vue/dist/vue.esm-bundler')
522
+ */
523
+ async resolveSubPath(moduleName) {
524
+ const [packageName, ...subPathParts] = moduleName.split('/');
525
+ const subPath = subPathParts.join('/');
526
+ if (!packageName) {
527
+ return null;
528
+ }
529
+ this.metrics.indexLookups++;
530
+ const moduleInfo = this.moduleIndex.get(packageName);
531
+ if (!moduleInfo) {
532
+ return null;
533
+ }
534
+ // Verificar exports field para subpaths
535
+ if (moduleInfo.hasExports && moduleInfo.packageJson.exports) {
536
+ const exportKey = `./${subPath}`;
537
+ const exportPath = moduleInfo.packageJson.exports[exportKey];
538
+ if (exportPath) {
539
+ if (typeof exportPath === 'string') {
540
+ return join(moduleInfo.fullPath, exportPath);
541
+ }
542
+ else if (typeof exportPath === 'object') {
543
+ const importPath = exportPath.import || exportPath.default;
544
+ if (typeof importPath === 'string') {
545
+ return join(moduleInfo.fullPath, importPath);
546
+ }
547
+ }
548
+ }
549
+ }
550
+ // Fallback: resolver directamente el subpath
551
+ const directPath = join(moduleInfo.fullPath, subPath);
552
+ if (existsSync(directPath)) {
553
+ this.metrics.filesystemAccess++;
554
+ return directPath;
555
+ }
556
+ // Intentar con extensiones comunes
557
+ const extensions = ['.mjs', '.js', '.cjs'];
558
+ for (const ext of extensions) {
559
+ const pathWithExt = directPath + ext;
560
+ if (existsSync(pathWithExt)) {
561
+ this.metrics.filesystemAccess++;
562
+ return pathWithExt;
563
+ }
564
+ }
565
+ return null;
566
+ }
567
+ /**
568
+ * Resolución de fallback cuando no se encuentra en índice
569
+ */
570
+ fallbackResolve(moduleName) {
571
+ const nodeModulesPath = join(cwd(), 'node_modules', moduleName);
572
+ const packagePath = join(nodeModulesPath, 'package.json');
573
+ if (!existsSync(packagePath)) {
574
+ this.metrics.filesystemAccess++;
575
+ return null;
576
+ }
577
+ try {
578
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
579
+ this.metrics.filesystemAccess++;
580
+ const entryPoint = this.determineOptimalEntryPoint(packageJson) || 'index.js';
581
+ const finalPath = join(nodeModulesPath, entryPoint);
582
+ if (existsSync(finalPath)) {
583
+ this.metrics.filesystemAccess++;
584
+ return finalPath;
585
+ }
586
+ }
587
+ catch {
588
+ // Ignorar errores
589
+ }
590
+ return null;
591
+ }
592
+ /**
593
+ * Encuentra alias que coincida con el path dado
594
+ */
595
+ findMatchingAlias(path) {
596
+ this.metrics.aliasMatches++;
597
+ for (const alias of this.aliasIndex) {
598
+ if (alias.regex.test(path)) {
599
+ return alias;
600
+ }
601
+ }
602
+ return null;
603
+ } /**
604
+ * Resuelve un alias a su ruta correspondiente
605
+ */
606
+ resolveAlias(path) {
607
+ const alias = this.findMatchingAlias(path);
608
+ if (!alias || !env.PATH_DIST) {
609
+ return null;
610
+ }
611
+ // El relativePath es lo que queda después del pattern
612
+ // Por ejemplo: '@/components/Button.vue' con pattern '@/components' → '/Button.vue'
613
+ const relativePath = path.replace(alias.pattern, '');
614
+ const targetPath = alias.target[0];
615
+ if (!targetPath) {
616
+ return null;
617
+ }
618
+ // Construir ruta final
619
+ let finalPath;
620
+ const pathDist = env.PATH_DIST.replace('./', '');
621
+ // Manejar caso especial: alias exacto sin wildcard (como #config -> config/index.js)
622
+ if (relativePath === '' && !targetPath.includes('*')) {
623
+ // Es un alias exacto, usar el target tal como está
624
+ if (targetPath.startsWith('/')) {
625
+ finalPath = join('/', pathDist, targetPath.substring(1));
626
+ }
627
+ else {
628
+ const cleanTarget = targetPath.replace('./', '');
629
+ if (cleanTarget.startsWith('src/')) {
630
+ const targetWithoutSrc = cleanTarget.replace('src/', '');
631
+ finalPath = join('/', pathDist, targetWithoutSrc);
632
+ }
633
+ else {
634
+ finalPath = join('/', pathDist, cleanTarget);
635
+ }
636
+ }
637
+ }
638
+ else if (targetPath.startsWith('/')) {
639
+ // Si el target empieza con /, es una ruta absoluta desde la raíz del proyecto
640
+ // Extraer la parte del target después de /src
641
+ const targetWithoutSlash = targetPath
642
+ .substring(1)
643
+ .replace('/*', '');
644
+ // El target puede ser:
645
+ // - "/src/*" → queremos mapear a "/dist/*"
646
+ // - "/src/components/*" → queremos mapear a "/dist/components/*"
647
+ if (targetWithoutSlash === 'src') {
648
+ // Para "/src/*", mapear directamente a "/pathDist/relativePath"
649
+ finalPath = join('/', pathDist, relativePath);
650
+ }
651
+ else if (targetWithoutSlash.startsWith('src/')) {
652
+ // Para "/src/components/*", extraer "components" y usarlo
653
+ // targetWithoutSlash = 'src/components'
654
+ // Queremos: 'components'
655
+ const targetSubpath = targetWithoutSlash.replace(/^src\/?/, '');
656
+ // relativePath ya incluye la barra inicial
657
+ finalPath = join('/', pathDist, targetSubpath, relativePath);
658
+ }
659
+ else {
660
+ // Para otros casos como "/examples/*"
661
+ finalPath = join('/', pathDist, targetWithoutSlash, relativePath);
662
+ }
663
+ }
664
+ else {
665
+ // Si es una ruta relativa, construir basándose en el target
666
+ const cleanTarget = targetPath.replace('./', '').replace('/*', '');
667
+ // Si el target ya incluye el directorio de distribución, no duplicar
668
+ if (cleanTarget === pathDist) {
669
+ finalPath = join('/', pathDist, relativePath);
670
+ }
671
+ else if (cleanTarget.startsWith(pathDist + '/')) {
672
+ // Si el target ya contiene PATH_DIST como prefijo
673
+ finalPath = join('/', cleanTarget, relativePath);
674
+ }
675
+ else {
676
+ // Caso normal: mapear manteniendo la estructura relativa al target
677
+ if (cleanTarget.startsWith('src/')) {
678
+ // Para "src/components/*" -> "/pathDist/components/*"
679
+ const targetWithoutSrc = cleanTarget.replace('src/', '');
680
+ finalPath = join('/', pathDist, targetWithoutSrc, relativePath);
681
+ }
682
+ else {
683
+ // Para casos como "examples/*" -> "/pathDist/*"
684
+ // No incluir el directorio raíz en la ruta final
685
+ const isRootDirectory = [
686
+ 'examples',
687
+ 'src',
688
+ 'app',
689
+ 'lib',
690
+ ].includes(cleanTarget);
691
+ if (isRootDirectory) {
692
+ finalPath = join('/', pathDist, relativePath);
693
+ }
694
+ else {
695
+ // Para subdirectorios específicos, mantener la estructura
696
+ finalPath = join('/', pathDist, cleanTarget, relativePath);
697
+ }
698
+ }
699
+ }
700
+ }
701
+ return finalPath.replace(/\\/g, '/');
702
+ }
703
+ /**
704
+ * Gestión de caché LRU
705
+ */
706
+ getFromCache(key) {
707
+ const entry = this.resolutionCache.get(key);
708
+ if (!entry) {
709
+ return undefined;
710
+ }
711
+ // Verificar expiración
712
+ if (Date.now() - entry.timestamp > this.cacheMaxAge) {
713
+ this.resolutionCache.delete(key);
714
+ this.cacheOrder = this.cacheOrder.filter(k => k !== key);
715
+ return undefined;
716
+ }
717
+ // Actualizar orden LRU
718
+ entry.hits++;
719
+ this.cacheOrder = this.cacheOrder.filter(k => k !== key);
720
+ this.cacheOrder.push(key);
721
+ return entry.result;
722
+ }
723
+ setCache(key, result) {
724
+ // Implementar límite de caché LRU
725
+ if (this.resolutionCache.size >= this.maxCacheSize) {
726
+ const oldestKey = this.cacheOrder.shift();
727
+ if (oldestKey) {
728
+ this.resolutionCache.delete(oldestKey);
729
+ }
730
+ }
731
+ this.resolutionCache.set(key, {
732
+ result,
733
+ timestamp: Date.now(),
734
+ hits: 0,
735
+ });
736
+ this.cacheOrder.push(key);
737
+ }
738
+ createCacheKey(moduleName, fromFile) {
739
+ const hash = createHash('md5');
740
+ hash.update(moduleName);
741
+ if (fromFile) {
742
+ hash.update(fromFile);
743
+ }
744
+ return hash.digest('hex');
745
+ }
746
+ /**
747
+ * Convierte ruta absoluta a ruta relativa desde node_modules
748
+ */
749
+ getNodeModulesRelativePath(fullPath) {
750
+ const idx = fullPath.indexOf('node_modules');
751
+ if (idx !== -1) {
752
+ return '/' + fullPath.substring(idx).replace(/\\/g, '/');
753
+ }
754
+ // Para rutas que no están en node_modules
755
+ const rel = relative(cwd(), fullPath).replace(/\\/g, '/');
756
+ return rel.startsWith('/') ? rel : '/' + rel;
757
+ }
758
+ /**
759
+ * Actualiza métricas de rendimiento
760
+ */
761
+ updateMetrics(resolveTime) {
762
+ this.metrics.averageResolveTime =
763
+ (this.metrics.averageResolveTime *
764
+ (this.metrics.totalResolutions - 1) +
765
+ resolveTime) /
766
+ this.metrics.totalResolutions;
767
+ }
768
+ /**
769
+ * Configura actualización periódica de índices
770
+ */
771
+ setupPeriodicRefresh() {
772
+ setInterval(() => {
773
+ if (Date.now() - this.lastIndexUpdate > this.indexRefreshInterval) {
774
+ if (env.VERBOSE === 'true') {
775
+ logger.info('🔄 Actualizando índices de resolución de módulos');
776
+ }
777
+ this.refreshIndexes();
778
+ }
779
+ }, this.indexRefreshInterval);
780
+ }
781
+ /**
782
+ * Actualiza los índices manteniendo el caché válido
783
+ */
784
+ refreshIndexes() {
785
+ try {
786
+ const oldSize = this.moduleIndex.size;
787
+ this.buildModuleIndex();
788
+ this.buildAliasIndex();
789
+ this.lastIndexUpdate = Date.now();
790
+ if (env.VERBOSE === 'true') {
791
+ logger.info(`📚 Índices actualizados: ${oldSize} → ${this.moduleIndex.size} módulos`);
792
+ }
793
+ }
794
+ catch (error) {
795
+ logger.error('Error actualizando índices:', error);
796
+ }
797
+ }
798
+ /**
799
+ * Limpia caché expirado
800
+ */
801
+ clearExpiredCache() {
802
+ const now = Date.now();
803
+ const keysToDelete = [];
804
+ for (const [key, entry] of this.resolutionCache.entries()) {
805
+ if (now - entry.timestamp > this.cacheMaxAge) {
806
+ keysToDelete.push(key);
807
+ }
808
+ }
809
+ for (const key of keysToDelete) {
810
+ this.resolutionCache.delete(key);
811
+ this.cacheOrder = this.cacheOrder.filter(k => k !== key);
812
+ }
813
+ if (env.VERBOSE === 'true' && keysToDelete.length > 0) {
814
+ logger.info(`🧹 Limpiado caché expirado: ${keysToDelete.length} entradas`);
815
+ }
816
+ }
817
+ /**
818
+ * Obtiene métricas de rendimiento
819
+ */
820
+ getMetrics() {
821
+ return {
822
+ ...this.metrics,
823
+ cacheSize: this.resolutionCache.size,
824
+ moduleIndexSize: this.moduleIndex.size,
825
+ aliasIndexSize: this.aliasIndex.length,
826
+ cacheHitRate: this.metrics.totalResolutions > 0
827
+ ? (this.metrics.cacheHits / this.metrics.totalResolutions) *
828
+ 100
829
+ : 0,
830
+ };
831
+ }
832
+ /**
833
+ * Resetea métricas de rendimiento
834
+ */
835
+ resetMetrics() {
836
+ this.metrics = {
837
+ totalResolutions: 0,
838
+ cacheHits: 0,
839
+ cacheMisses: 0,
840
+ averageResolveTime: 0,
841
+ indexLookups: 0,
842
+ filesystemAccess: 0,
843
+ aliasMatches: 0,
844
+ };
845
+ }
846
+ /**
847
+ * Forzar reconstrucción de índices
848
+ */
849
+ forceRefresh() {
850
+ this.initializeIndexes();
851
+ this.resolutionCache.clear();
852
+ this.cacheOrder = [];
853
+ if (env.VERBOSE === 'true') {
854
+ logger.info('🔄 Índices de resolución reconstruidos forzosamente');
855
+ }
856
+ }
857
+ /**
858
+ * Limpia todos los cachés y índices
859
+ */
860
+ cleanup() {
861
+ this.moduleIndex.clear();
862
+ this.resolutionCache.clear();
863
+ this.cacheOrder = [];
864
+ this.aliasIndex = [];
865
+ this.nodeModulesCache.clear();
866
+ if (env.VERBOSE === 'true') {
867
+ logger.info('🧹 Sistema de resolución de módulos limpiado');
868
+ }
869
+ }
870
+ }
871
+ // Funciones de compatibilidad con el sistema existente
872
+ export async function getOptimizedModulePath(moduleName, fromFile) {
873
+ const optimizer = ModuleResolutionOptimizer.getInstance();
874
+ const result = await optimizer.resolveModule(moduleName, fromFile);
875
+ return result.path;
876
+ }
877
+ export function getOptimizedAliasPath(path) {
878
+ const optimizer = ModuleResolutionOptimizer.getInstance();
879
+ return optimizer.resolveAlias(path);
880
+ }
881
+ export function getModuleResolutionMetrics() {
882
+ const optimizer = ModuleResolutionOptimizer.getInstance();
883
+ return optimizer.getMetrics();
884
+ }
885
+ export function resetModuleResolutionOptimizer() {
886
+ ModuleResolutionOptimizer.resetInstance();
887
+ }
888
+ //# sourceMappingURL=module-resolution-optimizer.js.map