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
@@ -0,0 +1,566 @@
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 { WebSocket, WebSocketServer } from 'ws';
18
+ import * as chokidar from 'chokidar';
19
+ import * as path from 'path';
20
+ import * as fs from 'fs';
21
+ import { IncomingMessage } from 'http';
22
+ import * as url from 'url';
23
+ import { clearFileCache } from './router';
24
+ import Console, {Colors, Levels} from "./api/console"
25
+
26
+ interface ClientConnection {
27
+ ws: WebSocket;
28
+ pingTimer: NodeJS.Timeout;
29
+ lastPong: number;
30
+ }
31
+
32
+ export class HotReloadManager {
33
+ private wss: WebSocketServer | null = null;
34
+ private watchers: chokidar.FSWatcher[] = [];
35
+ private projectDir: string;
36
+ private clients: Map<WebSocket, ClientConnection> = new Map();
37
+ private backendApiChangeCallback: (() => void) | null = null;
38
+ private frontendChangeCallback: (() => void) | null = null;
39
+ private isShuttingDown: boolean = false;
40
+ private debounceTimers: Map<string, NodeJS.Timeout> = new Map();
41
+ private customHotReloadListener: ((file: string) => Promise<void> | void) | null = null;
42
+ private isBuilding: boolean = false;
43
+ private buildCompleteResolve: (() => void) | null = null;
44
+
45
+ constructor(projectDir: string) {
46
+ this.projectDir = projectDir;
47
+ }
48
+
49
+ async start() {
50
+ this.setupWatchers();
51
+ }
52
+
53
+ // Método para integrar com Express
54
+ handleUpgrade(request: IncomingMessage, socket: any, head: Buffer) {
55
+ if (this.isShuttingDown) {
56
+ socket.destroy();
57
+ return;
58
+ }
59
+
60
+ if (!this.wss) {
61
+ this.wss = new WebSocketServer({
62
+ noServer: true,
63
+ perMessageDeflate: false, // Desabilita compressão para melhor performance
64
+ maxPayload: 1024 * 1024 // Limite de 1MB por mensagem
65
+ });
66
+ this.setupWebSocketServer();
67
+ }
68
+
69
+ this.wss.handleUpgrade(request, socket, head, (ws) => {
70
+ this.wss!.emit('connection', ws, request);
71
+ });
72
+ }
73
+
74
+ private setupWebSocketServer() {
75
+ if (!this.wss) return;
76
+
77
+ this.wss.on('connection', (ws: WebSocket) => {
78
+ if (this.isShuttingDown) {
79
+ ws.close();
80
+ return;
81
+ }
82
+
83
+ // Setup ping/pong para detectar conexões mortas
84
+ const pingTimer = setInterval(() => {
85
+ const client = this.clients.get(ws);
86
+ if (client && ws.readyState === WebSocket.OPEN) {
87
+ // Se não recebeu pong há mais de 60 segundos, desconecta
88
+ if (Date.now() - client.lastPong > 60000) {
89
+ ws.terminate();
90
+ return;
91
+ }
92
+ ws.ping();
93
+ }
94
+ }, 30000);
95
+
96
+ const clientConnection: ClientConnection = {
97
+ ws,
98
+ pingTimer,
99
+ lastPong: Date.now()
100
+ };
101
+
102
+ this.clients.set(ws, clientConnection);
103
+
104
+ ws.on('pong', () => {
105
+ const client = this.clients.get(ws);
106
+ if (client) {
107
+ client.lastPong = Date.now();
108
+ }
109
+ });
110
+
111
+ ws.on('close', () => {
112
+ this.cleanupClient(ws);
113
+ });
114
+
115
+ ws.on('error', (error) => {
116
+ Console.logWithout(Levels.ERROR, Colors.BgRed,`WebSocket error: ${error.message}`);
117
+ this.cleanupClient(ws);
118
+ });
119
+
120
+ });
121
+ }
122
+
123
+ private cleanupClient(ws: WebSocket) {
124
+ const client = this.clients.get(ws);
125
+ if (client) {
126
+ clearInterval(client.pingTimer);
127
+ this.clients.delete(ws);
128
+ }
129
+ }
130
+
131
+ private setupWatchers() {
132
+ // Remove watchers antigos e use apenas um watcher global para src
133
+ const debouncedChange = this.debounce((filePath: string) => {
134
+ this.handleAnySrcChange(filePath);
135
+ }, 100);
136
+
137
+ const watcher = chokidar.watch([
138
+ path.join(this.projectDir, 'src/**/*'),
139
+ ], {
140
+ ignored: [
141
+ /(^|[\/\\])\../, // arquivos ocultos
142
+ '**/node_modules/**',
143
+ '**/.git/**',
144
+ '**/dist/**'
145
+ ],
146
+ persistent: true,
147
+ ignoreInitial: true,
148
+ usePolling: false,
149
+ awaitWriteFinish: {
150
+ stabilityThreshold: 100,
151
+ pollInterval: 50
152
+ }
153
+ });
154
+
155
+ watcher.on('change', debouncedChange);
156
+ watcher.on('add', debouncedChange);
157
+ watcher.on('unlink', (filePath) => {
158
+ Console.info(`🗑️ Arquivo removido: ${path.basename(filePath)}`);
159
+ clearFileCache(filePath);
160
+ this.clearBackendCache(filePath);
161
+ this.frontendChangeCallback?.();
162
+ this.backendApiChangeCallback?.();
163
+ this.notifyClients('src-reload', { file: filePath, event: 'unlink' });
164
+ });
165
+
166
+ this.watchers.push(watcher);
167
+ }
168
+
169
+ private debounce(func: Function, wait: number): (...args: any[]) => void {
170
+ return (...args: any[]) => {
171
+ const key = args[0]; // usa o primeiro argumento como chave
172
+
173
+ const existingTimer = this.debounceTimers.get(key);
174
+ if (existingTimer) {
175
+ clearTimeout(existingTimer);
176
+ }
177
+
178
+ const timer = setTimeout(() => {
179
+ this.debounceTimers.delete(key);
180
+ func.apply(this, args);
181
+ }, wait);
182
+
183
+ this.debounceTimers.set(key, timer);
184
+ };
185
+ }
186
+
187
+ private async handleAnySrcChange(filePath: string) {
188
+ const dm = Console.dynamicLine(`File change detected ${path.basename(filePath)}, processing...`);
189
+
190
+ // Detecta se é arquivo de frontend ou backend
191
+ const isFrontendFile = filePath.includes(path.join('src', 'web', 'routes')) ||
192
+ filePath.includes(path.join('src', 'web', 'components')) ||
193
+ filePath.includes('layout.tsx') ||
194
+ filePath.includes('not-found.tsx') ||
195
+ filePath.endsWith('.tsx');
196
+
197
+ const isBackendFile = filePath.includes(path.join('src', 'backend')) && !isFrontendFile;
198
+
199
+ // Limpa o cache do arquivo alterado
200
+ clearFileCache(filePath);
201
+ this.clearBackendCache(filePath);
202
+
203
+ // Se for arquivo de frontend, aguarda o build terminar antes de recarregar
204
+ if (isFrontendFile) {
205
+ dm.update(`Waiting for frontend build for ${path.basename(filePath)}...`);
206
+
207
+ // Marca que estamos esperando um build
208
+ this.isBuilding = true;
209
+
210
+ // Cria uma promise que será resolvida quando o build terminar
211
+ const buildPromise = new Promise<void>((resolve) => {
212
+ this.buildCompleteResolve = resolve;
213
+ });
214
+
215
+ // Aguarda o build terminar (com timeout de 30 segundos)
216
+ const timeoutPromise = new Promise<void>((_, reject) => {
217
+ setTimeout(() => reject(new Error('Build timeout')), 30000);
218
+ });
219
+
220
+ try {
221
+ this.frontendChangeCallback?.();
222
+ await Promise.race([buildPromise, timeoutPromise]);
223
+ dm.end(`Build complete for ${path.basename(filePath)}, reloading frontend.`);
224
+ this.frontendChangeCallback?.();
225
+ this.notifyClients('frontend-reload', { file: filePath, event: 'change' });
226
+ } catch (error) {
227
+ dm.end(`Build timeout for ${path.basename(filePath)}, reloading frontend anyway.`);
228
+ this.frontendChangeCallback?.();
229
+ this.notifyClients('frontend-reload', { file: filePath, event: 'change' });
230
+ } finally {
231
+ this.isBuilding = false;
232
+ this.buildCompleteResolve = null;
233
+ }
234
+ }
235
+
236
+ // Se for arquivo de backend, recarrega o módulo e notifica
237
+ if (isBackendFile) {
238
+ Console.logWithout(Levels.INFO, Colors.BgRed,`Reloading backend...`);
239
+ this.backendApiChangeCallback?.();
240
+ this.notifyClients('backend-api-reload', { file: filePath, event: 'change' });
241
+ }
242
+
243
+ // Fallback: se não for nem frontend nem backend detectado, recarrega tudo
244
+ if (!isFrontendFile && !isBackendFile) {
245
+ Console.logWithout(Levels.INFO, Colors.BgRed,`Reloading application...`);
246
+ this.frontendChangeCallback?.();
247
+ this.backendApiChangeCallback?.();
248
+ this.notifyClients('src-reload', { file: filePath, event: 'change' });
249
+ }
250
+
251
+ // Chama listener customizado se definido
252
+ if (this.customHotReloadListener) {
253
+ try {
254
+ await this.customHotReloadListener(filePath);
255
+ } catch (error) {
256
+ // @ts-ignore
257
+ Console.logWithout(Levels.ERROR, `Error in custom listener: ${error.message}`);
258
+ }
259
+ }
260
+ }
261
+
262
+ private notifyClients(type: string, data?: any) {
263
+ if (this.isShuttingDown || this.clients.size === 0) {
264
+ return;
265
+ }
266
+
267
+ const message = JSON.stringify({ type, data, timestamp: Date.now() });
268
+ const deadClients: WebSocket[] = [];
269
+
270
+ this.clients.forEach((client, ws) => {
271
+ if (ws.readyState === WebSocket.OPEN) {
272
+ try {
273
+ ws.send(message);
274
+ } catch (error) {
275
+ Console.logWithout(Levels.ERROR, Colors.BgRed, `Error sending WebSocket message: ${error}`);
276
+ deadClients.push(ws);
277
+ }
278
+ } else {
279
+ deadClients.push(ws);
280
+ }
281
+ });
282
+
283
+ // Remove clientes mortos
284
+ deadClients.forEach(ws => this.cleanupClient(ws));
285
+ }
286
+
287
+ private restartServer() {
288
+ this.notifyClients('server-restart');
289
+ setTimeout(() => {
290
+ this.notifyClients('server-ready');
291
+ }, 2000);
292
+ }
293
+
294
+ stop() {
295
+ this.isShuttingDown = true;
296
+
297
+ // Limpa todos os debounce timers
298
+ this.debounceTimers.forEach(timer => clearTimeout(timer));
299
+ this.debounceTimers.clear();
300
+
301
+ // Para todos os watchers
302
+ this.watchers.forEach(watcher => watcher.close());
303
+ this.watchers = [];
304
+
305
+ // Limpa todos os clientes
306
+ this.clients.forEach((client, ws) => {
307
+ clearInterval(client.pingTimer);
308
+ if (ws.readyState === WebSocket.OPEN) {
309
+ ws.close();
310
+ }
311
+ });
312
+ this.clients.clear();
313
+
314
+ // Fecha WebSocket server
315
+ if (this.wss) {
316
+ this.wss.close();
317
+ this.wss = null;
318
+ }
319
+ }
320
+
321
+ // Script do cliente otimizado com reconnection backoff
322
+ getClientScript(): string {
323
+ return `
324
+ <script>
325
+ (function() {
326
+ if (typeof window !== 'undefined') {
327
+ let ws;
328
+ let reconnectAttempts = 0;
329
+ let maxReconnectInterval = 30000;
330
+ let reconnectInterval = 1000;
331
+ let reconnectTimer;
332
+ let isConnected = false;
333
+
334
+ function connect() {
335
+ const url = window.location; // Objeto com info da URL atual
336
+ const protocol = url.protocol === "https:" ? "wss:" : "ws:"; // Usa wss se for https
337
+ const wsUrl = protocol + '//' + url.host + '/hweb-hotreload/';
338
+ if (ws && (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN)) {
339
+ return;
340
+ }
341
+
342
+ try {
343
+ ws = new WebSocket(wsUrl);
344
+
345
+ ws.onopen = function() {
346
+ console.log('🔌 Hot-reload connected');
347
+ isConnected = true;
348
+ reconnectAttempts = 0;
349
+ reconnectInterval = 1000;
350
+ clearTimeout(reconnectTimer);
351
+ };
352
+
353
+ ws.onmessage = function(event) {
354
+ try {
355
+ const message = JSON.parse(event.data);
356
+
357
+ switch(message.type) {
358
+ case 'frontend-reload':
359
+ handleFrontendReload(message.data);
360
+ break;
361
+ case 'backend-api-reload':
362
+ // Backend sempre precisa recarregar
363
+ console.log('🔄 Backend changed, reloading...');
364
+ window.location.reload();
365
+ break;
366
+ case 'server-restart':
367
+ console.log('🔄 Server restarting...');
368
+ break;
369
+ case 'server-ready':
370
+ setTimeout(() => window.location.reload(), 500);
371
+ break;
372
+ case 'frontend-error':
373
+ console.error('❌ Frontend error:', message.data);
374
+ break;
375
+ case 'hmr-update':
376
+ handleHMRUpdate(message.data);
377
+ break;
378
+ }
379
+ } catch (e) {
380
+ console.error('Erro ao processar mensagem do hot-reload:', e);
381
+ }
382
+ };
383
+
384
+ function handleFrontendReload(data) {
385
+ if (!data || !data.file) {
386
+ window.location.reload();
387
+ return;
388
+ }
389
+
390
+ const file = data.file.toLowerCase();
391
+
392
+ // Mudanças que exigem reload completo
393
+ const needsFullReload =
394
+ file.includes('layout.tsx') ||
395
+ file.includes('not-found.tsx') ||
396
+ file.endsWith('.css');
397
+
398
+ if (needsFullReload) {
399
+ console.log('⚡ Layout/CSS changed, full reload...');
400
+ window.location.reload();
401
+ return;
402
+ }
403
+
404
+ // Mudanças em rotas: tenta HMR
405
+ if (file.includes('/routes/') || file.includes('routes')) {
406
+ console.log('⚡ Route component changed, hot reloading...');
407
+
408
+ // Dispara evento para forçar re-render
409
+ const event = new CustomEvent('hmr:component-update', {
410
+ detail: { file: data.file, timestamp: Date.now() }
411
+ });
412
+ window.dispatchEvent(event);
413
+
414
+ // Aguarda 500ms para ver se o HMR foi bem-sucedido
415
+ setTimeout(() => {
416
+ const hmrSuccess = window.__HMR_SUCCESS__;
417
+ if (!hmrSuccess) {
418
+ console.log('⚠️ HMR failed, falling back to full reload');
419
+ window.location.reload();
420
+ } else {
421
+ console.log('✅ HMR successful!');
422
+ }
423
+ }, 500);
424
+ } else {
425
+ // Outros arquivos: reload completo por segurança
426
+ window.location.reload();
427
+ }
428
+ }
429
+
430
+ function handleHMRUpdate(data) {
431
+ console.log('🔥 HMR Update:', data);
432
+
433
+ // Dispara evento customizado para o React capturar
434
+ const event = new CustomEvent('hmr:update', {
435
+ detail: data
436
+ });
437
+ window.dispatchEvent(event);
438
+ }
439
+
440
+ function attemptHMR(changedFile) {
441
+ // Tenta fazer Hot Module Replacement
442
+ // Dispara evento para o React App capturar
443
+ const event = new CustomEvent('hmr:component-update', {
444
+ detail: { file: changedFile, timestamp: Date.now() }
445
+ });
446
+ window.dispatchEvent(event);
447
+
448
+ // Fallback: se após 2s não houve sucesso, reload
449
+ setTimeout(() => {
450
+ const hmrSuccess = window.__HMR_SUCCESS__;
451
+ if (!hmrSuccess) {
452
+ console.log('⚠️ HMR failed, falling back to full reload');
453
+ window.location.reload();
454
+ }
455
+ }, 2000);
456
+ }
457
+
458
+ ws.onclose = function(event) {
459
+ isConnected = false;
460
+
461
+ // Não tenta reconectar se foi fechamento intencional
462
+ if (event.code === 1000) {
463
+ return;
464
+ }
465
+
466
+ scheduleReconnect();
467
+ };
468
+
469
+ ws.onerror = function(error) {
470
+ isConnected = false;
471
+ // Não loga erros de conexão para evitar spam no console
472
+ };
473
+
474
+ } catch (error) {
475
+ console.error('Error creating WebSocket:', error);
476
+ scheduleReconnect();
477
+ }
478
+ }
479
+
480
+ function scheduleReconnect() {
481
+ if (reconnectTimer) {
482
+ clearTimeout(reconnectTimer);
483
+ }
484
+
485
+ reconnectAttempts++;
486
+
487
+ // Exponential backoff com jitter
488
+ const baseInterval = Math.min(reconnectInterval * Math.pow(1.5, reconnectAttempts - 1), maxReconnectInterval);
489
+ const jitter = Math.random() * 1000; // Adiciona até 1 segundo de variação
490
+ const finalInterval = baseInterval + jitter;
491
+
492
+ reconnectTimer = setTimeout(() => {
493
+ if (!isConnected) {
494
+ connect();
495
+ }
496
+ }, finalInterval);
497
+ }
498
+
499
+ // Detecta quando a página está sendo fechada para evitar reconexões desnecessárias
500
+ window.addEventListener('beforeunload', function() {
501
+ if (ws && ws.readyState === WebSocket.OPEN) {
502
+ ws.close(1000, 'Page unloading');
503
+ }
504
+ clearTimeout(reconnectTimer);
505
+ });
506
+
507
+ // Detecta quando a aba fica visível novamente para reconectar se necessário
508
+ document.addEventListener('visibilitychange', function() {
509
+ if (!document.hidden && !isConnected) {
510
+ reconnectAttempts = 0; // Reset do contador quando a aba fica ativa
511
+ connect();
512
+ }
513
+ });
514
+
515
+ connect();
516
+ }
517
+ })();
518
+ </script>
519
+ `;
520
+ }
521
+
522
+ private clearBackendCache(filePath: string) {
523
+ const absolutePath = path.resolve(filePath);
524
+ delete require.cache[absolutePath];
525
+
526
+ // Limpa dependências relacionadas de forma mais eficiente
527
+ const dirname = path.dirname(absolutePath);
528
+ Object.keys(require.cache).forEach(key => {
529
+ if (key.startsWith(dirname)) {
530
+ delete require.cache[key];
531
+ }
532
+ });
533
+ }
534
+
535
+ onBackendApiChange(callback: () => void) {
536
+ this.backendApiChangeCallback = callback;
537
+ }
538
+
539
+ onFrontendChange(callback: () => void) {
540
+ this.frontendChangeCallback = callback;
541
+ }
542
+
543
+ setHotReloadListener(listener: (file: string) => Promise<void> | void) {
544
+ this.customHotReloadListener = listener;
545
+ Console.info('🔌 Hot reload custom listener registered');
546
+ }
547
+
548
+ removeHotReloadListener() {
549
+ this.customHotReloadListener = null;
550
+ }
551
+
552
+ onBuildComplete(success: boolean) {
553
+ if (this.buildCompleteResolve) {
554
+ this.buildCompleteResolve();
555
+ this.buildCompleteResolve = null;
556
+ }
557
+ this.isBuilding = false;
558
+
559
+ // Notifica os clientes que o build terminou
560
+ if (success) {
561
+ this.notifyClients('build-complete', { success: true });
562
+ } else {
563
+ this.notifyClients('build-error', { success: false });
564
+ }
565
+ }
566
+ }