hightjs 0.5.3 → 0.5.4

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 (45) hide show
  1. package/dist/adapters/express.d.ts +7 -0
  2. package/dist/adapters/express.js +63 -0
  3. package/dist/adapters/factory.d.ts +23 -0
  4. package/dist/adapters/factory.js +122 -0
  5. package/dist/adapters/fastify.d.ts +25 -0
  6. package/dist/adapters/fastify.js +61 -0
  7. package/dist/adapters/native.d.ts +8 -0
  8. package/dist/adapters/native.js +198 -0
  9. package/dist/api/console.d.ts +94 -0
  10. package/dist/api/console.js +294 -0
  11. package/dist/api/http.d.ts +180 -0
  12. package/dist/api/http.js +469 -0
  13. package/dist/bin/hightjs.d.ts +2 -0
  14. package/dist/bin/hightjs.js +214 -0
  15. package/dist/builder.d.ts +32 -0
  16. package/dist/builder.js +581 -0
  17. package/dist/client/DefaultNotFound.d.ts +1 -0
  18. package/dist/client/DefaultNotFound.js +79 -0
  19. package/dist/client/client.d.ts +3 -0
  20. package/dist/client/client.js +24 -0
  21. package/dist/client/clientRouter.d.ts +58 -0
  22. package/dist/client/clientRouter.js +132 -0
  23. package/dist/client/entry.client.d.ts +1 -0
  24. package/dist/client/entry.client.js +455 -0
  25. package/dist/components/Link.d.ts +7 -0
  26. package/dist/components/Link.js +13 -0
  27. package/dist/global/global.d.ts +117 -0
  28. package/dist/global/global.js +17 -0
  29. package/dist/helpers.d.ts +20 -0
  30. package/dist/helpers.js +583 -0
  31. package/dist/hotReload.d.ts +32 -0
  32. package/dist/hotReload.js +545 -0
  33. package/dist/index.d.ts +18 -0
  34. package/dist/index.js +494 -0
  35. package/dist/loaders.d.ts +1 -0
  36. package/dist/loaders.js +46 -0
  37. package/dist/renderer.d.ts +14 -0
  38. package/dist/renderer.js +380 -0
  39. package/dist/router.d.ts +101 -0
  40. package/dist/router.js +659 -0
  41. package/dist/types/framework.d.ts +37 -0
  42. package/dist/types/framework.js +2 -0
  43. package/dist/types.d.ts +192 -0
  44. package/dist/types.js +2 -0
  45. package/package.json +1 -1
