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