hightjs 0.2.53 → 0.3.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.
package/dist/index.js CHANGED
@@ -38,6 +38,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.app = exports.FrameworkAdapterFactory = exports.FastifyAdapter = exports.ExpressAdapter = exports.HightJSResponse = exports.HightJSRequest = void 0;
40
40
  exports.default = hweb;
41
+ /*
42
+ * This file is part of the HightJS Project.
43
+ * Copyright (c) 2025 itsmuzin
44
+ *
45
+ * Licensed under the Apache License, Version 2.0 (the "License");
46
+ * you may not use this file except in compliance with the License.
47
+ * You may obtain a copy of the License at
48
+ *
49
+ * http://www.apache.org/licenses/LICENSE-2.0
50
+ *
51
+ * Unless required by applicable law or agreed to in writing, software
52
+ * distributed under the License is distributed on an "AS IS" BASIS,
53
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
54
+ * See the License for the specific language governing permissions and
55
+ * limitations under the License.
56
+ */
41
57
  const path_1 = __importDefault(require("path"));
42
58
  const fs_1 = __importDefault(require("fs"));
43
59
  const express_1 = require("./adapters/express");
@@ -163,6 +179,8 @@ import '${relativeEntryPath}';
163
179
  }
164
180
  function hweb(options) {
165
181
  const { dev = true, dir = process.cwd(), port = 3000 } = options;
182
+ // @ts-ignore
183
+ process.hight = options;
166
184
  const userWebDir = path_1.default.join(dir, 'src', 'web');
167
185
  const userWebRoutesDir = path_1.default.join(userWebDir, 'routes');
168
186
  const userBackendRoutesDir = path_1.default.join(userWebDir, 'backend', 'routes');
@@ -175,8 +193,6 @@ function hweb(options) {
175
193
  * @returns Resposta do middleware ou handler final
176
194
  */
177
195
  async function executeMiddlewareChain(middlewares, finalHandler, request, params) {
178
- // @ts-ignore
179
- process.hight = options;
180
196
  if (!middlewares || middlewares.length === 0) {
181
197
  // Não há middlewares, executa diretamente o handler final
182
198
  return await finalHandler(request, params);
@@ -230,6 +246,15 @@ function hweb(options) {
230
246
  regenerateEntryFile();
231
247
  });
232
248
  }
249
+ const now = Date.now();
250
+ const timee = console_1.default.dynamicLine(` ${console_1.Colors.BgYellow} router ${console_1.Colors.Reset} Carregando rotas e componentes do frontend e backend`);
251
+ const spinnerFrames1 = ['|', '/', '-', '\\'];
252
+ let frameIndex1 = 0;
253
+ const spinner1 = setInterval(() => {
254
+ console_1.default.info('aaaa');
255
+ timee.update(` ${console_1.Colors.FgYellow}${spinnerFrames1[frameIndex1]}${console_1.Colors.Reset} Carregando rotas e componentes...`);
256
+ frameIndex1 = (frameIndex1 + 1) % spinnerFrames1.length;
257
+ }, 100); // muda a cada 100ms
233
258
  // ORDEM IMPORTANTE: Carrega TUDO antes de criar o arquivo de entrada
234
259
  frontendRoutes = (0, router_1.loadRoutes)(userWebRoutesDir);
235
260
  (0, router_1.loadBackendRoutes)(userBackendRoutesDir);
@@ -241,31 +266,30 @@ function hweb(options) {
241
266
  const outDir = path_1.default.join(dir, 'hweb-dist');
242
267
  fs_1.default.mkdirSync(outDir, { recursive: true });
243
268
  entryPoint = createEntryFile(dir, frontendRoutes);
244
- // Usa chunks quando há muitas rotas ou o projeto é grande
245
- const shouldUseChunks = frontendRoutes.length > 5 || isLargeProject(dir);
246
- if (shouldUseChunks) {
247
- const outDir = path_1.default.join(dir, 'hweb-dist');
248
- if (isProduction) {
249
- await (0, builder_1.buildWithChunks)(entryPoint, outDir, isProduction);
250
- console_1.default.info(`✅ Build com chunks finalizado! ${frontendRoutes.length} rotas processadas.`);
251
- }
252
- else {
253
- (0, builder_1.watchWithChunks)(entryPoint, outDir, hotReloadManager).catch(err => {
254
- console_1.default.error(`Erro ao iniciar o watch com chunks`, err);
255
- });
256
- console_1.default.info(`🚀 Modo watch com chunks ativo para ${frontendRoutes.length} rotas.`);
257
- }
269
+ clearInterval(spinner1);
270
+ timee.end(` ${console_1.Colors.BgGreen} router ${console_1.Colors.Reset} Rotas e componentes carregados em ${Date.now() - now}ms`);
271
+ if (isProduction) {
272
+ const time = console_1.default.dynamicLine(` ${console_1.Colors.BgYellow} build ${console_1.Colors.Reset} Iniciando build do cliente para produção`);
273
+ // Spinner
274
+ const spinnerFrames = ['|', '/', '-', '\\'];
275
+ let frameIndex = 0;
276
+ const spinner = setInterval(() => {
277
+ time.update(` ${console_1.Colors.FgYellow}${spinnerFrames[frameIndex]}${console_1.Colors.Reset} Buildando para produção...`);
278
+ frameIndex = (frameIndex + 1) % spinnerFrames.length;
279
+ }, 100); // muda a cada 100ms
280
+ const now = Date.now();
281
+ await (0, builder_1.buildWithChunks)(entryPoint, outDir, isProduction);
282
+ const elapsed = Date.now() - now;
283
+ clearInterval(spinner); // para o spinner
284
+ time.update(""); // limpa a linha
285
+ time.end(` ${console_1.Colors.BgGreen} build ${console_1.Colors.Reset} Build do cliente concluído em ${elapsed}ms`);
258
286
  }
259
287
  else {
260
- outfile = path_1.default.join(dir, 'hweb-dist', 'main.js');
261
- if (isProduction) {
262
- await (0, builder_1.build)(entryPoint, outfile, isProduction);
263
- }
264
- else {
265
- (0, builder_1.watch)(entryPoint, outfile, hotReloadManager).catch(err => {
266
- console_1.default.error(`Erro ao iniciar o watch`, err);
267
- });
268
- }
288
+ const time = console_1.default.dynamicLine(` ${console_1.Colors.BgYellow} watcher ${console_1.Colors.Reset} Iniciando watch do cliente`);
289
+ (0, builder_1.watchWithChunks)(entryPoint, outDir, hotReloadManager).catch(err => {
290
+ console_1.default.error(`Erro ao iniciar o watch`, err);
291
+ });
292
+ time.end(` ${console_1.Colors.BgGreen} watcher ${console_1.Colors.Reset} Watch do cliente iniciado`);
269
293
  }
270
294
  },
271
295
  executeInstrumentation: () => {
package/dist/router.js CHANGED
@@ -16,6 +16,22 @@ exports.getNotFound = getNotFound;
16
16
  exports.processWebSocketRoutes = processWebSocketRoutes;
17
17
  exports.findMatchingWebSocketRoute = findMatchingWebSocketRoute;
18
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
+ */
19
35
  const fs_1 = __importDefault(require("fs"));
20
36
  const path_1 = __importDefault(require("path"));
21
37
  const ws_1 = require("ws");
package/dist/types.d.ts CHANGED
@@ -20,6 +20,12 @@ export interface HightJSOptions {
20
20
  port?: number;
21
21
  dir?: string;
22
22
  framework?: 'express' | 'fastify' | 'native';
23
+ ssl?: {
24
+ redirectPort: number;
25
+ key: string;
26
+ cert: string;
27
+ ca?: string;
28
+ };
23
29
  }
24
30
  export interface Metadata {
25
31
  title?: string;
package/docs/cli.md CHANGED
@@ -2,16 +2,15 @@
2
2
 
3
3
  Comandos principais:
4
4
 
5
- | Comando | Descrição |
6
- |--------------------|-------------------------------------------|
7
- | `npx hight dev` | Modo desenvolvimento (hot reload) |
8
- | `npx hight start` | Modo produção (usa build gerado) |
5
+ | Comando | Descrição |
6
+ |-------------------|----------------------|
7
+ | `npx hight dev` | Modo desenvolvimento |
8
+ | `npx hight start` | Modo produção |
9
9
 
10
10
  ## Opções
11
11
 
12
12
  - `--port` Porta (default 3000)
13
13
  - `--hostname` Host (default 0.0.0.0)
14
- - `--framework` `native` | `express` | `fastify` (default: native)
15
14
 
16
15
  ## Produção
17
16
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hightjs",
3
- "version": "0.2.53",
3
+ "version": "0.3.0",
4
4
  "description": "HightJS is a high-level framework for building web applications with ease and speed. It provides a robust set of tools and features to streamline development and enhance productivity.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -21,6 +21,7 @@ export class ExpressAdapter implements FrameworkAdapter {
21
21
  type = 'express' as const;
22
22
 
23
23
  parseRequest(req: ExpressRequest): GenericRequest {
24
+
24
25
  return {
25
26
  method: req.method,
26
27
  url: req.url,
@@ -29,7 +30,7 @@ export class ExpressAdapter implements FrameworkAdapter {
29
30
  query: req.query as Record<string, any>,
30
31
  params: req.params,
31
32
  cookies: req.cookies || {},
32
- raw: req
33
+ raw: req,
33
34
  };
34
35
  }
35
36
 
@@ -48,7 +48,6 @@ export class DynamicLine {
48
48
  }
49
49
  }
50
50
 
51
-
52
51
  export enum Colors {
53
52
  Reset = "\x1b[0m",
54
53
  Bright = "\x1b[1m",
@@ -66,6 +65,7 @@ export enum Colors {
66
65
  FgMagenta = "\x1b[35m",
67
66
  FgCyan = "\x1b[36m",
68
67
  FgWhite = "\x1b[37m",
68
+ FgGray = "\x1b[90m", // ← adicionado
69
69
 
70
70
  BgBlack = "\x1b[40m",
71
71
  BgRed = "\x1b[41m",
@@ -75,8 +75,10 @@ export enum Colors {
75
75
  BgMagenta = "\x1b[45m",
76
76
  BgCyan = "\x1b[46m",
77
77
  BgWhite = "\x1b[47m",
78
+ BgGray = "\x1b[100m", // ← adicionado
78
79
  }
79
80
 
81
+
80
82
  export enum Levels {
81
83
  ERROR = "ERROR",
82
84
  WARN = "WARN",
@@ -194,27 +196,27 @@ export default class Console {
194
196
  static success(...args: any[]): void { this.log(Levels.SUCCESS, ...args); }
195
197
  static debug(...args: any[]): void { this.log(Levels.DEBUG, ...args); }
196
198
 
197
- static logCustomLevel(levelName: string, without: boolean = true, ...args: any[]): void {
198
- if (without) { this.logWithout(levelName as Levels, ...args); }
199
- else { this.log(levelName as Levels, ...args); }
199
+ static logCustomLevel(levelName: string, without: boolean = true, color?: Colors, ...args: any[]): void {
200
+ if (without) { this.logWithout(levelName as Levels, color, ...args); }
201
+ else { this.log(levelName as Levels, color, ...args); }
200
202
  }
201
203
 
202
- static logWithout(level: Levels, ...args: any[]): void {
203
- const color = level === Levels.ERROR ? Colors.FgRed : level === Levels.WARN ? Colors.FgYellow : level === Levels.INFO ? Colors.FgMagenta : level === Levels.SUCCESS ? Colors.FgGreen : Colors.FgCyan;
204
+ static logWithout(level: Levels, colors?:Colors, ...args: any[]): void {
205
+ const color = colors || level === Levels.ERROR ? Colors.BgRed : level === Levels.WARN ? Colors.BgYellow : level === Levels.INFO ? Colors.BgMagenta : level === Levels.SUCCESS ? Colors.BgGreen : Colors.BgCyan;
204
206
  let output = "";
205
207
  for (const arg of args) {
206
208
  let msg = (arg instanceof Error) ? arg.stack : (typeof arg === 'string') ? arg : JSON.stringify(arg, null, 2);
207
- if (msg) output += ` ${color}${level} ${Colors.Reset}${msg}\n`;
209
+ if (msg) output += ` ${color} ${level} ${Colors.Reset} ${msg}\n`;
208
210
  }
209
211
  this.writeStatic(output);
210
212
  }
211
213
 
212
- static log(level: Levels, ...args: any[]): void {
213
- const color = level === Levels.ERROR ? Colors.FgRed : level === Levels.WARN ? Colors.FgYellow : level === Levels.INFO ? Colors.FgMagenta : level === Levels.SUCCESS ? Colors.FgGreen : Colors.FgCyan;
214
+ static log(level: Levels, colors?: Colors, ...args: any[]): void {
215
+ const color = colors || level === Levels.ERROR ? Colors.BgRed : level === Levels.WARN ? Colors.BgYellow : level === Levels.INFO ? Colors.BgMagenta : level === Levels.SUCCESS ? Colors.BgGreen : Colors.BgCyan;
214
216
  let output = "\n";
215
217
  for (const arg of args) {
216
218
  let msg = (arg instanceof Error) ? arg.stack : (typeof arg === 'string') ? arg : JSON.stringify(arg, null, 2);
217
- if (msg) output += ` ${color}${level} ${Colors.Reset}${msg}\n`;
219
+ if (msg) output += ` ${color} ${level} ${Colors.Reset} ${msg}\n`;
218
220
  }
219
221
  this.writeStatic(output);
220
222
  }
@@ -17,6 +17,7 @@
17
17
  import { HightJSRequest, HightJSResponse } from '../api/http';
18
18
  import type { AuthConfig } from './types';
19
19
  import { HWebAuth } from './core';
20
+ import Console from "../api/console";
20
21
 
21
22
  /**
22
23
  * Cria o handler catch-all para /api/auth/[...value]
@@ -22,25 +22,76 @@
22
22
  require('ts-node').register();
23
23
 
24
24
  const { program } = require('commander');
25
- const teste = require("../helpers");
26
- const fs = require('fs');
27
- const path = require('path');
25
+
28
26
 
29
27
  program
30
28
  .version('1.0.0')
31
29
  .description('CLI para gerenciar a aplicação.');
32
30
 
31
+ // --- Comando DEV ---
32
+ const fs = require('fs');
33
+ const path = require('path');
34
+ // 'program' já deve estar definido no seu arquivo
35
+ // const { program } = require('commander');
36
+
37
+ /**
38
+ * Função centralizada para iniciar a aplicação
39
+ * @param {object} options - Opções vindas do commander
40
+ * @param {boolean} isDev - Define se é modo de desenvolvimento
41
+ */
42
+ function initializeApp(options, isDev) {
43
+ const appOptions = {
44
+ dev: isDev,
45
+ port: options.port,
46
+ hostname: options.hostname,
47
+ framework: 'native',
48
+ ssl: null, // Default
49
+ };
50
+
51
+ // 1. Verifica se a flag --ssl foi ativada
52
+ if (options.ssl) {
53
+ const C = require("../api/console")
54
+ const { Levels } = C;
55
+ const Console = C.default
56
+ const sslDir = path.resolve(process.cwd(), 'certs');
57
+ const keyPath = path.join(sslDir, 'key.pem'); // Padrão 1: key.pem
58
+ const certPath = path.join(sslDir, 'cert.pem'); // Padrão 2: cert.pem
59
+ // (Você pode mudar para 'cert.key' se preferir, apenas ajuste os nomes aqui)
60
+
61
+ // 2. Verifica se os arquivos existem
62
+ if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
63
+ appOptions.ssl = {
64
+ key: keyPath,
65
+ cert: certPath
66
+ };
67
+
68
+ // 3. Adiciona a porta de redirecionamento (útil para o initNativeServer)
69
+ appOptions.ssl.redirectPort = options.httpRedirectPort || 80;
70
+
71
+ } else {
72
+ Console.logWithout(Levels.ERROR, null, `Certifique-se que './certs/key.pem' e './certs/cert.pem' existem.`, `Flag --ssl foi usada, mas os arquivos não foram encontrados.`)
73
+
74
+
75
+ process.exit(1); // Encerra o processo com erro
76
+ }
77
+ }
78
+
79
+ // 4. Inicia o helper com as opções
80
+ const teste = require("../helpers");
81
+ const t = teste.default(appOptions);
82
+ t.init();
83
+ }
84
+
33
85
  // --- Comando DEV ---
34
86
  program
35
87
  .command('dev')
36
88
  .description('Inicia a aplicação em modo de desenvolvimento.')
37
89
  .option('-p, --port <number>', 'Especifica a porta para rodar', '3000')
38
90
  .option('-H, --hostname <string>', 'Especifica o hostname para rodar', '0.0.0.0')
39
- .option('-f, --framework <string>', 'Especifica o framework a ser usado (native/express/fastify)', 'native')
91
+ .option('--ssl', 'Ativa o modo HTTPS/SSL (requer ./ssl/key.pem e ./ssl/cert.pem)')
92
+ .option('--http-redirect-port <number>', 'Porta para redirecionamento HTTP->HTTPS', '80')
40
93
  .action((options) => {
41
- const teste = require("../helpers");
42
- const t = teste.default({ dev: true, port: options.port, hostname: options.hostname, framework: options.framework });
43
- t.init()
94
+ initializeApp(options, true); // Chama a função com dev: true
44
95
  });
45
96
 
46
97
  // --- Comando START (Produção) ---
@@ -49,11 +100,10 @@ program
49
100
  .description('Inicia a aplicação em modo produção.')
50
101
  .option('-p, --port <number>', 'Especifica a porta para rodar', '3000')
51
102
  .option('-H, --hostname <string>', 'Especifica o hostname para rodar', '0.0.0.0')
52
- .option('-f, --framework <string>', 'Especifica o framework a ser usado (native/express/fastify)', 'native')
103
+ .option('--ssl', 'Ativa o modo HTTPS/SSL (requer ./ssl/key.pem e ./ssl/cert.pem)')
104
+ .option('--http-redirect-port <number>', 'Porta para redirecionamento HTTP->HTTPS', '80')
53
105
  .action((options) => {
54
- const teste = require("../helpers");
55
- const t = teste.default({ dev: false, port: options.port, hostname: options.hostname, framework: options.framework });
56
- t.init()
106
+ initializeApp(options, false); // Chama a função com dev: false
57
107
  });
58
108
 
59
109
  // --- Comando EXPORT ---