nyte 1.0.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 (78) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +59 -0
  3. package/dist/adapters/express.d.ts +7 -0
  4. package/dist/adapters/express.js +63 -0
  5. package/dist/adapters/factory.d.ts +23 -0
  6. package/dist/adapters/factory.js +121 -0
  7. package/dist/adapters/fastify.d.ts +25 -0
  8. package/dist/adapters/fastify.js +61 -0
  9. package/dist/adapters/native.d.ts +8 -0
  10. package/dist/adapters/native.js +200 -0
  11. package/dist/api/console.d.ts +81 -0
  12. package/dist/api/console.js +318 -0
  13. package/dist/api/http.d.ts +180 -0
  14. package/dist/api/http.js +469 -0
  15. package/dist/bin/nytejs.d.ts +2 -0
  16. package/dist/bin/nytejs.js +277 -0
  17. package/dist/builder.d.ts +32 -0
  18. package/dist/builder.js +634 -0
  19. package/dist/client/DefaultNotFound.d.ts +1 -0
  20. package/dist/client/DefaultNotFound.js +79 -0
  21. package/dist/client/client.d.ts +4 -0
  22. package/dist/client/client.js +27 -0
  23. package/dist/client/clientRouter.d.ts +58 -0
  24. package/dist/client/clientRouter.js +132 -0
  25. package/dist/client/entry.client.d.ts +1 -0
  26. package/dist/client/entry.client.js +455 -0
  27. package/dist/client/rpc.d.ts +8 -0
  28. package/dist/client/rpc.js +97 -0
  29. package/dist/components/Link.d.ts +7 -0
  30. package/dist/components/Link.js +13 -0
  31. package/dist/global/global.d.ts +117 -0
  32. package/dist/global/global.js +17 -0
  33. package/dist/helpers.d.ts +20 -0
  34. package/dist/helpers.js +604 -0
  35. package/dist/hotReload.d.ts +32 -0
  36. package/dist/hotReload.js +545 -0
  37. package/dist/index.d.ts +18 -0
  38. package/dist/index.js +515 -0
  39. package/dist/loaders.d.ts +1 -0
  40. package/dist/loaders.js +138 -0
  41. package/dist/renderer.d.ts +14 -0
  42. package/dist/renderer.js +380 -0
  43. package/dist/router.d.ts +101 -0
  44. package/dist/router.js +659 -0
  45. package/dist/rpc/server.d.ts +11 -0
  46. package/dist/rpc/server.js +166 -0
  47. package/dist/rpc/types.d.ts +22 -0
  48. package/dist/rpc/types.js +20 -0
  49. package/dist/types/framework.d.ts +37 -0
  50. package/dist/types/framework.js +2 -0
  51. package/dist/types.d.ts +218 -0
  52. package/dist/types.js +2 -0
  53. package/package.json +87 -0
  54. package/src/adapters/express.ts +87 -0
  55. package/src/adapters/factory.ts +112 -0
  56. package/src/adapters/fastify.ts +104 -0
  57. package/src/adapters/native.ts +245 -0
  58. package/src/api/console.ts +348 -0
  59. package/src/api/http.ts +535 -0
  60. package/src/bin/nytejs.js +331 -0
  61. package/src/builder.js +690 -0
  62. package/src/client/DefaultNotFound.tsx +119 -0
  63. package/src/client/client.ts +24 -0
  64. package/src/client/clientRouter.ts +153 -0
  65. package/src/client/entry.client.tsx +529 -0
  66. package/src/client/rpc.ts +101 -0
  67. package/src/components/Link.tsx +38 -0
  68. package/src/global/global.ts +171 -0
  69. package/src/helpers.ts +657 -0
  70. package/src/hotReload.ts +566 -0
  71. package/src/index.ts +582 -0
  72. package/src/loaders.js +160 -0
  73. package/src/renderer.tsx +421 -0
  74. package/src/router.ts +732 -0
  75. package/src/rpc/server.ts +190 -0
  76. package/src/rpc/types.ts +45 -0
  77. package/src/types/framework.ts +58 -0
  78. package/src/types.ts +288 -0
