versacompiler 2.0.0 → 2.0.1

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