hightjs 0.2.42 → 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/.idea/copilotDiffState.xml +67 -0
- package/README.md +26 -514
- package/dist/auth/core.js +3 -3
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +2 -1
- package/dist/auth/providers/google.d.ts +63 -0
- package/dist/auth/providers/google.js +186 -0
- package/dist/auth/providers.d.ts +1 -0
- package/dist/auth/providers.js +3 -1
- package/dist/auth/types.d.ts +6 -7
- package/dist/bin/hightjs.js +393 -0
- package/dist/client/entry.client.js +11 -1
- package/dist/hotReload.d.ts +8 -1
- package/dist/hotReload.js +304 -144
- package/dist/index.d.ts +2 -1
- package/dist/index.js +20 -33
- package/dist/renderer.js +1 -1
- package/dist/router.d.ts +24 -1
- package/dist/router.js +201 -2
- package/dist/types.d.ts +19 -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/auth/core.ts +3 -3
- package/src/auth/index.ts +2 -3
- package/src/auth/providers/google.ts +218 -0
- package/src/auth/providers.ts +1 -1
- package/src/auth/types.ts +3 -8
- package/src/bin/hightjs.js +475 -0
- package/src/client/entry.client.tsx +12 -1
- package/src/hotReload.ts +333 -147
- package/src/index.ts +58 -51
- package/src/renderer.tsx +1 -1
- package/src/router.ts +230 -3
- package/src/types.ts +24 -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/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/auth/example.ts +0 -115
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GoogleProvider = void 0;
|
|
4
|
+
const http_1 = require("../../api/http");
|
|
5
|
+
/**
|
|
6
|
+
* Provider para autenticação com Google OAuth2
|
|
7
|
+
*
|
|
8
|
+
* Este provider permite autenticação usando Google OAuth2.
|
|
9
|
+
* Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
|
|
10
|
+
*
|
|
11
|
+
* Exemplo de uso:
|
|
12
|
+
* ```typescript
|
|
13
|
+
* new GoogleProvider({
|
|
14
|
+
* clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
15
|
+
* clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
16
|
+
* callbackUrl: "http://localhost:3000/api/auth/callback/google"
|
|
17
|
+
* })
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* Fluxo de autenticação:
|
|
21
|
+
* 1. GET /api/auth/signin/google - Gera URL e redireciona para Google
|
|
22
|
+
* 2. Google redireciona para /api/auth/callback/google com código
|
|
23
|
+
* 3. Provider troca código por token e busca dados do usuário
|
|
24
|
+
* 4. Retorna objeto User com dados do Google
|
|
25
|
+
*/
|
|
26
|
+
class GoogleProvider {
|
|
27
|
+
constructor(config) {
|
|
28
|
+
this.type = 'google';
|
|
29
|
+
this.defaultScope = [
|
|
30
|
+
'openid',
|
|
31
|
+
'https://www.googleapis.com/auth/userinfo.email',
|
|
32
|
+
'https://www.googleapis.com/auth/userinfo.profile'
|
|
33
|
+
];
|
|
34
|
+
/**
|
|
35
|
+
* Rotas adicionais específicas do Google OAuth
|
|
36
|
+
*/
|
|
37
|
+
this.additionalRoutes = [
|
|
38
|
+
// Rota de callback do Google
|
|
39
|
+
{
|
|
40
|
+
method: 'GET',
|
|
41
|
+
path: '/api/auth/callback/google',
|
|
42
|
+
handler: async (req, params) => {
|
|
43
|
+
const url = new URL(req.url || '', 'http://localhost');
|
|
44
|
+
const code = url.searchParams.get('code');
|
|
45
|
+
if (!code) {
|
|
46
|
+
return http_1.HightJSResponse.json({ error: 'Authorization code not provided' }, { status: 400 });
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
// Delega o 'code' para o endpoint de signin principal
|
|
50
|
+
const authResponse = await fetch(`${req.headers.origin || 'http://localhost:3000'}/api/auth/signin`, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
headers: {
|
|
53
|
+
'Content-Type': 'application/json',
|
|
54
|
+
},
|
|
55
|
+
body: JSON.stringify({
|
|
56
|
+
provider: this.id,
|
|
57
|
+
code,
|
|
58
|
+
})
|
|
59
|
+
});
|
|
60
|
+
if (authResponse.ok) {
|
|
61
|
+
// Propaga o cookie de sessão e redireciona para a URL de sucesso
|
|
62
|
+
const setCookieHeader = authResponse.headers.get('set-cookie');
|
|
63
|
+
if (this.config.successUrl) {
|
|
64
|
+
return http_1.HightJSResponse
|
|
65
|
+
.redirect(this.config.successUrl)
|
|
66
|
+
.header('Set-Cookie', setCookieHeader || '');
|
|
67
|
+
}
|
|
68
|
+
return http_1.HightJSResponse.json({ success: true })
|
|
69
|
+
.header('Set-Cookie', setCookieHeader || '');
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
const errorText = await authResponse.text();
|
|
73
|
+
console.error(`[${this.id} Provider] Session creation failed during callback. Status: ${authResponse.status}, Body: ${errorText}`);
|
|
74
|
+
return http_1.HightJSResponse.json({ error: 'Session creation failed' }, { status: 500 });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
console.error(`[${this.id} Provider] Callback handler fetch error:`, error);
|
|
79
|
+
return http_1.HightJSResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
];
|
|
84
|
+
this.config = config;
|
|
85
|
+
this.id = config.id || 'google';
|
|
86
|
+
this.name = config.name || 'Google';
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Método para gerar URL OAuth (usado pelo handleSignIn)
|
|
90
|
+
*/
|
|
91
|
+
handleOauth(credentials = {}) {
|
|
92
|
+
return this.getAuthorizationUrl();
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Método principal - redireciona para OAuth ou processa o callback
|
|
96
|
+
*/
|
|
97
|
+
async handleSignIn(credentials) {
|
|
98
|
+
// Se tem código, é o callback - processa a autenticação
|
|
99
|
+
if (credentials.code) {
|
|
100
|
+
return await this.processOAuthCallback(credentials);
|
|
101
|
+
}
|
|
102
|
+
// Se não tem código, é o início do OAuth - retorna a URL
|
|
103
|
+
return this.handleOauth(credentials);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Processa o callback do OAuth (troca o código pelo usuário)
|
|
107
|
+
*/
|
|
108
|
+
async processOAuthCallback(credentials) {
|
|
109
|
+
try {
|
|
110
|
+
const { code } = credentials;
|
|
111
|
+
if (!code) {
|
|
112
|
+
throw new Error('Authorization code not provided');
|
|
113
|
+
}
|
|
114
|
+
// Troca o código por um access token
|
|
115
|
+
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
|
|
116
|
+
method: 'POST',
|
|
117
|
+
headers: {
|
|
118
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
119
|
+
},
|
|
120
|
+
body: new URLSearchParams({
|
|
121
|
+
client_id: this.config.clientId,
|
|
122
|
+
client_secret: this.config.clientSecret,
|
|
123
|
+
grant_type: 'authorization_code',
|
|
124
|
+
code,
|
|
125
|
+
redirect_uri: this.config.callbackUrl || '',
|
|
126
|
+
}),
|
|
127
|
+
});
|
|
128
|
+
if (!tokenResponse.ok) {
|
|
129
|
+
const error = await tokenResponse.text();
|
|
130
|
+
throw new Error(`Failed to exchange code for token: ${error}`);
|
|
131
|
+
}
|
|
132
|
+
const tokens = await tokenResponse.json();
|
|
133
|
+
// Busca os dados do usuário com o access token
|
|
134
|
+
const userResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
|
|
135
|
+
headers: {
|
|
136
|
+
'Authorization': `Bearer ${tokens.access_token}`,
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
if (!userResponse.ok) {
|
|
140
|
+
throw new Error('Failed to fetch user data');
|
|
141
|
+
}
|
|
142
|
+
const googleUser = await userResponse.json();
|
|
143
|
+
// Retorna o objeto User padronizado
|
|
144
|
+
return {
|
|
145
|
+
id: googleUser.id,
|
|
146
|
+
name: googleUser.name,
|
|
147
|
+
email: googleUser.email,
|
|
148
|
+
image: googleUser.picture || null,
|
|
149
|
+
provider: this.id,
|
|
150
|
+
providerId: googleUser.id,
|
|
151
|
+
accessToken: tokens.access_token,
|
|
152
|
+
refreshToken: tokens.refresh_token
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
console.error(`[${this.id} Provider] Error during OAuth callback:`, error);
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Gera a URL de autorização do Google
|
|
162
|
+
*/
|
|
163
|
+
getAuthorizationUrl() {
|
|
164
|
+
const params = new URLSearchParams({
|
|
165
|
+
client_id: this.config.clientId,
|
|
166
|
+
redirect_uri: this.config.callbackUrl || '',
|
|
167
|
+
response_type: 'code',
|
|
168
|
+
scope: (this.config.scope || this.defaultScope).join(' ')
|
|
169
|
+
});
|
|
170
|
+
return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Retorna a configuração pública do provider
|
|
174
|
+
*/
|
|
175
|
+
getConfig() {
|
|
176
|
+
return {
|
|
177
|
+
id: this.id,
|
|
178
|
+
name: this.name,
|
|
179
|
+
type: this.type,
|
|
180
|
+
clientId: this.config.clientId, // Público
|
|
181
|
+
scope: this.config.scope || this.defaultScope,
|
|
182
|
+
callbackUrl: this.config.callbackUrl
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
exports.GoogleProvider = GoogleProvider;
|
package/dist/auth/providers.d.ts
CHANGED
package/dist/auth/providers.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DiscordProvider = exports.CredentialsProvider = void 0;
|
|
3
|
+
exports.GoogleProvider = exports.DiscordProvider = exports.CredentialsProvider = void 0;
|
|
4
4
|
// Exportações dos providers
|
|
5
5
|
var credentials_1 = require("./providers/credentials");
|
|
6
6
|
Object.defineProperty(exports, "CredentialsProvider", { enumerable: true, get: function () { return credentials_1.CredentialsProvider; } });
|
|
7
7
|
var discord_1 = require("./providers/discord");
|
|
8
8
|
Object.defineProperty(exports, "DiscordProvider", { enumerable: true, get: function () { return discord_1.DiscordProvider; } });
|
|
9
|
+
var google_1 = require("./providers/google");
|
|
10
|
+
Object.defineProperty(exports, "GoogleProvider", { enumerable: true, get: function () { return google_1.GoogleProvider; } });
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -48,7 +48,11 @@ export interface AuthConfig {
|
|
|
48
48
|
};
|
|
49
49
|
callbacks?: {
|
|
50
50
|
signIn?: (user: User, account: any, profile: any) => boolean | Promise<boolean>;
|
|
51
|
-
session?: (session
|
|
51
|
+
session?: ({ session, user, provider }: {
|
|
52
|
+
session: Session;
|
|
53
|
+
user: User;
|
|
54
|
+
provider: string;
|
|
55
|
+
}) => Session | Promise<Session>;
|
|
52
56
|
jwt?: (token: any, user: User, account: any, profile: any) => any | Promise<any>;
|
|
53
57
|
};
|
|
54
58
|
session?: {
|
|
@@ -58,12 +62,7 @@ export interface AuthConfig {
|
|
|
58
62
|
};
|
|
59
63
|
secret?: string;
|
|
60
64
|
debug?: boolean;
|
|
61
|
-
|
|
62
|
-
export interface AuthProvider {
|
|
63
|
-
id: string;
|
|
64
|
-
name: string;
|
|
65
|
-
type: 'credentials';
|
|
66
|
-
authorize?: (credentials: Record<string, string>) => Promise<User | null> | User | null;
|
|
65
|
+
secureCookies?: boolean;
|
|
67
66
|
}
|
|
68
67
|
export interface CredentialsConfig {
|
|
69
68
|
id?: string;
|
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);
|
|
@@ -49,7 +49,17 @@ function App({ componentMap, routes, initialComponentPath, initialParams, layout
|
|
|
49
49
|
const [params, setParams] = (0, react_1.useState)(initialParams);
|
|
50
50
|
const findRouteForPath = (0, react_1.useCallback)((path) => {
|
|
51
51
|
for (const route of routes) {
|
|
52
|
-
const regexPattern = route.pattern
|
|
52
|
+
const regexPattern = route.pattern
|
|
53
|
+
// [[...param]] → opcional catch-all
|
|
54
|
+
.replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
|
|
55
|
+
// [...param] → obrigatório catch-all
|
|
56
|
+
.replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
|
|
57
|
+
// /[[param]] → opcional com barra também opcional
|
|
58
|
+
.replace(/\/\[\[(\w+)\]\]/g, '(?:/(?<$1>[^/]+))?')
|
|
59
|
+
// [[param]] → segmento opcional (sem barra anterior)
|
|
60
|
+
.replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
|
|
61
|
+
// [param] → segmento obrigatório
|
|
62
|
+
.replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
|
|
53
63
|
const regex = new RegExp(`^${regexPattern}/?$`);
|
|
54
64
|
const match = path.match(regex);
|
|
55
65
|
if (match) {
|