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/src/bin/hightjs.js
CHANGED
|
@@ -5,6 +5,8 @@ require('ts-node').register();
|
|
|
5
5
|
|
|
6
6
|
const { program } = require('commander');
|
|
7
7
|
const teste = require("../helpers");
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
8
10
|
|
|
9
11
|
program
|
|
10
12
|
.version('1.0.0')
|
|
@@ -36,5 +38,478 @@ program
|
|
|
36
38
|
t.init()
|
|
37
39
|
});
|
|
38
40
|
|
|
41
|
+
// --- Comando EXPORT ---
|
|
42
|
+
program
|
|
43
|
+
.command('export')
|
|
44
|
+
.description('Exporta a aplicação como HTML estático na pasta "exported".')
|
|
45
|
+
.option('-o, --output <path>', 'Especifica o diretório de saída', 'exported')
|
|
46
|
+
.action(async (options) => {
|
|
47
|
+
const projectDir = process.cwd();
|
|
48
|
+
const exportDir = path.join(projectDir, options.output);
|
|
49
|
+
|
|
50
|
+
console.log('🚀 Iniciando exportação...\n');
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
// 1. Cria a pasta exported (limpa se já existir)
|
|
54
|
+
if (fs.existsSync(exportDir)) {
|
|
55
|
+
console.log('🗑️ Limpando pasta de exportação existente...');
|
|
56
|
+
fs.rmSync(exportDir, { recursive: true, force: true });
|
|
57
|
+
}
|
|
58
|
+
fs.mkdirSync(exportDir, { recursive: true });
|
|
59
|
+
console.log('✅ Pasta de exportação criada\n');
|
|
60
|
+
|
|
61
|
+
// 2. Inicializa e prepara o build
|
|
62
|
+
console.log('🔨 Buildando aplicação...');
|
|
63
|
+
const teste = require("../helpers");
|
|
64
|
+
const app = teste.default({ dev: false, port: 3000, hostname: '0.0.0.0', framework: 'native' });
|
|
65
|
+
await app.prepare();
|
|
66
|
+
console.log('✅ Build concluído\n');
|
|
67
|
+
|
|
68
|
+
// 3. Copia a pasta hweb-dist para exported
|
|
69
|
+
const distDir = path.join(projectDir, 'hweb-dist');
|
|
70
|
+
if (fs.existsSync(distDir)) {
|
|
71
|
+
console.log('📦 Copiando arquivos JavaScript...');
|
|
72
|
+
const exportDistDir = path.join(exportDir, 'hweb-dist');
|
|
73
|
+
fs.mkdirSync(exportDistDir, { recursive: true });
|
|
74
|
+
|
|
75
|
+
const files = fs.readdirSync(distDir);
|
|
76
|
+
files.forEach(file => {
|
|
77
|
+
fs.copyFileSync(
|
|
78
|
+
path.join(distDir, file),
|
|
79
|
+
path.join(exportDistDir, file)
|
|
80
|
+
);
|
|
81
|
+
});
|
|
82
|
+
console.log('✅ Arquivos JavaScript copiados\n');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 4. Copia a pasta public se existir
|
|
86
|
+
const publicDir = path.join(projectDir, 'public');
|
|
87
|
+
if (fs.existsSync(publicDir)) {
|
|
88
|
+
console.log('📁 Copiando arquivos públicos...');
|
|
89
|
+
const exportPublicDir = path.join(exportDir, 'public');
|
|
90
|
+
|
|
91
|
+
function copyRecursive(src, dest) {
|
|
92
|
+
if (fs.statSync(src).isDirectory()) {
|
|
93
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
94
|
+
fs.readdirSync(src).forEach(file => {
|
|
95
|
+
copyRecursive(path.join(src, file), path.join(dest, file));
|
|
96
|
+
});
|
|
97
|
+
} else {
|
|
98
|
+
fs.copyFileSync(src, dest);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
copyRecursive(publicDir, exportPublicDir);
|
|
103
|
+
console.log('✅ Arquivos públicos copiados\n');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 5. Gera o index.html
|
|
107
|
+
console.log('📝 Gerando index.html...');
|
|
108
|
+
const { render } = require('../renderer');
|
|
109
|
+
const { loadRoutes, loadLayout, loadNotFound } = require('../router');
|
|
110
|
+
|
|
111
|
+
// Carrega as rotas para gerar o HTML
|
|
112
|
+
const userWebDir = path.join(projectDir, 'src', 'web');
|
|
113
|
+
const userWebRoutesDir = path.join(userWebDir, 'routes');
|
|
114
|
+
|
|
115
|
+
const routes = loadRoutes(userWebRoutesDir);
|
|
116
|
+
loadLayout(userWebDir);
|
|
117
|
+
loadNotFound(userWebDir);
|
|
118
|
+
|
|
119
|
+
// Gera HTML para a rota raiz
|
|
120
|
+
const rootRoute = routes.find(r => r.pattern === '/') || routes[0];
|
|
121
|
+
|
|
122
|
+
if (rootRoute) {
|
|
123
|
+
const mockReq = {
|
|
124
|
+
url: '/',
|
|
125
|
+
method: 'GET',
|
|
126
|
+
headers: { host: 'localhost' },
|
|
127
|
+
hwebDev: false,
|
|
128
|
+
hotReloadManager: null
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const html = await render({
|
|
132
|
+
req: mockReq,
|
|
133
|
+
route: rootRoute,
|
|
134
|
+
params: {},
|
|
135
|
+
allRoutes: routes
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
const indexPath = path.join(exportDir, 'index.html');
|
|
139
|
+
fs.writeFileSync(indexPath, html, 'utf8');
|
|
140
|
+
console.log('✅ index.html gerado\n');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
console.log('🎉 Exportação concluída com sucesso!');
|
|
144
|
+
console.log(`📂 Arquivos exportados em: ${exportDir}\n`);
|
|
145
|
+
|
|
146
|
+
} catch (error) {
|
|
147
|
+
console.error('❌ Erro durante a exportação:', error.message);
|
|
148
|
+
process.exit(1);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// --- Comando MIGRATE FROM NEXTJS ---
|
|
153
|
+
program
|
|
154
|
+
.command('migrate-from-nextjs')
|
|
155
|
+
.description('Migra um projeto Next.js para HightJS.')
|
|
156
|
+
.option('-s, --source <path>', 'Caminho do projeto Next.js', process.cwd())
|
|
157
|
+
.option('-o, --output <path>', 'Diretório de saída para o projeto HightJS', './hightjs-project')
|
|
158
|
+
.action(async (options) => {
|
|
159
|
+
const sourcePath = path.resolve(options.source);
|
|
160
|
+
const outputPath = path.resolve(options.output);
|
|
161
|
+
|
|
162
|
+
console.log('🚀 Iniciando migração de Next.js para HightJS...\n');
|
|
163
|
+
console.log(`📂 Origem: ${sourcePath}`);
|
|
164
|
+
console.log(`📂 Destino: ${outputPath}\n`);
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
// Verifica se o diretório de origem existe
|
|
168
|
+
if (!fs.existsSync(sourcePath)) {
|
|
169
|
+
throw new Error(`Diretório de origem não encontrado: ${sourcePath}`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Verifica se é um projeto Next.js
|
|
173
|
+
const nextConfigPath = path.join(sourcePath, 'next.config.js');
|
|
174
|
+
const nextConfigMjsPath = path.join(sourcePath, 'next.config.mjs');
|
|
175
|
+
const packageJsonPath = path.join(sourcePath, 'package.json');
|
|
176
|
+
|
|
177
|
+
if (!fs.existsSync(nextConfigPath) && !fs.existsSync(nextConfigMjsPath) && !fs.existsSync(packageJsonPath)) {
|
|
178
|
+
throw new Error('Não foi encontrado um projeto Next.js válido no diretório especificado.');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Cria o diretório de saída
|
|
182
|
+
if (fs.existsSync(outputPath)) {
|
|
183
|
+
console.log('⚠️ Diretório de destino já existe. Limpando...');
|
|
184
|
+
fs.rmSync(outputPath, { recursive: true, force: true });
|
|
185
|
+
}
|
|
186
|
+
fs.mkdirSync(outputPath, { recursive: true });
|
|
187
|
+
|
|
188
|
+
// 1. Cria estrutura básica do HightJS
|
|
189
|
+
console.log('📁 Criando estrutura de diretórios...');
|
|
190
|
+
const srcDir = path.join(outputPath, 'src');
|
|
191
|
+
const webDir = path.join(srcDir, 'web');
|
|
192
|
+
const routesDir = path.join(webDir, 'routes');
|
|
193
|
+
const publicDir = path.join(outputPath, 'public');
|
|
194
|
+
|
|
195
|
+
fs.mkdirSync(srcDir, { recursive: true });
|
|
196
|
+
fs.mkdirSync(webDir, { recursive: true });
|
|
197
|
+
fs.mkdirSync(routesDir, { recursive: true });
|
|
198
|
+
fs.mkdirSync(publicDir, { recursive: true });
|
|
199
|
+
|
|
200
|
+
// 2. Copia arquivos públicos
|
|
201
|
+
console.log('📦 Copiando arquivos públicos...');
|
|
202
|
+
const nextPublicDir = path.join(sourcePath, 'public');
|
|
203
|
+
if (fs.existsSync(nextPublicDir)) {
|
|
204
|
+
copyDirectory(nextPublicDir, publicDir);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// 3. Migra páginas do Next.js para rotas do HightJS
|
|
208
|
+
console.log('🔄 Migrando páginas para rotas...');
|
|
209
|
+
const nextPagesDir = path.join(sourcePath, 'pages');
|
|
210
|
+
const nextAppDir = path.join(sourcePath, 'app');
|
|
211
|
+
const nextSrcPagesDir = path.join(sourcePath, 'src', 'pages');
|
|
212
|
+
const nextSrcAppDir = path.join(sourcePath, 'src', 'app');
|
|
213
|
+
|
|
214
|
+
let pagesDir = null;
|
|
215
|
+
let isAppRouter = false;
|
|
216
|
+
|
|
217
|
+
if (fs.existsSync(nextAppDir)) {
|
|
218
|
+
pagesDir = nextAppDir;
|
|
219
|
+
isAppRouter = true;
|
|
220
|
+
console.log('✅ Detectado Next.js App Router');
|
|
221
|
+
} else if (fs.existsSync(nextSrcAppDir)) {
|
|
222
|
+
pagesDir = nextSrcAppDir;
|
|
223
|
+
isAppRouter = true;
|
|
224
|
+
console.log('✅ Detectado Next.js App Router (em src/)');
|
|
225
|
+
} else if (fs.existsSync(nextPagesDir)) {
|
|
226
|
+
pagesDir = nextPagesDir;
|
|
227
|
+
console.log('✅ Detectado Next.js Pages Router');
|
|
228
|
+
} else if (fs.existsSync(nextSrcPagesDir)) {
|
|
229
|
+
pagesDir = nextSrcPagesDir;
|
|
230
|
+
console.log('✅ Detectado Next.js Pages Router (em src/)');
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (pagesDir) {
|
|
234
|
+
if (isAppRouter) {
|
|
235
|
+
migrateAppRouter(pagesDir, routesDir);
|
|
236
|
+
} else {
|
|
237
|
+
migratePagesRouter(pagesDir, routesDir);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
// 5. Cria package.json
|
|
243
|
+
console.log('📄 Criando package.json...');
|
|
244
|
+
let originalPackageJson = {};
|
|
245
|
+
if (fs.existsSync(packageJsonPath)) {
|
|
246
|
+
originalPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const newPackageJson = {
|
|
250
|
+
name: originalPackageJson.name || 'hightjs-app',
|
|
251
|
+
version: '1.0.0',
|
|
252
|
+
description: originalPackageJson.description || 'HightJS application migrated from Next.js',
|
|
253
|
+
scripts: {
|
|
254
|
+
dev: 'hight dev',
|
|
255
|
+
start: 'hight start',
|
|
256
|
+
build: 'hight export',
|
|
257
|
+
...originalPackageJson.scripts
|
|
258
|
+
},
|
|
259
|
+
dependencies: {
|
|
260
|
+
hightjs: 'latest',
|
|
261
|
+
react: originalPackageJson.dependencies?.react || '^18.2.0',
|
|
262
|
+
'react-dom': originalPackageJson.dependencies?.['react-dom'] || '^18.2.0',
|
|
263
|
+
...filterDependencies(originalPackageJson.dependencies)
|
|
264
|
+
},
|
|
265
|
+
devDependencies: {
|
|
266
|
+
'@types/node': '^20.11.24',
|
|
267
|
+
'@types/react': '^18.2.0',
|
|
268
|
+
'@types/react-dom': '^18.2.0',
|
|
269
|
+
typescript: '^5.3.3',
|
|
270
|
+
...filterDependencies(originalPackageJson.devDependencies)
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
fs.writeFileSync(
|
|
275
|
+
path.join(outputPath, 'package.json'),
|
|
276
|
+
JSON.stringify(newPackageJson, null, 2),
|
|
277
|
+
'utf8'
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
// 6. Cria tsconfig.json
|
|
281
|
+
console.log('⚙️ Criando tsconfig.json...');
|
|
282
|
+
const tsConfig = {
|
|
283
|
+
compilerOptions: {
|
|
284
|
+
target: 'ES2020',
|
|
285
|
+
lib: ['ES2020', 'DOM', 'DOM.Iterable'],
|
|
286
|
+
jsx: 'react-jsx',
|
|
287
|
+
module: 'commonjs',
|
|
288
|
+
moduleResolution: 'node',
|
|
289
|
+
esModuleInterop: true,
|
|
290
|
+
strict: true,
|
|
291
|
+
skipLibCheck: true,
|
|
292
|
+
forceConsistentCasingInFileNames: true,
|
|
293
|
+
resolveJsonModule: true,
|
|
294
|
+
allowSyntheticDefaultImports: true
|
|
295
|
+
},
|
|
296
|
+
include: ['src/**/*'],
|
|
297
|
+
exclude: ['node_modules']
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
fs.writeFileSync(
|
|
301
|
+
path.join(outputPath, 'tsconfig.json'),
|
|
302
|
+
JSON.stringify(tsConfig, null, 2),
|
|
303
|
+
'utf8'
|
|
304
|
+
);
|
|
305
|
+
|
|
306
|
+
// 7. Cria README
|
|
307
|
+
console.log('📖 Criando README...');
|
|
308
|
+
const readmeContent = `# ${originalPackageJson.name || 'HightJS App'}
|
|
309
|
+
|
|
310
|
+
Este projeto foi migrado de Next.js para HightJS.
|
|
311
|
+
|
|
312
|
+
## Comandos Disponíveis
|
|
313
|
+
|
|
314
|
+
- \`npm run dev\` - Inicia o servidor de desenvolvimento
|
|
315
|
+
- \`npm run start\` - Inicia o servidor em modo produção
|
|
316
|
+
- \`npm run build\` - Exporta a aplicação como HTML estático
|
|
317
|
+
|
|
318
|
+
## Próximos Passos
|
|
319
|
+
|
|
320
|
+
1. Instale as dependências: \`npm install\`
|
|
321
|
+
2. Revise os arquivos migrados em \`src/web/routes/\`
|
|
322
|
+
3. Ajuste manualmente qualquer código que precise de adaptação
|
|
323
|
+
4. Execute \`npm run dev\` para testar
|
|
324
|
+
|
|
325
|
+
## Notas de Migração
|
|
326
|
+
|
|
327
|
+
- Rotas dinâmicas do Next.js foram convertidas para o formato HightJS
|
|
328
|
+
- API Routes precisam ser migradas manualmente para HightJS API routes
|
|
329
|
+
- Server Components foram convertidos para componentes React padrão
|
|
330
|
+
- Revise imports e configurações específicas do Next.js
|
|
331
|
+
|
|
332
|
+
Para mais informações sobre HightJS, visite a documentação.
|
|
333
|
+
`;
|
|
334
|
+
|
|
335
|
+
fs.writeFileSync(path.join(outputPath, 'README.md'), readmeContent, 'utf8');
|
|
336
|
+
|
|
337
|
+
console.log('\n✅ Migração concluída com sucesso!');
|
|
338
|
+
console.log(`\n📂 Projeto criado em: ${outputPath}`);
|
|
339
|
+
console.log('\n📋 Próximos passos:');
|
|
340
|
+
console.log(` 1. cd ${path.relative(process.cwd(), outputPath)}`);
|
|
341
|
+
console.log(' 2. npm install');
|
|
342
|
+
console.log(' 3. npm run dev');
|
|
343
|
+
console.log('\n⚠️ IMPORTANTE: Revise os arquivos migrados e ajuste conforme necessário.\n');
|
|
344
|
+
|
|
345
|
+
} catch (error) {
|
|
346
|
+
console.error('❌ Erro durante a migração:', error.message);
|
|
347
|
+
console.error(error.stack);
|
|
348
|
+
process.exit(1);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
// Funções auxiliares para migração
|
|
353
|
+
function copyDirectory(src, dest) {
|
|
354
|
+
if (!fs.existsSync(src)) return;
|
|
355
|
+
|
|
356
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
357
|
+
const entries = fs.readdirSync(src, { withFileTypes: true });
|
|
358
|
+
|
|
359
|
+
for (const entry of entries) {
|
|
360
|
+
const srcPath = path.join(src, entry.name);
|
|
361
|
+
const destPath = path.join(dest, entry.name);
|
|
362
|
+
|
|
363
|
+
if (entry.isDirectory()) {
|
|
364
|
+
copyDirectory(srcPath, destPath);
|
|
365
|
+
} else {
|
|
366
|
+
fs.copyFileSync(srcPath, destPath);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function migratePagesRouter(pagesDir, routesDir) {
|
|
372
|
+
function processDirectory(dir, baseRoute = '') {
|
|
373
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
374
|
+
|
|
375
|
+
for (const entry of entries) {
|
|
376
|
+
const fullPath = path.join(dir, entry.name);
|
|
377
|
+
|
|
378
|
+
if (entry.isDirectory()) {
|
|
379
|
+
// Processa subdiretórios (rotas aninhadas)
|
|
380
|
+
const newBaseRoute = path.join(baseRoute, entry.name);
|
|
381
|
+
processDirectory(fullPath, newBaseRoute);
|
|
382
|
+
} else if (entry.name.match(/\.(tsx?|jsx?)$/)) {
|
|
383
|
+
// Ignora arquivos especiais do Next.js
|
|
384
|
+
if (['_app', '_document', '_error', 'api'].some(special => entry.name.startsWith(special))) {
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Converte nome do arquivo para rota HightJS
|
|
389
|
+
let fileName = entry.name.replace(/\.(tsx?|jsx?)$/, '');
|
|
390
|
+
let routePath = baseRoute;
|
|
391
|
+
|
|
392
|
+
if (fileName === 'index') {
|
|
393
|
+
// index.tsx -> route vazia ou baseRoute
|
|
394
|
+
routePath = baseRoute || '/';
|
|
395
|
+
} else {
|
|
396
|
+
// [id].tsx -> $id.tsx
|
|
397
|
+
fileName = fileName.replace(/\[([^\]]+)\]/g, '$$$1');
|
|
398
|
+
routePath = path.join(baseRoute, fileName);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// Lê o conteúdo original
|
|
402
|
+
const originalContent = fs.readFileSync(fullPath, 'utf8');
|
|
403
|
+
|
|
404
|
+
// Transforma o conteúdo
|
|
405
|
+
const transformedContent = transformNextJsPage(originalContent);
|
|
406
|
+
|
|
407
|
+
// Cria estrutura de diretórios se necessário
|
|
408
|
+
const targetDir = path.join(routesDir, baseRoute);
|
|
409
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
410
|
+
|
|
411
|
+
// Salva o arquivo transformado
|
|
412
|
+
const targetFileName = fileName === 'index' ? 'route.tsx' : `${fileName}.route.tsx`;
|
|
413
|
+
const targetPath = path.join(targetDir, targetFileName);
|
|
414
|
+
fs.writeFileSync(targetPath, transformedContent, 'utf8');
|
|
415
|
+
|
|
416
|
+
console.log(` ✓ ${path.relative(pagesDir, fullPath)} -> ${path.relative(routesDir, targetPath)}`);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
processDirectory(pagesDir);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function migrateAppRouter(appDir, routesDir) {
|
|
425
|
+
function processDirectory(dir, baseRoute = '') {
|
|
426
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
427
|
+
let hasPage = false;
|
|
428
|
+
|
|
429
|
+
for (const entry of entries) {
|
|
430
|
+
const fullPath = path.join(dir, entry.name);
|
|
431
|
+
|
|
432
|
+
if (entry.isDirectory()) {
|
|
433
|
+
// Suporta rotas dinâmicas como [id]
|
|
434
|
+
let dirName = entry.name;
|
|
435
|
+
if (dirName.startsWith('[') && dirName.endsWith(']')) {
|
|
436
|
+
dirName = '$' + dirName.slice(1, -1);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const newBaseRoute = path.join(baseRoute, dirName);
|
|
440
|
+
processDirectory(fullPath, newBaseRoute);
|
|
441
|
+
} else if (entry.name === 'page.tsx' || entry.name === 'page.jsx' || entry.name === 'page.ts' || entry.name === 'page.js') {
|
|
442
|
+
hasPage = true;
|
|
443
|
+
|
|
444
|
+
// Lê o conteúdo original
|
|
445
|
+
const originalContent = fs.readFileSync(fullPath, 'utf8');
|
|
446
|
+
|
|
447
|
+
// Transforma o conteúdo
|
|
448
|
+
const transformedContent = transformNextJsPage(originalContent);
|
|
449
|
+
|
|
450
|
+
// Cria estrutura de diretórios
|
|
451
|
+
const targetDir = path.join(routesDir, baseRoute);
|
|
452
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
453
|
+
|
|
454
|
+
// Salva como route.tsx
|
|
455
|
+
const targetPath = path.join(targetDir, 'route.tsx');
|
|
456
|
+
fs.writeFileSync(targetPath, transformedContent, 'utf8');
|
|
457
|
+
|
|
458
|
+
console.log(` ✓ ${path.relative(appDir, fullPath)} -> ${path.relative(routesDir, targetPath)}`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
processDirectory(appDir);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function transformNextJsPage(content) {
|
|
467
|
+
// Remove 'use client' e 'use server'
|
|
468
|
+
content = content.replace(/['"]use (client|server)['"]\s*;\s*/g, '');
|
|
469
|
+
|
|
470
|
+
// Remove imports específicos do Next.js
|
|
471
|
+
content = content.replace(/import\s+.*?from\s+['"]next\/.*?['"];?\s*/g, '');
|
|
472
|
+
|
|
473
|
+
// Substitui Link do Next.js por Link do HightJS
|
|
474
|
+
if (content.includes('Link')) {
|
|
475
|
+
content = `import { Link } from 'hightjs/client';\n` + content;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// Substitui useRouter do Next.js
|
|
479
|
+
content = content.replace(
|
|
480
|
+
/import\s*\{\s*useRouter\s*\}\s*from\s*['"]next\/router['"]/g,
|
|
481
|
+
"import { useRouter } from 'hightjs/client'"
|
|
482
|
+
);
|
|
483
|
+
|
|
484
|
+
// Substitui Image do Next.js por img normal (com comentário para revisão)
|
|
485
|
+
content = content.replace(
|
|
486
|
+
/<Image\s+/g,
|
|
487
|
+
'<img /* TODO: Migrado de Next.js Image - revisar otimizações */ '
|
|
488
|
+
);
|
|
489
|
+
|
|
490
|
+
// Remove getServerSideProps, getStaticProps, getStaticPaths
|
|
491
|
+
content = content.replace(/export\s+(async\s+)?function\s+get(ServerSideProps|StaticProps|StaticPaths)\s*\([^)]*\)\s*\{[\s\S]*?\n\}/g, '');
|
|
492
|
+
|
|
493
|
+
// Adiciona comentário sobre metadata se houver
|
|
494
|
+
if (content.includes('export const metadata')) {
|
|
495
|
+
content = '// TODO: Migrar metadata do Next.js para HightJS\n' + content;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
return content.trim();
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function filterDependencies(deps) {
|
|
502
|
+
if (!deps) return {};
|
|
503
|
+
|
|
504
|
+
const filtered = { ...deps };
|
|
505
|
+
|
|
506
|
+
// Remove dependências específicas do Next.js
|
|
507
|
+
delete filtered.next;
|
|
508
|
+
delete filtered['@next/font'];
|
|
509
|
+
delete filtered['next-auth'];
|
|
510
|
+
|
|
511
|
+
return filtered;
|
|
512
|
+
}
|
|
513
|
+
|
|
39
514
|
// Faz o "parse" dos argumentos passados na linha de comando
|
|
40
515
|
program.parse(process.argv);
|
package/src/router.ts
CHANGED
|
@@ -594,7 +594,6 @@ function handleWebSocketUpgrade(request: any, socket: any, head: Buffer, hotRelo
|
|
|
594
594
|
if (hotReloadManager) {
|
|
595
595
|
hotReloadManager.handleUpgrade(request, socket, head);
|
|
596
596
|
} else {
|
|
597
|
-
console.warn('⚠️ Hot-reload manager não disponível para:', pathname);
|
|
598
597
|
socket.destroy();
|
|
599
598
|
}
|
|
600
599
|
return;
|
|
File without changes
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
File without changes
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
File without changes
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
File without changes
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
File without changes
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";
|
package/dist/auth/example.d.ts
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Exemplo de como usar os novos providers baseados em classes
|
|
3
|
-
*/
|
|
4
|
-
export declare const authRoutes: {
|
|
5
|
-
pattern: string;
|
|
6
|
-
GET(req: import("..").HightJSRequest, params: {
|
|
7
|
-
[key: string]: string;
|
|
8
|
-
}): Promise<any>;
|
|
9
|
-
POST(req: import("..").HightJSRequest, params: {
|
|
10
|
-
[key: string]: string;
|
|
11
|
-
}): Promise<any>;
|
|
12
|
-
auth: import("./core").HWebAuth;
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Como usar em suas rotas API:
|
|
16
|
-
*
|
|
17
|
-
* // arquivo: /api/auth/[...value].ts
|
|
18
|
-
* import { authRoutes } from '../../../src/auth/example';
|
|
19
|
-
*
|
|
20
|
-
* export const GET = authRoutes.GET;
|
|
21
|
-
* export const POST = authRoutes.POST;
|
|
22
|
-
*/
|
|
23
|
-
/**
|
|
24
|
-
* Rotas disponíveis automaticamente:
|
|
25
|
-
*
|
|
26
|
-
* Core routes:
|
|
27
|
-
* - GET /api/auth/session - Obter sessão atual
|
|
28
|
-
* - GET /api/auth/providers - Listar providers
|
|
29
|
-
* - GET /api/auth/csrf - Obter token CSRF
|
|
30
|
-
* - POST /api/auth/signin - Login
|
|
31
|
-
* - POST /api/auth/signout - Logout
|
|
32
|
-
*
|
|
33
|
-
* Provider específico (CredentialsProvider):
|
|
34
|
-
* - GET /api/auth/credentials/config - Config do provider
|
|
35
|
-
*
|
|
36
|
-
* Provider específico (DiscordProvider):
|
|
37
|
-
* - GET /api/auth/signin/discord - Iniciar OAuth Discord
|
|
38
|
-
* - GET /api/auth/callback/discord - Callback OAuth Discord
|
|
39
|
-
* - GET /api/auth/discord/config - Config do provider Discord
|
|
40
|
-
*/
|
package/dist/auth/example.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Exemplo de como usar os novos providers baseados em classes
|
|
4
|
-
*/
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.authRoutes = void 0;
|
|
7
|
-
const routes_1 = require("./routes");
|
|
8
|
-
const providers_1 = require("./providers");
|
|
9
|
-
// Exemplo de configuração com os novos providers
|
|
10
|
-
const authConfig = {
|
|
11
|
-
providers: [
|
|
12
|
-
// Provider de credenciais customizado
|
|
13
|
-
new providers_1.CredentialsProvider({
|
|
14
|
-
name: "Login com Email",
|
|
15
|
-
credentials: {
|
|
16
|
-
email: {
|
|
17
|
-
label: "Email",
|
|
18
|
-
type: "email",
|
|
19
|
-
placeholder: "seu@email.com"
|
|
20
|
-
},
|
|
21
|
-
password: {
|
|
22
|
-
label: "Senha",
|
|
23
|
-
type: "password"
|
|
24
|
-
}
|
|
25
|
-
},
|
|
26
|
-
async authorize(credentials) {
|
|
27
|
-
// Aqui você faz a validação com seu banco de dados
|
|
28
|
-
const { email, password } = credentials;
|
|
29
|
-
// Exemplo de validação (substitua pela sua lógica)
|
|
30
|
-
if (email === "admin@example.com" && password === "123456") {
|
|
31
|
-
return {
|
|
32
|
-
id: "1",
|
|
33
|
-
name: "Admin User",
|
|
34
|
-
email: email,
|
|
35
|
-
role: "admin"
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
// Retorna null se credenciais inválidas
|
|
39
|
-
return null;
|
|
40
|
-
}
|
|
41
|
-
}),
|
|
42
|
-
// Provider do Discord
|
|
43
|
-
new providers_1.DiscordProvider({
|
|
44
|
-
clientId: process.env.DISCORD_CLIENT_ID,
|
|
45
|
-
clientSecret: process.env.DISCORD_CLIENT_SECRET,
|
|
46
|
-
callbackUrl: "http://localhost:3000/api/auth/callback/discord"
|
|
47
|
-
})
|
|
48
|
-
],
|
|
49
|
-
secret: process.env.HWEB_AUTH_SECRET || "seu-super-secret-aqui-32-chars-min",
|
|
50
|
-
session: {
|
|
51
|
-
strategy: 'jwt',
|
|
52
|
-
maxAge: 86400 // 24 horas
|
|
53
|
-
},
|
|
54
|
-
pages: {
|
|
55
|
-
signIn: '/auth/signin',
|
|
56
|
-
signOut: '/auth/signout'
|
|
57
|
-
},
|
|
58
|
-
callbacks: {
|
|
59
|
-
async signIn(user, account, profile) {
|
|
60
|
-
// Lógica customizada antes do login
|
|
61
|
-
console.log(`Usuário ${user.email} fazendo login via ${account.provider}`);
|
|
62
|
-
return true; // permitir login
|
|
63
|
-
},
|
|
64
|
-
async session(session, user) {
|
|
65
|
-
// Adicionar dados customizados à sessão
|
|
66
|
-
return {
|
|
67
|
-
...session,
|
|
68
|
-
user: {
|
|
69
|
-
...session.user,
|
|
70
|
-
customData: "dados extras"
|
|
71
|
-
}
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
// Criar as rotas de autenticação
|
|
77
|
-
exports.authRoutes = (0, routes_1.createAuthRoutes)(authConfig);
|
|
78
|
-
/**
|
|
79
|
-
* Como usar em suas rotas API:
|
|
80
|
-
*
|
|
81
|
-
* // arquivo: /api/auth/[...value].ts
|
|
82
|
-
* import { authRoutes } from '../../../src/auth/example';
|
|
83
|
-
*
|
|
84
|
-
* export const GET = authRoutes.GET;
|
|
85
|
-
* export const POST = authRoutes.POST;
|
|
86
|
-
*/
|
|
87
|
-
/**
|
|
88
|
-
* Rotas disponíveis automaticamente:
|
|
89
|
-
*
|
|
90
|
-
* Core routes:
|
|
91
|
-
* - GET /api/auth/session - Obter sessão atual
|
|
92
|
-
* - GET /api/auth/providers - Listar providers
|
|
93
|
-
* - GET /api/auth/csrf - Obter token CSRF
|
|
94
|
-
* - POST /api/auth/signin - Login
|
|
95
|
-
* - POST /api/auth/signout - Logout
|
|
96
|
-
*
|
|
97
|
-
* Provider específico (CredentialsProvider):
|
|
98
|
-
* - GET /api/auth/credentials/config - Config do provider
|
|
99
|
-
*
|
|
100
|
-
* Provider específico (DiscordProvider):
|
|
101
|
-
* - GET /api/auth/signin/discord - Iniciar OAuth Discord
|
|
102
|
-
* - GET /api/auth/callback/discord - Callback OAuth Discord
|
|
103
|
-
* - GET /api/auth/discord/config - Config do provider Discord
|
|
104
|
-
*/
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import React, { Component, ErrorInfo, ReactNode } from 'react';
|
|
2
|
-
interface Props {
|
|
3
|
-
children: ReactNode;
|
|
4
|
-
}
|
|
5
|
-
interface State {
|
|
6
|
-
hasError: boolean;
|
|
7
|
-
error?: Error;
|
|
8
|
-
errorInfo?: ErrorInfo;
|
|
9
|
-
}
|
|
10
|
-
export declare class ErrorBoundary extends Component<Props, State> {
|
|
11
|
-
constructor(props: Props);
|
|
12
|
-
static getDerivedStateFromError(error: Error): State;
|
|
13
|
-
componentDidCatch(error: Error, errorInfo: ErrorInfo): void;
|
|
14
|
-
render(): string | number | boolean | Iterable<React.ReactNode> | import("react/jsx-runtime").JSX.Element | null | undefined;
|
|
15
|
-
}
|
|
16
|
-
export {};
|