vatts 2.2.5 → 2.3.0-canary

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 (64) hide show
  1. package/README.md +3 -3
  2. package/dist/builder.js +54 -17
  3. package/dist/frameworks/FrontCore.d.ts +34 -0
  4. package/dist/frameworks/FrontCore.js +128 -0
  5. package/dist/{vue → frameworks/builds}/vue.build.js +1 -1
  6. package/dist/frameworks/react/client.d.ts +8 -0
  7. package/dist/{react → frameworks/react}/client.js +14 -14
  8. package/dist/{react → frameworks/react/components}/Link.js +2 -2
  9. package/dist/frameworks/react/entry.client.d.ts +14 -0
  10. package/dist/frameworks/react/entry.client.js +211 -0
  11. package/dist/frameworks/react/react-elements.d.ts +10 -0
  12. package/dist/{react → frameworks/renderers}/renderer-react.d.ts +2 -2
  13. package/dist/{react → frameworks/renderers}/renderer-react.js +34 -68
  14. package/dist/{vue → frameworks/renderers}/renderer.vue.d.ts +2 -2
  15. package/dist/frameworks/renderers/renderer.vue.js +193 -0
  16. package/dist/frameworks/themes/BuildingPage.d.ts +1 -0
  17. package/dist/frameworks/themes/BuildingPage.js +312 -0
  18. package/dist/frameworks/themes/DefaultNotFound.d.ts +1 -0
  19. package/dist/frameworks/themes/DefaultNotFound.js +330 -0
  20. package/dist/frameworks/themes/ErrorModal.d.ts +1 -0
  21. package/dist/frameworks/themes/ErrorModal.js +345 -0
  22. package/dist/frameworks/themes/ServerError.d.ts +1 -0
  23. package/dist/frameworks/themes/ServerError.js +401 -0
  24. package/dist/frameworks/themes/VattsDevBadge.d.ts +1 -0
  25. package/dist/frameworks/themes/VattsDevBadge.js +232 -0
  26. package/dist/frameworks/vue/App.vue +149 -0
  27. package/dist/frameworks/vue/client.d.ts +9 -0
  28. package/dist/{vue → frameworks/vue}/client.js +13 -11
  29. package/dist/{vue → frameworks/vue/components}/Link.vue +1 -1
  30. package/dist/frameworks/vue/entry.client.js +75 -0
  31. package/dist/global/global.d.ts +1 -2
  32. package/dist/index.js +12 -1
  33. package/dist/renderer.js +2 -2
  34. package/package.json +10 -26
  35. package/dist/react/BuildingPage.d.ts +0 -2
  36. package/dist/react/BuildingPage.js +0 -270
  37. package/dist/react/DefaultNotFound.d.ts +0 -2
  38. package/dist/react/DefaultNotFound.js +0 -248
  39. package/dist/react/DevIndicator.d.ts +0 -5
  40. package/dist/react/DevIndicator.js +0 -203
  41. package/dist/react/ErrorModal.d.ts +0 -20
  42. package/dist/react/ErrorModal.js +0 -266
  43. package/dist/react/client.d.ts +0 -8
  44. package/dist/react/entry.client.d.ts +0 -6
  45. package/dist/react/entry.client.js +0 -325
  46. package/dist/react/server-error.d.ts +0 -8
  47. package/dist/react/server-error.js +0 -346
  48. package/dist/vue/App.vue +0 -199
  49. package/dist/vue/BuildingPage.vue +0 -281
  50. package/dist/vue/DefaultNotFound.vue +0 -329
  51. package/dist/vue/DevIndicator.vue +0 -226
  52. package/dist/vue/ErrorModal.vue +0 -317
  53. package/dist/vue/client.d.ts +0 -9
  54. package/dist/vue/entry.client.js +0 -110
  55. package/dist/vue/renderer.vue.js +0 -387
  56. package/dist/vue/server-error.vue +0 -351
  57. /package/dist/{react → frameworks/builds}/react.build.d.ts +0 -0
  58. /package/dist/{react → frameworks/builds}/react.build.js +0 -0
  59. /package/dist/{vue → frameworks/builds}/vue.build.d.ts +0 -0
  60. /package/dist/{react → frameworks/react/components}/Link.d.ts +0 -0
  61. /package/dist/{react → frameworks/react/components}/image/Image.d.ts +0 -0
  62. /package/dist/{react → frameworks/react/components}/image/Image.js +0 -0
  63. /package/dist/{vue → frameworks/vue/components}/image/Image.vue +0 -0
  64. /package/dist/{vue → frameworks/vue}/entry.client.d.ts +0 -0
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  <div align="center">
2
2
  <picture>
