vatts 1.2.0-test.3 → 1.2.0-test.4

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 (2) hide show
  1. package/dist/builder.js +32 -46
  2. package/package.json +1 -1
package/dist/builder.js CHANGED
@@ -36,26 +36,20 @@ const esbuild = require('rollup-plugin-esbuild').default;
36
36
  const jsonPlugin = require("@rollup/plugin-json").default;
37
37
  const { loadTsConfigPaths, resolveTsConfigAlias } = require('./tsconfigPaths');
38
38
  // --- Helper de Detecção de Framework ---
39
- // Helper para determinar o framework principal do projeto
40
39
  function detectFramework(projectDir = process.cwd()) {
41
- // 1. Tenta detectar pelo package.json (mais preciso e evita conflitos)
42
40
  try {
43
41
  const pkgPath = path.join(projectDir, 'package.json');
44
42
  if (fs.existsSync(pkgPath)) {
45
43
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
46
44
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
47
- // Prioridade explicita para React se estiver listado
48
45
  if (deps.react || deps['react-dom'])
49
46
  return 'react';
50
- // Se tiver Vue e não React, é Vue
51
47
  if (deps.vue || deps['nuxt'])
52
48
  return 'vue';
53
49
  }
54
50
  }
55
- catch (e) {
56
- // Ignora erro de leitura
57
- }
58
- return 'react'; // Default fallback
51
+ catch (e) { }
52
+ return 'react';
59
53
  }
60
54
  const tsconfigPathsPlugin = (projectDir = process.cwd()) => {
61
55
  const info = loadTsConfigPaths(projectDir);
@@ -72,7 +66,6 @@ const tsconfigPathsPlugin = (projectDir = process.cwd()) => {
72
66
  }
73
67
  };
74
68
  };
75
- // Lista de módulos nativos do Node.js
76
69
  const nodeBuiltIns = [
77
70
  'assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns',
78
71
  'domain', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode',
@@ -89,23 +82,41 @@ const markdownPlugin = () => {
89
82
  if (id.endsWith('.md')) {
90
83
  return {
91
84
  code: `export default ${JSON.stringify(code)};`,
92
- map: null // Null map economiza memória se não precisa debugar markdown
85
+ map: null
93
86
  };
94
87
  }
95
88
  }
96
89
  };
97
90
  };
91
+ /**
92
+ * NOVO: Plugin de DEBUG para arquivos Vue+TS Virtuais
93
+ * Esse cara vai logar no console exatamente o que tá passando de um plugin pro outro.
94
+ */
95
+ const vueTsDebugPlugin = () => {
96
+ return {
97
+ name: 'vatts-vue-ts-debug',
98
+ transform(code, id) {
99
+ // Intercepta especificamente o arquivo virtual de script TS do Vue
100
+ if (id.includes('?vue&type=script&lang.ts')) {
101
+ Console.warn(`\n================= [DEBUG VUE TS] =================`);
102
+ Console.warn(`Arquivo Virtual: ${id}`);
103
+ Console.warn(`--- Código Original (Primeiras 10 linhas) ---`);
104
+ Console.warn(code.split('\n').slice(0, 10).join('\n'));
105
+ Console.warn(`==================================================\n`);
106
+ }
107
+ return null; // Não altera o código, só inspeciona
108
+ }
109
+ };
110
+ };
98
111
  /**
99
112
  * Plugin para CSS/PostCSS Manual (Otimizado para RAM)
100
113
  */
