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,552 @@
1
- import e,{readFileSync as t}from"node:fs";import{dirname as n,join as r,relative as i}from"node:path";import{cwd as a,env as o}from"node:process";import{logger as s}from"../servicios/logger.js";import{EXCLUDED_MODULES as c}from"./excluded-modules.js";function l(t,i){let a=n(i),c=(i.split(`/`).pop()||``).replace(/\.[^/.]+$/,``),l=r(t,a);if(!e.existsSync(l))return i;try{let t=e.readdirSync(l),n=[`${c}.esm-browser.js`,`${c}.esm.all.js`,`${c}.esm.js`,`${c}.module.js`,`${c}.browser.js`,`${c}.web.js`,`${c}.umd.js`,`${c}.global.js`,`${c}.esm-browser.min.js`,`${c}.esm-browser.prod.js`,`${c}.esm.all.min.js`,`${c}.esm.min.js`,`${c}.module.min.js`,`${c}.browser.min.js`,`${c}.browser.prod.js`,`${c}.web.min.js`,`${c}.umd.min.js`,`${c}.global.min.js`,`${c}.min.js`,`${c}.runtime.esm-browser.js`,`${c}.runtime.esm-browser.min.js`,`${c}.runtime.esm-browser.prod.js`];for(let e of n)if(t.includes(e))return r(a,e).replace(/\\/g,`/`);let i=t.filter(e=>{let t=e.toLowerCase();return(t.includes(`.esm-browser.`)||t.includes(`.esm.`)||t.includes(`.module.`)||t.includes(`.browser.`)||t.includes(`.web.`)||t.includes(`.runtime.esm-browser.`))&&(e.endsWith(`.js`)||e.endsWith(`.mjs`))});if(i.length>0){let e=i.filter(e=>e.toLowerCase().includes(`.esm-browser.`)&&!e.toLowerCase().includes(`.runtime.`));if(e.length>0){let t=e.filter(e=>!e.toLowerCase().includes(`.prod.`)&&!e.toLowerCase().includes(`.min.`));if(t.length>0&&t[0])return r(a,t[0]).replace(/\\/g,`/`);let n=e.filter(e=>e.toLowerCase().includes(`.prod.`));if(n.length>0&&n[0]){let e=r(a,n[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión ESM-Browser producción encontrada: ${e}`),e}let i=e.filter(e=>e.toLowerCase().includes(`.min.`));if(i.length>0&&i[0]){let e=r(a,i[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión ESM-Browser minificada encontrada: ${e}`),e}if(e[0]){let t=r(a,e[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión ESM-Browser encontrada: ${t}`),t}}let t=i.filter(e=>(e.toLowerCase().includes(`.esm.`)||e.toLowerCase().includes(`.module.`))&&!e.toLowerCase().includes(`.min.`)&&!e.toLowerCase().includes(`.prod.`)&&!e.toLowerCase().includes(`.runtime.`));if(t.length>0&&t[0]){let e=r(a,t[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión ESM dev encontrada: ${e}`),e}let n=i.filter(e=>(e.toLowerCase().includes(`.min.`)||e.toLowerCase().includes(`.prod.`))&&!e.toLowerCase().includes(`.runtime.`));if(n.length>0){let e=n.filter(e=>e.toLowerCase().includes(`.esm.`)||e.toLowerCase().includes(`.module.`));if(e.length>0&&e[0]){let t=r(a,e[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión ESM minificada encontrada: ${t}`),t}if(n[0]){let e=r(a,n[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión minificada encontrada: ${e}`),e}}let c=i.filter(e=>e.toLowerCase().includes(`.runtime.esm-browser.`));if(c.length>0){let e=c.filter(e=>!e.toLowerCase().includes(`.prod.`)&&!e.toLowerCase().includes(`.min.`));if(e.length>0&&e[0]){let t=r(a,e[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión Runtime ESM-Browser dev encontrada: ${t}`),t}if(c[0]){let e=r(a,c[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión Runtime ESM-Browser encontrada: ${e}`),e}}if(i[0]){let e=r(a,i[0]).replace(/\\/g,`/`);return o.VERBOSE===`true`&&s.info(`Versión browser encontrada: ${e}`),e}}}catch(e){o.VERBOSE===`true`&&s.warn(`No se pudo leer directorio ${l}:`,e instanceof Error?e.message:String(e))}return i}function u(i){try{let c=r(a(),`node_modules`,i),u;try{if(u=r(c,`package.json`),!e.existsSync(u))throw Error(`No se encontró package.json para ${i}`)}catch{return null}let d=JSON.parse(t(u,`utf-8`)),f=n(u),p=d.type===`module`,m=null;if(d.module)m=d.module;else if(d.exports){if(typeof d.exports==`string`)m=d.exports;else if(d.exports[`.`]){let e=d.exports[`.`];if(typeof e==`string`)m=e;else if(typeof e==`object`){let t=Object.keys(e).find(e=>e.includes(`browser`)&&(e.includes(`esm`)||e.includes(`module`)));m=t&&typeof e[t]==`string`?e[t]:(typeof e.import==`string`?e.import:null)||e.browser||(typeof e.default==`string`?e.default:null)}}}else d.browser?typeof d.browser==`string`?m=d.browser:typeof d.browser==`object`&&(m=d.browser[`.`]||d.browser[d.main]):d.main&&(m=d.main);m||(m=p?`index.js`:`index.cjs`),typeof m!=`string`&&(o.VERBOSE===`true`&&s.warn(`Entry point no es string para ${i}:`,m),m=p?`index.js`:`index.cjs`);let h=r(f,m),g=l(f,m);if(g&&g!==m&&(h=r(f,g)),p&&d.imports){let n=new Map;for(let[e,t]of Object.entries(d.imports))if(typeof t==`string`)n.set(e,r(f,t));else if(typeof t==`object`&&t){let i=t,a=i.browser||i.default||i.node;a&&n.set(e,r(f,a))}if(e.existsSync(h)){let e=t(h,`utf-8`),r=Array.from(e.matchAll(/from\s+['"]([#@][^'"]+)['"]/g));if(r.length>0){o.VERBOSE===`true`&&s.info(`Módulo ${i} usa imports privados:`,r.map(e=>e[1]));for(let e of r){let[,t]=e;n.has(t)||o.VERBOSE===`true`&&s.warn(`Import privado no resuelto: ${t} en ${i}`)}}}}if(!e.existsSync(h)){let t=[m,m.replace(`.js`,`.mjs`),m.replace(`.mjs`,`.js`),m.replace(`.js`,`.cjs`),`index.mjs`,`index.js`,`index.cjs`];for(let n of t){let t=r(f,n);if(e.existsSync(t)){h=t;break}}}return h}catch(e){return o.VERBOSE===`true`&&s.error(`Error resolviendo ${i}: ${e instanceof Error?e.message:String(e)}`),null}}function d(e,t){if(!e)return null;let n=e.indexOf(`node_modules`);if(n!==-1)return`/`+e.substring(n).replace(/\\/g,`/`);let r=i(a(),e).replace(/\\/g,`/`);return r||(r=`.`),r.startsWith(`/`)||(r=`/`+r),r}export function getModulePath(e,t){return c.has(e)?null:d(u(e),t)}export function getModuleSubPath(i,l){if(c.has(i))return null;if(i.includes(`/`)){let[c,...u]=i.split(`/`),f=u.join(`/`);if(!c)return null;try{let i=r(r(a(),`node_modules`,c),`package.json`);if(!e.existsSync(i))return null;let o=JSON.parse(t(i,`utf-8`)),s=n(i);if(o.exports&&typeof o.exports==`object`){let e=`./${f}`,t=o.exports[e];if(t){if(typeof t==`string`)return d(r(s,t),l);if(typeof t==`object`){let e=t.import||t.default;if(typeof e==`string`)return d(r(s,e),l)}}}let u=r(s,f);if(e.existsSync(u))return d(u,l);for(let t of[`.mjs`,`.js`,`.cjs`]){let n=u+t;if(e.existsSync(n))return d(n,l)}}catch(e){o.VERBOSE===`true`&&s.error(`Error resolviendo subpath ${i}:`,e instanceof Error?e.message:String(e))}}return getModulePath(i,l)}
1
+ // Opción con librería '/node_modules/resolve/index.js' (npm install resolve)
2
+ import fs, { readFileSync } from 'node:fs';
3
+ import { dirname, join, relative } from 'node:path';
4
+ import { cwd, env } from 'node:process';
5
+ // import pkg from '/node_modules/enhanced-resolve/lib/index.js';
6
+ // import resolve from '/node_modules/resolve/index.js';
7
+ import { logger } from '../servicios/logger.js';
8
+ import { EXCLUDED_MODULES } from './excluded-modules.js';
9
+ // function resolveESMWithLibrary(moduleName: string): string | null {
10
+ // try {
11
+ // // Resolver el módulo
12
+ // const resolved = resolve.sync(moduleName, {
13
+ // basedir: process.cwd(),
14
+ // packageFilter: (pkg: any) => {
15
+ // // Priorizar campos ESM
16
+ // if (pkg.module) pkg.main = pkg.module;
17
+ // else if (pkg.exports?.['.']?.import)
18
+ // pkg.main = pkg.exports['.'].import;
19
+ // else if (pkg.exports?.import) pkg.main = pkg.exports.import;
20
+ // return pkg;
21
+ // },
22
+ // });
23
+ // return resolved;
24
+ // } catch (error) {
25
+ // if (env.VERBOSE === 'true')
26
+ // logger.error(
27
+ // `Error resolviendo ${moduleName}:`,
28
+ // error instanceof Error ? error.message : String(error),
29
+ // );
30
+ // return null;
31
+ // }
32
+ // }
33
+ // Opción con '/node_modules/enhanced-resolve/lib/index.js' (webpack's resolver)
34
+ // npm install enhanced-resolve
35
+ // const { ResolverFactory } = pkg;
36
+ // const resolver = ResolverFactory.createResolver({
37
+ // fileSystem: {
38
+ // readFile,
39
+ // readlink,
40
+ // stat,
41
+ // readdir,
42
+ // },
43
+ // conditionNames: ['import', 'module', 'default'], // Priorizar ESM
44
+ // extensions: ['.mjs', '.js', '.json'],
45
+ // mainFields: ['module', 'main'], // Priorizar campo 'module'
46
+ // aliasFields: ['browser'],
47
+ // });
48
+ // function resolveESMEnhanced(moduleName: string): Promise<string | null> {
49
+ // return new Promise((resolve, reject) => {
50
+ // resolver.resolve({}, process.cwd(), moduleName, {}, (err, result) => {
51
+ // if (err) reject(err);
52
+ // else resolve(result as string);
53
+ // });
54
+ // });
55
+ // }
56
+ // Función para buscar la mejor versión ESM/browser optimizada de un archivo
57
+ function findOptimalESMVersion(moduleDir, entryPoint) {
58
+ const dir = dirname(entryPoint);
59
+ const baseName = entryPoint.split('/').pop() || '';
60
+ const nameWithoutExt = baseName.replace(/\.[^/.]+$/, '');
61
+ // Directorio donde buscar
62
+ const searchDir = join(moduleDir, dir);
63
+ if (!fs.existsSync(searchDir)) {
64
+ return entryPoint;
65
+ }
66
+ try {
67
+ const files = fs.readdirSync(searchDir);
68
+ // ✨ Patrones de prioridad dinámicos según modo producción
69
+ const priorityPatterns = env.isPROD === 'true'
70
+ ? [
71
+ // 🏭 MODO PRODUCCIÓN: Priorizar versiones optimizadas
72
+ // Máxima prioridad: ESM-Browser producción
73
+ `${nameWithoutExt}.esm-browser.prod.js`,
74
+ `${nameWithoutExt}.esm-browser.min.js`,
75
+ // ESM producción
76
+ `${nameWithoutExt}.esm.prod.js`,
77
+ `${nameWithoutExt}.esm.min.js`,
78
+ `${nameWithoutExt}.module.prod.js`,
79
+ `${nameWithoutExt}.module.min.js`,
80
+ // Browser producción
81
+ `${nameWithoutExt}.browser.prod.js`,
82
+ `${nameWithoutExt}.browser.min.js`,
83
+ `${nameWithoutExt}.web.prod.js`,
84
+ `${nameWithoutExt}.web.min.js`,
85
+ // Global/UMD producción
86
+ `${nameWithoutExt}.global.prod.js`,
87
+ `${nameWithoutExt}.global.min.js`,
88
+ `${nameWithoutExt}.umd.prod.js`,
89
+ `${nameWithoutExt}.umd.min.js`,
90
+ `${nameWithoutExt}.min.js`,
91
+ // Fallback a versiones de desarrollo si no hay producción
92
+ `${nameWithoutExt}.esm-browser.js`,
93
+ `${nameWithoutExt}.esm.js`,
94
+ `${nameWithoutExt}.module.js`,
95
+ `${nameWithoutExt}.browser.js`,
96
+ `${nameWithoutExt}.web.js`,
97
+ `${nameWithoutExt}.umd.js`,
98
+ `${nameWithoutExt}.global.js`,
99
+ // Último recurso: versiones runtime
100
+ `${nameWithoutExt}.runtime.esm-browser.prod.js`,
101
+ `${nameWithoutExt}.runtime.esm-browser.min.js`,
102
+ `${nameWithoutExt}.runtime.esm-browser.js`,
103
+ ]
104
+ : [
105
+ // 🔧 MODO DESARROLLO: Priorizar versiones sin minificar
106
+ // Máxima prioridad: ESM-Browser desarrollo
107
+ `${nameWithoutExt}.esm-browser.js`,
108
+ // ESM puro sin minificar
109
+ `${nameWithoutExt}.esm.all.js`,
110
+ `${nameWithoutExt}.esm.js`,
111
+ `${nameWithoutExt}.module.js`,
112
+ // Browser puro sin minificar
113
+ `${nameWithoutExt}.browser.js`,
114
+ `${nameWithoutExt}.web.js`,
115
+ // UMD sin minificar
116
+ `${nameWithoutExt}.umd.js`,
117
+ `${nameWithoutExt}.global.js`,
118
+ // Fallback a versiones minificadas
119
+ `${nameWithoutExt}.esm-browser.prod.js`,
120
+ `${nameWithoutExt}.esm-browser.min.js`,
121
+ `${nameWithoutExt}.esm.prod.js`,
122
+ `${nameWithoutExt}.esm.min.js`,
123
+ `${nameWithoutExt}.module.min.js`,
124
+ `${nameWithoutExt}.browser.prod.js`,
125
+ `${nameWithoutExt}.browser.min.js`,
126
+ `${nameWithoutExt}.web.min.js`,
127
+ `${nameWithoutExt}.umd.min.js`,
128
+ `${nameWithoutExt}.global.min.js`,
129
+ `${nameWithoutExt}.min.js`,
130
+ // Último recurso: versiones runtime
131
+ `${nameWithoutExt}.runtime.esm-browser.js`,
132
+ `${nameWithoutExt}.runtime.esm-browser.min.js`,
133
+ `${nameWithoutExt}.runtime.esm-browser.prod.js`,
134
+ ];
135
+ // Buscar archivos que coincidan exactamente con los patrones
136
+ for (const pattern of priorityPatterns) {
137
+ if (files.includes(pattern)) {
138
+ const optimizedPath = join(dir, pattern).replace(/\\/g, '/');
139
+ if (env.VERBOSE === 'true') {
140
+ logger.info(`📦 Versión optimizada encontrada (${env.isPROD === 'true' ? 'PROD' : 'DEV'}): ${optimizedPath}`);
141
+ }
142
+ return optimizedPath;
143
+ }
144
+ } // Buscar archivos que contengan patrones ESM/browser dinámicamente
145
+ const esmBrowserFiles = files.filter((file) => {
146
+ const lowerFile = file.toLowerCase();
147
+ return ((lowerFile.includes('.esm-browser.') || // Prioridad alta: combinación esm-browser
148
+ lowerFile.includes('.esm.') ||
149
+ lowerFile.includes('.module.') ||
150
+ lowerFile.includes('.browser.') ||
151
+ lowerFile.includes('.web.') ||
152
+ lowerFile.includes('.runtime.esm-browser.')) && // Runtime como última opción
153
+ (file.endsWith('.js') || file.endsWith('.mjs')));
154
+ });
155
+ if (esmBrowserFiles.length > 0) {
156
+ // Primera prioridad: archivos que combinan ESM y Browser (sin runtime)
157
+ const esmBrowserCombined = esmBrowserFiles.filter((file) => file.toLowerCase().includes('.esm-browser.') &&
158
+ !file.toLowerCase().includes('.runtime.'));
159
+ if (esmBrowserCombined.length > 0) {
160
+ // ✨ MODO PRODUCCIÓN: Priorizar .prod.js o .min.js
161
+ if (env.isPROD === 'true') {
162
+ // Primera opción: archivos .prod.js
163
+ const prodFiles = esmBrowserCombined.filter((file) => file.toLowerCase().includes('.prod.'));
164
+ if (prodFiles.length > 0 && prodFiles[0]) {
165
+ const optimizedPath = join(dir, prodFiles[0]).replace(/\\/g, '/');
166
+ if (env.VERBOSE === 'true') {
167
+ logger.info(`🏭 Versión ESM-Browser producción encontrada: ${optimizedPath}`);
168
+ }
169
+ return optimizedPath;
170
+ }
171
+ // Segunda opción: archivos .min.js
172
+ const minFiles = esmBrowserCombined.filter((file) => file.toLowerCase().includes('.min.'));
173
+ if (minFiles.length > 0 && minFiles[0]) {
174
+ const optimizedPath = join(dir, minFiles[0]).replace(/\\/g, '/');
175
+ if (env.VERBOSE === 'true') {
176
+ logger.info(`🗜️ Versión ESM-Browser minificada encontrada: ${optimizedPath}`);
177
+ }
178
+ return optimizedPath;
179
+ }
180
+ // Fallback: si no hay .prod ni .min, usar desarrollo
181
+ if (env.VERBOSE === 'true') {
182
+ logger.warn('⚠️ No se encontró versión de producción, usando desarrollo');
183
+ }
184
+ }
185
+ // ✨ MODO DESARROLLO: Priorizar desarrollo > .prod > .min
186
+ const devFiles = esmBrowserCombined.filter((file) => !file.toLowerCase().includes('.prod.') &&
187
+ !file.toLowerCase().includes('.min.'));
188
+ if (devFiles.length > 0 && devFiles[0]) {
189
+ const optimizedPath = join(dir, devFiles[0]).replace(/\\/g, '/');
190
+ if (env.VERBOSE === 'true') {
191
+ logger.info(`🔧 Versión ESM-Browser desarrollo encontrada: ${optimizedPath}`);
192
+ }
193
+ return optimizedPath;
194
+ }
195
+ // Fallback en desarrollo: si no hay versión dev, usar prod
196
+ const prodFiles = esmBrowserCombined.filter((file) => file.toLowerCase().includes('.prod.'));
197
+ if (prodFiles.length > 0 && prodFiles[0]) {
198
+ const optimizedPath = join(dir, prodFiles[0]).replace(/\\/g, '/');
199
+ if (env.VERBOSE === 'true') {
200
+ logger.info(`Versión ESM-Browser producción encontrada (fallback): ${optimizedPath}`);
201
+ }
202
+ return optimizedPath;
203
+ }
204
+ const minFiles = esmBrowserCombined.filter((file) => file.toLowerCase().includes('.min.'));
205
+ if (minFiles.length > 0 && minFiles[0]) {
206
+ const optimizedPath = join(dir, minFiles[0]).replace(/\\/g, '/');
207
+ if (env.VERBOSE === 'true') {
208
+ logger.info(`Versión ESM-Browser minificada encontrada (fallback): ${optimizedPath}`);
209
+ }
210
+ return optimizedPath;
211
+ }
212
+ if (esmBrowserCombined[0]) {
213
+ const optimizedPath = join(dir, esmBrowserCombined[0]).replace(/\\/g, '/');
214
+ if (env.VERBOSE === 'true') {
215
+ logger.info(`Versión ESM-Browser encontrada: ${optimizedPath}`);
216
+ }
217
+ return optimizedPath;
218
+ }
219
+ }
220
+ // Segunda prioridad: cualquier versión ESM disponible
221
+ if (env.isPROD === 'true') {
222
+ // En producción, buscar versiones minificadas/prod primero
223
+ const esmProdFiles = esmBrowserFiles.filter((file) => (file.toLowerCase().includes('.esm.') ||
224
+ file.toLowerCase().includes('.module.')) &&
225
+ (file.toLowerCase().includes('.prod.') ||
226
+ file.toLowerCase().includes('.min.')) &&
227
+ !file.toLowerCase().includes('.runtime.'));
228
+ if (esmProdFiles.length > 0 && esmProdFiles[0]) {
229
+ const optimizedPath = join(dir, esmProdFiles[0]).replace(/\\/g, '/');
230
+ if (env.VERBOSE === 'true') {
231
+ logger.info(`🏭 Versión ESM producción encontrada: ${optimizedPath}`);
232
+ }
233
+ return optimizedPath;
234
+ }
235
+ }
236
+ else {
237
+ // En desarrollo, buscar versiones sin minificar
238
+ const esmFiles = esmBrowserFiles.filter((file) => (file.toLowerCase().includes('.esm.') ||
239
+ file.toLowerCase().includes('.module.')) &&
240
+ !file.toLowerCase().includes('.min.') &&
241
+ !file.toLowerCase().includes('.prod.') &&
242
+ !file.toLowerCase().includes('.runtime.'));
243
+ if (esmFiles.length > 0 && esmFiles[0]) {
244
+ const optimizedPath = join(dir, esmFiles[0]).replace(/\\/g, '/');
245
+ if (env.VERBOSE === 'true') {
246
+ logger.info(`🔧 Versión ESM desarrollo encontrada: ${optimizedPath}`);
247
+ }
248
+ return optimizedPath;
249
+ }
250
+ }
251
+ // Tercera prioridad: archivos minificados de cualquier tipo ESM/browser (sin runtime)
252
+ const minifiedFiles = esmBrowserFiles.filter((file) => (file.toLowerCase().includes('.min.') ||
253
+ file.toLowerCase().includes('.prod.')) &&
254
+ !file.toLowerCase().includes('.runtime.'));
255
+ if (minifiedFiles.length > 0) {
256
+ // Priorizar ESM sobre browser sobre UMD
257
+ const esmFiles = minifiedFiles.filter((file) => file.toLowerCase().includes('.esm.') ||
258
+ file.toLowerCase().includes('.module.'));
259
+ if (esmFiles.length > 0 && esmFiles[0]) {
260
+ const optimizedPath = join(dir, esmFiles[0]).replace(/\\/g, '/');
261
+ if (env.VERBOSE === 'true') {
262
+ logger.info(`Versión ESM minificada encontrada: ${optimizedPath}`);
263
+ }
264
+ return optimizedPath;
265
+ }
266
+ if (minifiedFiles[0]) {
267
+ const optimizedPath = join(dir, minifiedFiles[0]).replace(/\\/g, '/');
268
+ if (env.VERBOSE === 'true') {
269
+ logger.info(`Versión minificada encontrada: ${optimizedPath}`);
270
+ }
271
+ return optimizedPath;
272
+ }
273
+ }
274
+ // Cuarta prioridad: versiones runtime como último recurso
275
+ const runtimeFiles = esmBrowserFiles.filter((file) => file.toLowerCase().includes('.runtime.esm-browser.'));
276
+ if (runtimeFiles.length > 0) {
277
+ // Priorizar desarrollo sobre producción en runtime también
278
+ const devRuntimeFiles = runtimeFiles.filter((file) => !file.toLowerCase().includes('.prod.') &&
279
+ !file.toLowerCase().includes('.min.'));
280
+ if (devRuntimeFiles.length > 0 && devRuntimeFiles[0]) {
281
+ const optimizedPath = join(dir, devRuntimeFiles[0]).replace(/\\/g, '/');
282
+ if (env.VERBOSE === 'true') {
283
+ logger.info(`Versión Runtime ESM-Browser dev encontrada: ${optimizedPath}`);
284
+ }
285
+ return optimizedPath;
286
+ }
287
+ if (runtimeFiles[0]) {
288
+ const optimizedPath = join(dir, runtimeFiles[0]).replace(/\\/g, '/');
289
+ if (env.VERBOSE === 'true') {
290
+ logger.info(`Versión Runtime ESM-Browser encontrada: ${optimizedPath}`);
291
+ }
292
+ return optimizedPath;
293
+ }
294
+ }
295
+ // Fallback: cualquier versión browser
296
+ if (esmBrowserFiles[0]) {
297
+ const optimizedPath = join(dir, esmBrowserFiles[0]).replace(/\\/g, '/');
298
+ if (env.VERBOSE === 'true') {
299
+ logger.info(`Versión browser encontrada: ${optimizedPath}`);
300
+ }
301
+ return optimizedPath;
302
+ }
303
+ }
304
+ }
305
+ catch (error) {
306
+ if (env.VERBOSE === 'true') {
307
+ logger.warn(`No se pudo leer directorio ${searchDir}:`, error instanceof Error ? error.message : String(error));
308
+ }
309
+ }
310
+ return entryPoint; // Fallback al entry point original
311
+ }
312
+ // Función mejorada para detectar automáticamente entry points browser-compatible
313
+ function simpleESMResolver(moduleName) {
314
+ try {
315
+ const nodeModulesPath = join(cwd(), 'node_modules', moduleName);
316
+ let packagePath;
317
+ try {
318
+ packagePath = join(nodeModulesPath, 'package.json');
319
+ if (!fs.existsSync(packagePath)) {
320
+ throw new Error(`No se encontró package.json para ${moduleName}`);
321
+ }
322
+ }
323
+ catch {
324
+ return null;
325
+ }
326
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
327
+ const moduleDir = dirname(packagePath);
328
+ const isESM = packageJson.type === 'module'; // Determinar el entry point ESM/Browser optimizado
329
+ let entryPoint = null;
330
+ // 1. Prioridad máxima: campo module para ESM
331
+ if (packageJson.module) {
332
+ entryPoint = packageJson.module;
333
+ }
334
+ // 2. Revisar exports field con prioridad ESM
335
+ else if (packageJson.exports) {
336
+ if (typeof packageJson.exports === 'string') {
337
+ entryPoint = packageJson.exports;
338
+ }
339
+ else if (packageJson.exports['.']) {
340
+ const dotExport = packageJson.exports['.'];
341
+ if (typeof dotExport === 'string') {
342
+ entryPoint = dotExport;
343
+ }
344
+ else if (typeof dotExport === 'object') {
345
+ // Priorizar import > browser > default para compatibilidad ESM
346
+ // Buscar específicamente patrones esm-browser primero
347
+ const exportKeys = Object.keys(dotExport);
348
+ const esmBrowserKey = exportKeys.find(key => key.includes('browser') &&
349
+ (key.includes('esm') || key.includes('module')));
350
+ if (esmBrowserKey &&
351
+ typeof dotExport[esmBrowserKey] === 'string') {
352
+ entryPoint = dotExport[esmBrowserKey];
353
+ }
354
+ else {
355
+ // Priorizar import > browser > default
356
+ entryPoint =
357
+ (typeof dotExport.import === 'string'
358
+ ? dotExport.import
359
+ : null) ||
360
+ dotExport.browser ||
361
+ (typeof dotExport.default === 'string'
362
+ ? dotExport.default
363
+ : null);
364
+ }
365
+ }
366
+ }
367
+ }
368
+ // 3. Revisar browser field específico
369
+ else if (packageJson.browser) {
370
+ if (typeof packageJson.browser === 'string') {
371
+ entryPoint = packageJson.browser;
372
+ }
373
+ else if (typeof packageJson.browser === 'object') {
374
+ // Si browser es un objeto de mapeo, buscar la entrada principal
375
+ entryPoint =
376
+ packageJson.browser['.'] ||
377
+ packageJson.browser[packageJson.main];
378
+ }
379
+ }
380
+ // 4. Fallback a main field
381
+ else if (packageJson.main) {
382
+ entryPoint = packageJson.main;
383
+ }
384
+ // 5. Fallback por defecto según el tipo de módulo
385
+ if (!entryPoint) {
386
+ entryPoint = isESM ? 'index.js' : 'index.cjs';
387
+ }
388
+ // Asegurarse de que el entry point es una cadena
389
+ if (typeof entryPoint !== 'string') {
390
+ if (env.VERBOSE === 'true')
391
+ logger.warn(`Entry point no es string para ${moduleName}:`, entryPoint);
392
+ entryPoint = isESM ? 'index.js' : 'index.cjs';
393
+ } // Resolver la ruta final
394
+ let finalPath = join(moduleDir, entryPoint);
395
+ // Buscar una versión ESM/browser optimizada
396
+ const optimizedEntry = findOptimalESMVersion(moduleDir, entryPoint);
397
+ if (optimizedEntry && optimizedEntry !== entryPoint) {
398
+ finalPath = join(moduleDir, optimizedEntry);
399
+ }
400
+ // Si es ESM, verificar si hay imports privados que necesiten ser resueltos
401
+ if (isESM && packageJson.imports) {
402
+ const importMap = new Map();
403
+ for (const [key, value] of Object.entries(packageJson.imports)) {
404
+ if (typeof value === 'string') {
405
+ importMap.set(key, join(moduleDir, value));
406
+ }
407
+ else if (typeof value === 'object' && value !== null) {
408
+ // Priorizar la versión browser
409
+ const valueObj = value;
410
+ const browserPath = valueObj.browser || valueObj.default || valueObj.node;
411
+ if (browserPath) {
412
+ importMap.set(key, join(moduleDir, browserPath));
413
+ }
414
+ }
415
+ }
416
+ // Si el archivo existe, leer su contenido y verificar imports privados
417
+ if (fs.existsSync(finalPath)) {
418
+ const content = readFileSync(finalPath, 'utf-8');
419
+ const privateImports = Array.from(content.matchAll(/from\s+['"]([#@][^'"]+)['"]/g));
420
+ if (privateImports.length > 0) {
421
+ if (env.VERBOSE === 'true')
422
+ logger.info(`Módulo ${moduleName} usa imports privados:`, privateImports.map(m => m[1]));
423
+ // Si usa imports privados, asegurarnos de que estén disponibles
424
+ for (const match of privateImports) {
425
+ const [, importPath] = match;
426
+ if (!importMap.has(importPath)) {
427
+ if (env.VERBOSE === 'true')
428
+ logger.warn(`Import privado no resuelto: ${importPath} en ${moduleName}`);
429
+ }
430
+ }
431
+ }
432
+ }
433
+ }
434
+ // Verificar que el archivo existe
435
+ if (!fs.existsSync(finalPath)) {
436
+ // Intentar alternativas comunes
437
+ const alternatives = [
438
+ entryPoint,
439
+ entryPoint.replace('.js', '.mjs'),
440
+ entryPoint.replace('.mjs', '.js'),
441
+ entryPoint.replace('.js', '.cjs'),
442
+ 'index.mjs',
443
+ 'index.js',
444
+ 'index.cjs',
445
+ ];
446
+ for (const alt of alternatives) {
447
+ const altPath = join(moduleDir, alt);
448
+ if (fs.existsSync(altPath)) {
449
+ finalPath = altPath;
450
+ break;
451
+ }
452
+ }
453
+ }
454
+ return finalPath;
455
+ }
456
+ catch (error) {
457
+ if (env.VERBOSE === 'true')
458
+ logger.error(`Error resolviendo ${moduleName}: ${error instanceof Error ? error.message : String(error)}`);
459
+ return null;
460
+ }
461
+ }
462
+ // Función utilitaria para obtener rutas absolutas desde la raíz del proyecto
463
+ function getNodeModulesRelativePath(fullPath, _fromFile) {
464
+ if (!fullPath)
465
+ return null;
466
+ const idx = fullPath.indexOf('node_modules');
467
+ if (idx !== -1) {
468
+ // Extraer solo la parte desde node_modules en adelante
469
+ const relativePath = fullPath.substring(idx).replace(/\\/g, '/');
470
+ // Devolver ruta absoluta desde la raíz del proyecto (sin ../)
471
+ // Esto permite que los archivos compilados accedan directamente a node_modules
472
+ return '/' + relativePath;
473
+ }
474
+ // Para rutas que no están en node_modules, convertir a ruta absoluta desde la raíz
475
+ let rel = relative(cwd(), fullPath).replace(/\\/g, '/');
476
+ if (!rel)
477
+ rel = '.';
478
+ // Convertir a ruta absoluta desde la raíz
479
+ if (!rel.startsWith('/')) {
480
+ rel = '/' + rel;
481
+ }
482
+ return rel;
483
+ }
484
+ export function getModulePath(moduleName, fromFile) {
485
+ // Verificar si el módulo está en la lista de excluidos
486
+ if (EXCLUDED_MODULES.has(moduleName)) {
487
+ return null; // Retornar null para mantener la importación original
488
+ }
489
+ return getNodeModulesRelativePath(simpleESMResolver(moduleName), fromFile);
490
+ }
491
+ // Nueva función para resolver subpaths de módulos (ej: 'yargs/helpers')
492
+ export function getModuleSubPath(moduleName, fromFile) {
493
+ // Verificar si el módulo está en la lista de excluidos
494
+ if (EXCLUDED_MODULES.has(moduleName)) {
495
+ return null; // Retornar null para mantener la importación original
496
+ } // Si contiene '/', es un subpath
497
+ if (moduleName.includes('/')) {
498
+ const [packageName, ...subPathParts] = moduleName.split('/');
499
+ const subPath = subPathParts.join('/');
500
+ // Verificar que packageName no esté vacío
501
+ if (!packageName) {
502
+ return null;
503
+ }
504
+ try {
505
+ const nodeModulesPath = join(cwd(), 'node_modules', packageName);
506
+ const packagePath = join(nodeModulesPath, 'package.json');
507
+ if (!fs.existsSync(packagePath)) {
508
+ return null;
509
+ }
510
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
511
+ const moduleDir = dirname(packagePath);
512
+ // Revisar exports field para subpaths
513
+ if (packageJson.exports &&
514
+ typeof packageJson.exports === 'object') {
515
+ const exportKey = `./${subPath}`;
516
+ const exportPath = packageJson.exports[exportKey];
517
+ if (exportPath) {
518
+ if (typeof exportPath === 'string') {
519
+ return getNodeModulesRelativePath(join(moduleDir, exportPath), fromFile);
520
+ }
521
+ else if (typeof exportPath === 'object') {
522
+ // Priorizar import > default para ESM
523
+ const importPath = exportPath.import || exportPath.default;
524
+ if (typeof importPath === 'string') {
525
+ return getNodeModulesRelativePath(join(moduleDir, importPath), fromFile);
526
+ }
527
+ }
528
+ }
529
+ }
530
+ // Fallback: intentar resolver directamente el subpath
531
+ const directPath = join(moduleDir, subPath);
532
+ if (fs.existsSync(directPath)) {
533
+ return getNodeModulesRelativePath(directPath, fromFile);
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 (fs.existsSync(pathWithExt)) {
540
+ return getNodeModulesRelativePath(pathWithExt, fromFile);
541
+ }
542
+ }
543
+ }
544
+ catch (error) {
545
+ if (env.VERBOSE === 'true')
546
+ logger.error(`Error resolviendo subpath ${moduleName}:`, error instanceof Error ? error.message : String(error));
547
+ }
548
+ }
549
+ // Si no es un subpath, usar el resolver normal
550
+ return getModulePath(moduleName, fromFile);
551
+ }
552
+ //# sourceMappingURL=module-resolver.js.map
@@ -1,2 +1,48 @@
1
- import e,{stdin as t,stdout as n}from"node:process";import*as r from"node:readline/promises";import{logger as i}from"../servicios/logger.js";export async function promptUser(a,o=3e4){let s=r.createInterface({input:t,output:n});return new Promise((t,n)=>{let r=!1,c=setTimeout(()=>{r||(r=!0,s.close(),n(Error(`Timeout: No se recibió respuesta del usuario`)))},o),l=()=>{r||(r=!0,clearTimeout(c),s.close(),i.info(`
2
- 🛑 Operación cancelada por el usuario.`),e.exit(0))};e.on(`SIGINT`,l),s.question(a).then(n=>{r||(r=!0,clearTimeout(c),e.removeListener(`SIGINT`,l),s.close(),t(n))}).catch(t=>{r||(r=!0,clearTimeout(c),e.removeListener(`SIGINT`,l),s.close(),n(t))})})}
1
+ import process, { stdin as input, stdout as output } from 'node:process';
2
+ import * as readline from 'node:readline/promises';
3
+ import { logger } from '../servicios/logger.js';
4
+ export async function promptUser(question, timeout = 30000) {
5
+ const rl = readline.createInterface({ input, output });
6
+ return new Promise((resolve, reject) => {
7
+ let isResolved = false;
8
+ // Timeout para evitar espera infinita
9
+ const timer = setTimeout(() => {
10
+ if (!isResolved) {
11
+ isResolved = true;
12
+ rl.close();
13
+ reject(new Error('Timeout: No se recibió respuesta del usuario'));
14
+ }
15
+ }, timeout);
16
+ // Manejar Ctrl+C
17
+ const handleSigint = () => {
18
+ if (!isResolved) {
19
+ isResolved = true;
20
+ clearTimeout(timer);
21
+ rl.close();
22
+ logger.info('\n🛑 Operación cancelada por el usuario.');
23
+ process.exit(0);
24
+ }
25
+ };
26
+ process.on('SIGINT', handleSigint);
27
+ rl.question(question)
28
+ .then((answer) => {
29
+ if (!isResolved) {
30
+ isResolved = true;
31
+ clearTimeout(timer);
32
+ process.removeListener('SIGINT', handleSigint);
33
+ rl.close();
34
+ resolve(answer);
35
+ }
36
+ })
37
+ .catch((error) => {
38
+ if (!isResolved) {
39
+ isResolved = true;
40
+ clearTimeout(timer);
41
+ process.removeListener('SIGINT', handleSigint);
42
+ rl.close();
43
+ reject(error);
44
+ }
45
+ });
46
+ });
47
+ }
48
+ //# sourceMappingURL=promptUser.js.map