hightjs 0.2.43 → 0.2.45
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/README.md +22 -562
- package/dist/bin/hightjs.js +393 -0
- package/dist/router.js +0 -1
- package/docs/README.md +59 -0
- package/docs/adapters.md +7 -0
- package/docs/arquivos-especiais.md +10 -0
- package/docs/autenticacao.md +212 -0
- package/docs/checklist.md +9 -0
- package/docs/cli.md +21 -0
- package/docs/estrutura.md +20 -0
- package/docs/faq.md +10 -0
- package/docs/hot-reload.md +5 -0
- package/docs/middlewares.md +73 -0
- package/docs/rotas-backend.md +45 -0
- package/docs/rotas-frontend.md +66 -0
- package/docs/seguranca.md +8 -0
- package/docs/websocket.md +45 -0
- package/package.json +1 -1
- package/src/bin/hightjs.js +475 -0
- package/src/router.ts +0 -1
- package/dist/adapters/starters/express.d.ts +0 -0
- package/dist/adapters/starters/express.js +0 -1
- package/dist/adapters/starters/factory.d.ts +0 -0
- package/dist/adapters/starters/factory.js +0 -1
- package/dist/adapters/starters/fastify.d.ts +0 -0
- package/dist/adapters/starters/fastify.js +0 -1
- package/dist/adapters/starters/index.d.ts +0 -0
- package/dist/adapters/starters/index.js +0 -1
- package/dist/adapters/starters/native.d.ts +0 -0
- package/dist/adapters/starters/native.js +0 -1
- package/dist/auth/example.d.ts +0 -40
- package/dist/auth/example.js +0 -104
- package/dist/client/ErrorBoundary.d.ts +0 -16
- package/dist/client/ErrorBoundary.js +0 -181
- package/dist/client/routerContext.d.ts +0 -26
- package/dist/client/routerContext.js +0 -62
- package/dist/eslint/index.d.ts +0 -32
- package/dist/eslint/index.js +0 -15
- package/dist/eslint/use-client-rule.d.ts +0 -19
- package/dist/eslint/use-client-rule.js +0 -99
- package/dist/eslintSetup.d.ts +0 -0
- package/dist/eslintSetup.js +0 -1
- package/dist/example/src/web/routes/index.d.ts +0 -3
- package/dist/example/src/web/routes/index.js +0 -15
- package/dist/hightweb-global.d.ts +0 -0
- package/dist/hightweb-global.js +0 -1
- package/dist/ssl/selfSigned.d.ts +0 -0
- package/dist/ssl/selfSigned.js +0 -1
- package/dist/types/websocket.d.ts +0 -27
- package/dist/types/websocket.js +0 -2
- package/dist/typescript/use-client-plugin.d.ts +0 -5
- package/dist/typescript/use-client-plugin.js +0 -113
- package/dist/validation.d.ts +0 -0
- package/dist/validation.js +0 -1
- package/src/hightweb-global.ts +0 -1
- package/src/ssl/selfSigned.ts +0 -2
package/dist/bin/hightjs.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
require('ts-node').register();
|
|
5
5
|
const { program } = require('commander');
|
|
6
6
|
const teste = require("../helpers");
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
7
9
|
program
|
|
8
10
|
.version('1.0.0')
|
|
9
11
|
.description('CLI para gerenciar a aplicação.');
|
|
@@ -31,5 +33,396 @@ program
|
|
|
31
33
|
const t = teste.default({ dev: false, port: options.port, hostname: options.hostname, framework: options.framework });
|
|
32
34
|
t.init();
|
|
33
35
|
});
|
|
36
|
+
// --- Comando EXPORT ---
|
|
37
|
+
program
|
|
38
|
+
.command('export')
|
|
39
|
+
.description('Exporta a aplicação como HTML estático na pasta "exported".')
|
|
40
|
+
.option('-o, --output <path>', 'Especifica o diretório de saída', 'exported')
|
|
41
|
+
.action(async (options) => {
|
|
42
|
+
const projectDir = process.cwd();
|
|
43
|
+
const exportDir = path.join(projectDir, options.output);
|
|
44
|
+
console.log('🚀 Iniciando exportação...\n');
|
|
45
|
+
try {
|
|
46
|
+
// 1. Cria a pasta exported (limpa se já existir)
|
|
47
|
+
if (fs.existsSync(exportDir)) {
|
|
48
|
+
console.log('🗑️ Limpando pasta de exportação existente...');
|
|
49
|
+
fs.rmSync(exportDir, { recursive: true, force: true });
|
|
50
|
+
}
|
|
51
|
+
fs.mkdirSync(exportDir, { recursive: true });
|
|
52
|
+
console.log('✅ Pasta de exportação criada\n');
|
|
53
|
+
// 2. Inicializa e prepara o build
|
|
54
|
+
console.log('🔨 Buildando aplicação...');
|
|
55
|
+
const teste = require("../helpers");
|
|
56
|
+
const app = teste.default({ dev: false, port: 3000, hostname: '0.0.0.0', framework: 'native' });
|
|
57
|
+
await app.prepare();
|
|
58
|
+
console.log('✅ Build concluído\n');
|
|
59
|
+
// 3. Copia a pasta hweb-dist para exported
|
|
60
|
+
const distDir = path.join(projectDir, 'hweb-dist');
|
|
61
|
+
if (fs.existsSync(distDir)) {
|
|
62
|
+
console.log('📦 Copiando arquivos JavaScript...');
|
|
63
|
+
const exportDistDir = path.join(exportDir, 'hweb-dist');
|
|
64
|
+
fs.mkdirSync(exportDistDir, { recursive: true });
|
|
65
|
+
const files = fs.readdirSync(distDir);
|
|
66
|
+
files.forEach(file => {
|
|
67
|
+
fs.copyFileSync(path.join(distDir, file), path.join(exportDistDir, file));
|
|
68
|
+
});
|
|
69
|
+
console.log('✅ Arquivos JavaScript copiados\n');
|
|
70
|
+
}
|
|
71
|
+
// 4. Copia a pasta public se existir
|
|
72
|
+
const publicDir = path.join(projectDir, 'public');
|
|
73
|
+
if (fs.existsSync(publicDir)) {
|
|
74
|
+
console.log('📁 Copiando arquivos públicos...');
|
|
75
|
+
const exportPublicDir = path.join(exportDir, 'public');
|
|
76
|
+
function copyRecursive(src, dest) {
|
|
77
|
+
if (fs.statSync(src).isDirectory()) {
|
|
78
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
79
|
+
fs.readdirSync(src).forEach(file => {
|
|
80
|
+
copyRecursive(path.join(src, file), path.join(dest, file));
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
fs.copyFileSync(src, dest);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
copyRecursive(publicDir, exportPublicDir);
|
|
88
|
+
console.log('✅ Arquivos públicos copiados\n');
|
|
89
|
+
}
|
|
90
|
+
// 5. Gera o index.html
|
|
91
|
+
console.log('📝 Gerando index.html...');
|
|
92
|
+
const { render } = require('../renderer');
|
|
93
|
+
const { loadRoutes, loadLayout, loadNotFound } = require('../router');
|
|
94
|
+
// Carrega as rotas para gerar o HTML
|
|
95
|
+
const userWebDir = path.join(projectDir, 'src', 'web');
|
|
96
|
+
const userWebRoutesDir = path.join(userWebDir, 'routes');
|
|
97
|
+
const routes = loadRoutes(userWebRoutesDir);
|
|
98
|
+
loadLayout(userWebDir);
|
|
99
|
+
loadNotFound(userWebDir);
|
|
100
|
+
// Gera HTML para a rota raiz
|
|
101
|
+
const rootRoute = routes.find(r => r.pattern === '/') || routes[0];
|
|
102
|
+
if (rootRoute) {
|
|
103
|
+
const mockReq = {
|
|
104
|
+
url: '/',
|
|
105
|
+
method: 'GET',
|
|
106
|
+
headers: { host: 'localhost' },
|
|
107
|
+
hwebDev: false,
|
|
108
|
+
hotReloadManager: null
|
|
109
|
+
};
|
|
110
|
+
const html = await render({
|
|
111
|
+
req: mockReq,
|
|
112
|
+
route: rootRoute,
|
|
113
|
+
params: {},
|
|
114
|
+
allRoutes: routes
|
|
115
|
+
});
|
|
116
|
+
const indexPath = path.join(exportDir, 'index.html');
|
|
117
|
+
fs.writeFileSync(indexPath, html, 'utf8');
|
|
118
|
+
console.log('✅ index.html gerado\n');
|
|
119
|
+
}
|
|
120
|
+
console.log('🎉 Exportação concluída com sucesso!');
|
|
121
|
+
console.log(`📂 Arquivos exportados em: ${exportDir}\n`);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
console.error('❌ Erro durante a exportação:', error.message);
|
|
125
|
+
process.exit(1);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
// --- Comando MIGRATE FROM NEXTJS ---
|
|
129
|
+
program
|
|
130
|
+
.command('migrate-from-nextjs')
|
|
131
|
+
.description('Migra um projeto Next.js para HightJS.')
|
|
132
|
+
.option('-s, --source <path>', 'Caminho do projeto Next.js', process.cwd())
|
|
133
|
+
.option('-o, --output <path>', 'Diretório de saída para o projeto HightJS', './hightjs-project')
|
|
134
|
+
.action(async (options) => {
|
|
135
|
+
const sourcePath = path.resolve(options.source);
|
|
136
|
+
const outputPath = path.resolve(options.output);
|
|
137
|
+
console.log('🚀 Iniciando migração de Next.js para HightJS...\n');
|
|
138
|
+
console.log(`📂 Origem: ${sourcePath}`);
|
|
139
|
+
console.log(`📂 Destino: ${outputPath}\n`);
|
|
140
|
+
try {
|
|
141
|
+
// Verifica se o diretório de origem existe
|
|
142
|
+
if (!fs.existsSync(sourcePath)) {
|
|
143
|
+
throw new Error(`Diretório de origem não encontrado: ${sourcePath}`);
|
|
144
|
+
}
|
|
145
|
+
// Verifica se é um projeto Next.js
|
|
146
|
+
const nextConfigPath = path.join(sourcePath, 'next.config.js');
|
|
147
|
+
const nextConfigMjsPath = path.join(sourcePath, 'next.config.mjs');
|
|
148
|
+
const packageJsonPath = path.join(sourcePath, 'package.json');
|
|
149
|
+
if (!fs.existsSync(nextConfigPath) && !fs.existsSync(nextConfigMjsPath) && !fs.existsSync(packageJsonPath)) {
|
|
150
|
+
throw new Error('Não foi encontrado um projeto Next.js válido no diretório especificado.');
|
|
151
|
+
}
|
|
152
|
+
// Cria o diretório de saída
|
|
153
|
+
if (fs.existsSync(outputPath)) {
|
|
154
|
+
console.log('⚠️ Diretório de destino já existe. Limpando...');
|
|
155
|
+
fs.rmSync(outputPath, { recursive: true, force: true });
|
|
156
|
+
}
|
|
157
|
+
fs.mkdirSync(outputPath, { recursive: true });
|
|
158
|
+
// 1. Cria estrutura básica do HightJS
|
|
159
|
+
console.log('📁 Criando estrutura de diretórios...');
|
|
160
|
+
const srcDir = path.join(outputPath, 'src');
|
|
161
|
+
const webDir = path.join(srcDir, 'web');
|
|
162
|
+
const routesDir = path.join(webDir, 'routes');
|
|
163
|
+
const publicDir = path.join(outputPath, 'public');
|
|
164
|
+
fs.mkdirSync(srcDir, { recursive: true });
|
|
165
|
+
fs.mkdirSync(webDir, { recursive: true });
|
|
166
|
+
fs.mkdirSync(routesDir, { recursive: true });
|
|
167
|
+
fs.mkdirSync(publicDir, { recursive: true });
|
|
168
|
+
// 2. Copia arquivos públicos
|
|
169
|
+
console.log('📦 Copiando arquivos públicos...');
|
|
170
|
+
const nextPublicDir = path.join(sourcePath, 'public');
|
|
171
|
+
if (fs.existsSync(nextPublicDir)) {
|
|
172
|
+
copyDirectory(nextPublicDir, publicDir);
|
|
173
|
+
}
|
|
174
|
+
// 3. Migra páginas do Next.js para rotas do HightJS
|
|
175
|
+
console.log('🔄 Migrando páginas para rotas...');
|
|
176
|
+
const nextPagesDir = path.join(sourcePath, 'pages');
|
|
177
|
+
const nextAppDir = path.join(sourcePath, 'app');
|
|
178
|
+
const nextSrcPagesDir = path.join(sourcePath, 'src', 'pages');
|
|
179
|
+
const nextSrcAppDir = path.join(sourcePath, 'src', 'app');
|
|
180
|
+
let pagesDir = null;
|
|
181
|
+
let isAppRouter = false;
|
|
182
|
+
if (fs.existsSync(nextAppDir)) {
|
|
183
|
+
pagesDir = nextAppDir;
|
|
184
|
+
isAppRouter = true;
|
|
185
|
+
console.log('✅ Detectado Next.js App Router');
|
|
186
|
+
}
|
|
187
|
+
else if (fs.existsSync(nextSrcAppDir)) {
|
|
188
|
+
pagesDir = nextSrcAppDir;
|
|
189
|
+
isAppRouter = true;
|
|
190
|
+
console.log('✅ Detectado Next.js App Router (em src/)');
|
|
191
|
+
}
|
|
192
|
+
else if (fs.existsSync(nextPagesDir)) {
|
|
193
|
+
pagesDir = nextPagesDir;
|
|
194
|
+
console.log('✅ Detectado Next.js Pages Router');
|
|
195
|
+
}
|
|
196
|
+
else if (fs.existsSync(nextSrcPagesDir)) {
|
|
197
|
+
pagesDir = nextSrcPagesDir;
|
|
198
|
+
console.log('✅ Detectado Next.js Pages Router (em src/)');
|
|
199
|
+
}
|
|
200
|
+
if (pagesDir) {
|
|
201
|
+
if (isAppRouter) {
|
|
202
|
+
migrateAppRouter(pagesDir, routesDir);
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
migratePagesRouter(pagesDir, routesDir);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// 5. Cria package.json
|
|
209
|
+
console.log('📄 Criando package.json...');
|
|
210
|
+
let originalPackageJson = {};
|
|
211
|
+
if (fs.existsSync(packageJsonPath)) {
|
|
212
|
+
originalPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
|
213
|
+
}
|
|
214
|
+
const newPackageJson = {
|
|
215
|
+
name: originalPackageJson.name || 'hightjs-app',
|
|
216
|
+
version: '1.0.0',
|
|
217
|
+
description: originalPackageJson.description || 'HightJS application migrated from Next.js',
|
|
218
|
+
scripts: {
|
|
219
|
+
dev: 'hight dev',
|
|
220
|
+
start: 'hight start',
|
|
221
|
+
build: 'hight export',
|
|
222
|
+
...originalPackageJson.scripts
|
|
223
|
+
},
|
|
224
|
+
dependencies: {
|
|
225
|
+
hightjs: 'latest',
|
|
226
|
+
react: originalPackageJson.dependencies?.react || '^18.2.0',
|
|
227
|
+
'react-dom': originalPackageJson.dependencies?.['react-dom'] || '^18.2.0',
|
|
228
|
+
...filterDependencies(originalPackageJson.dependencies)
|
|
229
|
+
},
|
|
230
|
+
devDependencies: {
|
|
231
|
+
'@types/node': '^20.11.24',
|
|
232
|
+
'@types/react': '^18.2.0',
|
|
233
|
+
'@types/react-dom': '^18.2.0',
|
|
234
|
+
typescript: '^5.3.3',
|
|
235
|
+
...filterDependencies(originalPackageJson.devDependencies)
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
fs.writeFileSync(path.join(outputPath, 'package.json'), JSON.stringify(newPackageJson, null, 2), 'utf8');
|
|
239
|
+
// 6. Cria tsconfig.json
|
|
240
|
+
console.log('⚙️ Criando tsconfig.json...');
|
|
241
|
+
const tsConfig = {
|
|
242
|
+
compilerOptions: {
|
|
243
|
+
target: 'ES2020',
|
|
244
|
+
lib: ['ES2020', 'DOM', 'DOM.Iterable'],
|
|
245
|
+
jsx: 'react-jsx',
|
|
246
|
+
module: 'commonjs',
|
|
247
|
+
moduleResolution: 'node',
|
|
248
|
+
esModuleInterop: true,
|
|
249
|
+
strict: true,
|
|
250
|
+
skipLibCheck: true,
|
|
251
|
+
forceConsistentCasingInFileNames: true,
|
|
252
|
+
resolveJsonModule: true,
|
|
253
|
+
allowSyntheticDefaultImports: true
|
|
254
|
+
},
|
|
255
|
+
include: ['src/**/*'],
|
|
256
|
+
exclude: ['node_modules']
|
|
257
|
+
};
|
|
258
|
+
fs.writeFileSync(path.join(outputPath, 'tsconfig.json'), JSON.stringify(tsConfig, null, 2), 'utf8');
|
|
259
|
+
// 7. Cria README
|
|
260
|
+
console.log('📖 Criando README...');
|
|
261
|
+
const readmeContent = `# ${originalPackageJson.name || 'HightJS App'}
|
|
262
|
+
|
|
263
|
+
Este projeto foi migrado de Next.js para HightJS.
|
|
264
|
+
|
|
265
|
+
## Comandos Disponíveis
|
|
266
|
+
|
|
267
|
+
- \`npm run dev\` - Inicia o servidor de desenvolvimento
|
|
268
|
+
- \`npm run start\` - Inicia o servidor em modo produção
|
|
269
|
+
- \`npm run build\` - Exporta a aplicação como HTML estático
|
|
270
|
+
|
|
271
|
+
## Próximos Passos
|
|
272
|
+
|
|
273
|
+
1. Instale as dependências: \`npm install\`
|
|
274
|
+
2. Revise os arquivos migrados em \`src/web/routes/\`
|
|
275
|
+
3. Ajuste manualmente qualquer código que precise de adaptação
|
|
276
|
+
4. Execute \`npm run dev\` para testar
|
|
277
|
+
|
|
278
|
+
## Notas de Migração
|
|
279
|
+
|
|
280
|
+
- Rotas dinâmicas do Next.js foram convertidas para o formato HightJS
|
|
281
|
+
- API Routes precisam ser migradas manualmente para HightJS API routes
|
|
282
|
+
- Server Components foram convertidos para componentes React padrão
|
|
283
|
+
- Revise imports e configurações específicas do Next.js
|
|
284
|
+
|
|
285
|
+
Para mais informações sobre HightJS, visite a documentação.
|
|
286
|
+
`;
|
|
287
|
+
fs.writeFileSync(path.join(outputPath, 'README.md'), readmeContent, 'utf8');
|
|
288
|
+
console.log('\n✅ Migração concluída com sucesso!');
|
|
289
|
+
console.log(`\n📂 Projeto criado em: ${outputPath}`);
|
|
290
|
+
console.log('\n📋 Próximos passos:');
|
|
291
|
+
console.log(` 1. cd ${path.relative(process.cwd(), outputPath)}`);
|
|
292
|
+
console.log(' 2. npm install');
|
|
293
|
+
console.log(' 3. npm run dev');
|
|
294
|
+
console.log('\n⚠️ IMPORTANTE: Revise os arquivos migrados e ajuste conforme necessário.\n');
|
|
295
|
+
}
|
|
296
|
+
catch (error) {
|
|
297
|
+
console.error('❌ Erro durante a migração:', error.message);
|
|
298
|
+
console.error(error.stack);
|
|
299
|
+
process.exit(1);
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
// Funções auxiliares para migração
|
|
303
|
+
function copyDirectory(src, dest) {
|
|
304
|
+
if (!fs.existsSync(src))
|
|
305
|
+
return;
|
|
306
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
307
|
+
const entries = fs.readdirSync(src, { withFileTypes: true });
|
|
308
|
+
for (const entry of entries) {
|
|
309
|
+
const srcPath = path.join(src, entry.name);
|
|
310
|
+
const destPath = path.join(dest, entry.name);
|
|
311
|
+
if (entry.isDirectory()) {
|
|
312
|
+
copyDirectory(srcPath, destPath);
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
fs.copyFileSync(srcPath, destPath);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
function migratePagesRouter(pagesDir, routesDir) {
|
|
320
|
+
function processDirectory(dir, baseRoute = '') {
|
|
321
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
322
|
+
for (const entry of entries) {
|
|
323
|
+
const fullPath = path.join(dir, entry.name);
|
|
324
|
+
if (entry.isDirectory()) {
|
|
325
|
+
// Processa subdiretórios (rotas aninhadas)
|
|
326
|
+
const newBaseRoute = path.join(baseRoute, entry.name);
|
|
327
|
+
processDirectory(fullPath, newBaseRoute);
|
|
328
|
+
}
|
|
329
|
+
else if (entry.name.match(/\.(tsx?|jsx?)$/)) {
|
|
330
|
+
// Ignora arquivos especiais do Next.js
|
|
331
|
+
if (['_app', '_document', '_error', 'api'].some(special => entry.name.startsWith(special))) {
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
// Converte nome do arquivo para rota HightJS
|
|
335
|
+
let fileName = entry.name.replace(/\.(tsx?|jsx?)$/, '');
|
|
336
|
+
let routePath = baseRoute;
|
|
337
|
+
if (fileName === 'index') {
|
|
338
|
+
// index.tsx -> route vazia ou baseRoute
|
|
339
|
+
routePath = baseRoute || '/';
|
|
340
|
+
}
|
|
341
|
+
else {
|
|
342
|
+
// [id].tsx -> $id.tsx
|
|
343
|
+
fileName = fileName.replace(/\[([^\]]+)\]/g, '$$$1');
|
|
344
|
+
routePath = path.join(baseRoute, fileName);
|
|
345
|
+
}
|
|
346
|
+
// Lê o conteúdo original
|
|
347
|
+
const originalContent = fs.readFileSync(fullPath, 'utf8');
|
|
348
|
+
// Transforma o conteúdo
|
|
349
|
+
const transformedContent = transformNextJsPage(originalContent);
|
|
350
|
+
// Cria estrutura de diretórios se necessário
|
|
351
|
+
const targetDir = path.join(routesDir, baseRoute);
|
|
352
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
353
|
+
// Salva o arquivo transformado
|
|
354
|
+
const targetFileName = fileName === 'index' ? 'route.tsx' : `${fileName}.route.tsx`;
|
|
355
|
+
const targetPath = path.join(targetDir, targetFileName);
|
|
356
|
+
fs.writeFileSync(targetPath, transformedContent, 'utf8');
|
|
357
|
+
console.log(` ✓ ${path.relative(pagesDir, fullPath)} -> ${path.relative(routesDir, targetPath)}`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
processDirectory(pagesDir);
|
|
362
|
+
}
|
|
363
|
+
function migrateAppRouter(appDir, routesDir) {
|
|
364
|
+
function processDirectory(dir, baseRoute = '') {
|
|
365
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
366
|
+
let hasPage = false;
|
|
367
|
+
for (const entry of entries) {
|
|
368
|
+
const fullPath = path.join(dir, entry.name);
|
|
369
|
+
if (entry.isDirectory()) {
|
|
370
|
+
// Suporta rotas dinâmicas como [id]
|
|
371
|
+
let dirName = entry.name;
|
|
372
|
+
if (dirName.startsWith('[') && dirName.endsWith(']')) {
|
|
373
|
+
dirName = '$' + dirName.slice(1, -1);
|
|
374
|
+
}
|
|
375
|
+
const newBaseRoute = path.join(baseRoute, dirName);
|
|
376
|
+
processDirectory(fullPath, newBaseRoute);
|
|
377
|
+
}
|
|
378
|
+
else if (entry.name === 'page.tsx' || entry.name === 'page.jsx' || entry.name === 'page.ts' || entry.name === 'page.js') {
|
|
379
|
+
hasPage = true;
|
|
380
|
+
// Lê o conteúdo original
|
|
381
|
+
const originalContent = fs.readFileSync(fullPath, 'utf8');
|
|
382
|
+
// Transforma o conteúdo
|
|
383
|
+
const transformedContent = transformNextJsPage(originalContent);
|
|
384
|
+
// Cria estrutura de diretórios
|
|
385
|
+
const targetDir = path.join(routesDir, baseRoute);
|
|
386
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
387
|
+
// Salva como route.tsx
|
|
388
|
+
const targetPath = path.join(targetDir, 'route.tsx');
|
|
389
|
+
fs.writeFileSync(targetPath, transformedContent, 'utf8');
|
|
390
|
+
console.log(` ✓ ${path.relative(appDir, fullPath)} -> ${path.relative(routesDir, targetPath)}`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
processDirectory(appDir);
|
|
395
|
+
}
|
|
396
|
+
function transformNextJsPage(content) {
|
|
397
|
+
// Remove 'use client' e 'use server'
|
|
398
|
+
content = content.replace(/['"]use (client|server)['"]\s*;\s*/g, '');
|
|
399
|
+
// Remove imports específicos do Next.js
|
|
400
|
+
content = content.replace(/import\s+.*?from\s+['"]next\/.*?['"];?\s*/g, '');
|
|
401
|
+
// Substitui Link do Next.js por Link do HightJS
|
|
402
|
+
if (content.includes('Link')) {
|
|
403
|
+
content = `import { Link } from 'hightjs/client';\n` + content;
|
|
404
|
+
}
|
|
405
|
+
// Substitui useRouter do Next.js
|
|
406
|
+
content = content.replace(/import\s*\{\s*useRouter\s*\}\s*from\s*['"]next\/router['"]/g, "import { useRouter } from 'hightjs/client'");
|
|
407
|
+
// Substitui Image do Next.js por img normal (com comentário para revisão)
|
|
408
|
+
content = content.replace(/<Image\s+/g, '<img /* TODO: Migrado de Next.js Image - revisar otimizações */ ');
|
|
409
|
+
// Remove getServerSideProps, getStaticProps, getStaticPaths
|
|
410
|
+
content = content.replace(/export\s+(async\s+)?function\s+get(ServerSideProps|StaticProps|StaticPaths)\s*\([^)]*\)\s*\{[\s\S]*?\n\}/g, '');
|
|
411
|
+
// Adiciona comentário sobre metadata se houver
|
|
412
|
+
if (content.includes('export const metadata')) {
|
|
413
|
+
content = '// TODO: Migrar metadata do Next.js para HightJS\n' + content;
|
|
414
|
+
}
|
|
415
|
+
return content.trim();
|
|
416
|
+
}
|
|
417
|
+
function filterDependencies(deps) {
|
|
418
|
+
if (!deps)
|
|
419
|
+
return {};
|
|
420
|
+
const filtered = { ...deps };
|
|
421
|
+
// Remove dependências específicas do Next.js
|
|
422
|
+
delete filtered.next;
|
|
423
|
+
delete filtered['@next/font'];
|
|
424
|
+
delete filtered['next-auth'];
|
|
425
|
+
return filtered;
|
|
426
|
+
}
|
|
34
427
|
// Faz o "parse" dos argumentos passados na linha de comando
|
|
35
428
|
program.parse(process.argv);
|
package/dist/router.js
CHANGED
|
@@ -531,7 +531,6 @@ function handleWebSocketUpgrade(request, socket, head, hotReloadManager) {
|
|
|
531
531
|
hotReloadManager.handleUpgrade(request, socket, head);
|
|
532
532
|
}
|
|
533
533
|
else {
|
|
534
|
-
console.warn('⚠️ Hot-reload manager não disponível para:', pathname);
|
|
535
534
|
socket.destroy();
|
|
536
535
|
}
|
|
537
536
|
return;
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# 📚 Documentação HightJS
|
|
2
|
+
|
|
3
|
+
Bem-vindo à documentação completa do HightJS!
|
|
4
|
+
|
|
5
|
+
## 📑 Índice
|
|
6
|
+
|
|
7
|
+
### Fundamentos
|
|
8
|
+
- [📦 Estrutura Recomendada](./estrutura.md) - Como organizar seu projeto
|
|
9
|
+
- [🖥️ Rotas Frontend](./rotas-frontend.md) - Criando páginas React
|
|
10
|
+
- [🌐 Rotas Backend](./rotas-backend.md) - Criando APIs e endpoints
|
|
11
|
+
|
|
12
|
+
### Recursos Avançados
|
|
13
|
+
- [🛜 WebSocket](./websocket.md) - Comunicação em tempo real
|
|
14
|
+
- [🧩 Middlewares](./middlewares.md) - Interceptando requisições
|
|
15
|
+
- [🔐 Autenticação](./autenticacao.md) - Sistema JWT integrado
|
|
16
|
+
|
|
17
|
+
### Ferramentas e Configuração
|
|
18
|
+
- [🛠️ CLI](./cli.md) - Comandos e opções
|
|
19
|
+
- [📂 Arquivos Especiais](./arquivos-especiais.md) - Arquivos com funções especiais
|
|
20
|
+
- [🧱 Adapters](./adapters.md) - Native, Express, Fastify
|
|
21
|
+
- [🔐 Segurança Interna](./seguranca.md) - Proteções nativas
|
|
22
|
+
- [♻️ Hot Reload](./hot-reload.md) - Desenvolvimento com recarregamento automático
|
|
23
|
+
|
|
24
|
+
### Ajuda
|
|
25
|
+
- [❓ FAQ Rápido](./faq.md) - Perguntas frequentes
|
|
26
|
+
- [✅ Checklist Mental](./checklist.md) - Guia rápido de referência
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 🚀 Início Rápido
|
|
31
|
+
|
|
32
|
+
Se você está começando agora, recomendamos seguir esta ordem:
|
|
33
|
+
|
|
34
|
+
1. [Estrutura Recomendada](./estrutura.md) - Entenda como organizar seu projeto
|
|
35
|
+
2. [Rotas Frontend](./rotas-frontend.md) - Crie sua primeira página
|
|
36
|
+
3. [Rotas Backend](./rotas-backend.md) - Crie sua primeira API
|
|
37
|
+
4. [CLI](./cli.md) - Aprenda os comandos básicos
|
|
38
|
+
|
|
39
|
+
## 💡 Recursos Avançados
|
|
40
|
+
|
|
41
|
+
Quando estiver confortável com o básico, explore:
|
|
42
|
+
|
|
43
|
+
- [Autenticação](./autenticacao.md) - Adicione login e proteção de rotas
|
|
44
|
+
- [WebSocket](./websocket.md) - Implemente recursos em tempo real
|
|
45
|
+
- [Middlewares](./middlewares.md) - Adicione lógica customizada nas requisições
|
|
46
|
+
|
|
47
|
+
## 📖 Referência Completa
|
|
48
|
+
|
|
49
|
+
Consulte estas páginas quando precisar de informações específicas:
|
|
50
|
+
|
|
51
|
+
- [Arquivos Especiais](./arquivos-especiais.md) - Todos os arquivos especiais do framework
|
|
52
|
+
- [Adapters](./adapters.md) - Diferentes formas de executar seu app
|
|
53
|
+
- [Segurança Interna](./seguranca.md) - Como o HightJS protege sua aplicação
|
|
54
|
+
- [Hot Reload](./hot-reload.md) - Como funciona o recarregamento automático
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
Voltar para o [README principal](../README.md)
|
|
59
|
+
|
package/docs/adapters.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# 📂 Arquivos Especiais
|
|
2
|
+
|
|
3
|
+
| Arquivo | Localização | Função |
|
|
4
|
+
|-----------------------------|---------------------------------------|------------------------------------------------|
|
|
5
|
+
| `layout.tsx` | `/src/web` | Layout global + `export const metadata` |
|
|
6
|
+
| `notFound.tsx` | `/src/web` | Página 404 customizada |
|
|
7
|
+
| `middleware.ts` | dentro de `/src/web/backend/routes` | Middlewares globais por pasta backend |
|
|
8
|
+
| `hightweb.ts` / `.tsx` | `/src/hightweb` | Instrumentação opcional executada no boot |
|
|
9
|
+
| `public/` | `/public` | Arquivos estáticos servidos diretamente |
|
|
10
|
+
|