hightjs 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +48 -116
  2. package/dist/bin/hightjs.js +51 -23
  3. package/dist/builder.js +139 -4
  4. package/dist/client/DefaultNotFound.d.ts +1 -1
  5. package/dist/client/DefaultNotFound.js +72 -46
  6. package/dist/client/client.d.ts +3 -0
  7. package/dist/{client.js → client/client.js} +4 -4
  8. package/dist/client/entry.client.js +39 -29
  9. package/dist/global/global.d.ts +117 -0
  10. package/dist/{auth/types.js → global/global.js} +0 -1
  11. package/dist/helpers.js +80 -2
  12. package/dist/hotReload.js +2 -2
  13. package/dist/index.js +16 -16
  14. package/dist/loaders.d.ts +1 -0
  15. package/dist/loaders.js +46 -0
  16. package/dist/renderer.js +158 -4
  17. package/dist/types.d.ts +44 -0
  18. package/package.json +36 -31
  19. package/.idea/HightJS.iml +0 -9
  20. package/.idea/copilot.data.migration.agent.xml +0 -6
  21. package/.idea/copilot.data.migration.ask.xml +0 -6
  22. package/.idea/copilot.data.migration.ask2agent.xml +0 -6
  23. package/.idea/copilot.data.migration.edit.xml +0 -6
  24. package/.idea/copilotDiffState.xml +0 -67
  25. package/.idea/inspectionProfiles/Project_Default.xml +0 -13
  26. package/.idea/libraries/test_package.xml +0 -9
  27. package/.idea/libraries/ts_commonjs_default_export.xml +0 -9
  28. package/.idea/misc.xml +0 -7
  29. package/.idea/modules.xml +0 -8
  30. package/.idea/vcs.xml +0 -6
  31. package/dist/auth/client.d.ts +0 -24
  32. package/dist/auth/client.js +0 -146
  33. package/dist/auth/components.d.ts +0 -29
  34. package/dist/auth/components.js +0 -100
  35. package/dist/auth/core.d.ts +0 -55
  36. package/dist/auth/core.js +0 -189
  37. package/dist/auth/index.d.ts +0 -7
  38. package/dist/auth/index.js +0 -45
  39. package/dist/auth/jwt.d.ts +0 -41
  40. package/dist/auth/jwt.js +0 -185
  41. package/dist/auth/providers/credentials.d.ts +0 -60
  42. package/dist/auth/providers/credentials.js +0 -97
  43. package/dist/auth/providers/discord.d.ts +0 -63
  44. package/dist/auth/providers/discord.js +0 -190
  45. package/dist/auth/providers/google.d.ts +0 -63
  46. package/dist/auth/providers/google.js +0 -186
  47. package/dist/auth/providers/index.d.ts +0 -2
  48. package/dist/auth/providers/index.js +0 -35
  49. package/dist/auth/providers.d.ts +0 -3
  50. package/dist/auth/providers.js +0 -26
  51. package/dist/auth/react/index.d.ts +0 -6
  52. package/dist/auth/react/index.js +0 -48
  53. package/dist/auth/react.d.ts +0 -22
  54. package/dist/auth/react.js +0 -199
  55. package/dist/auth/routes.d.ts +0 -16
  56. package/dist/auth/routes.js +0 -152
  57. package/dist/auth/types.d.ts +0 -76
  58. package/dist/client.d.ts +0 -3
  59. package/docs/README.md +0 -58
  60. package/docs/arquivos-especiais.md +0 -10
  61. package/docs/autenticacao.md +0 -212
  62. package/docs/checklist.md +0 -9
  63. package/docs/cli.md +0 -72
  64. package/docs/config.md +0 -216
  65. package/docs/estrutura.md +0 -20
  66. package/docs/faq.md +0 -10
  67. package/docs/hot-reload.md +0 -5
  68. package/docs/integracoes.md +0 -240
  69. package/docs/middlewares.md +0 -73
  70. package/docs/rotas-backend.md +0 -45
  71. package/docs/rotas-frontend.md +0 -66
  72. package/docs/seguranca.md +0 -8
  73. package/docs/websocket.md +0 -45
  74. package/example/certs/cert.pem +0 -20
  75. package/example/certs/key.pem +0 -27
  76. package/example/hightjs.config.ts +0 -87
  77. package/example/package-lock.json +0 -1174
  78. package/example/package.json +0 -26
  79. package/example/postcss.config.js +0 -8
  80. package/example/src/backend/auth.ts +0 -42
  81. package/example/src/backend/routes/auth.ts +0 -3
  82. package/example/src/backend/routes/version.ts +0 -13
  83. package/example/src/web/components/Home.tsx +0 -140
  84. package/example/src/web/components/LoginPage.tsx +0 -149
  85. package/example/src/web/globals.css +0 -5
  86. package/example/src/web/layout.tsx +0 -100
  87. package/example/src/web/routes/index.tsx +0 -13
  88. package/example/src/web/routes/login.tsx +0 -30
  89. package/example/tailwind.config.js +0 -12
  90. package/example/tsconfig.json +0 -15
  91. package/src/adapters/express.ts +0 -87
  92. package/src/adapters/factory.ts +0 -112
  93. package/src/adapters/fastify.ts +0 -104
  94. package/src/adapters/native.ts +0 -234
  95. package/src/api/console.ts +0 -305
  96. package/src/api/http.ts +0 -535
  97. package/src/auth/client.ts +0 -171
  98. package/src/auth/components.tsx +0 -125
  99. package/src/auth/core.ts +0 -215
  100. package/src/auth/index.ts +0 -25
  101. package/src/auth/jwt.ts +0 -210
  102. package/src/auth/providers/credentials.ts +0 -139
  103. package/src/auth/providers/discord.ts +0 -239
  104. package/src/auth/providers/google.ts +0 -234
  105. package/src/auth/providers/index.ts +0 -20
  106. package/src/auth/providers.ts +0 -20
  107. package/src/auth/react/index.ts +0 -25
  108. package/src/auth/react.tsx +0 -234
  109. package/src/auth/routes.ts +0 -183
  110. package/src/auth/types.ts +0 -108
  111. package/src/bin/hightjs.js +0 -222
  112. package/src/builder.js +0 -472
  113. package/src/client/DefaultNotFound.tsx +0 -84
  114. package/src/client/clientRouter.ts +0 -153
  115. package/src/client/entry.client.tsx +0 -511
  116. package/src/client.ts +0 -24
  117. package/src/components/Link.tsx +0 -38
  118. package/src/helpers.ts +0 -542
  119. package/src/hotReload.ts +0 -569
  120. package/src/index.ts +0 -555
  121. package/src/renderer.tsx +0 -263
  122. package/src/router.ts +0 -730
  123. package/src/types/framework.ts +0 -58
  124. package/src/types.ts +0 -207
  125. package/tsconfig.json +0 -17
