versacompiler 2.0.8 → 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 -26
  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 -0
  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 -41
  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 +587 -5
  28. package/dist/servicios/file-watcher.js +425 -4
  29. package/dist/servicios/logger.js +63 -3
  30. package/dist/servicios/readConfig.js +399 -105
  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 +147 -1
  39. package/dist/wrappers/oxlint-node.js +122 -1
  40. package/dist/wrappers/tailwind-node.js +94 -1
  41. package/package.json +39 -42
@@ -1,2 +1,304 @@
1
- import e from"node:fs";import i from"node:path";import*as a from"node:process";import{env as o}from"node:process";import*as s from"typescript";import{createUnifiedErrorMessage as c,parseTypeScriptErrors as l}from"./typescript-error-parser.js";import{validateTypesWithLanguageService as u}from"./typescript-sync-validator.js";import{TypeScriptWorkerPool as d}from"./typescript-worker-pool.js";let f={};export const loadTypeScriptConfig=o=>{let c=i.resolve(a.cwd(),`tsconfig.json`),l=i.dirname(o),u=e.existsSync(c)?c:s.findConfigFile(l,s.sys.fileExists,`tsconfig.json`);if(f.path===u&&f.options)return f.options;let d;if(u&&e.existsSync(u))try{let{config:e,error:a}=s.readConfigFile(u,s.sys.readFile);if(a)throw Error(`Error al leer tsconfig.json: ${a.messageText}`);{let a=s.parseJsonConfigFileContent(e,s.sys,i.dirname(u));d=a.options}}catch(e){throw console.warn(`[loadTypeScriptConfig] Error cargando ${u}:`,e),Error(`No se puede continuar sin un tsconfig.json válido. Error: ${e}`)}else throw Error(`No se encontró tsconfig.json en la raíz del proyecto (${c}) ni en el directorio del archivo. El compilador requiere un tsconfig.json para funcionar correctamente.`);return f={path:u,options:d},d};const p=e=>{let i={...e};return i};export const validateVueTypes=(e,i,a)=>{let o=``;if(i.endsWith(`.vue`)){let i=e.match(/<script[^>]*>([\s\S]*?)<\/script>/i);if(i&&i[1])o=i[1].trim();else return{diagnostics:[],hasErrors:!1}}else o=e;if(!o.trim())return{diagnostics:[],hasErrors:!1};let c=loadTypeScriptConfig(i),l;if(l=a?.compilerOptions?{...a.compilerOptions}:{...c},i.endsWith(`.vue`)){l.jsx=s.JsxEmit.Preserve,l.moduleResolution||=s.ModuleResolutionKind.NodeJs;let e=l.lib||c.lib||[`ES2020`],i=e.some(e=>typeof e==`string`&&(e.toLowerCase().includes(`dom`)||e.toLowerCase()===`dom`));i||(l.lib=[...e,`DOM`,`DOM.Iterable`]);let a=l.types||c.types||[];a.includes(`vue`)||(l.types=[...a,`vue`])}return l.skipLibCheck===void 0&&(l.skipLibCheck=!0),a?.strictMode!==void 0&&(l.noImplicitReturns===void 0&&(l.noImplicitReturns=a.strictMode),l.noImplicitThis===void 0&&(l.noImplicitThis=a.strictMode),l.strictNullChecks===void 0&&(l.strictNullChecks=a.strictMode),l.strictFunctionTypes===void 0&&(l.strictFunctionTypes=a.strictMode),l.exactOptionalPropertyTypes===void 0&&(l.exactOptionalPropertyTypes=!1),l.noFallthroughCasesInSwitch===void 0&&(l.noFallthroughCasesInSwitch=a.strictMode)),u(i,o,l)};const m=(e,i)=>{if(e.trim()===`export {};`)return``;let a=/(?:^|\s)(?:import|export)\s+(?!(?:\s*\{\s*\}\s*;?\s*$))/m.test(i);if(!a){let i=/export\s*\{\s*\}\s*;\s*$/m,a=i.test(e);if(a)return e.replace(i,``)}return e};export const preCompileTS=async(e,i)=>{try{if(!e.trim())return{error:null,data:e,lang:`ts`};let a=loadTypeScriptConfig(i),u=s.transpileModule(e,{compilerOptions:{...a,noLib:!0,skipLibCheck:!0,isolatedModules:!0},fileName:i,reportDiagnostics:!0});if(u.diagnostics?.length){let a=u.diagnostics.filter(e=>{if(e.category!==s.DiagnosticCategory.Error)return!1;let i=s.flattenDiagnosticMessageText(e.messageText,`
2
- `);return!i.includes(`Cannot find module`)&&!i.includes(`Could not find source file`)&&e.code!==2307&&e.code!==6059});if(a.length>0){let o=c(l(a,i,e));return{error:Error(o),data:null,lang:`ts`}}}if(o.typeCheck===`true`)try{let o=d.getInstance(),s=p(a),u=await o.typeCheck(i,e,s);if(u.hasErrors){let a=c(l(u.diagnostics,i,e));return{error:Error(a),data:null,lang:`ts`}}}catch(e){console.warn(`[preCompileTS] ❌ Type checking falló, usando transpilación sin verificación de tipos:`,e)}let f=u.outputText;return f=m(f,e),{error:null,data:f,lang:`ts`}}catch(e){return{error:e instanceof Error?e:Error(`Error desconocido`),data:null,lang:`ts`}}};
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import * as process from 'node:process';
4
+ import { env } from 'node:process';
5
+ import * as typescript from 'typescript';
6
+ import { createUnifiedErrorMessage, parseTypeScriptErrors, } from './typescript-error-parser.js';
7
+ import { validateTypesWithLanguageService } from './typescript-sync-validator.js';
8
+ import { TypeScriptWorkerPool } from './typescript-worker-pool.js';
9
+ /**
10
+ * Cache para la configuración de TypeScript para evitar lecturas repetidas
11
+ * ✨ FIX #9: Ahora incluye timestamp para detectar cambios en el archivo
12
+ */
13
+ let configCache = {};
14
+ /**
15
+ * Carga la configuración de TypeScript desde tsconfig.json
16
+ * @param fileName - Nombre del archivo para buscar el tsconfig.json relativo
17
+ * @returns Opciones del compilador TypeScript
18
+ */
19
+ export const loadTypeScriptConfig = (fileName) => {
20
+ // Siempre buscar primero en la raíz del proyecto
21
+ const rootConfigPath = path.resolve(process.cwd(), 'tsconfig.json');
22
+ // Si no existe en la raíz, buscar desde el directorio del archivo
23
+ const fileDir = path.dirname(fileName);
24
+ const configPath = fs.existsSync(rootConfigPath)
25
+ ? rootConfigPath
26
+ : typescript.findConfigFile(fileDir, typescript.sys.fileExists, 'tsconfig.json');
27
+ // ✨ FIX #9: Verificar si el archivo cambió comparando timestamp
28
+ if (configPath && fs.existsSync(configPath)) {
29
+ const stats = fs.statSync(configPath);
30
+ const currentMtime = stats.mtimeMs;
31
+ // Usar cache solo si el archivo no cambió
32
+ if (configCache.path === configPath &&
33
+ configCache.mtime === currentMtime &&
34
+ configCache.options) {
35
+ return configCache.options;
36
+ }
37
+ }
38
+ let compilerOptions;
39
+ if (configPath && fs.existsSync(configPath)) {
40
+ const stats = fs.statSync(configPath);
41
+ const currentMtime = stats.mtimeMs;
42
+ try {
43
+ const { config, error: configError } = typescript.readConfigFile(configPath, typescript.sys.readFile);
44
+ if (!configError) {
45
+ const parsedConfig = typescript.parseJsonConfigFileContent(config, typescript.sys, path.dirname(configPath)); // Usar exactamente la configuración del tsconfig.json del usuario sin modificaciones
46
+ compilerOptions = parsedConfig.options;
47
+ // DEBUG: Verificar las opciones cargadas
48
+ // console.log(`[DEBUG] Opciones de TypeScript cargadas desde ${configPath}:`);
49
+ // console.log(` noImplicitAny: ${compilerOptions.noImplicitAny}`);
50
+ // console.log(` strict: ${compilerOptions.strict}`);
51
+ }
52
+ else {
53
+ throw new Error(`Error al leer tsconfig.json: ${configError.messageText}`);
54
+ }
55
+ }
56
+ catch (error) {
57
+ console.warn(`[loadTypeScriptConfig] Error cargando ${configPath}:`, error);
58
+ throw new Error(`No se puede continuar sin un tsconfig.json válido. Error: ${error}`, { cause: error });
59
+ }
60
+ // ✨ FIX #9: Guardar en cache con timestamp
61
+ configCache = {
62
+ path: configPath,
63
+ options: compilerOptions,
64
+ mtime: currentMtime,
65
+ };
66
+ return compilerOptions;
67
+ }
68
+ else {
69
+ throw new Error(`No se encontró tsconfig.json en la raíz del proyecto (${rootConfigPath}) ni en el directorio del archivo. ` +
70
+ `El compilador requiere un tsconfig.json para funcionar correctamente.`);
71
+ }
72
+ };
73
+ /**
74
+ * ✨ FIX #9: Invalida el cache de configuración de TypeScript
75
+ * Útil cuando se detectan cambios en tsconfig.json o para tests
76
+ */
77
+ export function invalidateConfigCache() {
78
+ configCache = {};
79
+ }
80
+ /**
81
+ * Crea una versión optimizada y serializable de las opciones del compilador typescript.
82
+ * @param options - Opciones originales del compilador
83
+ * @returns Opciones serializables seguras para workers
84
+ */
85
+ const createSerializableCompilerOptions = (options) => {
86
+ // Respetar exactamente las opciones del tsconfig.json del usuario // Respetar completamente la configuración del usuario del tsconfig.json
87
+ const result = { ...options };
88
+ // NO modificar ninguna opción del usuario - usar configuración exacta del tsconfig.json
89
+ return result;
90
+ };
91
+ /**
92
+ * Crea un Language Service Host optimizado para validación de tipos eficiente.
93
+ */
94
+ /**
95
+ * Valida tipos en archivos Vue antes de la compilación con soporte mejorado
96
+ * @param vueContent - Contenido del archivo Vue
97
+ * @param fileName - Nombre del archivo Vue
98
+ * @param options - Opciones adicionales para la validación
99
+ * @returns Resultado de la validación de tipos
100
+ */
101
+ export const validateVueTypes = (vueContent, fileName, options) => {
102
+ // Extraer contenido del script de Vue
103
+ let scriptContent = '';
104
+ if (fileName.endsWith('.vue')) {
105
+ // Extraer contenido entre <script> y </script>
106
+ const scriptMatch = vueContent.match(/<script[^>]*>([\s\S]*?)<\/script>/i);
107
+ if (scriptMatch && scriptMatch[1]) {
108
+ scriptContent = scriptMatch[1].trim();
109
+ }
110
+ else {
111
+ // Si no hay script, no hay nada que validar
112
+ return { diagnostics: [], hasErrors: false };
113
+ }
114
+ }
115
+ else {
116
+ // Para archivos .ts/.js normales, usar todo el contenido
117
+ scriptContent = vueContent;
118
+ }
119
+ // Si el script está vacío, no validar
120
+ if (!scriptContent.trim()) {
121
+ return { diagnostics: [], hasErrors: false };
122
+ }
123
+ // Cargar la configuración del usuario como base
124
+ const userConfig = loadTypeScriptConfig(fileName);
125
+ // Crear opciones del compilador respetando la configuración del usuario
126
+ let compilerOptions;
127
+ if (options?.compilerOptions) {
128
+ // Si se proporcionaron opciones explícitas, usarlas como base
129
+ compilerOptions = { ...options.compilerOptions };
130
+ }
131
+ else {
132
+ // Usar la configuración del usuario como base
133
+ compilerOptions = { ...userConfig };
134
+ }
135
+ // Solo forzar las opciones ABSOLUTAMENTE necesarias para Vue
136
+ // Estas opciones se fuerzan porque son técnicamente requeridas para el funcionamiento correcto
137
+ if (fileName.endsWith('.vue')) {
138
+ // JSX: Necesario para que funcione el template compilation de Vue
139
+ compilerOptions.jsx = typescript.JsxEmit.Preserve;
140
+ // ModuleResolution: Necesario para resolver módulos Vue correctamente
141
+ if (!compilerOptions.moduleResolution) {
142
+ compilerOptions.moduleResolution =
143
+ typescript.ModuleResolutionKind.NodeJs;
144
+ }
145
+ // Lib: Asegurar que DOM esté disponible para archivos Vue, pero respetar otras libs del usuario
146
+ const currentLibs = compilerOptions.lib || userConfig.lib || ['ES2020'];
147
+ const hasDOM = currentLibs.some((lib) => typeof lib === 'string' &&
148
+ (lib.toLowerCase().includes('dom') ||
149
+ lib.toLowerCase() === 'dom'));
150
+ if (!hasDOM) {
151
+ compilerOptions.lib = [...currentLibs, 'DOM', 'DOM.Iterable'];
152
+ }
153
+ // Types: Agregar 'vue' si no está presente, pero mantener otros types del usuario
154
+ const currentTypes = compilerOptions.types || userConfig.types || [];
155
+ if (!currentTypes.includes('vue')) {
156
+ compilerOptions.types = [...currentTypes, 'vue'];
157
+ }
158
+ }
159
+ // Configuraciones que mejoran la detección de errores pero respetan preferencias del usuario
160
+ // Solo se aplican si el usuario no las ha configurado explícitamente
161
+ if (compilerOptions.skipLibCheck === undefined) {
162
+ compilerOptions.skipLibCheck = true; // Para evitar errores en librerías externas
163
+ }
164
+ // Aplicar strictMode solo si el usuario no ha configurado estas opciones individualmente
165
+ if (options?.strictMode !== undefined) {
166
+ if (compilerOptions.noImplicitReturns === undefined) {
167
+ compilerOptions.noImplicitReturns = options.strictMode;
168
+ }
169
+ if (compilerOptions.noImplicitThis === undefined) {
170
+ compilerOptions.noImplicitThis = options.strictMode;
171
+ }
172
+ if (compilerOptions.strictNullChecks === undefined) {
173
+ compilerOptions.strictNullChecks = options.strictMode;
174
+ }
175
+ if (compilerOptions.strictFunctionTypes === undefined) {
176
+ compilerOptions.strictFunctionTypes = options.strictMode;
177
+ }
178
+ if (compilerOptions.exactOptionalPropertyTypes === undefined) {
179
+ compilerOptions.exactOptionalPropertyTypes = false; // Menos estricto por defecto
180
+ }
181
+ if (compilerOptions.noFallthroughCasesInSwitch === undefined) {
182
+ compilerOptions.noFallthroughCasesInSwitch = options.strictMode;
183
+ }
184
+ }
185
+ return validateTypesWithLanguageService(fileName, scriptContent, // Usar solo el contenido del script
186
+ compilerOptions);
187
+ };
188
+ /**
189
+ * Limpia los export {} innecesarios que TypeScript agrega automáticamente
190
+ * @param compiledOutput - Código JavaScript compilado
191
+ * @param originalSource - Código TypeScript original
192
+ * @returns Código limpio sin export {} innecesarios
193
+ */
194
+ const cleanupUnnecessaryExports = (compiledOutput, originalSource) => {
195
+ // Si el output está vacío o solo contiene export {}
196
+ if (compiledOutput.trim() === 'export {};') {
197
+ return '';
198
+ }
199
+ // Verificar si el código fuente original tiene imports/exports reales
200
+ const hasRealImportsExports = /(?:^|\s)(?:import|export)\s+(?!(?:\s*\{\s*\}\s*;?\s*$))/m.test(originalSource);
201
+ // Si no hay imports/exports reales, eliminar export {} del final
202
+ if (!hasRealImportsExports) {
203
+ // Buscar el patrón exacto en el archivo
204
+ const exportPattern = /export\s*\{\s*\}\s*;\s*$/m;
205
+ const hasExportAtEnd = exportPattern.test(compiledOutput);
206
+ if (hasExportAtEnd) {
207
+ return compiledOutput.replace(exportPattern, '');
208
+ }
209
+ }
210
+ return compiledOutput;
211
+ };
212
+ /**
213
+ * Precompila el código TypeScript con pipeline optimizado para máxima performance.
214
+ * @param {string} data - El código TypeScript a precompilar.
215
+ * @param {string} fileName - El nombre del archivo que contiene el código typescript.
216
+ * @returns {Promise<CompileResult>} - Un objeto con el código precompilado o un error.
217
+ */
218
+ export const preCompileTS = async (data, fileName) => {
219
+ try {
220
+ // Validación temprana: contenido vacío
221
+ if (!data.trim()) {
222
+ return { error: null, data: data, lang: 'ts' };
223
+ }
224
+ // Cargar configuración de TypeScript desde tsconfig.json
225
+ const compilerOptions = loadTypeScriptConfig(fileName);
226
+ // PASO 1: Transpilación ULTRA RÁPIDA con mínima verificación
227
+ // Optimizaciones agresivas para máxima velocidad
228
+ const transpileResult = typescript.transpileModule(data, {
229
+ compilerOptions: {
230
+ ...compilerOptions,
231
+ // Optimizaciones de velocidad
232
+ noLib: true,
233
+ skipLibCheck: true,
234
+ isolatedModules: true,
235
+ // Deshabilitar checks innecesarios
236
+ noResolve: true,
237
+ // ✅ REMOVIDAS opciones obsoletas de TypeScript 5.9:
238
+ // - suppressImplicitAnyIndexErrors (ya no existe)
239
+ // - suppressExcessPropertyErrors (ya no existe)
240
+ allowSyntheticDefaultImports: true,
241
+ // Modo más rápido
242
+ incremental: false, // No usar incremental en transpileModule
243
+ diagnostics: false,
244
+ },
245
+ fileName,
246
+ reportDiagnostics: env.VERBOSE === 'true', // Solo reportar en verbose
247
+ });
248
+ // const transpileResult = traspileTStoJS(
249
+ // fileName,data)
250
+ // Verificar errores críticos de sintaxis
251
+ if (transpileResult.diagnostics?.length) {
252
+ const criticalErrors = transpileResult.diagnostics.filter((diag) => {
253
+ if (diag.category !== typescript.DiagnosticCategory.Error)
254
+ return false;
255
+ const messageText = typescript.flattenDiagnosticMessageText(diag.messageText, '\n');
256
+ // Ignorar errores de módulo no encontrado
257
+ return (!messageText.includes('Cannot find module') &&
258
+ !messageText.includes('Could not find source file') &&
259
+ diag.code !== 2307 &&
260
+ diag.code !== 6059);
261
+ });
262
+ if (criticalErrors.length > 0) {
263
+ const errorMessage = createUnifiedErrorMessage(parseTypeScriptErrors(criticalErrors, fileName, data));
264
+ return {
265
+ error: new Error(errorMessage),
266
+ data: null,
267
+ lang: 'ts',
268
+ };
269
+ }
270
+ } // PASO 2: Type checking opcional (solo si está habilitado)
271
+ if (env.typeCheck === 'true') {
272
+ try {
273
+ const workerPool = TypeScriptWorkerPool.getInstance();
274
+ const serializableOptions = createSerializableCompilerOptions(compilerOptions);
275
+ const typeCheckResult = await workerPool.typeCheck(fileName, data, serializableOptions);
276
+ if (typeCheckResult.hasErrors) {
277
+ const errorMessage = createUnifiedErrorMessage(parseTypeScriptErrors(typeCheckResult.diagnostics, fileName, data));
278
+ return {
279
+ error: new Error(errorMessage),
280
+ data: null,
281
+ lang: 'ts',
282
+ };
283
+ }
284
+ }
285
+ catch (typeCheckError) {
286
+ // Type checking falla, pero continuar con transpilación
287
+ console.warn('[preCompileTS] ❌ Type checking falló, usando transpilación sin verificación de tipos:', typeCheckError);
288
+ }
289
+ }
290
+ // PASO 3: Devolver resultado optimizado
291
+ let output = transpileResult.outputText;
292
+ // Limpiar export {} innecesarios
293
+ output = cleanupUnnecessaryExports(output, data);
294
+ return { error: null, data: output, lang: 'ts' };
295
+ }
296
+ catch (error) {
297
+ return {
298
+ error: error instanceof Error ? error : new Error('Error desconocido'),
299
+ data: null,
300
+ lang: 'ts',
301
+ };
302
+ }
303
+ };
304
+ //# sourceMappingURL=typescript-manager.js.map
@@ -1,32 +1,296 @@
1
- import*as e from"node:fs";import*as t from"node:path";import*as n from"node:process";import*as r from"typescript";const i=()=>`// Declaraciones básicas de tipos Vue para validación
2
- declare global {
3
- function ref<T>(value: T): { value: T };
4
- function reactive<T extends object>(target: T): T;
5
- function computed<T>(getter: () => T): { value: T };
6
- function defineComponent<T>(options: T): T;
7
- function defineProps<T = {}>(): T;
8
- function defineEmits<T = {}>(): T;
9
- function defineExpose<T = {}>(exposed: T): void;
10
- function onMounted(fn: () => void): void;
11
- function onUnmounted(fn: () => void): void;
12
- function onBeforeMount(fn: () => void): void;
13
- function onBeforeUnmount(fn: () => void): void;
14
- function onUpdated(fn: () => void): void;
15
- function onBeforeUpdate(fn: () => void): void;
16
- function provide<T>(key: string | symbol, value: T): void;
17
- function inject<T>(key: string | symbol, defaultValue?: T): T | undefined;
18
- function useSlots(): { [key: string]: (...args: any[]) => any };
19
- function useAttrs(): { [key: string]: any };
20
- function useModel<T>(modelName?: string): { value: T };
21
- function watch<T>(source: () => T, callback: (newValue: T, oldValue: T) => void): void;
22
- function watchEffect(effect: () => void): void;
23
- function nextTick(callback?: () => void): Promise<void>;
24
- function getCurrentInstance(): any;
25
- function mergeModels<T>(models: T): T;
1
+ /**
2
+ * TypeScript Sync Validator - Validación síncrona de tipos como fallback
3
+ * Contiene la lógica extraída del módulo principal para cuando el worker no está disponible
4
+ */
5
+ import * as fs from 'node:fs';
6
+ import * as path from 'node:path';
7
+ import * as process from 'node:process';
8
+ import * as typescript from 'typescript';
9
+ /**
10
+ * Genera declaraciones básicas de tipos para Vue como fallback
11
+ */
12
+ const generateBasicVueTypes = () => {
13
+ return `// Declaraciones básicas de tipos Vue para validación
14
+ declare global {
15
+ function ref<T>(value: T): { value: T };
16
+ function reactive<T extends object>(target: T): T;
17
+ function computed<T>(getter: () => T): { value: T };
18
+ function defineComponent<T>(options: T): T;
19
+ function defineProps<T = {}>(): T;
20
+ function defineEmits<T = {}>(): T;
21
+ function defineExpose<T = {}>(exposed: T): void;
22
+ function onMounted(fn: () => void): void;
23
+ function onUnmounted(fn: () => void): void;
24
+ function onBeforeMount(fn: () => void): void;
25
+ function onBeforeUnmount(fn: () => void): void;
26
+ function onUpdated(fn: () => void): void;
27
+ function onBeforeUpdate(fn: () => void): void;
28
+ function provide<T>(key: string | symbol, value: T): void;
29
+ function inject<T>(key: string | symbol, defaultValue?: T): T | undefined;
30
+ function useSlots(): { [key: string]: (...args: any[]) => any };
31
+ function useAttrs(): { [key: string]: any };
32
+ function useModel<T>(modelName?: string): { value: T };
33
+ function watch<T>(source: () => T, callback: (newValue: T, oldValue: T) => void): void;
34
+ function watchEffect(effect: () => void): void;
35
+ function nextTick(callback?: () => void): Promise<void>;
36
+ function getCurrentInstance(): any;
37
+ function mergeModels<T>(models: T): T;
38
+ }
39
+ declare module '*.vue' {
40
+ const component: any;
41
+ export default component;
42
+ }
43
+ export {};`;
44
+ };
45
+ /**
46
+ * Language Service Host para validación de tipos eficiente
47
+ */
48
+ class TypeScriptLanguageServiceHost {
49
+ files = new Map();
50
+ compilerOptions;
51
+ constructor(compilerOptions) {
52
+ this.compilerOptions = {
53
+ ...compilerOptions,
54
+ // Asegurar que las librerías DOM estén incluidas para archivos Vue
55
+ lib: compilerOptions.lib || ['ES2020', 'DOM', 'DOM.Iterable'],
56
+ };
57
+ }
58
+ addFile(fileName, content) {
59
+ const existing = this.files.get(fileName);
60
+ this.files.set(fileName, {
61
+ version: existing ? existing.version + 1 : 1,
62
+ content,
63
+ });
64
+ }
65
+ getCompilationSettings() {
66
+ return this.compilerOptions;
67
+ }
68
+ getScriptFileNames() {
69
+ return Array.from(this.files.keys());
70
+ }
71
+ getScriptVersion(fileName) {
72
+ const file = this.files.get(fileName);
73
+ return file ? file.version.toString() : '0';
74
+ }
75
+ getScriptSnapshot(fileName) {
76
+ const file = this.files.get(fileName);
77
+ if (file) {
78
+ return typescript.ScriptSnapshot.fromString(file.content);
79
+ } // Intentar leer el archivo del sistema de archivos para dependencias
80
+ if (fs.existsSync(fileName)) {
81
+ try {
82
+ const content = fs.readFileSync(fileName, 'utf-8');
83
+ return typescript.ScriptSnapshot.fromString(content);
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ return undefined;
90
+ }
91
+ getCurrentDirectory() {
92
+ return process.cwd();
93
+ }
94
+ getDefaultLibFileName(options) {
95
+ return typescript.getDefaultLibFilePath(options);
96
+ }
97
+ fileExists(path) {
98
+ return this.files.has(path) || fs.existsSync(path);
99
+ }
100
+ readFile(path) {
101
+ const file = this.files.get(path);
102
+ if (file) {
103
+ return file.content;
104
+ }
105
+ if (fs.existsSync(path)) {
106
+ try {
107
+ return fs.readFileSync(path, 'utf-8');
108
+ }
109
+ catch {
110
+ return undefined;
111
+ }
112
+ }
113
+ return undefined;
114
+ }
115
+ getNewLine() {
116
+ return typescript.sys.newLine;
117
+ }
26
118
  }
27
- declare module '*.vue' {
28
- const component: any;
29
- export default component;
30
- }
31
- export {};`;class a{files=new Map;compilerOptions;constructor(e){this.compilerOptions={...e,lib:e.lib||[`ES2020`,`DOM`,`DOM.Iterable`]}}addFile(e,t){let n=this.files.get(e);this.files.set(e,{version:n?n.version+1:1,content:t})}getCompilationSettings(){return this.compilerOptions}getScriptFileNames(){return Array.from(this.files.keys())}getScriptVersion(e){let t=this.files.get(e);return t?t.version.toString():`0`}getScriptSnapshot(t){let n=this.files.get(t);if(n)return r.ScriptSnapshot.fromString(n.content);if(e.existsSync(t))try{let n=e.readFileSync(t,`utf-8`);return r.ScriptSnapshot.fromString(n)}catch{return}}getCurrentDirectory(){return n.cwd()}getDefaultLibFileName(e){return r.getDefaultLibFilePath(e)}fileExists(t){return this.files.has(t)||e.existsSync(t)}readFile(t){let n=this.files.get(t);if(n)return n.content;if(e.existsSync(t))try{return e.readFileSync(t,`utf-8`)}catch{return}}getNewLine(){return r.sys.newLine}}export const validateTypesWithLanguageService=(o,s,c)=>{try{if(!s.trim())return{diagnostics:[],hasErrors:!1};let l=new a(c),u=o;if(o.endsWith(`.vue`)&&(u=o.replace(`.vue`,`.vue.ts`)),l.addFile(u,s),o.endsWith(`.vue`)){let r=n.cwd(),a=t.join(r,`src/types/vue-shims.d.ts`);try{if(e.existsSync(a)){let t=e.readFileSync(a,`utf-8`);l.addFile(a,t)}else{let e=i(),n=t.join(t.dirname(o),`vue-fallback.d.ts`);l.addFile(n,e)}}catch(e){console.warn(`Error al cargar tipos Vue:`,e);let n=i(),r=t.join(t.dirname(o),`vue-fallback.d.ts`);l.addFile(r,n)}}let d=r.createLanguageService(l);try{if(!l.fileExists(u))return console.log(`File does not exist in host, returning empty result`),{diagnostics:[],hasErrors:!1};let e=[],t=[];try{e=d.getSyntacticDiagnostics(u)}catch{}try{t=d.getSemanticDiagnostics(u)}catch{}let n=[...e,...t],i=n.filter(e=>{let t=r.flattenDiagnosticMessageText(e.messageText,`
32
- `);if(e.category!==r.DiagnosticCategory.Error)return!1;let n=[`Cannot find module`,`Could not find source file`,`has no exported member 'mergeModels'`,`Unable to resolve signature of method decorator`,`The runtime will invoke the decorator with`,`Module resolution kind is not specified`,`Cannot resolve module`,`Cannot find name 'console'`,`Do you need to change your target library`];for(let e of n)if(t.includes(e))return!1;let i=[1241,2307,2584,6133];if(i.includes(e.code))return!1;if(o.endsWith(`.vue`)){let e=[`$props`,`$setup`,`$data`,`$options`,`$event`,`_ctx`,`_cache`,`__expose`,`__emit`,`__slots`,`__props`,`__defaults`];if(t.includes(`implicitly has an 'any' type`)){let n=e.some(e=>t.includes(`'${e}'`)||t.includes(`"${e}"`));if(n)return!1}if(t.includes(`Parameter`)&&t.includes(`implicitly has an`)&&e.some(e=>t.includes(e)))return!1}return!0});return{diagnostics:i,hasErrors:i.length>0}}catch{return{diagnostics:[],hasErrors:!1}}}catch(e){let t={file:void 0,start:void 0,length:void 0,messageText:`Error en validación de tipos: ${e instanceof Error?e.message:`Error desconocido`}`,category:r.DiagnosticCategory.Error,code:0};return{diagnostics:[t],hasErrors:!0}}};export const validateVueTypes=(e,t,n)=>validateTypesWithLanguageService(t,e,n);
119
+ /**
120
+ * Realiza validación de tipos usando TypeScript Language Service (versión síncrona)
121
+ * @param fileName - Nombre del archivo
122
+ * @param content - Contenido del archivo
123
+ * @param compilerOptions - Opciones del compilador
124
+ * @returns Resultado de la validación de tipos
125
+ */
126
+ export const validateTypesWithLanguageService = (fileName, content, compilerOptions) => {
127
+ try {
128
+ // Si el script está vacío o es solo espacios en blanco, no validar
129
+ if (!content.trim()) {
130
+ return { diagnostics: [], hasErrors: false };
131
+ } // Crear Language Service Host
132
+ const host = new TypeScriptLanguageServiceHost(compilerOptions);
133
+ // Para archivos Vue, crear un archivo virtual .ts
134
+ let actualFileName = fileName;
135
+ if (fileName.endsWith('.vue')) {
136
+ // Crear un nombre de archivo virtual con extensión .ts
137
+ actualFileName = fileName.replace('.vue', '.vue.ts');
138
+ }
139
+ // Agregar el archivo al host con el nombre correcto
140
+ host.addFile(actualFileName, content);
141
+ // Agregar declaraciones de tipos para Vue si es necesario
142
+ if (fileName.endsWith('.vue')) {
143
+ // Cargar declaraciones de tipos Vue desde archivo shims
144
+ const projectRoot = process.cwd();
145
+ const vueShimsPath = path.join(projectRoot, 'src/types/vue-shims.d.ts');
146
+ try {
147
+ if (fs.existsSync(vueShimsPath)) {
148
+ const vueShimsContent = fs.readFileSync(vueShimsPath, 'utf-8');
149
+ host.addFile(vueShimsPath, vueShimsContent);
150
+ }
151
+ else {
152
+ // Fallback a declaraciones básicas si no se encuentra el archivo shims
153
+ const basicVueTypes = generateBasicVueTypes();
154
+ const fallbackTypesPath = path.join(path.dirname(fileName), 'vue-fallback.d.ts');
155
+ host.addFile(fallbackTypesPath, basicVueTypes);
156
+ }
157
+ }
158
+ catch (error) {
159
+ // Si hay error cargando los tipos, usar fallback básico
160
+ console.warn('Error al cargar tipos Vue:', error);
161
+ const basicVueTypes = generateBasicVueTypes();
162
+ const fallbackTypesPath = path.join(path.dirname(fileName), 'vue-fallback.d.ts');
163
+ host.addFile(fallbackTypesPath, basicVueTypes);
164
+ }
165
+ } // Crear Language Service
166
+ const languageService = typescript.createLanguageService(host);
167
+ try {
168
+ // Verificar que el archivo existe en el host antes de solicitar diagnósticos
169
+ if (!host.fileExists(actualFileName)) {
170
+ console.log('File does not exist in host, returning empty result');
171
+ return { diagnostics: [], hasErrors: false };
172
+ } // Obtener diagnósticos de tipos con manejo de errores
173
+ let syntacticDiagnostics = [];
174
+ let semanticDiagnostics = [];
175
+ try {
176
+ syntacticDiagnostics =
177
+ languageService.getSyntacticDiagnostics(actualFileName);
178
+ }
179
+ catch {
180
+ // Ignorar errores de diagnósticos sintácticos
181
+ }
182
+ try {
183
+ semanticDiagnostics =
184
+ languageService.getSemanticDiagnostics(actualFileName);
185
+ }
186
+ catch {
187
+ // Ignorar errores de diagnósticos semánticos
188
+ }
189
+ // Combinar todos los diagnósticos
190
+ const allDiagnostics = [
191
+ ...syntacticDiagnostics,
192
+ ...semanticDiagnostics,
193
+ ];
194
+ // Filtrar diagnósticos relevantes con mejor manejo para Vue
195
+ const filteredDiagnostics = allDiagnostics.filter((diag) => {
196
+ const messageText = typescript.flattenDiagnosticMessageText(diag.messageText, '\n');
197
+ // Solo errores de categoría Error (no warnings)
198
+ if (diag.category !== typescript.DiagnosticCategory.Error) {
199
+ return false;
200
+ } // Errores de infraestructura que siempre se filtran
201
+ const infrastructureErrors = [
202
+ 'Cannot find module',
203
+ 'Could not find source file',
204
+ "has no exported member 'mergeModels'",
205
+ 'Unable to resolve signature of method decorator',
206
+ 'The runtime will invoke the decorator with',
207
+ 'Module resolution kind is not specified',
208
+ 'Cannot resolve module',
209
+ "Cannot find name 'console'", // Error común al usar console en entorno sin DOM
210
+ 'Do you need to change your target library', // Sugerencia de librerías
211
+ ];
212
+ for (const errorPattern of infrastructureErrors) {
213
+ if (messageText.includes(errorPattern)) {
214
+ return false;
215
+ }
216
+ } // Códigos de error específicos que se filtran
217
+ const filteredErrorCodes = [
218
+ 1241, // decorator signature mismatch
219
+ 2307, // Cannot find module (redundant but explicit)
220
+ 2584, // Cannot find name (ej: console sin DOM lib)
221
+ 6133, // unused variables (warnings, not errors in this context)
222
+ ];
223
+ if (filteredErrorCodes.includes(diag.code)) {
224
+ return false;
225
+ }
226
+ // Para archivos Vue, filtrar solo errores específicos de infraestructura
227
+ if (fileName.endsWith('.vue')) {
228
+ // Parámetros implícitos generados automáticamente por Vue
229
+ const vueImplicitParams = [
230
+ '$props',
231
+ '$setup',
232
+ '$data',
233
+ '$options',
234
+ '$event',
235
+ '_ctx',
236
+ '_cache',
237
+ '__expose',
238
+ '__emit',
239
+ '__slots',
240
+ '__props',
241
+ '__defaults',
242
+ ];
243
+ // Solo filtrar errores de 'any' implícito para parámetros de infraestructura de Vue
244
+ if (messageText.includes("implicitly has an 'any' type")) {
245
+ const hasVueImplicitParam = vueImplicitParams.some(param => messageText.includes(`'${param}'`) ||
246
+ messageText.includes(`"${param}"`));
247
+ if (hasVueImplicitParam) {
248
+ return false;
249
+ }
250
+ }
251
+ // Filtrar errores específicos de setup function
252
+ if (messageText.includes('Parameter') &&
253
+ messageText.includes('implicitly has an') &&
254
+ vueImplicitParams.some(param => messageText.includes(param))) {
255
+ return false;
256
+ }
257
+ }
258
+ // Mantener TODOS los demás errores - especialmente errores de tipos del usuario
259
+ return true;
260
+ });
261
+ return {
262
+ diagnostics: filteredDiagnostics,
263
+ hasErrors: filteredDiagnostics.length > 0,
264
+ };
265
+ }
266
+ catch {
267
+ return { diagnostics: [], hasErrors: false };
268
+ }
269
+ }
270
+ catch (error) {
271
+ // En caso de error, devolver diagnóstico de error
272
+ const errorDiagnostic = {
273
+ file: undefined,
274
+ start: undefined,
275
+ length: undefined,
276
+ messageText: `Error en validación de tipos: ${error instanceof Error ? error.message : 'Error desconocido'}`,
277
+ category: typescript.DiagnosticCategory.Error,
278
+ code: 0,
279
+ };
280
+ return {
281
+ diagnostics: [errorDiagnostic],
282
+ hasErrors: true,
283
+ };
284
+ }
285
+ };
286
+ /**
287
+ * Valida tipos en archivos Vue antes de la compilación (versión síncrona)
288
+ * @param vueContent - Contenido del archivo Vue
289
+ * @param fileName - Nombre del archivo Vue
290
+ * @param compilerOptions - Opciones del compilador
291
+ * @returns Resultado de la validación de tipos
292
+ */
293
+ export const validateVueTypes = (vueContent, fileName, compilerOptions) => {
294
+ return validateTypesWithLanguageService(fileName, vueContent, compilerOptions);
295
+ };
296
+ //# sourceMappingURL=typescript-sync-validator.js.map