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