package/src/router.ts ADDED
@@ -0,0 +1,732 @@
1
+ /*
2
+ * This file is part of the Nyte.js Project.
3
+ * Copyright (c) 2026 itsmuzin
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+ import { RouteConfig, BackendRouteConfig, NyteMiddleware, WebSocketHandler, WebSocketContext } from './types';
20
+ import { WebSocketServer as WSServer, WebSocket } from 'ws';
21
+ import { IncomingMessage } from 'http';
22
+ import { URL } from 'url';
23
+ import Console from "./api/console"
24
+ import {FrameworkAdapterFactory} from "./adapters/factory";
25
+ import {NyteRequest} from "./api/http";
26
+
27
+ // --- Roteamento do Frontend ---
28
+
29
+ // Guarda todas as rotas de PÁGINA (React) encontradas
30
+ // A rota agora também armazena o caminho do arquivo para ser usado como um ID único no cliente
31
+ let allRoutes: (RouteConfig & { componentPath: string })[] = [];
32
+
33
+ // Guarda o layout se existir
34
+ let layoutComponent: { componentPath: string; metadata?: any } | null = null;
35
+
36
+ // Guarda o componente 404 personalizado se existir
37
+ let notFoundComponent: { componentPath: string } | null = null;
38
+
39
+ // Cache de arquivos carregados para limpeza
40
+ let loadedRouteFiles: Set<string> = new Set();
41
+ let loadedLayoutFiles: Set<string> = new Set();
42
+ let loadedNotFoundFiles: Set<string> = new Set();
43
+
44
+ /**
45
+ * Limpa o cache do require para um arquivo específico
46
+ * @param filePath Caminho do arquivo para limpar
47
+ */
48
+ function clearRequireCache(filePath: string) {
49
+ try {
50
+ const resolvedPath = require.resolve(filePath);
51
+ delete require.cache[resolvedPath];
52
+
53
+ // Também limpa arquivos temporários relacionados (apenas se existir no cache)
54
+ const tempFile = filePath.replace(/\.(tsx|ts|jsx|js)$/, '.temp.$1');
55
+ const tempResolvedPath = require.cache[require.resolve(tempFile)];
56
+ if (tempResolvedPath) {
57
+ delete require.cache[require.resolve(tempFile)];
58
+ }
59
+ } catch {
60
+ // Arquivo pode não estar no cache ou não ser resolvível
61
+ }
62
+ }
63
+
64
+ // Nota: Suporte apenas para TypeScript (.ts, .tsx). Não tratamos .jsx aqui.
65
+
66
+ /**
67
+ * Limpa todo o cache de rotas carregadas
68
+ */
69
+ export function clearAllRouteCache() {
70
+ // Limpa cache das rotas
71
+ loadedRouteFiles.forEach(filePath => {
72
+ clearRequireCache(filePath);
73
+ });
74
+ loadedRouteFiles.clear();
75
+
76
+ // Limpa cache do layout
77
+ loadedLayoutFiles.forEach(filePath => {
78
+ clearRequireCache(filePath);
79
+ });
80
+ loadedLayoutFiles.clear();
81
+
82
+ // Limpa cache do notFound
83
+ loadedNotFoundFiles.forEach(filePath => {
84
+ clearRequireCache(filePath);
85
+ });
86
+ loadedNotFoundFiles.clear();
87
+ }
88
+
89
+ /**
90
+ * Limpa o cache de um arquivo específico e recarrega as rotas se necessário
91
+ * @param changedFilePath Caminho do arquivo que foi alterado
92
+ */
93
+ export function clearFileCache(changedFilePath: string) {
94
+ const absolutePath = path.isAbsolute(changedFilePath) ? changedFilePath : path.resolve(changedFilePath);
95
+
96
+ // Limpa o cache do arquivo específico
97
+ clearRequireCache(absolutePath);
98
+
99
+ // Remove das listas de arquivos carregados
100
+ loadedRouteFiles.delete(absolutePath);
101
+ loadedLayoutFiles.delete(absolutePath);
102
+ loadedNotFoundFiles.delete(absolutePath);
103
+ }
104
+
105
+ /**
106
+ * Carrega o layout.tsx se existir no diretório web
107
+ * @param webDir O diretório web onde procurar o layout
108
+ * @returns O layout carregado ou null se não existir
109
+ */
110
+ export function loadLayout(webDir: string): { componentPath: string; metadata?: any } | null {
111
+ const layoutPath = path.join(webDir, 'layout.tsx');
112
+ const layoutPathTs = path.join(webDir, 'layout.ts');
113
+ const layoutFile = fs.existsSync(layoutPath) ? layoutPath :
114
+ fs.existsSync(layoutPathTs) ? layoutPathTs : null;
115
+
116
+ if (layoutFile) {
117
+ const absolutePath = path.resolve(layoutFile);
118
+ const componentPath = path.relative(process.cwd(), layoutFile).replace(/\\/g, '/');
119
+
120
+ try {
121
+ // HACK: Cria uma versão temporária do layout SEM imports de CSS para carregar no servidor
122
+ const layoutContent = fs.readFileSync(layoutFile, 'utf8');
123
+ const tempContent = layoutContent
124
+ .replace(/import\s+['"][^'"]*\.css['"];?/g, '// CSS import removido para servidor')
125
+ .replace(/import\s+['"][^'"]*\.scss['"];?/g, '// SCSS import removido para servidor')
126
+ .replace(/import\s+['"][^'"]*\.sass['"];?/g, '// SASS import removido para servidor');
127
+
128
+ // Escreve um arquivo temporário .temp.tsx ou .temp.ts sem imports de CSS
129
+ const ext = path.extname(layoutFile).toLowerCase();
130
+ const tempFile = layoutFile.replace(/\.(tsx|ts)$/i, '.temp.$1');
131
+ fs.writeFileSync(tempFile, tempContent, 'utf8');
132
+
133
+ // Otimização: limpa cache apenas se existir
134
+ try {
135
+ const resolvedPath = require.resolve(tempFile);
136
+ if (require.cache[resolvedPath]) {
137
+ delete require.cache[resolvedPath];
138
+ }
139
+ } catch {}
140
+
141
+ const layoutModule = require(tempFile);
142
+
143
+ // Remove o arquivo temporário
144
+ try { fs.unlinkSync(tempFile); } catch {}
145
+
146
+ const metadata = layoutModule.metadata || null;
147
+
148
+ // Registra o arquivo como carregado
149
+ loadedLayoutFiles.add(absolutePath);
150
+
151
+ layoutComponent = { componentPath, metadata };
152
+ return layoutComponent;
153
+ } catch (error) {
154
+ Console.error(`Error loading layout ${layoutFile}:`, error);
155
+ layoutComponent = { componentPath };
156
+ return layoutComponent;
157
+ }
158
+ }
159
+
160
+ layoutComponent = null;
161
+ return null;
162
+ }
163
+
164
+ /**
165
+ * Retorna o layout atual se carregado
166
+ */
167
+ export function getLayout(): { componentPath: string; metadata?: any } | null {
168
+ return layoutComponent;
169
+ }
170
+
171
+ /**
172
+ * Carrega dinamicamente todas as rotas de frontend do diretório do usuário.
173
+ * @param routesDir O diretório onde as rotas de página estão localizadas.
174
+ * @returns A lista de rotas de página que foram carregadas.
175
+ */
176
+ export function loadRoutes(routesDir: string): (RouteConfig & { componentPath: string })[] {
177
+ if (!fs.existsSync(routesDir)) {
178
+ Console.warn(`Frontend routes directory not found at ${routesDir}. No page will be loaded.`);
179
+ allRoutes = [];
180
+ return allRoutes;
181
+ }
182
+
183
+ // Otimização: usa função recursiva manual para evitar overhead do recursive: true
184
+ const routeFiles: string[] = [];
185
+ const scanDirectory = (dir: string, baseDir: string = '') => {
186
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
187
+ for (const entry of entries) {
188
+ const relativePath = baseDir ? path.join(baseDir, entry.name) : entry.name;
189
+
190
+ if (entry.isDirectory()) {
191
+ // Pula diretório backend inteiro
192
+ if (entry.name === 'backend') continue;
193
+ scanDirectory(path.join(dir, entry.name), relativePath);
194
+ } else if (entry.isFile()) {
195
+ // Filtra apenas arquivos .ts/.tsx
196
+ if (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx')) {
197
+ routeFiles.push(relativePath);
198
+ }
199
+ }
200
+ }
201
+ };
202
+
203
+ scanDirectory(routesDir);
204
+
205
+ const loaded: (RouteConfig & { componentPath: string })[] = [];
206
+ const cwdPath = process.cwd();
207
+
208
+ // Otimização: processa arquivos em lote
209
+ for (const file of routeFiles) {
210
+ const filePath = path.join(routesDir, file);
211
+ const absolutePath = path.resolve(filePath);
212
+
213
+ try {
214
+ // Otimização: limpa cache apenas se já existir
215
+ const resolvedPath = require.resolve(filePath);
216
+ if (require.cache[resolvedPath]) {
217
+ delete require.cache[resolvedPath];
218
+ }
219
+
220
+ const routeModule = require(filePath);
221
+ if (routeModule.default?.pattern && routeModule.default?.component) {
222
+ // Otimização: calcula componentPath apenas uma vez
223
+ const componentPath = path.relative(cwdPath, filePath).replace(/\\/g, '/');
224
+ loaded.push({ ...routeModule.default, componentPath });
225
+ loadedRouteFiles.add(absolutePath);
226
+ }
227
+ } catch (error) {
228
+ Console.error(`Error loading page route ${filePath}:`, error);
229
+ }
230
+ }
231
+
232
+ allRoutes = loaded;
233
+ return allRoutes;
234
+ }
235
+
236
+ /**
237
+ * Encontra a rota de página correspondente para uma URL.
238
+ * @param pathname O caminho da URL (ex: "/users/123").
239
+ * @returns Um objeto com a rota e os parâmetros, ou null se não encontrar.
240
+ */
241
+ export function findMatchingRoute(pathname: string) {
242
+ for (const route of allRoutes) {
243
+ if (!route.pattern) continue;
244
+
245
+ const regexPattern = route.pattern
246
+ // [[...param]] → opcional catch-all
247
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
248
+ // [...param] → obrigatório catch-all
249
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
250
+ // /[[param]] → opcional com barra também opcional
251
+ .replace(/\/\[\[(\w+)\]\]/g, '(?:/(?<$1>[^/]+))?')
252
+ // [[param]] → segmento opcional (sem barra anterior)
253
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
254
+ // [param] → segmento obrigatório
255
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
256
+
257
+ // permite / opcional no final
258
+ const regex = new RegExp(`^${regexPattern}/?$`);
259
+ const match = pathname.match(regex);
260
+
261
+ if (match) {
262
+ return {
263
+ route,
264
+ params: match.groups || {}
265
+ };
266
+ }
267
+ }
268
+
269
+ return null;
270
+ }
271
+
272
+
273
+ // --- Roteamento do Backend ---
274
+
275
+ // Guarda todas as rotas de API encontradas
276
+ let allBackendRoutes: BackendRouteConfig[] = [];
277
+
278
+ // Cache de middlewares carregados por diretório
279
+ let loadedMiddlewares: Map<string, NyteMiddleware[]> = new Map();
280
+
281
+ /**
282
+ * Carrega middlewares de um diretório específico
283
+ * @param dir O diretório onde procurar por middleware.ts
284
+ * @returns Array de middlewares encontrados
285
+ */
286
+ function loadMiddlewareFromDirectory(dir: string): NyteMiddleware[] {
287
+ const middlewares: NyteMiddleware[] = [];
288
+
289
+ // Procura por middleware.ts, middleware.tsx
290
+ const middlewarePath = path.join(dir, 'middleware.ts');
291
+ const middlewarePathTsx = path.join(dir, 'middleware.tsx');
292
+
293
+ const middlewareFile = fs.existsSync(middlewarePath) ? middlewarePath :
294
+ fs.existsSync(middlewarePathTsx) ? middlewarePathTsx : null;
295
+
296
+ if (middlewareFile) {
297
+ try {
298
+ const absolutePath = path.resolve(middlewareFile);
299
+ clearRequireCache(absolutePath);
300
+
301
+ const middlewareModule = require(middlewareFile);
302
+
303
+ // Suporte para export default (função única) ou export { middleware1, middleware2 }
304
+ if (typeof middlewareModule.default === 'function') {
305
+ middlewares.push(middlewareModule.default);
306
+ } else if (middlewareModule.default && Array.isArray(middlewareModule.default)) {
307
+ middlewares.push(...middlewareModule.default);
308
+ } else {
309
+ // Procura por exports nomeados que sejam funções
310
+ Object.keys(middlewareModule).forEach(key => {
311
+ if (key !== 'default' && typeof middlewareModule[key] === 'function') {
312
+ middlewares.push(middlewareModule[key]);
313
+ }
314
+ });
315
+ }
316
+
317
+ } catch (error) {
318
+ Console.error(`Error loading middleware ${middlewareFile}:`, error);
319
+ }
320
+ }
321
+
322
+ return middlewares;
323
+ }
324
+
325
+ /**
326
+ * Coleta middlewares do diretório específico da rota (não herda dos pais)
327
+ * @param routeFilePath Caminho completo do arquivo de rota
328
+ * @param backendRoutesDir Diretório raiz das rotas de backend
329
+ * @returns Array com middlewares apenas do diretório da rota
330
+ */
331
+ function collectMiddlewaresForRoute(routeFilePath: string, backendRoutesDir: string): NyteMiddleware[] {
332
+ const relativePath = path.relative(backendRoutesDir, routeFilePath);
333
+ const routeDir = path.dirname(path.join(backendRoutesDir, relativePath));
334
+
335
+ // Carrega middlewares APENAS do diretório específico da rota (não herda dos pais)
336
+ if (!loadedMiddlewares.has(routeDir)) {
337
+ const middlewares = loadMiddlewareFromDirectory(routeDir);
338
+ loadedMiddlewares.set(routeDir, middlewares);
339
+ }
340
+
341
+ return loadedMiddlewares.get(routeDir) || [];
342
+ }
343
+
344
+ /**
345
+ * Carrega dinamicamente todas as rotas de API do diretório de backend.
346
+ * @param backendRoutesDir O diretório onde as rotas de API estão localizadas.
347
+ */
348
+ export function loadBackendRoutes(backendRoutesDir: string) {
349
+ if (!fs.existsSync(backendRoutesDir)) {
350
+ // É opcional ter uma API, então não mostramos um aviso se a pasta não existir.
351
+ allBackendRoutes = [];
352
+ return;
353
+ }
354
+
355
+ // Limpa cache de middlewares para recarregar
356
+ loadedMiddlewares.clear();
357
+
358
+ // Otimização: usa função recursiva manual e coleta middlewares durante o scan
359
+ const routeFiles: string[] = [];
360
+ const middlewareFiles: Map<string, string> = new Map(); // dir -> filepath
361
+
362
+ const scanDirectory = (dir: string, baseDir: string = '') => {
363
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
364
+
365
+ for (const entry of entries) {
366
+ const relativePath = baseDir ? path.join(baseDir, entry.name) : entry.name;
367
+
368
+ if (entry.isDirectory()) {
369
+ scanDirectory(path.join(dir, entry.name), relativePath);
370
+ } else if (entry.isFile()) {
371
+ const isSupported = entry.name.endsWith('.ts') || entry.name.endsWith('.tsx');
372
+ if (!isSupported) continue;
373
+
374
+ // Identifica middlewares durante o scan
375
+ if (entry.name.startsWith('middleware')) {
376
+ const dirPath = path.dirname(path.join(backendRoutesDir, relativePath));
377
+ middlewareFiles.set(dirPath, path.join(backendRoutesDir, relativePath));
378
+ } else {
379
+ routeFiles.push(relativePath);
380
+ }
381
+ }
382
+ }
383
+ };
384
+
385
+ scanDirectory(backendRoutesDir);
386
+
387
+ // Otimização: pré-carrega todos os middlewares em um único passe
388
+ for (const [dirPath, middlewarePath] of middlewareFiles) {
389
+ try {
390
+ const resolvedPath = require.resolve(middlewarePath);
391
+ if (require.cache[resolvedPath]) {
392
+ delete require.cache[resolvedPath];
393
+ }
394
+
395
+ const middlewareModule = require(middlewarePath);
396
+ const middlewares: NyteMiddleware[] = [];
397
+
398
+ if (typeof middlewareModule.default === 'function') {
399
+ middlewares.push(middlewareModule.default);
400
+ } else if (Array.isArray(middlewareModule.default)) {
401
+ middlewares.push(...middlewareModule.default);
402
+ } else {
403
+ // Exports nomeados
404
+ for (const key in middlewareModule) {
405
+ if (key !== 'default' && typeof middlewareModule[key] === 'function') {
406
+ middlewares.push(middlewareModule[key]);
407
+ }
408
+ }
409
+ }
410
+
411
+ if (middlewares.length > 0) {
412
+ loadedMiddlewares.set(dirPath, middlewares);
413
+ }
414
+ } catch (error) {
415
+ Console.error(`Error loading middleware ${middlewarePath}:`, error);
416
+ }
417
+ }
418
+
419
+ // Otimização: processa rotas com cache já limpo
420
+ const loaded: BackendRouteConfig[] = [];
421
+ for (const file of routeFiles) {
422
+ const filePath = path.join(backendRoutesDir, file);
423
+
424
+ try {
425
+ // Otimização: limpa cache apenas se existir
426
+ const resolvedPath = require.resolve(filePath);
427
+ if (require.cache[resolvedPath]) {
428
+ delete require.cache[resolvedPath];
429
+ }
430
+
431
+ const routeModule = require(filePath);
432
+ if (routeModule.default?.pattern) {
433
+ const routeConfig = { ...routeModule.default };
434
+ // Se a rota NÃO tem middleware definido, usa os da pasta
435
+ if (!routeConfig.hasOwnProperty('middleware')) {
436
+ const routeDir = path.dirname(path.resolve(filePath));
437
+ const folderMiddlewares = loadedMiddlewares.get(routeDir);
438
+ if (folderMiddlewares && folderMiddlewares.length > 0) {
439
+ routeConfig.middleware = folderMiddlewares;
440
+ }
441
+ }
442
+
443
+ loaded.push(routeConfig);
444
+ }
445
+ } catch (error) {
446
+ Console.error(`Error loading API route ${filePath}:`, error);
447
+ }
448
+ }
449
+
450
+ allBackendRoutes = loaded;
451
+ }
452
+
453
+ /**
454
+ * Encontra a rota de API correspondente para uma URL e método HTTP.
455
+ * @param pathname O caminho da URL (ex: "/api/users/123").
456
+ * @param method O método HTTP da requisição (GET, POST, etc.).
457
+ * @returns Um objeto com a rota e os parâmetros, ou null se não encontrar.
458
+ */
459
+ export function findMatchingBackendRoute(pathname: string, method: string) {
460
+ for (const route of allBackendRoutes) {
461
+ // Verifica se a rota tem um handler para o método HTTP atual
462
+ if (!route.pattern || !route[method.toUpperCase() as keyof BackendRouteConfig]) continue;
463
+ const regexPattern = route.pattern
464
+ // [[...param]] → opcional catch-all
465
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
466
+ // [...param] → obrigatório catch-all
467
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
468
+ // [[param]] → segmento opcional
469
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
470
+ // [param] → segmento obrigatório
471
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
472
+
473
+ const regex = new RegExp(`^${regexPattern}/?$`);
474
+ const match = pathname.match(regex);
475
+
476
+ if (match) {
477
+ return {
478
+ route,
479
+ params: match.groups || {}
480
+ };
481
+ }
482
+ }
483
+ return null;
484
+ }
485
+
486
+ /**
487
+ * Carrega o notFound.tsx se existir no diretório web
488
+ * @param webDir O diretório web onde procurar o notFound
489
+ * @returns O notFound carregado ou null se não existir
490
+ */
491
+ export function loadNotFound(webDir: string): { componentPath: string } | null {
492
+ const notFoundPath = path.join(webDir, 'notFound.tsx');
493
+ const notFoundPathTs = path.join(webDir, 'notFound.ts');
494
+ const notFoundFile = fs.existsSync(notFoundPath) ? notFoundPath :
495
+ fs.existsSync(notFoundPathTs) ? notFoundPathTs : null;
496
+
497
+ if (notFoundFile) {
498
+ const absolutePath = path.resolve(notFoundFile);
499
+ const componentPath = path.relative(process.cwd(), notFoundFile).replace(/\\/g, '/');
500
+
501
+ try {
502
+ // Otimização: limpa cache apenas se existir
503
+ try {
504
+ const resolvedPath = require.resolve(notFoundFile);
505
+ if (require.cache[resolvedPath]) {
506
+ delete require.cache[resolvedPath];
507
+ }
508
+ } catch {}
509
+
510
+ // Registra o arquivo como carregado
511
+ loadedNotFoundFiles.add(absolutePath);
512
+
513
+ notFoundComponent = { componentPath };
514
+ return notFoundComponent;
515
+ } catch (error) {
516
+ Console.error(`Error loading notFound ${notFoundFile}:`, error);
517
+ notFoundComponent = { componentPath };
518
+ return notFoundComponent;
519
+ }
520
+ }
521
+
522
+ notFoundComponent = null;
523
+ return null;
524
+ }
525
+
526
+ /**
527
+ * Retorna o componente 404 atual se carregado
528
+ */
529
+ export function getNotFound(): { componentPath: string } | null {
530
+ return notFoundComponent;
531
+ }
532
+
533
+ // --- WebSocket Functions ---
534
+
535
+ // Guarda todas as rotas WebSocket encontradas
536
+ let allWebSocketRoutes: { pattern: string; handler: WebSocketHandler; middleware?: NyteMiddleware[] }[] = [];
537
+
538
+ // Conexões WebSocket ativas
539
+ let wsConnections: Set<WebSocket> = new Set();
540
+
541
+ /**
542
+ * Processa e registra rotas WebSocket encontradas nas rotas backend
543
+ */
544
+ export function processWebSocketRoutes() {
545
+ allWebSocketRoutes = [];
546
+
547
+ for (const route of allBackendRoutes) {
548
+ if (route.WS) {
549
+ const wsRoute = {
550
+ pattern: route.pattern,
551
+ handler: route.WS,
552
+ middleware: route.middleware
553
+ };
554
+
555
+ allWebSocketRoutes.push(wsRoute);
556
+ }
557
+ }
558
+ }
559
+
560
+ /**
561
+ * Encontra a rota WebSocket correspondente para uma URL
562
+ */
563
+ export function findMatchingWebSocketRoute(pathname: string) {
564
+ for (const route of allWebSocketRoutes) {
565
+ if (!route.pattern) continue;
566
+
567
+ const regexPattern = route.pattern
568
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
569
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
570
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
571
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
572
+
573
+ const regex = new RegExp(`^${regexPattern}/?$`);
574
+ const match = pathname.match(regex);
575
+
576
+ if (match) {
577
+ return {
578
+ route,
579
+ params: match.groups || {}
580
+ };
581
+ }
582
+ }
583
+ return null;
584
+ }
585
+
586
+ /**
587
+ * Trata uma nova conexão WebSocket
588
+ */
589
+ function handleWebSocketConnection(ws: WebSocket, req: IncomingMessage, hwebReq: NyteRequest) {
590
+ if (!req.url) return;
591
+
592
+ const url = new URL(req.url, `http://${req.headers.host}`);
593
+ const pathname = url.pathname;
594
+
595
+ const matchedRoute = findMatchingWebSocketRoute(pathname);
596
+ if (!matchedRoute) {
597
+ ws.close(1000, 'Route not found');
598
+ return;
599
+ }
600
+
601
+ const params = extractWebSocketParams(pathname, matchedRoute.route.pattern);
602
+ const query = Object.fromEntries(url.searchParams.entries());
603
+
604
+ const context: WebSocketContext = {
605
+ nyteReq: hwebReq,
606
+ ws,
607
+ req,
608
+ url,
609
+ params,
610
+ query,
611
+ send: (data: any) => {
612
+ if (ws.readyState === WebSocket.OPEN) {
613
+ const message = typeof data === 'string' ? data : JSON.stringify(data);
614
+ ws.send(message);
615
+ }
616
+ },
617
+ close: (code?: number, reason?: string) => {
618
+ ws.close(code || 1000, reason);
619
+ },
620
+ broadcast: (data: any, exclude?: WebSocket[]) => {
621
+ const message = typeof data === 'string' ? data : JSON.stringify(data);
622
+ const excludeSet = new Set(exclude || []);
623
+ wsConnections.forEach(connection => {
624
+ if (connection.readyState === WebSocket.OPEN && !excludeSet.has(connection)) {
625
+ connection.send(message);
626
+ }
627
+ });
628
+ }
629
+ };
630
+
631
+ try {
632
+ matchedRoute.route.handler(context);
633
+ } catch (error) {
634
+ console.error('Error in WebSocket handler:', error);
635
+ ws.close(1011, 'Internal server error');
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Extrai parâmetros da URL para WebSocket
641
+ */
642
+ function extractWebSocketParams(pathname: string, pattern: string): Record<string, string> {
643
+ const params: Record<string, string> = {};
644
+
645
+ const regexPattern = pattern
646
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
647
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
648
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
649
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
650
+
651
+ const regex = new RegExp(`^${regexPattern}/?$`);
652
+ const match = pathname.match(regex);
653
+
654
+ if (match && match.groups) {
655
+ Object.assign(params, match.groups);
656
+ }
657
+
658
+ return params;
659
+ }
660
+
661
+ /**
662
+ * Configura WebSocket upgrade no servidor HTTP existente
663
+ * @param server Servidor HTTP (Express, Fastify ou Native)
664
+ * @param hotReloadManager Instância do gerenciador de hot-reload para coordenação
665
+ */
666
+ export function setupWebSocketUpgrade(server: any, hotReloadManager?: any) {
667
+ // NÃO remove listeners existentes para preservar hot-reload
668
+ // Em vez disso, coordena com o sistema existente
669
+
670
+ // Verifica se já existe um listener de upgrade
671
+ const existingListeners = server.listeners('upgrade');
672
+
673
+ // Se não há listeners, ou se o hot-reload ainda não foi configurado, adiciona o nosso
674
+ if (existingListeners.length === 0) {
675
+ server.on('upgrade', (request: any, socket: any, head: Buffer) => {
676
+
677
+ handleWebSocketUpgrade(request, socket, head, hotReloadManager);
678
+ });
679
+ }
680
+ }
681
+
682
+ function handleWebSocketUpgrade(request: any, socket: any, head: Buffer, hotReloadManager?: any) {
683
+ const adapter = FrameworkAdapterFactory.getCurrentAdapter()
684
+ if (!adapter) {
685
+ console.error('❌ Framework adapter not detected. Unable to process WebSocket upgrade.');
686
+ socket.destroy();
687
+ return;
688
+ }
689
+ const genericReq = adapter.parseRequest(request);
690
+ const hwebReq = new NyteRequest(genericReq);
691
+ const { pathname } = new URL(request.url, `http://${request.headers.host}`);
692
+
693
+ // Prioridade 1: Hot reload (sistema interno)
694
+ if (pathname === '/hweb-hotreload/') {
695
+
696
+ if (hotReloadManager) {
697
+ hotReloadManager.handleUpgrade(request, socket, head);
698
+ } else {
699
+ socket.destroy();
700
+ }
701
+ return;
702
+ }
703
+
704
+ // Prioridade 2: Rotas WebSocket do usuário
705
+ const matchedRoute = findMatchingWebSocketRoute(pathname);
706
+ if (matchedRoute) {
707
+ // Faz upgrade para WebSocket usando noServer
708
+ const wss = new WSServer({
709
+ noServer: true,
710
+ perMessageDeflate: false, // Melhor performance
711
+ maxPayload: 1024 * 1024 // Limite de 1MB
712
+ });
713
+
714
+ wss.handleUpgrade(request, socket, head, (ws) => {
715
+ wsConnections.add(ws);
716
+
717
+ ws.on('close', () => {
718
+ wsConnections.delete(ws);
719
+ });
720
+
721
+ ws.on('error', (error) => {
722
+ wsConnections.delete(ws);
723
+ });
724
+
725
+ // Processa a conexão
726
+ handleWebSocketConnection(ws, request, hwebReq);
727
+ });
728
+ return;
729
+ }
730
+
731
+ socket.destroy();
732
+ }