101
114
  const customPostCssPlugin = (isProduction) => {
102
115
  let cachedProcessor = null;
103
116
  let configLoaded = false;
104
- // Função auxiliar para inicializar o PostCSS apenas uma vez
105
117
  const initPostCss = async (projectDir) => {
106
118
  if (configLoaded)
107
119
  return cachedProcessor;
108
- // CRÍTICO: Garante que o Tailwind saiba que é produção para purgar CSS não usado
109
120
  process.env.NODE_ENV = isProduction ? 'production' : 'development';
110
121
  const postcssConfigPath = path.join(projectDir, 'postcss.config.js');
111
122
  const postcssConfigMjsPath = path.join(projectDir, 'postcss.config.mjs');
@@ -170,7 +181,6 @@ const customPostCssPlugin = (isProduction) => {
170
181
  return {
171
182
  name: 'custom-postcss-plugin',
172
183
  async transform(code, id) {
173
- // Intercepta arquivos CSS e requests virtuais de estilo do Vue (que terminam em .css)
174
184
  if (!id.endsWith('.css'))
175
185
  return null;
176
186
  const processor = await initPostCss(process.cwd());
@@ -180,7 +190,7 @@ const customPostCssPlugin = (isProduction) => {
180
190
  const result = await processor.process(code, {
181
191
  from: id,
182
192
  to: id,
183
- map: false // Mapas inline ou não, melhor manter simples aqui
193
+ map: false
184
194
  });
185
195
  processedCss = result.css;
186
196
  }
@@ -188,16 +198,12 @@ const customPostCssPlugin = (isProduction) => {
188
198
  Console.warn(`PostCSS process error:`, e.message);
189
199
  }
190
200
  }
191
- // Emite o arquivo CSS processado como asset
192
- // Remove query params do Vue (ex: ?vue&type=style...) para gerar um nome de arquivo limpo
193
201
  const cleanName = path.basename(id).split('?')[0];
194
202
  const referenceId = this.emitFile({
195
203
  type: 'asset',
196
204
  name: cleanName,
197
205
  source: processedCss
198
206
  });
199
- // Retorna o módulo JS que injeta o CSS via <link>
200
- // FIX: Retorna um objeto com 'code' e 'map' para evitar o aviso "Sourcemap is likely to be incorrect"
201
207
  return {
202
208
  code: `
203
209
  const cssUrl = String(import.meta.ROLLUP_FILE_URL_${referenceId});
@@ -291,16 +297,13 @@ const smartAssetPlugin = (isProduction) => {
291
297
  * Gera a configuração base do Rollup (Agora Async e Estrita)
292
298
  */
293
299
  async function createRollupConfig(entryPoint, outdir, isProduction) {
294
- // Detecta Framework de forma exclusiva e robusta
295
300
  const framework = detectFramework();
296
301
  const hasVue = framework === 'vue';
297
302
  const hasReact = framework === 'react';
298
- // Define variáveis de ambiente
299
303
  const replaceValues = {
300
304
  'process.env.NODE_ENV': JSON.stringify(isProduction ? 'production' : 'development'),
301
305
  'process.env.PORT': JSON.stringify(process.vatts.port || 3000)
302
306
  };
303
- // --- LÓGICA VUE ESTRITA ---
304
307
  let vuePlugin = null;
305
308
  if (hasVue) {
306
309
  replaceValues['__VUE_OPTIONS_API__'] = JSON.stringify(true);
@@ -331,35 +334,25 @@ async function createRollupConfig(entryPoint, outdir, isProduction) {
331
334
  Console.warn("Vue detected but failed to load rollup-plugin-vue:", e.message);
332
335
  }
333
336
  }
334
- // --- CONFIGURAÇÃO DE EXTENSÕES ---
335
- // Fix: Prioriza .vue se for um projeto Vue para evitar que o NodeResolve pegue artefatos gerados (como .vue.js do Volar)
336
- // ao invés do arquivo fonte .vue.
337
337
  let extensions = ['.mjs', '.js', '.json', '.node', '.jsx', '.tsx', '.ts'];
338
338
  if (hasVue) {
339
- // Coloca .vue no INÍCIO da lista
340
339
  extensions = ['.vue', ...extensions];
341
340
  }
342
- // --- CONFIGURAÇÃO DO ESBUILD ---
343
- // SEPARAÇÃO: Regex específico para cada framework.
344
- // FIX ERRO VUE: O Regex do Vue inclui os arquivos virtuais `?vue`,
345
- // mas o loader '.vue': 'ts' foi removido para evitar conflito com o plugin do Vue.
341
+ // CORREÇÃO CRÍTICA AQUI: O Regex precisa aceitar "?vue&type=script&lang.ts"
346
342
  let esbuildInclude;
347
343
  if (hasVue) {
348
- esbuildInclude = /\.[jt]sx?$|\.vue\?vue/;
344
+ // Captura TS, TSX, JS, JSX E os scripts TS virtuais do Vue
345
+ esbuildInclude = /\.[jt]sx?$|\.vue\?vue.*lang\.ts/;
349
346
  }
350
347
  else {
351
- esbuildInclude = /\.[jt]sx?$/; // React/Vanilla: ignora arquivos virtuais do Vue
348
+ esbuildInclude = /\.[jt]sx?$/;
352
349
  }
353
350
  const esbuildLoaders = {
354
351
  '.js': 'jsx',
355
352
  '.ts': 'ts',
356
353
  '.tsx': 'tsx',
357
- // RESTAURADO: .vue para ts. Isso é NECESSÁRIO para processar blocos <script lang="ts">
358
- // Se houver erros do tipo __VLS_, o plugin 'block-volar-artifacts' abaixo deve resolver.
359
354
  '.vue': 'ts'
360
355
  };
361
- // No Vue, partes do arquivo podem virar TS, mas isso é pego pela extensão do arquivo virtual,
362
- // não precisamos forçar no loader geral.
363
356
  return {
364
357
  input: entryPoint,
365
358
  external: nodeBuiltIns,
@@ -376,40 +369,33 @@ async function createRollupConfig(entryPoint, outdir, isProduction) {
376
369
  values: replaceValues
377
370
  }),
378
371
  tsconfigPathsPlugin(process.cwd()),
379
- // NOVO: Blocker agressivo para artefatos gerados pelo Volar/TS (.vue.js, .vue.d.ts)
380
- // Isso previne que o build tente empacotar arquivos temporários de tipagem como se fossem código fonte.
381
372
  {
382
373
  name: 'block-volar-artifacts',
383
374
  load(id) {
384
- // Ignora arquivos que terminam em .vue.js, .vue.ts, ou .vue.d.ts
385
- // Esses arquivos frequentemente contêm código "virtual" (__VLS_...) que causa erros em runtime.
386
375
  if (/\.vue\.(js|ts|d\.ts|map)$/.test(id)) {
387
376
  return 'export default {};';
388
377
  }
389
378
  return null;
390
379
  }
391
380
  },
392
- // NOVO: Blocker para artefatos Vue (.vue e .vue.js) em projetos React
393
- // Impede que arquivos compilados do Vue quebrem o build React
394
381
  {
395
382
  name: 'block-vue-artifacts',
396
383
  load(id) {
397
- // Verifica se não estamos no Vue e se o arquivo é um artefato Vue
398
384
  if (!hasVue && (id.endsWith('.vue') || id.endsWith('.vue.js'))) {
399
- // Retorna módulo vazio para "matar" o arquivo e impedir erros de runtime
400
385
  return 'export default {};';
401
386
  }
402
387
  return null;
403
388
  }
404
389
  },
405
390
  nodeResolve({
406
- extensions, // Agora com .vue prioritário se hasVue for true
391
+ extensions,
407
392
  preferBuiltins: true,
408
393
  browser: true,
409
394
  dedupe: hasReact ? ['react', 'react-dom'] : (hasVue ? ['vue'] : [])
410
395
  }),
411
- // CRÍTICO: Injeta plugin do Vue APENAS se for Vue e ANTES de commonjs/esbuild.
412
396
  ...(hasVue && vuePlugin ? [vuePlugin] : []),
397
+ // INSIRA O DEBUG AQUI: Logo depois do plugin do Vue e antes do ESBuild
398
+ ...(hasVue ? [vueTsDebugPlugin()] : []),
413
399
  commonjs({
414
400
  sourceMap: !isProduction,
415
401
  requireReturnsDefault: 'auto',
@@ -421,7 +407,7 @@ async function createRollupConfig(entryPoint, outdir, isProduction) {
421
407
  jsonPlugin(),
422
408
  esbuild({
423
409
  include: esbuildInclude,
424
- exclude: /node_modules/, // Se for React, arquivos .vue serão ignorados pelo regex do include
410
+ exclude: /node_modules/,
425
411
  sourceMap: !isProduction,
426
412
  minify: isProduction,
427
413
  legalComments: 'none',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vatts",
3
- "version": "1.2.0-test.3",
3
+ "version": "1.2.0-test.4",
4
4
  "description": "Vatts.js is a high-level framework for building web applications with ease and speed. It provides a robust set of tools and features to streamline development and enhance productivity.",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "itsmuzin",