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.
@@ -0,0 +1,421 @@
1
+ /*
2
+ * This file is part of the HightJS Project.
3
+ * Copyright (c) 2025 itsmuzin
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import React from 'react';
18
+ import { RouteConfig, Metadata } from './types';
19
+ import { getLayout } from './router';
20
+ import type { GenericRequest } from './types/framework';
21
+ import fs from 'fs';
22
+ import path from 'path';
23
+
24
+ // Função para gerar todas as meta tags
25
+ function generateMetaTags(metadata: Metadata): string {
26
+ const tags: string[] = [];
27
+
28
+ // Charset
29
+ tags.push(`<meta charset="${metadata.charset || 'UTF-8'}">`);
30
+
31
+ // Viewport
32
+ tags.push(`<meta name="viewport" content="${metadata.viewport || 'width=device-width, initial-scale=1.0'}">`);
33
+
34
+ // Description
35
+ if (metadata.description) {
36
+ tags.push(`<meta name="description" content="${metadata.description}">`);
37
+ }
38
+
39
+ // Keywords
40
+ if (metadata.keywords) {
41
+ const keywordsStr = Array.isArray(metadata.keywords)
42
+ ? metadata.keywords.join(', ')
43
+ : metadata.keywords;
44
+ tags.push(`<meta name="keywords" content="${keywordsStr}">`);
45
+ }
46
+
47
+ // Author
48
+ if (metadata.author) {
49
+ tags.push(`<meta name="author" content="${metadata.author}">`);
50
+ }
51
+
52
+ // Theme color
53
+ if (metadata.themeColor) {
54
+ tags.push(`<meta name="theme-color" content="${metadata.themeColor}">`);
55
+ }
56
+
57
+ // Robots
58
+ if (metadata.robots) {
59
+ tags.push(`<meta name="robots" content="${metadata.robots}">`);
60
+ }
61
+
62
+ // Canonical
63
+ if (metadata.canonical) {
64
+ tags.push(`<link rel="canonical" href="${metadata.canonical}">`);
65
+ }
66
+
67
+ // Favicon
68
+ if (metadata.favicon) {
69
+ tags.push(`<link rel="icon" href="${metadata.favicon}">`);
70
+ }
71
+
72
+ // Apple Touch Icon
73
+ if (metadata.appleTouchIcon) {
74
+ tags.push(`<link rel="apple-touch-icon" href="${metadata.appleTouchIcon}">`);
75
+ }
76
+
77
+ // Manifest
78
+ if (metadata.manifest) {
79
+ tags.push(`<link rel="manifest" href="${metadata.manifest}">`);
80
+ }
81
+
82
+ // Open Graph
83
+ if (metadata.openGraph) {
84
+ const og = metadata.openGraph;
85
+ if (og.title) tags.push(`<meta property="og:title" content="${og.title}">`);
86
+ if (og.description) tags.push(`<meta property="og:description" content="${og.description}">`);
87
+ if (og.type) tags.push(`<meta property="og:type" content="${og.type}">`);
88
+ if (og.url) tags.push(`<meta property="og:url" content="${og.url}">`);
89
+ if (og.siteName) tags.push(`<meta property="og:site_name" content="${og.siteName}">`);
90
+ if (og.locale) tags.push(`<meta property="og:locale" content="${og.locale}">`);
91
+
92
+ if (og.image) {
93
+ if (typeof og.image === 'string') {
94
+ tags.push(`<meta property="og:image" content="${og.image}">`);
95
+ } else {
96
+ tags.push(`<meta property="og:image" content="${og.image.url}">`);
97
+ if (og.image.width) tags.push(`<meta property="og:image:width" content="${og.image.width}">`);
98
+ if (og.image.height) tags.push(`<meta property="og:image:height" content="${og.image.height}">`);
99
+ if (og.image.alt) tags.push(`<meta property="og:image:alt" content="${og.image.alt}">`);
100
+ }
101
+ }
102
+ }
103
+
104
+ // Twitter Card
105
+ if (metadata.twitter) {
106
+ const tw = metadata.twitter;
107
+ if (tw.card) tags.push(`<meta name="twitter:card" content="${tw.card}">`);
108
+ if (tw.site) tags.push(`<meta name="twitter:site" content="${tw.site}">`);
109
+ if (tw.creator) tags.push(`<meta name="twitter:creator" content="${tw.creator}">`);
110
+ if (tw.title) tags.push(`<meta name="twitter:title" content="${tw.title}">`);
111
+ if (tw.description) tags.push(`<meta name="twitter:description" content="${tw.description}">`);
112
+ if (tw.image) tags.push(`<meta name="twitter:image" content="${tw.image}">`);
113
+ if (tw.imageAlt) tags.push(`<meta name="twitter:image:alt" content="${tw.imageAlt}">`);
114
+ }
115
+
116
+ // Custom meta tags
117
+ if (metadata.other) {
118
+ for (const [key, value] of Object.entries(metadata.other)) {
119
+ tags.push(`<meta name="${key}" content="${value}">`);
120
+ }
121
+ }
122
+
123
+ return tags.join('\n');
124
+ }
125
+
126
+ // Função para ofuscar dados (não é criptografia, apenas ofuscação)
127
+ function obfuscateData(data: any): string {
128
+ // 1. Serializa para JSON minificado
129
+ const jsonStr = JSON.stringify(data);
130
+
131
+ // 2. Converte para base64
132
+ const base64 = Buffer.from(jsonStr).toString('base64');
133
+
134
+ // 3. Adiciona um hash fake no início para parecer um token
135
+ const hash = Buffer.from(Date.now().toString()).toString('base64').substring(0, 8);
136
+
137
+ return `${hash}.${base64}`;
138
+ }
139
+
140
+ // Função para criar script ofuscado
141
+ function createInitialDataScript(data: any): string {
142
+ const obfuscated = obfuscateData(data);
143
+
144
+ // Usa um atributo data-* ao invés de JSON visível
145
+ return `<script id="__hight_data__" type="text/plain" data-h="${obfuscated}"></script>`;
146
+ }
147
+
148
+ // Interface para opções de renderização apenas do cliente
149
+ interface RenderOptions {
150
+ req: GenericRequest;
151
+ route: RouteConfig & { componentPath: string };
152
+ params: Record<string, string>;
153
+ allRoutes: (RouteConfig & { componentPath: string })[];
154
+ }
155
+
156
+ export async function render({ req, route, params, allRoutes }: RenderOptions): Promise<string> {
157
+ const { generateMetadata } = route;
158
+
159
+ // Pega a opção dev e hot reload manager do req
160
+ const isProduction = !(req as any).hwebDev;
161
+ const hotReloadManager = (req as any).hotReloadManager;
162
+
163
+ // Pega o layout se existir
164
+ const layout = getLayout();
165
+
166
+ let metadata: Metadata = { title: 'App hweb' };
167
+
168
+ // Primeiro usa o metadata do layout se existir
169
+ if (layout && layout.metadata) {
170
+ metadata = { ...metadata, ...layout.metadata };
171
+ }
172
+
173
+ // Depois sobrescreve com metadata específico da rota se existir
174
+ if (generateMetadata) {
175
+ const routeMetadata = await Promise.resolve(generateMetadata(params, req));
176
+ metadata = { ...metadata, ...routeMetadata };
177
+ }
178
+
179
+ // Prepara os dados para injetar na janela do navegador
180
+ const initialData = {
181
+ routes: allRoutes.map(r => ({ pattern: r.pattern, componentPath: r.componentPath })),
182
+ initialComponentPath: route.componentPath,
183
+ initialParams: params,
184
+ };
185
+
186
+ // Cria script JSON limpo
187
+ const initialDataScript = createInitialDataScript(initialData);
188
+
189
+ // Script de hot reload apenas em desenvolvimento
190
+ const hotReloadScript = !isProduction && hotReloadManager
191
+ ? hotReloadManager.getClientScript()
192
+ : '';
193
+
194
+ // Gera todas as meta tags
195
+ const metaTags = generateMetaTags(metadata);
196
+
197
+ // Determina quais arquivos JavaScript carregar
198
+ const jsFiles = getJavaScriptFiles(req);
199
+
200
+ const htmlLang = metadata.language || 'pt-BR';
201
+
202
+ // HTML base sem SSR - apenas o container e scripts para client-side rendering
203
+ return `<!DOCTYPE html>
204
+ <html lang="${htmlLang}">
205
+ <head>
206
+ ${metaTags}
207
+ <title>${metadata.title || 'App hweb'}</title>
208
+ </head>
209
+ <body>
210
+ <div id="root"></div>
211
+ ${initialDataScript}
212
+ ${jsFiles}
213
+ ${hotReloadScript}
214
+ </body>
215
+ </html>`;
216
+ }
217
+
218
+ // Função para determinar quais arquivos JavaScript carregar
219
+ function getJavaScriptFiles(req: GenericRequest): string {
220
+ const projectDir = process.cwd();
221
+ const distDir = path.join(projectDir, '.hight');
222
+
223
+ // Verifica se o diretório de build existe
224
+ if (!fs.existsSync(distDir)) {
225
+ // Diretório não existe - build ainda não foi executado
226
+ return getBuildingHTML();
227
+ }
228
+
229
+ try {
230
+ // Verifica se existe um manifesto de chunks (gerado pelo ESBuild com splitting)
231
+ const manifestPath = path.join(distDir, 'manifest.json');
232
+
233
+ if (fs.existsSync(manifestPath)) {
234
+ // Modo chunks - carrega todos os arquivos necessários
235
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
236
+ const scripts = Object.values(manifest)
237
+ .filter((file: any) => file.endsWith('.js'))
238
+ .map((file: any) => `<script src="/_hight/${file}"></script>`)
239
+ .join('');
240
+
241
+ // Se não há arquivos JS no manifesto, build em andamento
242
+ if (!scripts) {
243
+ return getBuildingHTML();
244
+ }
245
+
246
+ return scripts;
247
+ } else {
248
+ // Verifica se existem múltiplos arquivos JS (chunks sem manifesto)
249
+ const jsFiles = fs.readdirSync(distDir)
250
+ .filter(file => file.endsWith('.js') && !file.endsWith('.map'))
251
+ .sort((a, b) => {
252
+ // Ordena para carregar arquivos principais primeiro
253
+ if (a.includes('main')) return -1;
254
+ if (b.includes('main')) return 1;
255
+ if (a.includes('vendor') || a.includes('react')) return -1;
256
+ if (b.includes('vendor') || b.includes('react')) return 1;
257
+ return a.localeCompare(b);
258
+ });
259
+
260
+ // @ts-ignore
261
+ if (jsFiles.length >= 1) {
262
+ // Modo chunks sem manifesto
263
+ return jsFiles
264
+ .map(file => `<script src="/_hight/${file}"></script>`)
265
+ .join('');
266
+ } else {
267
+ // Nenhum arquivo JS encontrado - build em andamento ou erro
268
+ return getBuildingHTML();
269
+ }
270
+ }
271
+ } catch (error) {
272
+ // Erro ao ler diretório - build em andamento ou erro
273
+ return getBuildingHTML();
274
+ }
275
+ }
276
+
277
+ // Função para retornar HTML de "Build em andamento" com auto-refresh
278
+ function getBuildingHTML(): string {
279
+ return `
280
+ <style>
281
+ /*
282
+ * Estilo combinado:
283
+ * - Tema (light/dark) adaptativo como o Next.js
284
+ * - Ícone personalizado
285
+ * - Efeito Glassmorphism para o card
286
+ */
287
+
288
+ html, body {
289
+ margin: 0;
290
+ padding: 0;
291
+ width: 100%;
292
+ height: 100%;
293
+ font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
294
+ -webkit-font-smoothing: antialiased;
295
+ -moz-osx-font-smoothing: grayscale;
296
+ box-sizing: border-box;
297
+ }
298
+
299
+ *, *:before, *:after {
300
+ box-sizing: inherit;
301
+ }
302
+
303
+ /* Tema Claro (Default) */
304
+ body {
305
+ color: #000;
306
+ background: linear-gradient(to bottom, #e9e9e9, #ffffff);
307
+ background-attachment: fixed;
308
+
309
+ display: flex;
310
+ align-items: center;
311
+ justify-content: center;
312
+ min-height: 100vh;
313
+ text-align: center;
314
+ padding: 20px;
315
+ }
316
+
317
+ /* Contêiner com Glassmorphism */
318
+ .building-container {
319
+ width: 100%;
320
+ max-width: 500px;
321
+ padding: 40px 50px;
322
+
323
+ /* Efeito de vidro */
324
+ background: rgba(255, 255, 255, 0.15); /* Mais transparente no modo claro */
325
+ backdrop-filter: blur(12px); /* Um pouco mais de blur */
326
+ -webkit-backdrop-filter: blur(12px);
327
+
328
+ border-radius: 16px;
329
+ border: 1px solid rgba(255, 255, 255, 0.3); /* Borda mais visível no claro */
330
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); /* Sombra mais leve no claro */
331
+ }
332
+
333
+ /* Ícone */
334
+ .building-icon {
335
+ width: 70px; /* Tamanho do ícone */
336
+ height: 70px;
337
+ margin-bottom: 20px; /* Espaço abaixo do ícone */
338
+ vertical-align: middle;
339
+ filter: drop-shadow(0 0 5px rgba(0,0,0,0.1)); /* Leve sombra para destacar */
340
+ }
341
+
342
+ /* Título */
343
+ .building-title {
344
+ font-size: 2.8rem;
345
+ font-weight: 700;
346
+ margin-top: 0; /* Ajusta a margem superior após o ícone */
347
+ margin-bottom: 20px;
348
+ text-shadow: 0 0 10px rgba(0, 0, 0, 0.05); /* Sombra de texto sutil */
349
+ color: inherit; /* Garante que a cor se adapta ao tema */
350
+ }
351
+
352
+ /* Texto de apoio */
353
+ .building-text {
354
+ font-size: 1.15rem;
355
+ margin-bottom: 35px;
356
+ font-weight: 400;
357
+ opacity: 0.9;
358
+ color: inherit; /* Garante que a cor se adapta ao tema */
359
+ }
360
+
361
+ /* Spinner adaptado para light/dark */
362
+ .spinner {
363
+ width: 50px;
364
+ height: 50px;
365
+ margin: 0 auto;
366
+ border-radius: 50%;
367
+
368
+ /* Estilo para Modo Claro */
369
+ border: 5px solid rgba(0, 0, 0, 0.1);
370
+ border-top-color: #000;
371
+
372
+ animation: spin 1s linear infinite;
373
+ }
374
+
375
+ /* Animação de rotação */
376
+ @keyframes spin {
377
+ 0% { transform: rotate(0deg); }
378
+ 100% { transform: rotate(360deg); }
379
+ }
380
+
381
+ /* Tema Escuro (via @media query) */
382
+ @media (prefers-color-scheme: dark) {
383
+ body {
384
+ color: #fff;
385
+ background: linear-gradient(to bottom, #222, #000);
386
+ }
387
+
388
+ .building-container {
389
+ background: rgba(255, 255, 255, 0.05); /* Mais opaco no modo escuro */
390
+ border: 1px solid rgba(255, 255, 255, 0.1); /* Borda mais sutil no escuro */
391
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3); /* Sombra mais forte no escuro */
392
+ }
393
+
394
+ .building-title {
395
+ text-shadow: 0 0 10px rgba(255, 255, 255, 0.1);
396
+ }
397
+
398
+ .building-icon {
399
+ filter: drop-shadow(0 0 5px rgba(255,255,255,0.1));
400
+ }
401
+
402
+ .spinner {
403
+ border: 5px solid rgba(255, 255, 255, 0.1);
404
+ border-top-color: #fff;
405
+ }
406
+ }
407
+ </style>
408
+ <div class="building-container">
409
+ <!-- Ícone da imagem --><img src="https://repository-images.githubusercontent.com/1069175740/e5c59d3a-e1fd-446c-a89f-785ed08f6a16" alt="HightJS Logo" class="building-icon">
410
+
411
+ <div class="building-title">HightJS</div>
412
+ <div class="building-text">Build in progress...</div>
413
+ <div class="spinner"></div>
414
+ </div>
415
+ <script>
416
+ // Auto-refresh a cada 2 segundos para verificar se o build terminou
417
+ setTimeout(() => {
418
+ window.location.reload();
419
+ }, 2000);
420
+ </script>`;
421
+ }