package/dist/index.js ADDED
@@ -0,0 +1,494 @@
1
+ "use strict";
2
+ /*
3
+ * This file is part of the HightJS Project.
4
+ * Copyright (c) 2025 itsmuzin
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ var desc = Object.getOwnPropertyDescriptor(m, k);
21
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
22
+ desc = { enumerable: true, get: function() { return m[k]; } };
23
+ }
24
+ Object.defineProperty(o, k2, desc);
25
+ }) : (function(o, m, k, k2) {
26
+ if (k2 === undefined) k2 = k;
27
+ o[k2] = m[k];
28
+ }));
29
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
30
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
31
+ }) : function(o, v) {
32
+ o["default"] = v;
33
+ });
34
+ var __importStar = (this && this.__importStar) || (function () {
35
+ var ownKeys = function(o) {
36
+ ownKeys = Object.getOwnPropertyNames || function (o) {
37
+ var ar = [];
38
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
39
+ return ar;
40
+ };
41
+ return ownKeys(o);
42
+ };
43
+ return function (mod) {
44
+ if (mod && mod.__esModule) return mod;
45
+ var result = {};
46
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
47
+ __setModuleDefault(result, mod);
48
+ return result;
49
+ };
50
+ })();
51
+ var __importDefault = (this && this.__importDefault) || function (mod) {
52
+ return (mod && mod.__esModule) ? mod : { "default": mod };
53
+ };
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.app = exports.FrameworkAdapterFactory = exports.FastifyAdapter = exports.ExpressAdapter = exports.HightJSResponse = exports.HightJSRequest = void 0;
56
+ exports.default = hweb;
57
+ const path_1 = __importDefault(require("path"));
58
+ const fs_1 = __importDefault(require("fs"));
59
+ const express_1 = require("./adapters/express");
60
+ const builder_1 = require("./builder");
61
+ const router_1 = require("./router");
62
+ const renderer_1 = require("./renderer");
63
+ const http_1 = require("./api/http");
64
+ Object.defineProperty(exports, "HightJSRequest", { enumerable: true, get: function () { return http_1.HightJSRequest; } });
65
+ Object.defineProperty(exports, "HightJSResponse", { enumerable: true, get: function () { return http_1.HightJSResponse; } });
66
+ const hotReload_1 = require("./hotReload");
67
+ const factory_1 = require("./adapters/factory");
68
+ const console_1 = __importStar(require("./api/console"));
69
+ // Exporta os adapters para uso manual se necessário
70
+ var express_2 = require("./adapters/express");
71
+ Object.defineProperty(exports, "ExpressAdapter", { enumerable: true, get: function () { return express_2.ExpressAdapter; } });
72
+ var fastify_1 = require("./adapters/fastify");
73
+ Object.defineProperty(exports, "FastifyAdapter", { enumerable: true, get: function () { return fastify_1.FastifyAdapter; } });
74
+ var factory_2 = require("./adapters/factory");
75
+ Object.defineProperty(exports, "FrameworkAdapterFactory", { enumerable: true, get: function () { return factory_2.FrameworkAdapterFactory; } });
76
+ // Exporta os helpers para facilitar integração
77
+ var helpers_1 = require("./helpers");
78
+ Object.defineProperty(exports, "app", { enumerable: true, get: function () { return helpers_1.app; } });
79
+ // Função para verificar se o projeto é grande o suficiente para se beneficiar de chunks
80
+ function isLargeProject(projectDir) {
81
+ try {
82
+ const srcDir = path_1.default.join(projectDir, 'src');
83
+ if (!fs_1.default.existsSync(srcDir))
84
+ return false;
85
+ let totalFiles = 0;
86
+ let totalSize = 0;
87
+ function scanDirectory(dir) {
88
+ const items = fs_1.default.readdirSync(dir, { withFileTypes: true });
89
+ for (const item of items) {
90
+ const fullPath = path_1.default.join(dir, item.name);
91
+ if (item.isDirectory() && item.name !== 'node_modules' && item.name !== '.git') {
92
+ scanDirectory(fullPath);
93
+ }
94
+ else if (item.isFile() && /\.(tsx?|jsx?|css|scss|less)$/i.test(item.name)) {
95
+ totalFiles++;
96
+ totalSize += fs_1.default.statSync(fullPath).size;
97
+ }
98
+ }
99
+ }
100
+ scanDirectory(srcDir);
101
+ // Considera projeto grande se:
102
+ // - Mais de 20 arquivos de frontend/style
103
+ // - Ou tamanho total > 500KB
104
+ return totalFiles > 20 || totalSize > 500 * 1024;
105
+ }
106
+ catch (error) {
107
+ // Em caso de erro, assume que não é um projeto grande
108
+ return false;
109
+ }
110
+ }
111
+ // Função para gerar o arquivo de entrada para o esbuild
112
+ function createEntryFile(projectDir, routes) {
113
+ try {
114
+ const tempDir = path_1.default.join(projectDir, '.hight', 'temp');
115
+ fs_1.default.mkdirSync(tempDir, { recursive: true });
116
+ const entryFilePath = path_1.default.join(tempDir, 'entry.client.js');
117
+ // Verifica se há layout
118
+ const layout = (0, router_1.getLayout)();
119
+ // Verifica se há notFound personalizado
120
+ const notFound = (0, router_1.getNotFound)();
121
+ // Gera imports dinâmicos para cada componente
122
+ const imports = routes
123
+ .map((route, index) => {
124
+ const relativePath = path_1.default.relative(tempDir, route.componentPath).replace(/\\/g, '/');
125
+ return `import route${index} from '${relativePath}';`;
126
+ })
127
+ .join('\n');
128
+ // Import do layout se existir
129
+ const layoutImport = layout
130
+ ? `import LayoutComponent from '${path_1.default.relative(tempDir, layout.componentPath).replace(/\\/g, '/')}';`
131
+ : '';
132
+ // Import do notFound se existir
133
+ const notFoundImport = notFound
134
+ ? `import NotFoundComponent from '${path_1.default.relative(tempDir, notFound.componentPath).replace(/\\/g, '/')}';`
135
+ : '';
136
+ // Registra os componentes no window para o cliente acessar
137
+ const componentRegistration = routes
138
+ .map((route, index) => ` '${route.componentPath}': route${index}.component || route${index}.default?.component,`)
139
+ .join('\n');
140
+ // Registra o layout se existir
141
+ const layoutRegistration = layout
142
+ ? `window.__HWEB_LAYOUT__ = LayoutComponent.default || LayoutComponent;`
143
+ : `window.__HWEB_LAYOUT__ = null;`;
144
+ // Registra o notFound se existir
145
+ const notFoundRegistration = notFound
146
+ ? `window.__HWEB_NOT_FOUND__ = NotFoundComponent.default || NotFoundComponent;`
147
+ : `window.__HWEB_NOT_FOUND__ = null;`;
148
+ // Caminho correto para o entry.client.tsx
149
+ const sdkDir = path_1.default.dirname(__dirname); // Vai para a pasta pai de src (onde está o hweb-sdk)
150
+ const entryClientPath = path_1.default.join(sdkDir, 'src', 'client', 'entry.client.tsx');
151
+ const relativeEntryPath = path_1.default.relative(tempDir, entryClientPath).replace(/\\/g, '/');
152
+ // Import do DefaultNotFound do SDK
153
+ const defaultNotFoundPath = path_1.default.join(sdkDir, 'src', 'client', 'DefaultNotFound.tsx');
154
+ const relativeDefaultNotFoundPath = path_1.default.relative(tempDir, defaultNotFoundPath).replace(/\\/g, '/');
155
+ const entryContent = `// Arquivo gerado automaticamente pelo hweb
156
+ ${imports}
157
+ ${layoutImport}
158
+ ${notFoundImport}
159
+ import DefaultNotFound from '${relativeDefaultNotFoundPath}';
160
+
161
+ // Registra os componentes para o cliente
162
+ window.__HWEB_COMPONENTS__ = {
163
+ ${componentRegistration}
164
+ };
165
+
166
+ // Registra o layout se existir
167
+ ${layoutRegistration}
168
+
169
+ // Registra o notFound se existir
170
+ ${notFoundRegistration}
171
+
172
+ // Registra o DefaultNotFound do hweb
173
+ window.__HWEB_DEFAULT_NOT_FOUND__ = DefaultNotFound;
174
+
175
+ // Importa e executa o entry.client.tsx
176
+ import '${relativeEntryPath}';
177
+ `;
178
+ try {
179
+ fs_1.default.writeFileSync(entryFilePath, entryContent);
180
+ }
181
+ catch (e) {
182
+ console.error("sdfijnsdfnijfsdijnfsdnijsdfnijfsdnijfsdnijfsdn", e);
183
+ }
184
+ return entryFilePath;
185
+ }
186
+ catch (e) {
187
+ console_1.default.error("Error creating entry file:", e);
188
+ throw e;
189
+ }
190
+ }
191
+ function hweb(options) {
192
+ const { dev = true, dir = process.cwd(), port = 3000 } = options;
193
+ // @ts-ignore
194
+ process.hight = options;
195
+ const userWebDir = path_1.default.join(dir, 'src', 'web');
196
+ const userWebRoutesDir = path_1.default.join(userWebDir, 'routes');
197
+ const userBackendRoutesDir = path_1.default.join(dir, 'src', 'backend', 'routes');
198
+ /**
199
+ * Executa middlewares sequencialmente e depois o handler final
200
+ * @param middlewares Array de middlewares para executar
201
+ * @param finalHandler Handler final da rota
202
+ * @param request Requisição do HightJS
203
+ * @param params Parâmetros da rota
204
+ * @returns Resposta do middleware ou handler final
205
+ */
206
+ async function executeMiddlewareChain(middlewares, finalHandler, request, params) {
207
+ if (!middlewares || middlewares.length === 0) {
208
+ // Não há middlewares, executa diretamente o handler final
209
+ return await finalHandler(request, params);
210
+ }
211
+ let currentIndex = 0;
212
+ // Função next que será chamada pelos middlewares
213
+ const next = async () => {
214
+ if (currentIndex < middlewares.length) {
215
+ // Ainda há middlewares para executar
216
+ const currentMiddleware = middlewares[currentIndex];
217
+ currentIndex++;
218
+ return await currentMiddleware(request, params, next);
219
+ }
220
+ else {
221
+ // Todos os middlewares foram executados, chama o handler final
222
+ return await finalHandler(request, params);
223
+ }
224
+ };
225
+ // Inicia a cadeia de execução
226
+ return await next();
227
+ }
228
+ let frontendRoutes = [];
229
+ let hotReloadManager = null;
230
+ let entryPoint;
231
+ let outfile;
232
+ // Função para regenerar o entry file
233
+ const regenerateEntryFile = () => {
234
+ // Recarrega todas as rotas e componentes
235
+ frontendRoutes = (0, router_1.loadRoutes)(userWebRoutesDir);
236
+ (0, router_1.loadLayout)(userWebDir);
237
+ (0, router_1.loadNotFound)(userWebDir);
238
+ // Regenera o entry file
239
+ entryPoint = createEntryFile(dir, frontendRoutes);
240
+ };
241
+ return {
242
+ prepare: async () => {
243
+ const isProduction = !dev;
244
+ if (!isProduction) {
245
+ // Inicia hot reload apenas em desenvolvimento (com suporte ao main)
246
+ hotReloadManager = new hotReload_1.HotReloadManager(dir);
247
+ await hotReloadManager.start();
248
+ // Adiciona callback para recarregar TUDO quando qualquer arquivo mudar
249
+ hotReloadManager.onBackendApiChange(() => {
250
+ (0, router_1.loadBackendRoutes)(userBackendRoutesDir);
251
+ (0, router_1.processWebSocketRoutes)(); // Processa rotas WS após recarregar backend
252
+ });
253
+ // Adiciona callback para regenerar entry file quando frontend mudar
254
+ hotReloadManager.onFrontendChange(() => {
255
+ regenerateEntryFile();
256
+ });
257
+ }
258
+ const now = Date.now();
259
+ const timee = console_1.default.dynamicLine(` ${console_1.Colors.BgYellow} router ${console_1.Colors.Reset} Loading routes and components`);
260
+ const spinnerFrames1 = ['|', '/', '-', '\\'];
261
+ let frameIndex1 = 0;
262
+ const spinner1 = setInterval(() => {
263
+ timee.update(` ${console_1.Colors.FgYellow}${spinnerFrames1[frameIndex1]}${console_1.Colors.Reset} Loading routes and components...`);
264
+ frameIndex1 = (frameIndex1 + 1) % spinnerFrames1.length;
265
+ }, 100); // muda a cada 100ms
266
+ // ORDEM IMPORTANTE: Carrega TUDO antes de criar o arquivo de entrada
267
+ frontendRoutes = (0, router_1.loadRoutes)(userWebRoutesDir);
268
+ (0, router_1.loadBackendRoutes)(userBackendRoutesDir);
269
+ // Processa rotas WebSocket após carregar backend
270
+ (0, router_1.processWebSocketRoutes)();
271
+ // Carrega layout.tsx ANTES de criar o entry file
272
+ const layout = (0, router_1.loadLayout)(userWebDir);
273
+ const notFound = (0, router_1.loadNotFound)(userWebDir);
274
+ const outDir = path_1.default.join(dir, '.hight');
275
+ fs_1.default.mkdirSync(outDir, { recursive: true });
276
+ entryPoint = createEntryFile(dir, frontendRoutes);
277
+ clearInterval(spinner1);
278
+ timee.end(` ${console_1.Colors.BgGreen} router ${console_1.Colors.Reset} Routes and components loaded in ${Date.now() - now}ms`);
279
+ if (isProduction) {
280
+ const time = console_1.default.dynamicLine(` ${console_1.Colors.BgYellow} build ${console_1.Colors.Reset} Starting client build`);
281
+ // Spinner
282
+ const spinnerFrames = ['|', '/', '-', '\\'];
283
+ let frameIndex = 0;
284
+ const spinner = setInterval(() => {
285
+ time.update(` ${console_1.Colors.FgYellow}${spinnerFrames[frameIndex]}${console_1.Colors.Reset} Building...`);
286
+ frameIndex = (frameIndex + 1) % spinnerFrames.length;
287
+ }, 100); // muda a cada 100ms
288
+ const now = Date.now();
289
+ await (0, builder_1.buildWithChunks)(entryPoint, outDir, isProduction);
290
+ const elapsed = Date.now() - now;
291
+ clearInterval(spinner); // para o spinner
292
+ time.update(""); // limpa a linha
293
+ time.end(` ${console_1.Colors.BgGreen} build ${console_1.Colors.Reset} Client build completed in ${elapsed}ms`);
294
+ // Notifica o hot reload manager que o build foi concluído
295
+ if (hotReloadManager) {
296
+ hotReloadManager.onBuildComplete(true);
297
+ }
298
+ }
299
+ else {
300
+ const time = console_1.default.dynamicLine(` ${console_1.Colors.BgYellow} watcher ${console_1.Colors.Reset} Starting client watch`);
301
+ (0, builder_1.watchWithChunks)(entryPoint, outDir, hotReloadManager).catch(err => {
302
+ console_1.default.error(`Error starting watch`, err);
303
+ });
304
+ time.end(` ${console_1.Colors.BgGreen} watcher ${console_1.Colors.Reset} Client Watch started`);
305
+ }
306
+ },
307
+ executeInstrumentation: () => {
308
+ // verificar se dir/src/instrumentation.(tsx/jsx/js/ts) existe com regex
309
+ const instrumentationFile = fs_1.default.readdirSync(path_1.default.join(dir, 'src')).find(file => /^hightweb\.(tsx|jsx|js|ts)$/.test(file));
310
+ if (instrumentationFile) {
311
+ const instrumentationPath = path_1.default.join(dir, 'src', instrumentationFile);
312
+ // dar require, e executar a função principal do arquivo
313
+ const instrumentation = require(instrumentationPath);
314
+ // Registra o listener de hot reload se existir
315
+ if (instrumentation.hotReloadListener && typeof instrumentation.hotReloadListener === 'function') {
316
+ if (hotReloadManager) {
317
+ hotReloadManager.setHotReloadListener(instrumentation.hotReloadListener);
318
+ }
319
+ }
320
+ if (typeof instrumentation === 'function') {
321
+ instrumentation();
322
+ }
323
+ else if (typeof instrumentation.default === 'function') {
324
+ instrumentation.default();
325
+ }
326
+ else {
327
+ console_1.default.warn(`The instrumentation file ${instrumentationFile} does not export a default function.`);
328
+ }
329
+ }
330
+ },
331
+ getRequestHandler: () => {
332
+ return async (req, res) => {
333
+ // Detecta automaticamente o framework e cria o adapter apropriado
334
+ const adapter = factory_1.FrameworkAdapterFactory.detectFramework(req, res);
335
+ const genericReq = adapter.parseRequest(req);
336
+ const genericRes = adapter.createResponse(res);
337
+ // Adiciona informações do hweb na requisição genérica
338
+ genericReq.hwebDev = dev;
339
+ genericReq.hotReloadManager = hotReloadManager;
340
+ const { pathname } = new URL(genericReq.url, `http://${genericReq.headers.host || 'localhost'}`);
341
+ const method = genericReq.method.toUpperCase();
342
+ // 1. Verifica se é WebSocket upgrade para hot reload
343
+ if (pathname === '/hweb-hotreload/' && genericReq.headers.upgrade === 'websocket' && hotReloadManager) {
344
+ // Framework vai chamar o evento 'upgrade' do servidor HTTP
345
+ return;
346
+ }
347
+ // 2. Primeiro verifica se é um arquivo estático da pasta public
348
+ if (pathname !== '/' && !pathname.startsWith('/api/') && !pathname.startsWith('/.hight')) {
349
+ const publicDir = path_1.default.join(dir, 'public');
350
+ const filePath = path_1.default.join(publicDir, pathname);
351
+ if (fs_1.default.existsSync(filePath) && fs_1.default.statSync(filePath).isFile()) {
352
+ const ext = path_1.default.extname(filePath).toLowerCase();
353
+ const contentTypes = {
354
+ '.html': 'text/html',
355
+ '.css': 'text/css',
356
+ '.js': 'application/javascript',
357
+ '.json': 'application/json',
358
+ '.png': 'image/png',
359
+ '.jpg': 'image/jpeg',
360
+ '.jpeg': 'image/jpeg',
361
+ '.gif': 'image/gif',
362
+ '.svg': 'image/svg+xml',
363
+ '.ico': 'image/x-icon',
364
+ '.webp': 'image/webp',
365
+ '.mp4': 'video/mp4',
366
+ '.webm': 'video/webm',
367
+ '.mp3': 'audio/mpeg',
368
+ '.wav': 'audio/wav',
369
+ '.pdf': 'application/pdf',
370
+ '.txt': 'text/plain',
371
+ '.xml': 'application/xml',
372
+ '.zip': 'application/zip'
373
+ };
374
+ genericRes.header('Content-Type', contentTypes[ext] || 'application/octet-stream');
375
+ // Para arquivos estáticos, usamos o método nativo do framework
376
+ if (adapter.type === 'express') {
377
+ res.sendFile(filePath);
378
+ }
379
+ else if (adapter.type === 'fastify') {
380
+ const fileContent = fs_1.default.readFileSync(filePath);
381
+ genericRes.send(fileContent);
382
+ }
383
+ else if (adapter.type === 'native') {
384
+ const fileContent = fs_1.default.readFileSync(filePath);
385
+ genericRes.send(fileContent);
386
+ }
387
+ return;
388
+ }
389
+ }
390
+ // 3. Verifica se é um arquivo estático do .hight
391
+ if (pathname.startsWith('/_hight/')) {
392
+ const staticPath = path_1.default.join(dir, '.hight');
393
+ const filePath = path_1.default.join(staticPath, pathname.replace('/_hight/', ''));
394
+ if (fs_1.default.existsSync(filePath)) {
395
+ const ext = path_1.default.extname(filePath).toLowerCase();
396
+ const contentTypes = {
397
+ '.js': 'application/javascript',
398
+ '.css': 'text/css',
399
+ '.map': 'application/json'
400
+ };
401
+ genericRes.header('Content-Type', contentTypes[ext] || 'text/plain');
402
+ // Para arquivos estáticos, usamos o método nativo do framework
403
+ if (adapter.type === 'express') {
404
+ res.sendFile(filePath);
405
+ }
406
+ else if (adapter.type === 'fastify') {
407
+ const fileContent = fs_1.default.readFileSync(filePath);
408
+ genericRes.send(fileContent);
409
+ }
410
+ else if (adapter.type === 'native') {
411
+ const fileContent = fs_1.default.readFileSync(filePath);
412
+ genericRes.send(fileContent);
413
+ }
414
+ return;
415
+ }
416
+ }
417
+ // 4. REMOVIDO: Verificação de arquivos React UMD - não precisamos mais
418
+ // O React agora será bundlado diretamente no main.js
419
+ // 5. Verifica se é uma rota de API (backend)
420
+ const backendMatch = (0, router_1.findMatchingBackendRoute)(pathname, method);
421
+ if (backendMatch) {
422
+ try {
423
+ const handler = backendMatch.route[method];
424
+ if (handler) {
425
+ const hwebReq = new http_1.HightJSRequest(genericReq);
426
+ // Executa middlewares e depois o handler final
427
+ const hwebRes = await executeMiddlewareChain(backendMatch.route.middleware, handler, hwebReq, backendMatch.params);
428
+ // Aplica a resposta usando o adapter correto
429
+ hwebRes._applyTo(genericRes);
430
+ return;
431
+ }
432
+ }
433
+ catch (error) {
434
+ console_1.default.error(`API route error ${pathname}:`, error);
435
+ genericRes.status(500).text('Internal server error in API');
436
+ return;
437
+ }
438
+ }
439
+ // 6. Por último, tenta renderizar uma página (frontend) ou 404
440
+ const pageMatch = (0, router_1.findMatchingRoute)(pathname);
441
+ if (!pageMatch) {
442
+ // Em vez de enviar texto simples, renderiza a página 404 React
443
+ try {
444
+ // Cria uma "rota falsa" para a página 404
445
+ const notFoundRoute = {
446
+ pattern: '/__404__',
447
+ component: () => null, // Componente vazio, será tratado no cliente
448
+ componentPath: '__404__'
449
+ };
450
+ const html = await (0, renderer_1.render)({
451
+ req: genericReq,
452
+ route: notFoundRoute,
453
+ params: {},
454
+ allRoutes: frontendRoutes
455
+ });
456
+ genericRes.status(404).header('Content-Type', 'text/html').send(html);
457
+ return;
458
+ }
459
+ catch (error) {
460
+ console_1.default.error(`Error rendering page 404:`, error);
461
+ genericRes.status(404).text('Page not found');
462
+ return;
463
+ }
464
+ }
465
+ try {
466
+ const html = await (0, renderer_1.render)({
467
+ req: genericReq,
468
+ route: pageMatch.route,
469
+ params: pageMatch.params,
470
+ allRoutes: frontendRoutes
471
+ });
472
+ genericRes.status(200).header('Content-Type', 'text/html').send(html);
473
+ }
474
+ catch (error) {
475
+ console_1.default.error(`Error rendering page ${pathname}:`, error);
476
+ genericRes.status(500).text('Internal server error');
477
+ }
478
+ };
479
+ },
480
+ // Método para configurar WebSocket upgrade nos servidores Express e Fastify
481
+ setupWebSocket: (server) => {
482
+ // Detecta se é um servidor Express ou Fastify
483
+ const isExpressServer = factory_1.FrameworkAdapterFactory.getCurrentAdapter() instanceof express_1.ExpressAdapter;
484
+ const actualServer = isExpressServer ? server : (server.server || server);
485
+ // Usa o sistema coordenado de WebSocket upgrade que integra hot-reload e rotas de usuário
486
+ (0, router_1.setupWebSocketUpgrade)(actualServer, hotReloadManager);
487
+ },
488
+ stop: () => {
489
+ if (hotReloadManager) {
490
+ hotReloadManager.stop();
491
+ }
492
+ }
493
+ };
494
+ }
@@ -0,0 +1 @@
1
+ export = filename;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ /*
3
+ * This file is part of the HightJS Project.
4
+ * Copyright (c) 2025 itsmuzin
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ const fs = require('fs');
19
+ /**
20
+ * Registra loaders customizados para Node.js
21
+ * Permite importar arquivos não-JS diretamente no servidor
22
+ */
23
+ function registerLoaders() {
24
+ // Loader para arquivos Markdown (.md)
25
+ require.extensions['.md'] = function (module, filename) {
26
+ const content = fs.readFileSync(filename, 'utf8');
27
+ module.exports = content;
28
+ };
29
+ // Loader para arquivos de texto (.txt)
30
+ require.extensions['.txt'] = function (module, filename) {
31
+ const content = fs.readFileSync(filename, 'utf8');
32
+ module.exports = content;
33
+ };
34
+ // Loader para arquivos JSON (já existe nativamente, mas garantimos consistência)
35
+ // require.extensions['.json'] já existe
36
+ // Loader para imagens - retorna o caminho do arquivo
37
+ const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.ico', '.bmp', '.svg'];
38
+ imageExtensions.forEach(ext => {
39
+ require.extensions[ext] = function (module, filename) {
40
+ // No servidor, retornamos o caminho do arquivo
41
+ // O frontend usará o plugin do esbuild para converter em base64
42
+ module.exports = filename;
43
+ };
44
+ });
45
+ }
46
+ module.exports = { registerLoaders };
@@ -0,0 +1,14 @@
1
+ import { RouteConfig } from './types';
2
+ import type { GenericRequest } from './types/framework';
3
+ interface RenderOptions {
4
+ req: GenericRequest;
5
+ route: RouteConfig & {
6
+ componentPath: string;
7
+ };
8
+ params: Record<string, string>;
9
+ allRoutes: (RouteConfig & {
10
+ componentPath: string;
11
+ })[];
12
+ }
13
+ export declare function render({ req, route, params, allRoutes }: RenderOptions): Promise<string>;
14
+ export {};