hightjs 0.5.0 → 0.5.2

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.
package/src/helpers.ts ADDED
@@ -0,0 +1,631 @@
1
+ #!/usr/bin/env node
2
+
3
+ /*
4
+ * This file is part of the HightJS Project.
5
+ * Copyright (c) 2025 itsmuzin
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ // Imports Nativos do Node.js (movidos para o topo)
21
+ import http, {IncomingMessage, Server, ServerResponse} from 'http';
22
+ import os from 'os';
23
+ import {URLSearchParams} from 'url'; // API moderna, substitui 'querystring'
24
+ import path from 'path';
25
+ // Helpers para integração com diferentes frameworks
26
+ import hweb, {FrameworkAdapterFactory} from './index'; // Importando o tipo
27
+ import type {HightJSOptions, HightConfig, HightConfigFunction} from './types';
28
+ import Console, {Colors} from "./api/console";
29
+ import https, { Server as HttpsServer } from 'https'; // <-- ADICIONAR
30
+ import fs from 'fs'; // <-- ADICIONAR
31
+
32
+ // Registra loaders customizados para importar arquivos não-JS
33
+ const { registerLoaders } = require('./loaders');
34
+ registerLoaders();
35
+
36
+ // --- Tipagem ---
37
+
38
+ /**
39
+ * Interface para a instância principal do hweb, inferida pelo uso.
40
+ */
41
+ interface HWebApp {
42
+ prepare: () => Promise<void>;
43
+ // O handler pode ter assinaturas diferentes dependendo do framework
44
+ getRequestHandler: () => (req: any, res: any, next?: any) => Promise<void> | void;
45
+ setupWebSocket: (server: Server | any) => void; // Aceita http.Server ou app (Express/Fastify)
46
+ executeInstrumentation: () => void;
47
+ }
48
+
49
+ /**
50
+ * Estende a request nativa do Node para incluir o body parseado.
51
+ */
52
+ interface HWebIncomingMessage extends IncomingMessage {
53
+ body?: object | string | null;
54
+ }
55
+
56
+ // --- Helpers ---
57
+
58
+ /**
59
+ * Encontra o IP externo local (rede)
60
+ */
61
+ function getLocalExternalIp(): string {
62
+ const interfaces = os.networkInterfaces();
63
+ for (const name of Object.keys(interfaces)) {
64
+ const ifaceList = interfaces[name];
65
+ if (ifaceList) {
66
+ for (const iface of ifaceList) {
67
+ if (iface.family === 'IPv4' && !iface.internal) {
68
+ return iface.address;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ return 'localhost'; // Fallback
74
+ }
75
+
76
+ const sendBox = (options: HightJSOptions) => {
77
+ const isDev = options.dev ? "Running in development mode" : null;
78
+
79
+ // 1. Verifica se o SSL está ativado (baseado na mesma lógica do initNativeServer)
80
+ const isSSL = options.ssl && options.ssl.key && options.ssl.cert;
81
+ const protocol = isSSL ? 'https' : 'http';
82
+ const localIp = getLocalExternalIp(); // Assume que getLocalExternalIp() existe
83
+
84
+ // 2. Monta as mensagens com o protocolo correto
85
+ const messages = [
86
+ ` ${Colors.FgGray}┃${Colors.Reset} Local: ${Colors.FgGreen}${protocol}://localhost:${options.port}${Colors.Reset}`,
87
+ ];
88
+
89
+ // Só adiciona a rede se o IP local for encontrado
90
+ if (localIp) {
91
+ messages.push(` ${Colors.FgGray}┃${Colors.Reset} Network: ${Colors.FgGreen}${protocol}://${localIp}:${options.port}${Colors.Reset}`);
92
+ }
93
+
94
+ if (isDev) {
95
+ messages.push(` ${Colors.FgGray}┃${Colors.Reset} ${isDev}`);
96
+ }
97
+
98
+ // Adiciona aviso de redirecionamento se estiver em modo SSL
99
+ if (isSSL && options.ssl?.redirectPort) {
100
+ messages.push(` ${Colors.FgGray}┃${Colors.Reset} HTTP (port ${options.ssl?.redirectPort}) is redirecting to HTTPS.`);
101
+ }
102
+
103
+ Console.box(messages.join("\n"), { title: "Access on:" });
104
+ }
105
+
106
+ /**
107
+ * Carrega o arquivo de configuração hightjs.config.ts ou hightjs.config.js do projeto
108
+ * @param projectDir Diretório raiz do projeto
109
+ * @param phase Fase de execução ('development' ou 'production')
110
+ * @returns Configuração mesclada com os valores padrão
111
+ */
112
+ async function loadHightConfig(projectDir: string, phase: string): Promise<HightConfig> {
113
+ const defaultConfig: HightConfig = {
114
+ maxHeadersCount: 100,
115
+ headersTimeout: 60000,
116
+ requestTimeout: 30000,
117
+ serverTimeout: 35000,
118
+ individualRequestTimeout: 30000,
119
+ maxUrlLength: 2048,
120
+ accessLogging: true,
121
+ };
122
+
123
+ try {
124
+ // Tenta primeiro .ts, depois .js
125
+ const possiblePaths = [
126
+ path.join(projectDir, 'hightjs.config.ts'),
127
+ path.join(projectDir, 'hightjs.config.js'),
128
+ ];
129
+
130
+ let configPath: string | null = null;
131
+ for (const p of possiblePaths) {
132
+ if (fs.existsSync(p)) {
133
+ configPath = p;
134
+ break;
135
+ }
136
+ }
137
+
138
+ if (!configPath) {
139
+ return defaultConfig;
140
+ }
141
+
142
+ // Remove do cache para permitir hot reload da configuração em dev
143
+ delete require.cache[require.resolve(configPath)];
144
+
145
+ const configModule = require(configPath);
146
+ const configExport = configModule.default || configModule;
147
+
148
+ let userConfig: HightConfig;
149
+
150
+ if (typeof configExport === 'function') {
151
+ // Suporta tanto função síncrona quanto assíncrona
152
+ userConfig = await Promise.resolve(
153
+ (configExport as HightConfigFunction)(phase, { defaultConfig })
154
+ );
155
+ } else {
156
+ userConfig = configExport;
157
+ }
158
+
159
+ // Mescla a configuração do usuário com a padrão
160
+ const mergedConfig = { ...defaultConfig, ...userConfig };
161
+
162
+ const configFileName = path.basename(configPath);
163
+ Console.info(`${Colors.FgCyan}[Config]${Colors.Reset} Loaded ${configFileName}`);
164
+
165
+ return mergedConfig;
166
+ } catch (error) {
167
+ if (error instanceof Error) {
168
+ Console.warn(`${Colors.FgYellow}[Config]${Colors.Reset} Error loading hightjs.config: ${error.message}`);
169
+ Console.warn(`${Colors.FgYellow}[Config]${Colors.Reset} Using default configuration`);
170
+ }
171
+ return defaultConfig;
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Aplica headers CORS na resposta baseado na configuração.
177
+ * @param req Requisição HTTP
178
+ * @param res Resposta HTTP
179
+ * @param corsConfig Configuração de CORS
180
+ * @returns true se a requisição foi finalizada (OPTIONS), false caso contrário
181
+ */
182
+ function applyCors(req: IncomingMessage, res: ServerResponse, corsConfig?: HightConfig['cors']): boolean {
183
+ if (!corsConfig || !corsConfig.enabled) {
184
+ return false;
185
+ }
186
+
187
+ const origin = req.headers.origin || req.headers.referer;
188
+
189
+ // Verifica se a origem é permitida
190
+ let allowOrigin = false;
191
+ if (corsConfig.origin === '*') {
192
+ res.setHeader('Access-Control-Allow-Origin', '*');
193
+ allowOrigin = true;
194
+ } else if (typeof corsConfig.origin === 'string' && origin === corsConfig.origin) {
195
+ res.setHeader('Access-Control-Allow-Origin', corsConfig.origin);
196
+ allowOrigin = true;
197
+ } else if (Array.isArray(corsConfig.origin) && origin && corsConfig.origin.includes(origin)) {
198
+ res.setHeader('Access-Control-Allow-Origin', origin);
199
+ allowOrigin = true;
200
+ } else if (typeof corsConfig.origin === 'function' && origin) {
201
+ try {
202
+ if (corsConfig.origin(origin)) {
203
+ res.setHeader('Access-Control-Allow-Origin', origin);
204
+ allowOrigin = true;
205
+ }
206
+ } catch (error) {
207
+ Console.warn(`${Colors.FgYellow}[CORS]${Colors.Reset} Error validating origin: ${error instanceof Error ? error.message : 'Unknown error'}`);
208
+ }
209
+ }
210
+
211
+ // Se a origem não for permitida e não for wildcard, não aplica outros headers
212
+ if (!allowOrigin && corsConfig.origin !== '*') {
213
+ return false;
214
+ }
215
+
216
+ // Credenciais (não pode ser usado com origin: '*')
217
+ if (corsConfig.credentials && corsConfig.origin !== '*') {
218
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
219
+ }
220
+
221
+ // Métodos permitidos
222
+ const methods = corsConfig.methods || ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'];
223
+ res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
224
+
225
+ // Headers permitidos
226
+ const allowedHeaders = corsConfig.allowedHeaders || ['Content-Type', 'Authorization'];
227
+ res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '));
228
+
229
+ // Headers expostos
230
+ if (corsConfig.exposedHeaders && corsConfig.exposedHeaders.length > 0) {
231
+ res.setHeader('Access-Control-Expose-Headers', corsConfig.exposedHeaders.join(', '));
232
+ }
233
+
234
+ // Max age para cache de preflight
235
+ const maxAge = corsConfig.maxAge !== undefined ? corsConfig.maxAge : 86400;
236
+ res.setHeader('Access-Control-Max-Age', maxAge.toString());
237
+
238
+ // Responde requisições OPTIONS (preflight)
239
+ if (req.method === 'OPTIONS') {
240
+ res.statusCode = 204; // No Content
241
+ res.end();
242
+ return true;
243
+ }
244
+
245
+ return false;
246
+ }
247
+
248
+ /**
249
+ * Middleware para parsing do body com proteções de segurança (versão melhorada).
250
+ */
251
+
252
+ const parseBody = (req: IncomingMessage): Promise<object | string | null> => {
253
+ // Constantes para limites de segurança
254
+ const MAX_BODY_SIZE = 10 * 1024 * 1024; // 10MB limite total
255
+ const MAX_JSON_SIZE = 1 * 1024 * 1024; // 1MB limite para JSON
256
+ const BODY_TIMEOUT = 30000; // 30 segundos
257
+
258
+ return new Promise((resolve, reject) => {
259
+ if (req.method === 'GET' || req.method === 'HEAD') {
260
+ resolve(null);
261
+ return;
262
+ }
263
+
264
+ let body = '';
265
+ let totalSize = 0;
266
+
267
+ // Timeout para requisições lentas
268
+ const timeout = setTimeout(() => {
269
+ req.destroy();
270
+ reject(new Error('Request body timeout'));
271
+ }, BODY_TIMEOUT);
272
+
273
+ req.on('data', (chunk: Buffer) => {
274
+ totalSize += chunk.length;
275
+
276
+ // Proteção contra DoS (Payload Too Large)
277
+ if (totalSize > MAX_BODY_SIZE) {
278
+ clearTimeout(timeout);
279
+ req.destroy();
280
+ reject(new Error('Request body too large'));
281
+ return;
282
+ }
283
+ body += chunk.toString();
284
+ });
285
+
286
+ req.on('end', () => {
287
+ clearTimeout(timeout);
288
+
289
+ if (!body) {
290
+ resolve(null);
291
+ return;
292
+ }
293
+
294
+ try {
295
+ const contentType = req.headers['content-type'] || '';
296
+
297
+ if (contentType.includes('application/json')) {
298
+ if (body.length > MAX_JSON_SIZE) {
299
+ reject(new Error('JSON body too large'));
300
+ return;
301
+ }
302
+ // Rejeita promise se o JSON for inválido
303
+ try {
304
+ resolve(JSON.parse(body));
305
+ } catch (e) {
306
+ reject(new Error('Invalid JSON body'));
307
+ }
308
+ } else if (contentType.includes('application/x-www-form-urlencoded')) {
309
+ // Usa API moderna URLSearchParams (segura contra prototype pollution)
310
+ resolve(Object.fromEntries(new URLSearchParams(body)));
311
+ } else {
312
+ resolve(body); // Fallback para texto plano
313
+ }
314
+ } catch (error) {
315
+ // Pega qualquer outro erro síncrono
316
+ reject(error);
317
+ }
318
+ });
319
+
320
+ req.on('error', (error: Error) => {
321
+ clearTimeout(timeout);
322
+ reject(error);
323
+ });
324
+ });
325
+ };
326
+
327
+ /**
328
+ * Inicializa servidor nativo do HightJS usando HTTP ou HTTPS
329
+ */
330
+ async function initNativeServer(hwebApp: HWebApp, options: HightJSOptions, port: number, hostname: string) {
331
+ const time = Date.now();
332
+
333
+ await hwebApp.prepare();
334
+
335
+ // Carrega a configuração do arquivo hightjs.config.js
336
+ const projectDir = options.dir || process.cwd();
337
+ const phase = options.dev ? 'development' : 'production';
338
+ const hightConfig = await loadHightConfig(projectDir, phase);
339
+
340
+ const handler = hwebApp.getRequestHandler();
341
+ const msg = Console.dynamicLine(` ${Colors.BgYellow} ready ${Colors.Reset} ${Colors.Bright}Starting HightJS on port ${options.port}${Colors.Reset}`);
342
+
343
+ // --- LÓGICA DO LISTENER (REUTILIZÁVEL) ---
344
+ // Extraímos a lógica principal para uma variável
345
+ // para que possa ser usada tanto pelo servidor HTTP quanto HTTPS.
346
+ const requestListener = async (req: HWebIncomingMessage, res: ServerResponse) => {
347
+ const requestStartTime = Date.now();
348
+ const method = req.method || 'GET';
349
+ const url = req.url || '/';
350
+
351
+ // Aplica CORS se configurado
352
+ const corsHandled = applyCors(req, res, hightConfig.cors);
353
+ if (corsHandled) {
354
+ // Requisição OPTIONS foi respondida pelo CORS
355
+ if (hightConfig.accessLogging) {
356
+ const duration = Date.now() - requestStartTime;
357
+ Console.logCustomLevel('OPTIONS', true, Colors.BgMagenta, `${url} ${Colors.FgGreen}204${Colors.Reset} ${Colors.FgGray}${duration}ms${Colors.Reset} ${Colors.FgCyan}[CORS]${Colors.Reset}`);
358
+ }
359
+ return;
360
+ }
361
+
362
+ // Configurações de segurança básicas
363
+ res.setHeader('X-Content-Type-Options', 'nosniff');
364
+ res.setHeader('X-Frame-Options', 'DENY');
365
+ res.setHeader('X-XSS-Protection', '1; mode=block');
366
+ res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
367
+
368
+ // IMPORTANTE: Adiciona HSTS (Strict-Transport-Security) se estiver em modo SSL
369
+ // Isso força o navegador a usar HTTPS no futuro.
370
+ if (options.ssl) {
371
+ res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
372
+ }
373
+
374
+ // Timeout por requisição (usa configuração personalizada)
375
+ req.setTimeout(hightConfig.individualRequestTimeout || 30000, () => {
376
+ res.statusCode = 408; // Request Timeout
377
+ res.end('Request timeout');
378
+
379
+ // Log de timeout
380
+ if (hightConfig.accessLogging) {
381
+ const duration = Date.now() - requestStartTime;
382
+ Console.info(`${Colors.FgYellow}${method}${Colors.Reset} ${url} ${Colors.FgRed}408${Colors.Reset} ${Colors.FgGray}${duration}ms${Colors.Reset}`);
383
+ }
384
+ });
385
+
386
+ // Intercepta o método end() para logar quando a resposta for enviada
387
+ const originalEnd = res.end.bind(res);
388
+ let hasEnded = false;
389
+
390
+ res.end = function(this: ServerResponse, ...args: any[]): any {
391
+ if (!hasEnded && hightConfig.accessLogging) {
392
+ hasEnded = true;
393
+ const duration = Date.now() - requestStartTime;
394
+ const statusCode = res.statusCode || 200;
395
+
396
+ // Define cor baseada no status code
397
+ let statusColor = Colors.FgGreen; // 2xx
398
+ if (statusCode >= 500) statusColor = Colors.FgRed; // 5xx
399
+ else if (statusCode >= 400) statusColor = Colors.FgYellow; // 4xx
400
+ else if (statusCode >= 300) statusColor = Colors.FgCyan; // 3xx
401
+
402
+ // Formata o método com cor
403
+ let methodColor = Colors.BgCyan;
404
+ if (method === 'POST') methodColor = Colors.BgGreen;
405
+ else if (method === 'PUT') methodColor = Colors.BgYellow;
406
+ else if (method === 'DELETE') methodColor = Colors.BgRed;
407
+ else if (method === 'PATCH') methodColor = Colors.BgMagenta;
408
+ Console.logCustomLevel(method, true, methodColor, `${url} ${statusColor}${statusCode}${Colors.Reset} ${Colors.FgGray}${duration}ms${Colors.Reset}`);
409
+ }
410
+ // @ts-ignore
411
+ return originalEnd.apply(this, args);
412
+ } as any;
413
+
414
+ try {
415
+ // Validação básica de URL (usa configuração personalizada)
416
+ const maxUrlLength = hightConfig.maxUrlLength || 2048;
417
+ if (url.length > maxUrlLength) {
418
+ res.statusCode = 414; // URI Too Long
419
+ res.end('URL too long');
420
+ return;
421
+ }
422
+
423
+ // Parse do body com proteções
424
+ req.body = await parseBody(req); // Assumindo que parseBody existe
425
+
426
+ // Adiciona host se não existir (necessário para `new URL`)
427
+ req.headers.host = req.headers.host || `localhost:${port}`;
428
+
429
+ // Chama o handler do HightJS
430
+ await handler(req, res);
431
+
432
+ } catch (error) {
433
+ // Log do erro no servidor
434
+ if (error instanceof Error) {
435
+ Console.error(`Native server error: ${error.message}`);
436
+ } else {
437
+ Console.error('Unknown native server error:', error);
438
+ }
439
+
440
+ // Tratamento de erro (idêntico ao seu original)
441
+ if (!res.headersSent) {
442
+ res.setHeader('Content-Type', 'text/plain');
443
+ if (error instanceof Error) {
444
+ if (error.message.includes('too large')) {
445
+ res.statusCode = 413; // Payload Too Large
446
+ res.end('Request too large');
447
+ } else if (error.message.includes('timeout')) {
448
+ res.statusCode = 408; // Request Timeout
449
+ res.end('Request timeout');
450
+ } else if (error.message.includes('Invalid JSON')) {
451
+ res.statusCode = 400; // Bad Request
452
+ res.end('Invalid JSON body');
453
+ } else {
454
+ res.statusCode = 500;
455
+ res.end('Internal server error');
456
+ }
457
+ } else {
458
+ res.statusCode = 500;
459
+ res.end('Internal server error');
460
+ }
461
+ }
462
+ }
463
+ };
464
+ // --- FIM DO LISTENER ---
465
+
466
+ let server: Server | HttpsServer; // O tipo do servidor pode variar
467
+ const isSSL = options.ssl && options.ssl.key && options.ssl.cert;
468
+
469
+ if (isSSL && options.ssl) {
470
+
471
+ const sslOptions = {
472
+ key: fs.readFileSync(options.ssl.key),
473
+ cert: fs.readFileSync(options.ssl.cert),
474
+ ca: options.ssl.ca ? fs.readFileSync(options.ssl.ca) : undefined
475
+ };
476
+
477
+ // 1. Cria o servidor HTTPS principal
478
+ server = https.createServer(sslOptions, requestListener as any); // (any para contornar HWebIncomingMessage)
479
+
480
+ // 2. Cria o servidor de REDIRECIONAMENTO (HTTP -> HTTPS)
481
+ const httpRedirectPort = options.ssl.redirectPort;
482
+ http.createServer((req, res) => {
483
+ const host = req.headers['host'] || hostname;
484
+ // Remove a porta do host (ex: meusite.com:80)
485
+ const hostWithoutPort = host.split(':')[0];
486
+
487
+ // Monta a URL de redirecionamento
488
+ let redirectUrl = `https://${hostWithoutPort}`;
489
+ // Adiciona a porta HTTPS apenas se não for a padrão (443)
490
+ if (port !== 443) {
491
+ redirectUrl += `:${port}`;
492
+ }
493
+ redirectUrl += req.url || '/';
494
+
495
+ res.writeHead(301, { 'Location': redirectUrl });
496
+ res.end();
497
+ }).listen(httpRedirectPort, hostname, () => {});
498
+
499
+ } else {
500
+ // --- MODO HTTP (Original) ---
501
+ // Cria o servidor HTTP nativo
502
+ server = http.createServer(requestListener as any); // (any para contornar HWebIncomingMessage)
503
+ }
504
+
505
+ // Configurações de segurança do servidor (usa configuração personalizada)
506
+ server.setTimeout(hightConfig.serverTimeout || 35000); // Timeout geral do servidor
507
+ server.maxHeadersCount = hightConfig.maxHeadersCount || 100; // Limita número de headers
508
+ server.headersTimeout = hightConfig.headersTimeout || 60000; // Timeout para headers
509
+ server.requestTimeout = hightConfig.requestTimeout || 30000; // Timeout para requisições
510
+
511
+ server.listen(port, hostname, () => {
512
+ sendBox({ ...options, port });
513
+ msg.end(` ${Colors.BgGreen} ready ${Colors.Reset} ${Colors.Bright}Ready on port ${Colors.BgGreen} ${options.port} ${Colors.Reset}${Colors.Bright} in ${Date.now() - time}ms${Colors.Reset}\n`);
514
+ });
515
+
516
+ // Configura WebSocket para hot reload (Comum a ambos)
517
+ hwebApp.setupWebSocket(server);
518
+ hwebApp.executeInstrumentation();
519
+ return server;
520
+ }
521
+
522
+ // --- Função Principal ---
523
+
524
+ export function app(options: HightJSOptions = {}) {
525
+ const framework = options.framework || 'native';
526
+ FrameworkAdapterFactory.setFramework(framework)
527
+
528
+ // Tipando a app principal do hweb
529
+ const hwebApp: HWebApp = hweb(options);
530
+
531
+ return {
532
+ ...hwebApp,
533
+
534
+ /**
535
+ * Integra com uma aplicação de qualquer framework (Express, Fastify, etc)
536
+ * O 'serverApp: any' é mantido para flexibilidade, já que pode ser de tipos diferentes.
537
+ */
538
+ integrate: async (serverApp: any) => {
539
+ await hwebApp.prepare();
540
+ const handler = hwebApp.getRequestHandler();
541
+
542
+ // O framework é setado nas opções do hweb, que deve
543
+ // retornar o handler correto em getRequestHandler()
544
+ // A lógica de integração original parece correta.
545
+
546
+ if (framework === 'express') {
547
+ const express = require('express');
548
+ try {
549
+ const cookieParser = require('cookie-parser');
550
+ serverApp.use(cookieParser());
551
+ } catch (e) {
552
+ Console.error("Could not find cookie-parser");
553
+ }
554
+ serverApp.use(express.json());
555
+ serverApp.use(express.urlencoded({ extended: true }));
556
+ serverApp.use(handler);
557
+ hwebApp.setupWebSocket(serverApp);
558
+
559
+ } else if (framework === 'fastify') {
560
+ try {
561
+ await serverApp.register(require('@fastify/cookie'));
562
+ } catch (e) {
563
+ Console.error("Could not find @fastify/cookie");
564
+ }
565
+ try {
566
+ await serverApp.register(require('@fastify/formbody'));
567
+ } catch (e) {
568
+ Console.error("Could not find @fastify/formbody");
569
+ }
570
+ await serverApp.register(async (fastify: any) => {
571
+ fastify.all('*', handler);
572
+ });
573
+ hwebApp.setupWebSocket(serverApp);
574
+
575
+ } else {
576
+ // Generic integration (assume Express-like)
577
+ serverApp.use(handler);
578
+ hwebApp.setupWebSocket(serverApp);
579
+ }
580
+
581
+ hwebApp.executeInstrumentation();
582
+ return serverApp;
583
+ },
584
+
585
+ /**
586
+ * Inicia um servidor HightJS fechado (o usuário não tem acesso ao framework)
587
+ */
588
+ init: async () => {
589
+ const currentVersion = require('../package.json').version;
590
+
591
+ async function verifyVersion(): Promise<string> {
592
+ // node fetch
593
+ try {
594
+ const response = await fetch('https://registry.npmjs.org/hightjs/latest');
595
+ const data = await response.json();
596
+ return data.version;
597
+ } catch (error) {
598
+ Console.error('Could not check for the latest HightJS version:', error);
599
+ return currentVersion; // Retorna a versão atual em caso de erro
600
+ }
601
+ }
602
+ const latestVersion = await verifyVersion();
603
+ const isUpToDate = latestVersion === currentVersion;
604
+ let message;
605
+ if (!isUpToDate) {
606
+ message = `${Colors.FgGreen} A new version is available (v${latestVersion})${Colors.FgMagenta}`
607
+ } else {
608
+ message = `${Colors.FgGreen} You are on the latest version${Colors.FgMagenta}`
609
+ }
610
+ console.log(`${Colors.FgMagenta}
611
+ __ ___ ${Colors.FgGreen} __ ${Colors.FgMagenta}
612
+ |__| | / _\` |__| | ${Colors.FgGreen} | /__\` ${Colors.FgMagenta} ${Colors.FgMagenta}HightJS ${Colors.FgGray}(v${require('../package.json').version}) - itsmuzin${Colors.FgMagenta}
613
+ | | | \\__> | | | ${Colors.FgGreen}\\__/ .__/ ${message}
614
+ ${Colors.Reset}`);
615
+
616
+ const actualPort = options.port || 3000;
617
+ const actualHostname = options.hostname || "0.0.0.0";
618
+
619
+ if (framework !== 'native') {
620
+ Console.warn(`The "${framework}" framework was selected, but the init() method only works with the "native" framework. Starting native server...`);
621
+ }
622
+
623
+
624
+
625
+ return await initNativeServer(hwebApp, options, actualPort, actualHostname);
626
+ }
627
+ }
628
+ }
629
+
630
+ // Exporta a função 'app' como nomeada e também como padrão
631
+ export default app;