versacompiler 2.1.0 → 2.2.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 +844 -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 +466 -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 +106 -103
@@ -1 +1,466 @@
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); // Patrones de prioridad para buscar versiones optimizadas
68
+ // Prioriza versiones completas de desarrollo para mejor debugging
69
+ const priorityPatterns = [
70
+ // Máxima prioridad: ESM-Browser completo (sin runtime, desarrollo)
71
+ `${nameWithoutExt}.esm-browser.js`,
72
+ // ESM puro sin minificar (desarrollo)
73
+ `${nameWithoutExt}.esm.all.js`,
74
+ `${nameWithoutExt}.esm.js`,
75
+ `${nameWithoutExt}.module.js`,
76
+ // Browser puro sin minificar (desarrollo)
77
+ `${nameWithoutExt}.browser.js`,
78
+ `${nameWithoutExt}.web.js`,
79
+ // UMD sin minificar (desarrollo)
80
+ `${nameWithoutExt}.umd.js`,
81
+ `${nameWithoutExt}.global.js`,
82
+ // Fallback a versiones minificadas sin runtime
83
+ `${nameWithoutExt}.esm-browser.min.js`,
84
+ `${nameWithoutExt}.esm-browser.prod.js`,
85
+ `${nameWithoutExt}.esm.all.min.js`,
86
+ `${nameWithoutExt}.esm.min.js`,
87
+ `${nameWithoutExt}.module.min.js`,
88
+ `${nameWithoutExt}.browser.min.js`,
89
+ `${nameWithoutExt}.browser.prod.js`,
90
+ `${nameWithoutExt}.web.min.js`,
91
+ `${nameWithoutExt}.umd.min.js`,
92
+ `${nameWithoutExt}.global.min.js`,
93
+ `${nameWithoutExt}.min.js`,
94
+ // Último recurso: versiones runtime (solo si no hay alternativas)
95
+ `${nameWithoutExt}.runtime.esm-browser.js`,
96
+ `${nameWithoutExt}.runtime.esm-browser.min.js`,
97
+ `${nameWithoutExt}.runtime.esm-browser.prod.js`,
98
+ ];
99
+ // Buscar archivos que coincidan exactamente con los patrones
100
+ for (const pattern of priorityPatterns) {
101
+ if (files.includes(pattern)) {
102
+ const optimizedPath = join(dir, pattern).replace(/\\/g, '/');
103
+ return optimizedPath;
104
+ }
105
+ } // Buscar archivos que contengan patrones ESM/browser dinámicamente
106
+ const esmBrowserFiles = files.filter((file) => {
107
+ const lowerFile = file.toLowerCase();
108
+ return ((lowerFile.includes('.esm-browser.') || // Prioridad alta: combinación esm-browser
109
+ lowerFile.includes('.esm.') ||
110
+ lowerFile.includes('.module.') ||
111
+ lowerFile.includes('.browser.') ||
112
+ lowerFile.includes('.web.') ||
113
+ lowerFile.includes('.runtime.esm-browser.')) && // Runtime como última opción
114
+ (file.endsWith('.js') || file.endsWith('.mjs')));
115
+ });
116
+ if (esmBrowserFiles.length > 0) {
117
+ // Primera prioridad: archivos que combinan ESM y Browser (sin runtime)
118
+ const esmBrowserCombined = esmBrowserFiles.filter((file) => file.toLowerCase().includes('.esm-browser.') &&
119
+ !file.toLowerCase().includes('.runtime.'));
120
+ if (esmBrowserCombined.length > 0) {
121
+ // Dentro de esm-browser, priorizar desarrollo > .prod > .min
122
+ const devFiles = esmBrowserCombined.filter((file) => !file.toLowerCase().includes('.prod.') &&
123
+ !file.toLowerCase().includes('.min.'));
124
+ if (devFiles.length > 0 && devFiles[0]) {
125
+ const optimizedPath = join(dir, devFiles[0]).replace(/\\/g, '/');
126
+ return optimizedPath;
127
+ }
128
+ const prodFiles = esmBrowserCombined.filter((file) => file.toLowerCase().includes('.prod.'));
129
+ if (prodFiles.length > 0 && prodFiles[0]) {
130
+ const optimizedPath = join(dir, prodFiles[0]).replace(/\\/g, '/');
131
+ if (env.VERBOSE === 'true') {
132
+ logger.info(`Versión ESM-Browser producción encontrada: ${optimizedPath}`);
133
+ }
134
+ return optimizedPath;
135
+ }
136
+ const minFiles = esmBrowserCombined.filter((file) => file.toLowerCase().includes('.min.'));
137
+ if (minFiles.length > 0 && minFiles[0]) {
138
+ const optimizedPath = join(dir, minFiles[0]).replace(/\\/g, '/');
139
+ if (env.VERBOSE === 'true') {
140
+ logger.info(`Versión ESM-Browser minificada encontrada: ${optimizedPath}`);
141
+ }
142
+ return optimizedPath;
143
+ }
144
+ if (esmBrowserCombined[0]) {
145
+ const optimizedPath = join(dir, esmBrowserCombined[0]).replace(/\\/g, '/');
146
+ if (env.VERBOSE === 'true') {
147
+ logger.info(`Versión ESM-Browser encontrada: ${optimizedPath}`);
148
+ }
149
+ return optimizedPath;
150
+ }
151
+ }
152
+ // Segunda prioridad: cualquier versión ESM disponible (sin minificar)
153
+ const esmFiles = esmBrowserFiles.filter((file) => (file.toLowerCase().includes('.esm.') ||
154
+ file.toLowerCase().includes('.module.')) &&
155
+ !file.toLowerCase().includes('.min.') &&
156
+ !file.toLowerCase().includes('.prod.') &&
157
+ !file.toLowerCase().includes('.runtime.'));
158
+ if (esmFiles.length > 0 && esmFiles[0]) {
159
+ const optimizedPath = join(dir, esmFiles[0]).replace(/\\/g, '/');
160
+ if (env.VERBOSE === 'true') {
161
+ logger.info(`Versión ESM dev encontrada: ${optimizedPath}`);
162
+ }
163
+ return optimizedPath;
164
+ }
165
+ // Tercera prioridad: archivos minificados de cualquier tipo ESM/browser (sin runtime)
166
+ const minifiedFiles = esmBrowserFiles.filter((file) => (file.toLowerCase().includes('.min.') ||
167
+ file.toLowerCase().includes('.prod.')) &&
168
+ !file.toLowerCase().includes('.runtime.'));
169
+ if (minifiedFiles.length > 0) {
170
+ // Priorizar ESM sobre browser sobre UMD
171
+ const esmFiles = minifiedFiles.filter((file) => file.toLowerCase().includes('.esm.') ||
172
+ file.toLowerCase().includes('.module.'));
173
+ if (esmFiles.length > 0 && esmFiles[0]) {
174
+ const optimizedPath = join(dir, esmFiles[0]).replace(/\\/g, '/');
175
+ if (env.VERBOSE === 'true') {
176
+ logger.info(`Versión ESM minificada encontrada: ${optimizedPath}`);
177
+ }
178
+ return optimizedPath;
179
+ }
180
+ if (minifiedFiles[0]) {
181
+ const optimizedPath = join(dir, minifiedFiles[0]).replace(/\\/g, '/');
182
+ if (env.VERBOSE === 'true') {
183
+ logger.info(`Versión minificada encontrada: ${optimizedPath}`);
184
+ }
185
+ return optimizedPath;
186
+ }
187
+ }
188
+ // Cuarta prioridad: versiones runtime como último recurso
189
+ const runtimeFiles = esmBrowserFiles.filter((file) => file.toLowerCase().includes('.runtime.esm-browser.'));
190
+ if (runtimeFiles.length > 0) {
191
+ // Priorizar desarrollo sobre producción en runtime también
192
+ const devRuntimeFiles = runtimeFiles.filter((file) => !file.toLowerCase().includes('.prod.') &&
193
+ !file.toLowerCase().includes('.min.'));
194
+ if (devRuntimeFiles.length > 0 && devRuntimeFiles[0]) {
195
+ const optimizedPath = join(dir, devRuntimeFiles[0]).replace(/\\/g, '/');
196
+ if (env.VERBOSE === 'true') {
197
+ logger.info(`Versión Runtime ESM-Browser dev encontrada: ${optimizedPath}`);
198
+ }
199
+ return optimizedPath;
200
+ }
201
+ if (runtimeFiles[0]) {
202
+ const optimizedPath = join(dir, runtimeFiles[0]).replace(/\\/g, '/');
203
+ if (env.VERBOSE === 'true') {
204
+ logger.info(`Versión Runtime ESM-Browser encontrada: ${optimizedPath}`);
205
+ }
206
+ return optimizedPath;
207
+ }
208
+ }
209
+ // Fallback: cualquier versión browser
210
+ if (esmBrowserFiles[0]) {
211
+ const optimizedPath = join(dir, esmBrowserFiles[0]).replace(/\\/g, '/');
212
+ if (env.VERBOSE === 'true') {
213
+ logger.info(`Versión browser encontrada: ${optimizedPath}`);
214
+ }
215
+ return optimizedPath;
216
+ }
217
+ }
218
+ }
219
+ catch (error) {
220
+ if (env.VERBOSE === 'true') {
221
+ logger.warn(`No se pudo leer directorio ${searchDir}:`, error instanceof Error ? error.message : String(error));
222
+ }
223
+ }
224
+ return entryPoint; // Fallback al entry point original
225
+ }
226
+ // Función mejorada para detectar automáticamente entry points browser-compatible
227
+ function simpleESMResolver(moduleName) {
228
+ try {
229
+ const nodeModulesPath = join(cwd(), 'node_modules', moduleName);
230
+ let packagePath;
231
+ try {
232
+ packagePath = join(nodeModulesPath, 'package.json');
233
+ if (!fs.existsSync(packagePath)) {
234
+ throw new Error(`No se encontró package.json para ${moduleName}`);
235
+ }
236
+ }
237
+ catch {
238
+ return null;
239
+ }
240
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
241
+ const moduleDir = dirname(packagePath);
242
+ const isESM = packageJson.type === 'module'; // Determinar el entry point ESM/Browser optimizado
243
+ let entryPoint = null;
244
+ // 1. Prioridad máxima: campo module para ESM
245
+ if (packageJson.module) {
246
+ entryPoint = packageJson.module;
247
+ }
248
+ // 2. Revisar exports field con prioridad ESM
249
+ else if (packageJson.exports) {
250
+ if (typeof packageJson.exports === 'string') {
251
+ entryPoint = packageJson.exports;
252
+ }
253
+ else if (packageJson.exports['.']) {
254
+ const dotExport = packageJson.exports['.'];
255
+ if (typeof dotExport === 'string') {
256
+ entryPoint = dotExport;
257
+ }
258
+ else if (typeof dotExport === 'object') {
259
+ // Priorizar import > browser > default para compatibilidad ESM
260
+ // Buscar específicamente patrones esm-browser primero
261
+ const exportKeys = Object.keys(dotExport);
262
+ const esmBrowserKey = exportKeys.find(key => key.includes('browser') &&
263
+ (key.includes('esm') || key.includes('module')));
264
+ if (esmBrowserKey &&
265
+ typeof dotExport[esmBrowserKey] === 'string') {
266
+ entryPoint = dotExport[esmBrowserKey];
267
+ }
268
+ else {
269
+ // Priorizar import > browser > default
270
+ entryPoint =
271
+ (typeof dotExport.import === 'string'
272
+ ? dotExport.import
273
+ : null) ||
274
+ dotExport.browser ||
275
+ (typeof dotExport.default === 'string'
276
+ ? dotExport.default
277
+ : null);
278
+ }
279
+ }
280
+ }
281
+ }
282
+ // 3. Revisar browser field específico
283
+ else if (packageJson.browser) {
284
+ if (typeof packageJson.browser === 'string') {
285
+ entryPoint = packageJson.browser;
286
+ }
287
+ else if (typeof packageJson.browser === 'object') {
288
+ // Si browser es un objeto de mapeo, buscar la entrada principal
289
+ entryPoint =
290
+ packageJson.browser['.'] ||
291
+ packageJson.browser[packageJson.main];
292
+ }
293
+ }
294
+ // 4. Fallback a main field
295
+ else if (packageJson.main) {
296
+ entryPoint = packageJson.main;
297
+ }
298
+ // 5. Fallback por defecto según el tipo de módulo
299
+ if (!entryPoint) {
300
+ entryPoint = isESM ? 'index.js' : 'index.cjs';
301
+ }
302
+ // Asegurarse de que el entry point es una cadena
303
+ if (typeof entryPoint !== 'string') {
304
+ if (env.VERBOSE === 'true')
305
+ logger.warn(`Entry point no es string para ${moduleName}:`, entryPoint);
306
+ entryPoint = isESM ? 'index.js' : 'index.cjs';
307
+ } // Resolver la ruta final
308
+ let finalPath = join(moduleDir, entryPoint);
309
+ // Buscar una versión ESM/browser optimizada
310
+ const optimizedEntry = findOptimalESMVersion(moduleDir, entryPoint);
311
+ if (optimizedEntry && optimizedEntry !== entryPoint) {
312
+ finalPath = join(moduleDir, optimizedEntry);
313
+ }
314
+ // Si es ESM, verificar si hay imports privados que necesiten ser resueltos
315
+ if (isESM && packageJson.imports) {
316
+ const importMap = new Map();
317
+ for (const [key, value] of Object.entries(packageJson.imports)) {
318
+ if (typeof value === 'string') {
319
+ importMap.set(key, join(moduleDir, value));
320
+ }
321
+ else if (typeof value === 'object' && value !== null) {
322
+ // Priorizar la versión browser
323
+ const valueObj = value;
324
+ const browserPath = valueObj.browser || valueObj.default || valueObj.node;
325
+ if (browserPath) {
326
+ importMap.set(key, join(moduleDir, browserPath));
327
+ }
328
+ }
329
+ }
330
+ // Si el archivo existe, leer su contenido y verificar imports privados
331
+ if (fs.existsSync(finalPath)) {
332
+ const content = readFileSync(finalPath, 'utf-8');
333
+ const privateImports = Array.from(content.matchAll(/from\s+['"]([#@][^'"]+)['"]/g));
334
+ if (privateImports.length > 0) {
335
+ if (env.VERBOSE === 'true')
336
+ logger.info(`Módulo ${moduleName} usa imports privados:`, privateImports.map(m => m[1]));
337
+ // Si usa imports privados, asegurarnos de que estén disponibles
338
+ for (const match of privateImports) {
339
+ const [, importPath] = match;
340
+ if (!importMap.has(importPath)) {
341
+ if (env.VERBOSE === 'true')
342
+ logger.warn(`Import privado no resuelto: ${importPath} en ${moduleName}`);
343
+ }
344
+ }
345
+ }
346
+ }
347
+ }
348
+ // Verificar que el archivo existe
349
+ if (!fs.existsSync(finalPath)) {
350
+ // Intentar alternativas comunes
351
+ const alternatives = [
352
+ entryPoint,
353
+ entryPoint.replace('.js', '.mjs'),
354
+ entryPoint.replace('.mjs', '.js'),
355
+ entryPoint.replace('.js', '.cjs'),
356
+ 'index.mjs',
357
+ 'index.js',
358
+ 'index.cjs',
359
+ ];
360
+ for (const alt of alternatives) {
361
+ const altPath = join(moduleDir, alt);
362
+ if (fs.existsSync(altPath)) {
363
+ finalPath = altPath;
364
+ break;
365
+ }
366
+ }
367
+ }
368
+ return finalPath;
369
+ }
370
+ catch (error) {
371
+ if (env.VERBOSE === 'true')
372
+ logger.error(`Error resolviendo ${moduleName}: ${error instanceof Error ? error.message : String(error)}`);
373
+ return null;
374
+ }
375
+ }
376
+ // Función utilitaria para obtener rutas absolutas desde la raíz del proyecto
377
+ function getNodeModulesRelativePath(fullPath, _fromFile) {
378
+ if (!fullPath)
379
+ return null;
380
+ const idx = fullPath.indexOf('node_modules');
381
+ if (idx !== -1) {
382
+ // Extraer solo la parte desde node_modules en adelante
383
+ const relativePath = fullPath.substring(idx).replace(/\\/g, '/');
384
+ // Devolver ruta absoluta desde la raíz del proyecto (sin ../)
385
+ // Esto permite que los archivos compilados accedan directamente a node_modules
386
+ return '/' + relativePath;
387
+ }
388
+ // Para rutas que no están en node_modules, convertir a ruta absoluta desde la raíz
389
+ let rel = relative(cwd(), fullPath).replace(/\\/g, '/');
390
+ if (!rel)
391
+ rel = '.';
392
+ // Convertir a ruta absoluta desde la raíz
393
+ if (!rel.startsWith('/')) {
394
+ rel = '/' + rel;
395
+ }
396
+ return rel;
397
+ }
398
+ export function getModulePath(moduleName, fromFile) {
399
+ // Verificar si el módulo está en la lista de excluidos
400
+ if (EXCLUDED_MODULES.has(moduleName)) {
401
+ return null; // Retornar null para mantener la importación original
402
+ }
403
+ return getNodeModulesRelativePath(simpleESMResolver(moduleName), fromFile);
404
+ }
405
+ // Nueva función para resolver subpaths de módulos (ej: 'yargs/helpers')
406
+ export function getModuleSubPath(moduleName, fromFile) {
407
+ // Verificar si el módulo está en la lista de excluidos
408
+ if (EXCLUDED_MODULES.has(moduleName)) {
409
+ return null; // Retornar null para mantener la importación original
410
+ } // Si contiene '/', es un subpath
411
+ if (moduleName.includes('/')) {
412
+ const [packageName, ...subPathParts] = moduleName.split('/');
413
+ const subPath = subPathParts.join('/');
414
+ // Verificar que packageName no esté vacío
415
+ if (!packageName) {
416
+ return null;
417
+ }
418
+ try {
419
+ const nodeModulesPath = join(cwd(), 'node_modules', packageName);
420
+ const packagePath = join(nodeModulesPath, 'package.json');
421
+ if (!fs.existsSync(packagePath)) {
422
+ return null;
423
+ }
424
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
425
+ const moduleDir = dirname(packagePath);
426
+ // Revisar exports field para subpaths
427
+ if (packageJson.exports &&
428
+ typeof packageJson.exports === 'object') {
429
+ const exportKey = `./${subPath}`;
430
+ const exportPath = packageJson.exports[exportKey];
431
+ if (exportPath) {
432
+ if (typeof exportPath === 'string') {
433
+ return getNodeModulesRelativePath(join(moduleDir, exportPath), fromFile);
434
+ }
435
+ else if (typeof exportPath === 'object') {
436
+ // Priorizar import > default para ESM
437
+ const importPath = exportPath.import || exportPath.default;
438
+ if (typeof importPath === 'string') {
439
+ return getNodeModulesRelativePath(join(moduleDir, importPath), fromFile);
440
+ }
441
+ }
442
+ }
443
+ }
444
+ // Fallback: intentar resolver directamente el subpath
445
+ const directPath = join(moduleDir, subPath);
446
+ if (fs.existsSync(directPath)) {
447
+ return getNodeModulesRelativePath(directPath, fromFile);
448
+ }
449
+ // Intentar con extensiones comunes
450
+ const extensions = ['.mjs', '.js', '.cjs'];
451
+ for (const ext of extensions) {
452
+ const pathWithExt = directPath + ext;
453
+ if (fs.existsSync(pathWithExt)) {
454
+ return getNodeModulesRelativePath(pathWithExt, fromFile);
455
+ }
456
+ }
457
+ }
458
+ catch (error) {
459
+ if (env.VERBOSE === 'true')
460
+ logger.error(`Error resolviendo subpath ${moduleName}:`, error instanceof Error ? error.message : String(error));
461
+ }
462
+ }
463
+ // Si no es un subpath, usar el resolver normal
464
+ return getModulePath(moduleName, fromFile);
465
+ }
466
+ //# 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
@@ -1 +1,68 @@
1
- import{get as e}from"node:http";import{get as t}from"node:https";import{URL as n}from"node:url";export async function validateProxyAvailability(r,i=5e3){return new Promise(a=>{try{let o=new n(r),s=o.protocol===`https:`,c=(s?t:e)({hostname:o.hostname,port:o.port||(s?443:80),path:`/`,method:`HEAD`,timeout:i,headers:{"User-Agent":`VersaCompiler-ProxyValidator/1.0`}},e=>{a(!0)});c.on(`error`,()=>{a(!1)}),c.on(`timeout`,()=>{c.destroy(),a(!1)}),c.setTimeout(i),c.end()}catch{a(!1)}})}export function getProxyInfo(e){try{let t=new n(e);return{host:t.hostname,port:t.port||(t.protocol===`https:`?`443`:`80`),protocol:t.protocol.replace(`:`,``)}}catch{return{host:`unknown`,port:`unknown`,protocol:`unknown`}}}
1
+ import { get as httpGet } from 'node:http';
2
+ import { get as httpsGet } from 'node:https';
3
+ import { URL } from 'node:url';
4
+ /**
5
+ * Valida si un servidor proxy está disponible
6
+ * @param proxyUrl URL del proxy a validar
7
+ * @param timeout Timeout en milisegundos (default: 5000)
8
+ * @returns Promise que resuelve a true si el proxy está disponible
9
+ */
10
+ export async function validateProxyAvailability(proxyUrl, timeout = 5000) {
11
+ return new Promise(resolve => {
12
+ try {
13
+ const url = new URL(proxyUrl);
14
+ const isHttps = url.protocol === 'https:';
15
+ const requestMethod = isHttps ? httpsGet : httpGet;
16
+ const options = {
17
+ hostname: url.hostname,
18
+ port: url.port || (isHttps ? 443 : 80),
19
+ path: '/',
20
+ method: 'HEAD',
21
+ timeout: timeout,
22
+ headers: {
23
+ 'User-Agent': 'VersaCompiler-ProxyValidator/1.0',
24
+ },
25
+ };
26
+ const req = requestMethod(options, (_res) => {
27
+ // Cualquier respuesta HTTP (incluso errores 4xx/5xx) indica que el servidor está arriba
28
+ resolve(true);
29
+ });
30
+ req.on('error', () => {
31
+ resolve(false);
32
+ });
33
+ req.on('timeout', () => {
34
+ req.destroy();
35
+ resolve(false);
36
+ });
37
+ req.setTimeout(timeout);
38
+ req.end();
39
+ }
40
+ catch {
41
+ // Error al parsear URL o crear request
42
+ resolve(false);
43
+ }
44
+ });
45
+ }
46
+ /**
47
+ * Extrae información legible del proxy URL para mostrar al usuario
48
+ * @param proxyUrl URL del proxy
49
+ * @returns Objeto con información del proxy
50
+ */
51
+ export function getProxyInfo(proxyUrl) {
52
+ try {
53
+ const url = new URL(proxyUrl);
54
+ return {
55
+ host: url.hostname,
56
+ port: url.port || (url.protocol === 'https:' ? '443' : '80'),
57
+ protocol: url.protocol.replace(':', ''),
58
+ };
59
+ }
60
+ catch {
61
+ return {
62
+ host: 'unknown',
63
+ port: 'unknown',
64
+ protocol: 'unknown',
65
+ };
66
+ }
67
+ }
68
+ //# sourceMappingURL=proxyValidator.js.map
@@ -1 +1,58 @@
1
- import*as e from"node:path";import*as t from"node:process";import n from"find-root";import r from"fs-extra";function i(t,n){for(let i of n)try{let n=e.join(i,`node_modules`,t);if(r.existsSync(n))return n}catch{}throw Error(`Cannot resolve module ${t} from paths: ${n.join(`, `)}`)}export function resolveBin(a,{executable:o=a,paths:s=[t.cwd()]}={}){let c;try{c=n(i(a,s))}catch{let n=s[0]||t.cwd(),i=e.join(n,`node_modules`,a,`package.json`);if(r.existsSync(i))c=e.dirname(i);else throw Error(`Cannot resolve module ${a}`)}let l=e.join(c,`package.json`),u=r.readJsonSync(l);if(!u.bin)throw Error(`no bin found in ${u.name}@${u.version} in path ${l}`);let d=typeof u.bin==`string`?u.bin:u.bin[o];return e.join(c,d)}
1
+ import * as path from 'node:path';
2
+ import * as process from 'node:process';
3
+ import * as fs from 'fs-extra';
4
+ // Reimplementación simple de findRoot para evitar dependencias problemáticas
5
+ function findRoot(start) {
6
+ let current = start;
7
+ while (current !== path.dirname(current)) {
8
+ if (fs.existsSync(path.join(current, 'package.json'))) {
9
+ return current;
10
+ }
11
+ current = path.dirname(current);
12
+ }
13
+ throw new Error(`Cannot find package.json from ${start}`);
14
+ }
15
+ // Función helper para resolver módulos sin createRequire
16
+ function resolveModule(moduleName, paths) {
17
+ for (const searchPath of paths) {
18
+ try {
19
+ const nodeModulesPath = path.join(searchPath, 'node_modules', moduleName);
20
+ if (fs.existsSync(nodeModulesPath)) {
21
+ return nodeModulesPath;
22
+ }
23
+ }
24
+ catch {
25
+ // Continuar con el siguiente path
26
+ }
27
+ }
28
+ throw new Error(`Cannot resolve module ${moduleName} from paths: ${paths.join(', ')}`);
29
+ }
30
+ export function resolveBin(moduleName, { executable = moduleName, paths = [process.cwd()], } = {}) {
31
+ let rootDir;
32
+ try {
33
+ const resolved = resolveModule(moduleName, paths);
34
+ rootDir = findRoot(resolved);
35
+ }
36
+ catch {
37
+ // Intentar resolver package.json directamente
38
+ const basePath = paths[0] || process.cwd();
39
+ const packagePath = path.join(basePath, 'node_modules', moduleName, 'package.json');
40
+ if (fs.existsSync(packagePath)) {
41
+ rootDir = path.dirname(packagePath);
42
+ }
43
+ else {
44
+ throw new Error(`Cannot resolve module ${moduleName}`);
45
+ }
46
+ }
47
+ const packageJsonPath = path.join(rootDir, 'package.json');
48
+ const packageJson = fs.readJsonSync(packageJsonPath);
49
+ if (!packageJson.bin) {
50
+ throw new Error(`no bin found in ${packageJson.name}@${packageJson.version} in path ${packageJsonPath}`);
51
+ }
52
+ const binProp = typeof packageJson.bin === 'string'
53
+ ? packageJson.bin
54
+ : packageJson.bin[executable];
55
+ const binPath = path.join(rootDir, binProp);
56
+ return binPath;
57
+ }
58
+ //# sourceMappingURL=resolve-bin.js.map