@@ -1,234 +0,0 @@
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, { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
18
- import type { Session, SessionContextType, SignInOptions, SignInResult, User } from './types';
19
- import { router } from "../client/clientRouter";
20
-
21
- const SessionContext = createContext<SessionContextType | undefined>(undefined);
22
-
23
- interface SessionProviderProps {
24
- children: ReactNode;
25
- basePath?: string;
26
- refetchInterval?: number;
27
- refetchOnWindowFocus?: boolean;
28
- }
29
-
30
- export function SessionProvider({
31
- children,
32
- basePath = '/api/auth',
33
- refetchInterval = 0,
34
- refetchOnWindowFocus = true
35
- }: SessionProviderProps) {
36
- const [session, setSession] = useState<Session | null>(null);
37
- const [status, setStatus] = useState<'loading' | 'authenticated' | 'unauthenticated'>('loading');
38
-
39
- // Fetch da sessão atual
40
- const fetchSession = useCallback(async (): Promise<Session | null> => {
41
- try {
42
- const response = await fetch(`${basePath}/session`, {
43
- credentials: 'include'
44
- });
45
-
46
- if (!response.ok) {
47
- setStatus('unauthenticated');
48
- return null;
49
- }
50
-
51
- const data = await response.json();
52
- const sessionData = data.session;
53
-
54
- if (sessionData) {
55
- setSession(sessionData);
56
- setStatus('authenticated');
57
- return sessionData;
58
- } else {
59
- setSession(null);
60
- setStatus('unauthenticated');
61
- return null;
62
- }
63
- } catch (error) {
64
- console.error('[hweb-auth] Error fetching session:', error);
65
- setSession(null);
66
- setStatus('unauthenticated');
67
- return null;
68
- }
69
- }, [basePath]);
70
-
71
- // SignIn function
72
- const signIn = useCallback(async (
73
- provider: string = 'credentials',
74
- options: SignInOptions = {}
75
- ): Promise<SignInResult | undefined> => {
76
- try {
77
- const { redirect = true, callbackUrl, ...credentials } = options;
78
-
79
- const response = await fetch(`${basePath}/signin`, {
80
- method: 'POST',
81
- headers: {
82
- 'Content-Type': 'application/json',
83
- },
84
- credentials: 'include',
85
- body: JSON.stringify({
86
- provider,
87
- ...credentials
88
- })
89
- });
90
-
91
- const data = await response.json();
92
-
93
- if (response.ok && data.success) {
94
- await fetchSession();
95
- // Se é OAuth, redireciona para URL fornecida
96
- if (data.type === 'oauth' && data.redirectUrl) {
97
- if (redirect && typeof window !== 'undefined') {
98
- window.location.href = data.redirectUrl;
99
- }
100
-
101
- return {
102
- ok: true,
103
- status: 200,
104
- url: data.redirectUrl
105
- };
106
- }
107
-
108
- // Se é sessão (credentials), redireciona para callbackUrl
109
- if (data.type === 'session') {
110
- if (redirect && typeof window !== 'undefined') {
111
- window.location.href = callbackUrl || '/';
112
- }
113
-
114
- return {
115
- ok: true,
116
- status: 200,
117
- url: callbackUrl || '/'
118
- };
119
- }
120
- } else {
121
- return {
122
- error: data.error || 'Authentication failed',
123
- status: response.status,
124
- ok: false
125
- };
126
- }
127
- } catch (error) {
128
- console.error('[hweb-auth] Error on signIn:', error);
129
- return {
130
- error: 'Network error',
131
- status: 500,
132
- ok: false
133
- };
134
- }
135
- }, [basePath, fetchSession]);
136
-
137
- // SignOut function
138
- const signOut = useCallback(async (options: { callbackUrl?: string } = {}): Promise<void> => {
139
- try {
140
- await fetch(`${basePath}/signout`, {
141
- method: 'POST',
142
- credentials: 'include'
143
- });
144
-
145
- setSession(null);
146
- setStatus('unauthenticated');
147
-
148
- if (typeof window !== 'undefined') {
149
- try {
150
- router.push(options.callbackUrl || '/');
151
- } catch (e) {
152
- window.location.href = options.callbackUrl || '/';
153
- }
154
- }
155
- } catch (error) {
156
- console.error('[hweb-auth] Error on signOut:', error);
157
- }
158
- }, [basePath]);
159
-
160
- // Update session
161
- const update = useCallback(async (): Promise<Session | null> => {
162
- return await fetchSession();
163
- }, [fetchSession]);
164
-
165
- // Initial session fetch
166
- useEffect(() => {
167
- fetchSession();
168
- }, [fetchSession]);
169
-
170
- // Refetch interval
171
- useEffect(() => {
172
- if (refetchInterval > 0) {
173
- const interval = setInterval(() => {
174
- if (status === 'authenticated') {
175
- fetchSession();
176
- }
177
- }, refetchInterval * 1000);
178
-
179
- return () => clearInterval(interval);
180
- }
181
- }, [refetchInterval, status, fetchSession]);
182
-
183
- // Refetch on window focus
184
- useEffect(() => {
185
- if (refetchOnWindowFocus) {
186
- const handleFocus = () => {
187
- if (status === 'authenticated') {
188
- fetchSession();
189
- }
190
- };
191
-
192
- window.addEventListener('focus', handleFocus);
193
- return () => window.removeEventListener('focus', handleFocus);
194
- }
195
- }, [refetchOnWindowFocus, status, fetchSession]);
196
-
197
- const value: SessionContextType = {
198
- data: session,
199
- status,
200
- signIn,
201
- signOut,
202
- update
203
- };
204
-
205
- return (
206
- <SessionContext.Provider value={value}>
207
- {children}
208
- </SessionContext.Provider>
209
- );
210
- }
211
-
212
- /**
213
- * Hook para acessar a sessão atual
214
- */
215
- export function useSession(): SessionContextType {
216
- const context = useContext(SessionContext);
217
- if (context === undefined) {
218
- throw new Error('useSession must be used inside a SessionProvider');
219
- }
220
- return context;
221
- }
222
-
223
- /**
224
- * Hook para verificar se o usuário está autenticado
225
- */
226
- export function useAuth(): { user: User | null; isAuthenticated: boolean; isLoading: boolean } {
227
- const { data: session, status } = useSession();
228
-
229
- return {
230
- user: session?.user || null,
231
- isAuthenticated: status === 'authenticated',
232
- isLoading: status === 'loading'
233
- };
234
- }
@@ -1,183 +0,0 @@
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 { HightJSRequest, HightJSResponse } from '../api/http';
18
- import type { AuthConfig } from './types';
19
- import { HWebAuth } from './core';
20
- import Console from "../api/console";
21
-
22
- /**
23
- * Cria o handler catch-all para /api/auth/[...value]
24
- */
25
- export function createAuthRoutes(config: AuthConfig) {
26
- const auth = new HWebAuth(config);
27
-
28
- /**
29
- * Handler principal que gerencia todas as rotas de auth
30
- * Uso: /api/auth/[...value].ts
31
- */
32
- return {
33
- pattern: '/api/auth/[...value]',
34
-
35
- async GET(req: HightJSRequest, params: { [key: string]: string }) {
36
-
37
- const path = params["value"];
38
- const route = Array.isArray(path) ? path.join('/') : path || '';
39
-
40
- // Verifica rotas adicionais dos providers primeiro
41
- const additionalRoutes = auth.getAllAdditionalRoutes();
42
- for (const { provider, route: additionalRoute } of additionalRoutes) {
43
-
44
- if (additionalRoute.method === 'GET' && additionalRoute.path.includes(route)) {
45
- try {
46
- return await additionalRoute.handler(req, params);
47
- } catch (error) {
48
- console.error(`[${provider} Provider] Error in additional route:`, error);
49
- return HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
50
- }
51
- }
52
- }
53
-
54
- // Rotas padrão do sistema
55
- switch (route) {
56
- case 'session':
57
- return await handleSession(req, auth);
58
-
59
- case 'csrf':
60
- return await handleCsrf(req);
61
-
62
- case 'providers':
63
- return await handleProviders(auth);
64
-
65
- default:
66
- return HightJSResponse.json({ error: 'Route not found' }, { status: 404 });
67
- }
68
- },
69
-
70
- async POST(req: HightJSRequest, params: { [key: string]: string }) {
71
- const path = params["value"];
72
- const route = Array.isArray(path) ? path.join('/') : path || '';
73
-
74
- // Verifica rotas adicionais dos providers primeiro
75
- const additionalRoutes = auth.getAllAdditionalRoutes();
76
- for (const { provider, route: additionalRoute } of additionalRoutes) {
77
- if (additionalRoute.method === 'POST' && additionalRoute.path.includes(route)) {
78
- try {
79
- return await additionalRoute.handler(req, params);
80
- } catch (error) {
81
- console.error(`[${provider} Provider] Error in additional route:`, error);
82
- return HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
83
- }
84
- }
85
- }
86
-
87
- // Rotas padrão do sistema
88
- switch (route) {
89
- case 'signin':
90
- return await handleSignIn(req, auth);
91
-
92
- case 'signout':
93
- return await handleSignOut(req, auth);
94
-
95
- default:
96
- return HightJSResponse.json({ error: 'Route not found' }, { status: 404 });
97
- }
98
- },
99
-
100
- // Instância do auth para uso manual
101
- auth
102
- };
103
- }
104
-
105
- /**
106
- * Handler para GET /api/auth/session
107
- */
108
- async function handleSession(req: HightJSRequest, auth: HWebAuth) {
109
- const session = await auth.getSession(req);
110
-
111
- if (!session) {
112
- return HightJSResponse.json({ session: null });
113
- }
114
-
115
- return HightJSResponse.json({ session });
116
- }
117
-
118
- /**
119
- * Handler para GET /api/auth/csrf
120
- */
121
- async function handleCsrf(req: HightJSRequest) {
122
- // Token CSRF simples para proteção
123
- const csrfToken = Math.random().toString(36).substring(2, 15) +
124
- Math.random().toString(36).substring(2, 15);
125
-
126
- return HightJSResponse.json({ csrfToken });
127
- }
128
-
129
- /**
130
- * Handler para GET /api/auth/providers
131
- */
132
- async function handleProviders(auth: HWebAuth) {
133
- const providers = auth.getProviders();
134
-
135
- return HightJSResponse.json({ providers });
136
- }
137
-
138
- /**
139
- * Handler para POST /api/auth/signin
140
- */
141
- async function handleSignIn(req: HightJSRequest, auth: HWebAuth) {
142
- try {
143
- const { provider = 'credentials', ...credentials } = await req.json();
144
-
145
- const result = await auth.signIn(provider, credentials);
146
-
147
- if (!result) {
148
- return HightJSResponse.json(
149
- { error: 'Invalid credentials' },
150
- { status: 401 }
151
- );
152
- }
153
-
154
- // Se tem redirectUrl, é OAuth - retorna URL para redirecionamento
155
- if ('redirectUrl' in result) {
156
- return HightJSResponse.json({
157
- success: true,
158
- redirectUrl: result.redirectUrl,
159
- type: 'oauth'
160
- });
161
- }
162
-
163
- // Se tem session, é credentials - retorna sessão
164
- return auth.createAuthResponse(result.token, {
165
- success: true,
166
- user: result.session.user,
167
- type: 'session'
168
- });
169
- } catch (error) {
170
- console.error('[hweb-auth] Error on handleSignIn:', error);
171
- return HightJSResponse.json(
172
- { error: 'Authentication failed' },
173
- { status: 500 }
174
- );
175
- }
176
- }
177
-
178
- /**
179
- * Handler para POST /api/auth/signout
180
- */
181
- async function handleSignOut(req: HightJSRequest, auth: HWebAuth) {
182
- return await auth.signOut(req);
183
- }
package/src/auth/types.ts DELETED
@@ -1,108 +0,0 @@
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
-
18
- // Tipos para o sistema de autenticação
19
- export type User = Record<string, any>;
20
-
21
- export interface Session {
22
- user: User;
23
- expires: string;
24
- accessToken?: string;
25
- }
26
-
27
- // Client-side types
28
- export interface SignInOptions {
29
- redirect?: boolean;
30
- callbackUrl?: string;
31
- [key: string]: any;
32
- }
33
-
34
- export interface SignInResult {
35
- error?: string;
36
- status?: number;
37
- ok?: boolean;
38
- url?: string;
39
- }
40
-
41
- export interface SessionContextType {
42
- data: Session | null;
43
- status: 'loading' | 'authenticated' | 'unauthenticated';
44
- signIn: (provider?: string, options?: SignInOptions) => Promise<SignInResult | undefined>;
45
- signOut: (options?: { callbackUrl?: string }) => Promise<void>;
46
- update: () => Promise<Session | null>;
47
- }
48
-
49
- export interface AuthRoute {
50
- method: 'GET' | 'POST' | 'PUT' | 'DELETE';
51
- path: string;
52
- handler: (req: any, params: any) => Promise<any>;
53
- }
54
-
55
- export interface AuthProviderClass {
56
- id: string;
57
- name: string;
58
- type: string;
59
-
60
- // Para providers OAuth - retorna URL de redirecionamento
61
- handleOauth?(credentials: Record<string, string>): Promise<string> | string;
62
-
63
- // Métodos principais
64
- handleSignIn(credentials: Record<string, string>): Promise<User | string | null>;
65
- handleSignOut?(): Promise<void>;
66
-
67
- // Rotas adicionais que o provider pode ter
68
- additionalRoutes?: AuthRoute[];
69
-
70
- // Configurações específicas do provider
71
- getConfig?(): any;
72
- }
73
-
74
- export interface AuthConfig {
75
- providers: AuthProviderClass[];
76
- pages?: {
77
- signIn?: string;
78
- signOut?: string;
79
- error?: string;
80
- };
81
- callbacks?: {
82
- signIn?: (user: User, account: any, profile: any) => boolean | Promise<boolean>;
83
- session?: ({session, user, provider}: {session: Session, user: User, provider: string}) => Session | Promise<Session>;
84
- jwt?: (token: any, user: User, account: any, profile: any) => any | Promise<any>;
85
- };
86
- session?: {
87
- strategy?: 'jwt' | 'database';
88
- maxAge?: number;
89
- updateAge?: number;
90
- };
91
- secret?: string;
92
- debug?: boolean;
93
- secureCookies?: boolean;
94
- }
95
-
96
-
97
-
98
- // Provider para credenciais
99
- export interface CredentialsConfig {
100
- id?: string;
101
- name?: string;
102
- credentials: Record<string, {
103
- label: string;
104
- type: string;
105
- placeholder?: string;
106
- }>;
107
- authorize: (credentials: Record<string, string>) => Promise<User | null> | User | null;
108
- }