3
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/mfrazlab/vatts-docs/master/public/logo.png">
4
- <img alt="Vatts.js logo" src="https://raw.githubusercontent.com/mfrazlab/vatts-docs/master/public/logo.png" width="128">
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/murillo-frazao-cunha/vatts-docs/master/public/logo.png">
4
+ <img alt="Vatts.js logo" src="https://raw.githubusercontent.com/murillo-frazao-cunha/vatts-docs/master/public/logo.png" width="128">
5
5
  </picture>
6
6
  <h1>Vatts.js</h1>
7
7
 
8
8
  [![NPM](https://img.shields.io/npm/v/vatts.svg?style=for-the-badge&labelColor=000000)](https://www.npmjs.com/package/vatts)
9
9
  [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=for-the-badge&labelColor=000000)](./LICENSE)
10
- [![GitHub](https://img.shields.io/badge/GitHub-mfrazlab/vatts.js-100000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/mfrazlab/vatts.js)
10
+ [![GitHub](https://img.shields.io/badge/GitHub-murillo-frazao-cunha/vatts.js-100000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/murillo-frazao-cunha/vatts.js)
11
11
 
12
12
  [![HTTP/3 Supported](https://img.shields.io/badge/SUPPORTED-HTTP/3-brightgreen?style=for-the-badge&labelColor=000000)](#)
13
13
  </div>
package/dist/builder.js CHANGED
@@ -22,8 +22,8 @@ const fs = require('fs');
22
22
  const { readdir, stat, rm, rename } = require("node:fs/promises");
23
23
  const { config } = require("./helpers");
24
24
  // Import Framework specific builders
25
- const { createReactConfig } = require('./react/react.build');
26
- const { createVueConfig } = require('./vue/vue.build');
25
+ const { createReactConfig } = require('./frameworks/builds/react.build');
26
+ const { createVueConfig } = require('./frameworks/builds/vue.build');
27
27
  const routerModule = require("./router");
28
28
  const excludedFiles = ['vatts.sock'];
29
29
  // --- Custom Plugin: Require Context (Adapted for Esbuild) ---
@@ -146,13 +146,19 @@ const virtualEntryPlugin = (options) => ({
146
146
  .join('\n');
147
147
  const layoutImport = layout ? `import LayoutComponent from '${layout.componentPath.replace(/\\/g, '/')}';` : '';
148
148
  const notFoundImport = notFound ? `import NotFoundComponent from '${notFound.componentPath.replace(/\\/g, '/')}';` : '';
149
- const defaultNotFoundPath = path.join(__dirname, framework, framework === 'vue' ? 'DefaultNotFound.vue' : 'DefaultNotFound.js').replace(/\\/g, '/');
149
+ const defaultNotFoundPath = path.join(__dirname, 'frameworks', 'themes', 'DefaultNotFound.js').replace(/\\/g, '/');
150
150
  let componentRegistration = routes
151
151
  .map((route, index) => ` '${route.componentPath.replace(/\\/g, '/')}': (route${index} && route${index}.default) ? route${index}.default : route${index},`)
152
152
  .join('\n');
153
153
  const layoutRegistration = layout ? `window.__VATTS_LAYOUT__ = LayoutComponent.default || LayoutComponent;` : `window.__VATTS_LAYOUT__ = null;`;
154
154
  const notFoundRegistration = notFound ? `window.__VATTS_NOT_FOUND__ = NotFoundComponent.default || NotFoundComponent;` : `window.__VATTS_NOT_FOUND__ = null;`;
155
- const entryClientPath = path.join(__dirname, framework, 'entry.client.js').replace(/\\/g, '/');
155
+ // Mapeamos as rotas e injetamos globalmente na entry
156
+ const clientRoutes = routes.map(r => ({
157
+ pattern: r.pattern,
158
+ componentPath: r.componentPath,
159
+ metadata: r.metadata || {}
160
+ }));
161
+ const entryClientPath = path.join(__dirname, 'frameworks', framework, 'entry.client.js').replace(/\\/g, '/');
156
162
  const code = `
157
163
  ${imports}
158
164
  ${layoutImport}
@@ -163,6 +169,8 @@ window.__VATTS_COMPONENTS__ = {
163
169
  ${componentRegistration}
164
170
  };
165
171
 
172
+ window.__VATTS_ROUTES__ = ${JSON.stringify(clientRoutes)};
173
+
166
174
  ${layoutRegistration}
167
175
  ${notFoundRegistration}
168
176
  window.__VATTS_DEFAULT_NOT_FOUND__ = DefaultNotFound;
@@ -296,12 +304,48 @@ async function getFrameworkConfig(vattsOptions, outdir, isProduction, isWatch =
296
304
  ];
297
305
  const pluginConfig = { prePlugins, postPlugins, isWatch };
298
306
  const entryPoint = 'virtual:vatts-entry';
307
+ let config;
299
308
  if (framework === 'vue') {
300
- return await createVueConfig(entryPoint, outdir, isProduction, pluginConfig);
309
+ config = await createVueConfig(entryPoint, outdir, isProduction, pluginConfig);
301
310
  }
302
311
  else {
303
- return await createReactConfig(entryPoint, outdir, isProduction, pluginConfig);
312
+ config = await createReactConfig(entryPoint, outdir, isProduction, pluginConfig);
313
+ }
314
+ // --- INÍCIO DA IMPLEMENTAÇÃO DE CHUNKS E OTIMIZAÇÃO MÁXIMA ---
315
+ const entryPoints = { 'main': entryPoint };
316
+ if (vattsOptions.layout) {
317
+ entryPoints['pages/layout'] = vattsOptions.layout.componentPath;
318
+ }
319
+ if (vattsOptions.notFound) {
320
+ entryPoints['pages/not-found'] = vattsOptions.notFound.componentPath;
321
+ }
322
+ if (vattsOptions.routes && Array.isArray(vattsOptions.routes)) {
323
+ vattsOptions.routes.forEach((route, index) => {
324
+ const fileName = path.basename(route.componentPath, path.extname(route.componentPath));
325
+ entryPoints[`pages/${fileName}-${index}`] = route.componentPath;
326
+ });
327
+ }
328
+ config.entryPoints = entryPoints;
329
+ config.format = 'esm';
330
+ config.splitting = true;
331
+ config.chunkNames = 'chunks/[name]-[hash]';
332
+ config.assetNames = 'assets/[name]-[hash]';
333
+ config.treeShaking = true;
334
+ config.legalComments = 'none';
335
+ config.define = {
336
+ ...(config.define || {}),
337
+ 'process.env.NODE_ENV': isProduction ? '"production"' : '"development"'
338
+ };
339
+ if (isProduction) {
340
+ config.minify = true;
341
+ config.minifyWhitespace = true;
342
+ config.minifyIdentifiers = true;
343
+ config.minifySyntax = true;
344
+ config.target = ['es2020'];
304
345
  }
346
+ // --- FIM DA IMPLEMENTAÇÃO ---
347
+ config.entryNames = '[name]-[hash]';
348
+ return config;
305
349
  }
306
350
  async function buildWithChunks(vattsOptions, outdir, isProduction = false) {
307
351
  await cleanDirectoryExcept(outdir, excludedFiles);
@@ -313,24 +357,18 @@ async function buildWithChunks(vattsOptions, outdir, isProduction = false) {
313
357
  try {
314
358
  const { runOptimizer } = require('./api/optimizer');
315
359
  const optimizedDir = path.join(outdir, 'optimized');
316
- runOptimizer({ targetDir: outdir, outputDir: optimizedDir, ignoredPatterns: ['assets'] });
317
- const rootFiles = await readdir(outdir);
318
- for (const file of rootFiles) {
319
- if ((file.startsWith('main') && file.endsWith('.js')) || file === 'chunks') {
320
- await rm(path.join(outdir, file), { recursive: true, force: true });
321
- }
322
- }
360
+ runOptimizer({ targetDir: outdir, outputDir: optimizedDir, ignoredPatterns: ['assets', 'chunks', 'pages'] });
323
361
  if (fs.existsSync(optimizedDir)) {
324
362
  const optFiles = await readdir(optimizedDir);
325
363
  for (const file of optFiles) {
326
364
  const srcPath = path.join(optimizedDir, file);
327
365
  const destPath = path.join(outdir, file);
328
- await rm(destPath, { recursive: true, force: true });
366
+ await rm(destPath, { recursive: true, force: true }).catch(() => { });
329
367
  await rename(srcPath, destPath);
330
368
  }
331
- await rm(optimizedDir, { recursive: true, force: true });
369
+ await rm(optimizedDir, { recursive: true, force: true }).catch(() => { });
332
370
  }
333
- Console.log("✅ Build successfully optimized with native optimizer.");
371
+ Console.log("✅ Build successfully optimized with heavy chunking enabled.");
334
372
  }
335
373
  catch (err) {
336
374
  Console.error('Native optimization failed:', err);
@@ -351,7 +389,6 @@ async function watchWithChunks(vattsOptions, outdir, hotReloadManager = null) {
351
389
  config.plugins.push({
352
390
  name: 'watch-notifier',
353
391
  setup(build) {
354
- // AGORA ELE AVISA O HOT RELOAD EXATAMENTE QUANDO O ESBUILD INICIA
355
392
  build.onStart(() => {
356
393
  if (hotReloadManager && typeof hotReloadManager.onBuildStart === 'function') {
357
394
  hotReloadManager.onBuildStart();
@@ -0,0 +1,34 @@
1
+ export interface VattsBuildError {
2
+ message?: string;
3
+ name?: string;
4
+ stack?: string;
5
+ frame?: string;
6
+ id?: string;
7
+ plugin?: string;
8
+ pluginCode?: string;
9
+ loc?: any;
10
+ watchFiles?: any;
11
+ cause?: any;
12
+ ts?: number;
13
+ }
14
+ export interface RouteConfig {
15
+ pattern: string;
16
+ componentPath: string;
17
+ metadata?: any;
18
+ }
19
+ export declare function renderCriticalError(error: any, framework: string): void;
20
+ export declare function findRouteForPath(path: string, routes: RouteConfig[]): {
21
+ componentPath: string;
22
+ params: {
23
+ [key: string]: string;
24
+ };
25
+ metadata: any;
26
+ } | null;
27
+ export declare function updateDocumentTitle(title?: string): void;
28
+ export declare function copyBuildError(error: VattsBuildError | null): Promise<void>;
29
+ export declare function setupBuildErrorEvents(onErr: (error: VattsBuildError) => void, onOk: () => void): () => void;
30
+ export declare function setupHMREvents(onComponentUpdate: (file: string | null, timestamp: number) => void): () => void;
31
+ export declare function dispatchHmrReady(pending: {
32
+ file: string | null;
33
+ timestamp: number;
34
+ } | null): void;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ /*
3
+ * This file is part of the Vatts.js Project.
4
+ * Copyright (c) 2026 mfraz
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * ...
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.renderCriticalError = renderCriticalError;
11
+ exports.findRouteForPath = findRouteForPath;
12
+ exports.updateDocumentTitle = updateDocumentTitle;
13
+ exports.copyBuildError = copyBuildError;
14
+ exports.setupBuildErrorEvents = setupBuildErrorEvents;
15
+ exports.setupHMREvents = setupHMREvents;
16
+ exports.dispatchHmrReady = dispatchHmrReady;
17
+ // --- Funções de Dados e Inicialização ---
18
+ function renderCriticalError(error, framework) {
19
+ console.error(`[Vatts Core] ❌ Critical Error rendering application (${framework}):`, error);
20
+ if (typeof document !== 'undefined') {
21
+ document.body.innerHTML = `
22
+ <div style="font-family: monospace; padding: 20px; color: #ff4444; background: #000000; min-height: 100vh;">
23
+ <h1>Vatts Client Error (${framework})</h1>
24
+ <p>A critical error occurred while initializing the application.</p>
25
+ <pre style="background: #0a0a0a; padding: 15px; border-radius: 5px; overflow: auto;">${error?.message || error}</pre>
26
+ <pre style="color: #666; font-size: 12px; margin-top: 10px;">${error?.stack || ''}</pre>
27
+ </div>
28
+ `;
29
+ }
30
+ }
31
+ // --- Roteamento e Utils ---
32
+ function findRouteForPath(path, routes) {
33
+ for (const route of routes) {
34
+ const regexPattern = route.pattern
35
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
36
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
37
+ .replace(/\/\[\[(\w+)\]\]/g, '(?:/(?<$1>[^/]+))?')
38
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
39
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
40
+ const regex = new RegExp(`^${regexPattern}/?$`);
41
+ const match = path.match(regex);
42
+ if (match) {
43
+ return {
44
+ componentPath: route.componentPath,
45
+ params: match.groups || {},
46
+ metadata: route.metadata
47
+ };
48
+ }
49
+ }
50
+ return null;
51
+ }
52
+ function updateDocumentTitle(title) {
53
+ if (title != null) {
54
+ try {
55
+ window.document.title = decodeURIComponent(escape(title));
56
+ }
57
+ catch (e) {
58
+ window.document.title = title;
59
+ }
60
+ }
61
+ }
62
+ async function copyBuildError(error) {
63
+ try {
64
+ if (!error)
65
+ return;
66
+ const payload = JSON.stringify(error, null, 2);
67
+ await navigator.clipboard.writeText(payload);
68
+ }
69
+ catch {
70
+ console.error('[Vatts Core] ❌ Falha ao copiar o erro.');
71
+ }
72
+ }
73
+ // --- Gerenciadores de Eventos (HMR & Errors) ---
74
+ function setupBuildErrorEvents(onErr, onOk) {
75
+ const handleErr = (ev) => {
76
+ const e = ev?.detail;
77
+ console.error('[Vatts Core] 🛑 Erro de build (vatts:build-error):', e);
78
+ window.__VATTS_HAD_BUILD_ERROR__ = true;
79
+ onErr(e);
80
+ };
81
+ const handleOk = () => {
82
+ const hadError = window.__VATTS_HAD_BUILD_ERROR__;
83
+ onOk();
84
+ if (hadError) {
85
+ window.__VATTS_HAD_BUILD_ERROR__ = false;
86
+ console.log('[Vatts Core] 🔄 Erro foi corrigido! Sincronizando dados de rotas com servidor...');
87
+ setTimeout(() => {
88
+ window.location.reload();
89
+ }, 300);
90
+ }
91
+ };
92
+ window.addEventListener('vatts:build-error', handleErr);
93
+ window.addEventListener('vatts:build-ok', handleOk);
94
+ return () => {
95
+ window.removeEventListener('vatts:build-error', handleErr);
96
+ window.removeEventListener('vatts:build-ok', handleOk);
97
+ };
98
+ }
99
+ function setupHMREvents(onComponentUpdate) {
100
+ window.__HWEB_HMR__ = true;
101
+ const handleHMRUpdate = (event) => {
102
+ const { file, timestamp } = event.detail;
103
+ const fileName = file ? file.split('/').pop()?.split('\\').pop() : 'unknown';
104
+ try {
105
+ const fileLower = (file || '').toLowerCase();
106
+ const isPageFile = fileLower.includes('page.tsx') || fileLower.includes('page.jsx') ||
107
+ fileLower.includes('page.ts') || fileLower.includes('page.js') ||
108
+ fileLower.includes('page.vue');
109
+ if (isPageFile) {
110
+ console.log('[Vatts Core] 📄 Page file HMR detected, reloading to sync route data...');
111
+ setTimeout(() => window.location.reload(), 300);
112
+ return;
113
+ }
114
+ console.log(`[Vatts Core] ⚡ HMR Update Triggered: ${fileName}`);
115
+ onComponentUpdate(file || null, timestamp);
116
+ }
117
+ catch (error) {
118
+ console.error('[Vatts Core] ❌ HMR Error:', error);
119
+ }
120
+ };
121
+ window.addEventListener('hmr:component-update', handleHMRUpdate);
122
+ return () => window.removeEventListener('hmr:component-update', handleHMRUpdate);
123
+ }
124
+ function dispatchHmrReady(pending) {
125
+ if (!pending)
126
+ return;
127
+ window.dispatchEvent(new CustomEvent('vatts:hmr-ready', { detail: pending }));
128
+ }
@@ -3,7 +3,7 @@
3
3
  * This file is part of the Vatts.js Project.
4
4
  * Copyright (c) 2026 mfraz
5
5
  */
6
- const Console = require("../api/console").default;
6
+ const Console = require("../../api/console").default;
7
7
  /**
8
8
  * Cria a configuração do Esbuild otimizada para Vue
9
9
  */
@@ -0,0 +1,8 @@
1
+ export { Link } from './components/Link.tsx';
2
+ export { RouteConfig, Metadata } from "../../types.ts";
3
+ export { router } from '../../client/clientRouter.ts';
4
+ export { requireDynamic } from '../../client/requireDynamic.ts';
5
+ export { importServer } from '../../client/rpc.ts';
6
+ export { importPhpServer } from '../../client/rpcPhp.ts';
7
+ export { default as Image } from "./components/image/Image.tsx";
8
+ export { default as VattsImage } from "./components/image/Image.tsx";
@@ -21,18 +21,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
21
21
  Object.defineProperty(exports, "__esModule", { value: true });
22
22
  exports.VattsImage = exports.Image = exports.importPhpServer = exports.importServer = exports.requireDynamic = exports.router = exports.Link = void 0;
23
23
  // Este arquivo exporta apenas código seguro para o cliente (navegador)
24
- var Link_1 = require("./Link");
25
- Object.defineProperty(exports, "Link", { enumerable: true, get: function () { return Link_1.Link; } });
26
- var clientRouter_1 = require("../client/clientRouter");
27
- Object.defineProperty(exports, "router", { enumerable: true, get: function () { return clientRouter_1.router; } });
28
- var requireDynamic_1 = require("../client/requireDynamic");
29
- Object.defineProperty(exports, "requireDynamic", { enumerable: true, get: function () { return requireDynamic_1.requireDynamic; } });
24
+ var Link_tsx_1 = require("./components/Link.js");
25
+ Object.defineProperty(exports, "Link", { enumerable: true, get: function () { return Link_tsx_1.Link; } });
26
+ var clientRouter_ts_1 = require("../../client/clientRouter.js");
27
+ Object.defineProperty(exports, "router", { enumerable: true, get: function () { return clientRouter_ts_1.router; } });
28
+ var requireDynamic_ts_1 = require("../../client/requireDynamic.js");
29
+ Object.defineProperty(exports, "requireDynamic", { enumerable: true, get: function () { return requireDynamic_ts_1.requireDynamic; } });
30
30
  // RPC (client-side)
31
- var rpc_1 = require("../client/rpc");
32
- Object.defineProperty(exports, "importServer", { enumerable: true, get: function () { return rpc_1.importServer; } });
33
- var rpcPhp_1 = require("../client/rpcPhp");
34
- Object.defineProperty(exports, "importPhpServer", { enumerable: true, get: function () { return rpcPhp_1.importPhpServer; } });
35
- var Image_1 = require("./image/Image");
36
- Object.defineProperty(exports, "Image", { enumerable: true, get: function () { return __importDefault(Image_1).default; } });
37
- var Image_2 = require("./image/Image");
38
- Object.defineProperty(exports, "VattsImage", { enumerable: true, get: function () { return __importDefault(Image_2).default; } });
31
+ var rpc_ts_1 = require("../../client/rpc.js");
32
+ Object.defineProperty(exports, "importServer", { enumerable: true, get: function () { return rpc_ts_1.importServer; } });
33
+ var rpcPhp_ts_1 = require("../../client/rpcPhp.js");
34
+ Object.defineProperty(exports, "importPhpServer", { enumerable: true, get: function () { return rpcPhp_ts_1.importPhpServer; } });
35
+ var Image_tsx_1 = require("./components/image/Image.js");
36
+ Object.defineProperty(exports, "Image", { enumerable: true, get: function () { return __importDefault(Image_tsx_1).default; } });
37
+ var Image_tsx_2 = require("./components/image/Image.js");
38
+ Object.defineProperty(exports, "VattsImage", { enumerable: true, get: function () { return __importDefault(Image_tsx_2).default; } });
@@ -21,12 +21,12 @@ exports.Link = Link;
21
21
  * limitations under the License.
22
22
  */
23
23
  const react_1 = __importDefault(require("react"));
24
- const clientRouter_1 = require("../client/clientRouter");
24
+ const clientRouter_ts_1 = require("../../../client/clientRouter.js");
25
25
  function Link({ href, children, ...props }) {
26
26
  const handleClick = async (e) => {
27
27
  e.preventDefault();
28
28
  // Usa o novo sistema de router
29
- await clientRouter_1.router.push(href);
29
+ await clientRouter_ts_1.router.push(href);
30
30
  };
31
31
  return (react_1.default.createElement("a", { href: href, ...props, onClick: handleClick }, children));
32
32
  }
@@ -0,0 +1,14 @@
1
+ import { Root } from 'react-dom/client';
2
+ import '../themes/VattsDevBadge';
3
+ import '../themes/ErrorModal';
4
+ declare global {
5
+ namespace JSX {
6
+ interface IntrinsicElements {
7
+ 'vatts-dev-badge': any;
8
+ 'vatts-error-modal': any;
9
+ }
10
+ }
11
+ interface Window {
12
+ __VATTS_ROOT__?: Root;
13
+ }
14
+ }
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ /*
37
+ * This file is part of the Vatts.js Project.
38
+ * ...
39
+ */
40
+ const react_1 = __importStar(require("react"));
41
+ const client_1 = require("react-dom/client");
42
+ const clientRouter_ts_1 = require("../../client/clientRouter.js");
43
+ const FrontCore_1 = require("../FrontCore");
44
+ require("../themes/VattsDevBadge");
45
+ require("../themes/ErrorModal");
46
+ function App({ componentMap, routes, initialComponentPath, initialParams, layoutComponent }) {
47
+ const [hmrTimestamp, setHmrTimestamp] = (0, react_1.useState)(Date.now());
48
+ const pendingHmrReadyRef = (0, react_1.useRef)(null);
49
+ const [buildError, setBuildError] = (0, react_1.useState)(() => {
50
+ const initialError = window.__VATTS_BUILD_ERROR__ || null;
51
+ if (initialError)
52
+ console.warn('[Vatts React] ⚠️ Erro de build inicial detectado:', initialError);
53
+ return initialError;
54
+ });
55
+ const [isErrorOpen, setIsErrorOpen] = (0, react_1.useState)(() => !!window.__VATTS_BUILD_ERROR__);
56
+ const devBadgeRef = (0, react_1.useRef)(null);
57
+ const errorModalRef = (0, react_1.useRef)(null);
58
+ // Setup de eventos compartilhados
59
+ (0, react_1.useEffect)(() => {
60
+ const cleanupErrorEvents = (0, FrontCore_1.setupBuildErrorEvents)((err) => { setBuildError(err); setIsErrorOpen(true); }, () => { setBuildError(null); setIsErrorOpen(false); });
61
+ const cleanupHmrEvents = (0, FrontCore_1.setupHMREvents)((file, timestamp) => {
62
+ setHmrTimestamp(timestamp);
63
+ pendingHmrReadyRef.current = { file, timestamp };
64
+ });
65
+ return () => {
66
+ cleanupErrorEvents();
67
+ cleanupHmrEvents();
68
+ };
69
+ }, []);
70
+ (0, react_1.useEffect)(() => {
71
+ (0, FrontCore_1.dispatchHmrReady)(pendingHmrReadyRef.current);
72
+ pendingHmrReadyRef.current = null;
73
+ }, [hmrTimestamp]);
74
+ const handleCopyLog = (0, react_1.useCallback)(() => (0, FrontCore_1.copyBuildError)(buildError), [buildError]);
75
+ // Sincroniza refs dos Web Components
76
+ (0, react_1.useEffect)(() => {
77
+ const badge = devBadgeRef.current;
78
+ const modal = errorModalRef.current;
79
+ if (badge)
80
+ badge.setAttribute('has-build-error', buildError ? 'true' : 'false');
81
+ if (modal) {
82
+ modal.error = buildError;
83
+ modal.isOpen = isErrorOpen;
84
+ }
85
+ }, [buildError, isErrorOpen]);
86
+ (0, react_1.useEffect)(() => {
87
+ const badge = devBadgeRef.current;
88
+ const modal = errorModalRef.current;
89
+ const handleBadgeClick = () => setIsErrorOpen(true);
90
+ const handleModalClose = () => setIsErrorOpen(false);
91
+ if (badge)
92
+ badge.addEventListener('click-build-error', handleBadgeClick);
93
+ if (modal) {
94
+ modal.addEventListener('close-modal', handleModalClose);
95
+ modal.addEventListener('copy-log', handleCopyLog);
96
+ }
97
+ return () => {
98
+ if (badge)
99
+ badge.removeEventListener('click-build-error', handleBadgeClick);
100
+ if (modal) {
101
+ modal.removeEventListener('close-modal', handleModalClose);
102
+ modal.removeEventListener('copy-log', handleCopyLog);
103
+ }
104
+ };
105
+ }, [handleCopyLog]);
106
+ // Roteamento
107
+ const getMatch = (0, react_1.useCallback)((path) => (0, FrontCore_1.findRouteForPath)(path, routes), [routes]);
108
+ const [CurrentPageComponent, setCurrentPageComponent] = (0, react_1.useState)(() => {
109
+ const currentPath = window.location.pathname.replace("index.html", '');
110
+ const match = getMatch(currentPath);
111
+ return match ? componentMap[match.componentPath] : null;
112
+ });
113
+ const [params, setParams] = (0, react_1.useState)(() => {
114
+ const currentPath = window.location.pathname.replace("index.html", '');
115
+ const match = getMatch(currentPath);
116
+ return match ? match.params : {};
117
+ });
118
+ const updateRoute = (0, react_1.useCallback)(() => {
119
+ const currentPath = clientRouter_ts_1.router.pathname.replace("index.html", '');
120
+ const match = getMatch(currentPath);
121
+ if (match) {
122
+ setCurrentPageComponent(() => componentMap[match.componentPath]);
123
+ setParams(match.params);
124
+ (0, FrontCore_1.updateDocumentTitle)(match.metadata?.title);
125
+ }
126
+ else {
127
+ console.warn(`[Vatts React] ⚠️ Rota não encontrada (404): ${currentPath}`);
128
+ setCurrentPageComponent(null);
129
+ setParams({});
130
+ }
131
+ }, [clientRouter_ts_1.router.pathname, getMatch, componentMap]);
132
+ (0, react_1.useEffect)(() => {
133
+ const handlePopState = () => updateRoute();
134
+ window.addEventListener('popstate', handlePopState);
135
+ const unsubscribe = clientRouter_ts_1.router.subscribe(updateRoute);
136
+ return () => {
137
+ window.removeEventListener('popstate', handlePopState);
138
+ unsubscribe();
139
+ };
140
+ }, [updateRoute]);
141
+ // Renderização
142
+ let resolvedContent;
143
+ if (!CurrentPageComponent || initialComponentPath === '__404__') {
144
+ const NotFoundComponent = window.__VATTS_NOT_FOUND__;
145
+ let NotFoundContent;
146
+ if (NotFoundComponent) {
147
+ NotFoundContent = react_1.default.createElement(NotFoundComponent, null);
148
+ }
149
+ else {
150
+ const { getDefaultNotFound } = window.__VATTS_DEFAULT_NOT_FOUND__;
151
+ NotFoundContent = react_1.default.createElement("div", { dangerouslySetInnerHTML: { __html: getDefaultNotFound() } });
152
+ }
153
+ resolvedContent = typeof layoutComponent === "function"
154
+ ? react_1.default.createElement(layoutComponent, { children: NotFoundContent })
155
+ : NotFoundContent;
156
+ }
157
+ else {
158
+ const PageContent = react_1.default.createElement(CurrentPageComponent, { key: `page-${hmrTimestamp}`, params: params });
159
+ resolvedContent = typeof layoutComponent === "function"
160
+ ? react_1.default.createElement(layoutComponent, { children: PageContent })
161
+ : react_1.default.createElement("div", null, PageContent);
162
+ }
163
+ return (react_1.default.createElement(react_1.default.Fragment, null,
164
+ resolvedContent,
165
+ process.env.NODE_ENV !== 'production' ? (react_1.default.createElement("vatts-dev-badge", { ref: devBadgeRef })) : null,
166
+ react_1.default.createElement("vatts-error-modal", { ref: errorModalRef })));
167
+ }
168
+ // --- Inicialização do Cliente ---
169
+ function initializeClient() {
170
+ try {
171
+ // Resolve a rota e params inicial calculando diretamente no lado do cliente
172
+ // a partir da injeção do esbuild!
173
+ const routes = window.__VATTS_ROUTES__ || [];
174
+ const currentPath = window.location.pathname.replace("index.html", '');
175
+ const match = (0, FrontCore_1.findRouteForPath)(currentPath, routes);
176
+ const initialComponentPath = match ? match.componentPath : '__404__';
177
+ const initialParams = match ? match.params : {};
178
+ const componentMap = {};
179
+ if (window.__VATTS_COMPONENTS__) {
180
+ Object.assign(componentMap, window.__VATTS_COMPONENTS__);
181
+ }
182
+ else {
183
+ console.warn('[Vatts React] ⚠️ No components found in window.__VATTS_COMPONENTS__');
184
+ }
185
+ const container = document.getElementById('root');
186
+ if (!container)
187
+ throw new Error('Container #root not found.');
188
+ if (window.__VATTS_ROOT__) {
189
+ console.log('[Vatts React] ♻️ HMR detectado: Limpando a root do React...');
190
+ try {
191
+ window.__VATTS_ROOT__.unmount();
192
+ container.innerHTML = '';
193
+ }
194
+ catch (e) {
195
+ console.warn('[Vatts React] ⚠️ Warning during unmount:', e);
196
+ }
197
+ }
198
+ const root = (0, client_1.createRoot)(container);
199
+ window.__VATTS_ROOT__ = root;
200
+ root.render(react_1.default.createElement(App, { componentMap: componentMap, routes: routes, initialComponentPath: initialComponentPath, initialParams: initialParams, layoutComponent: window.__VATTS_LAYOUT__ }));
201
+ }
202
+ catch (error) {
203
+ (0, FrontCore_1.renderCriticalError)(error, 'React');
204
+ }
205
+ }
206
+ if (document.readyState === 'loading') {
207
+ document.addEventListener('DOMContentLoaded', initializeClient);
208
+ }
209
+ else {
210
+ setTimeout(initializeClient, 0);
211
+ }
@@ -0,0 +1,10 @@
1
+ import * as React from 'react';
2
+
3
+ declare module 'react' {
4
+ namespace JSX {
5
+ interface IntrinsicElements {
6
+ 'vatts-dev-badge': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> | any;
7
+ 'vatts-error-modal': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> | any;
8
+ }
9
+ }
10
+ }
@@ -1,5 +1,5 @@
1
- import { RouteConfig } from '../types';
2
- import type { GenericRequest } from '../types/framework';
1
+ import { RouteConfig } from '../../types.ts';
2
+ import type { GenericRequest } from '../../types/framework.ts';
3
3
  interface RenderOptions {
4
4
  req: GenericRequest;
5
5
  res: any;