hightjs 0.5.2 → 0.5.3

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