@greatapps/common 1.1.70 → 1.1.73
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/dist/components/account/AccountModals.mjs +18 -0
- package/dist/components/account/AccountModals.mjs.map +1 -0
- package/dist/components/account/ConfigurationsMyAccountModal.mjs +132 -0
- package/dist/components/account/ConfigurationsMyAccountModal.mjs.map +1 -0
- package/dist/components/account/ConfirmDeleteAccountModal.mjs +45 -0
- package/dist/components/account/ConfirmDeleteAccountModal.mjs.map +1 -0
- package/dist/components/account/ConfirmGlobalPreferencesModal.mjs +45 -0
- package/dist/components/account/ConfirmGlobalPreferencesModal.mjs.map +1 -0
- package/dist/components/account/DeleteAccountModal.mjs +123 -0
- package/dist/components/account/DeleteAccountModal.mjs.map +1 -0
- package/dist/components/account/DisableTwoFactorAuthModal.mjs +67 -0
- package/dist/components/account/DisableTwoFactorAuthModal.mjs.map +1 -0
- package/dist/components/account/IsntPossibleDeleteAccountModal.mjs +42 -0
- package/dist/components/account/IsntPossibleDeleteAccountModal.mjs.map +1 -0
- package/dist/components/account/TwoFactorAuthModal.mjs +190 -0
- package/dist/components/account/TwoFactorAuthModal.mjs.map +1 -0
- package/dist/components/account/constants.mjs +29 -0
- package/dist/components/account/constants.mjs.map +1 -0
- package/dist/components/handlers/SearchParamsHandler.mjs +24 -0
- package/dist/components/handlers/SearchParamsHandler.mjs.map +1 -0
- package/dist/components/layouts/AppMobileNavBar.mjs +53 -0
- package/dist/components/layouts/AppMobileNavBar.mjs.map +1 -0
- package/dist/components/layouts/AppNavBar.mjs +73 -0
- package/dist/components/layouts/AppNavBar.mjs.map +1 -0
- package/dist/components/layouts/MainLayout.mjs +60 -0
- package/dist/components/layouts/MainLayout.mjs.map +1 -0
- package/dist/components/layouts/MdSideBarNavigation.mjs +39 -0
- package/dist/components/layouts/MdSideBarNavigation.mjs.map +1 -0
- package/dist/components/layouts/NavBar.mjs +64 -0
- package/dist/components/layouts/NavBar.mjs.map +1 -0
- package/dist/components/layouts/NavBarItem.mjs +23 -0
- package/dist/components/layouts/NavBarItem.mjs.map +1 -0
- package/dist/components/layouts/NotificationItem.mjs +11 -0
- package/dist/components/layouts/NotificationItem.mjs.map +1 -0
- package/dist/components/layouts/NotificationsPopover.mjs +96 -0
- package/dist/components/layouts/NotificationsPopover.mjs.map +1 -0
- package/dist/components/layouts/ProfilePopover.mjs +150 -0
- package/dist/components/layouts/ProfilePopover.mjs.map +1 -0
- package/dist/components/layouts/SideBarNavigation.mjs +22 -0
- package/dist/components/layouts/SideBarNavigation.mjs.map +1 -0
- package/dist/components/layouts/UsersSelectorPopover.mjs +236 -0
- package/dist/components/layouts/UsersSelectorPopover.mjs.map +1 -0
- package/dist/components/modals/ModalManager.mjs +19 -0
- package/dist/components/modals/ModalManager.mjs.map +1 -0
- package/dist/components/modals/Modals.mjs +20 -0
- package/dist/components/modals/Modals.mjs.map +1 -0
- package/dist/enums/AccountSectionType.mjs +11 -0
- package/dist/enums/AccountSectionType.mjs.map +1 -0
- package/dist/hooks/copy-to-clipboard.hook.mjs +39 -0
- package/dist/hooks/copy-to-clipboard.hook.mjs.map +1 -0
- package/dist/hooks/useCountdownTimer.mjs +29 -0
- package/dist/hooks/useCountdownTimer.mjs.map +1 -0
- package/dist/hooks/useIsMobile.mjs +18 -0
- package/dist/hooks/useIsMobile.mjs.map +1 -0
- package/dist/hooks/usePasswordVisibility.mjs +13 -0
- package/dist/hooks/usePasswordVisibility.mjs.map +1 -0
- package/dist/index.mjs +434 -0
- package/dist/index.mjs.map +1 -0
- package/dist/infra/api/client.mjs +122 -0
- package/dist/infra/api/client.mjs.map +1 -0
- package/dist/infra/api/types.mjs +31 -0
- package/dist/infra/api/types.mjs.map +1 -0
- package/dist/infra/utils/client-info.mjs +27 -0
- package/dist/infra/utils/client-info.mjs.map +1 -0
- package/dist/infra/utils/clsx.mjs +9 -0
- package/dist/infra/utils/clsx.mjs.map +1 -0
- package/dist/infra/utils/params.mjs +21 -0
- package/dist/infra/utils/params.mjs.map +1 -0
- package/dist/infra/utils/parser.mjs +24 -0
- package/dist/infra/utils/parser.mjs.map +1 -0
- package/dist/infra/utils/percentage.mjs +20 -0
- package/dist/infra/utils/percentage.mjs.map +1 -0
- package/dist/middlewares/chain.mjs +37 -0
- package/dist/middlewares/chain.mjs.map +1 -0
- package/dist/middlewares/create-auth-middleware.mjs +28 -0
- package/dist/middlewares/create-auth-middleware.mjs.map +1 -0
- package/dist/middlewares/types.mjs +11 -0
- package/dist/middlewares/types.mjs.map +1 -0
- package/dist/modules/accounts/types.mjs +1 -0
- package/dist/modules/accounts/types.mjs.map +1 -0
- package/dist/modules/auth/actions/login.action.mjs +1 -1
- package/dist/modules/auth/actions/login.action.mjs.map +1 -1
- package/dist/modules/auth/hooks/login.hook.mjs +5 -1
- package/dist/modules/auth/hooks/login.hook.mjs.map +1 -1
- package/dist/modules/auth/hooks/useUserQuery.mjs +2 -1
- package/dist/modules/auth/hooks/useUserQuery.mjs.map +1 -1
- package/dist/modules/auth/schema.mjs +1 -0
- package/dist/modules/auth/schema.mjs.map +1 -0
- package/dist/modules/auth/services/auth.service.mjs +2 -2
- package/dist/modules/auth/services/auth.service.mjs.map +1 -1
- package/dist/modules/ia-credits/types.mjs +25 -0
- package/dist/modules/ia-credits/types.mjs.map +1 -0
- package/dist/modules/projects/types.mjs +22 -0
- package/dist/modules/projects/types.mjs.map +1 -0
- package/dist/modules/subscriptions/types.mjs +57 -0
- package/dist/modules/subscriptions/types.mjs.map +1 -0
- package/dist/modules/users/action/list-messages.action.mjs +9 -0
- package/dist/modules/users/action/list-messages.action.mjs.map +1 -0
- package/dist/modules/users/action/mark-all-messages-as-read.action.mjs +9 -0
- package/dist/modules/users/action/mark-all-messages-as-read.action.mjs.map +1 -0
- package/dist/modules/users/action/mark-message-as-read.action.mjs +9 -0
- package/dist/modules/users/action/mark-message-as-read.action.mjs.map +1 -0
- package/dist/modules/users/hooks/messages.hook.mjs +38 -0
- package/dist/modules/users/hooks/messages.hook.mjs.map +1 -0
- package/dist/modules/users/schema/messages.schema.mjs +21 -0
- package/dist/modules/users/schema/messages.schema.mjs.map +1 -0
- package/dist/modules/users/schema.mjs +11 -0
- package/dist/modules/users/schema.mjs.map +1 -0
- package/dist/modules/users/services/messages.service.mjs +35 -0
- package/dist/modules/users/services/messages.service.mjs.map +1 -0
- package/dist/modules/whitelabel/schema.mjs +1 -0
- package/dist/modules/whitelabel/schema.mjs.map +1 -0
- package/dist/providers/auth.provider.mjs +98 -0
- package/dist/providers/auth.provider.mjs.map +1 -0
- package/dist/providers/query.provider.mjs +41 -0
- package/dist/providers/query.provider.mjs.map +1 -0
- package/dist/providers/whitelabel.provider.mjs +34 -0
- package/dist/providers/whitelabel.provider.mjs.map +1 -0
- package/dist/server.mjs +74 -0
- package/dist/server.mjs.map +1 -0
- package/dist/store/useAccountModals.mjs +18 -0
- package/dist/store/useAccountModals.mjs.map +1 -0
- package/dist/store/useMdSidebarStore.mjs +11 -0
- package/dist/store/useMdSidebarStore.mjs.map +1 -0
- package/dist/store/useModalManager.mjs +75 -0
- package/dist/store/useModalManager.mjs.map +1 -0
- package/dist/utils/browser/clipboard.mjs +36 -0
- package/dist/utils/browser/clipboard.mjs.map +1 -0
- package/dist/utils/file/index.mjs +9 -0
- package/dist/utils/file/index.mjs.map +1 -0
- package/dist/utils/format/masks.mjs +56 -0
- package/dist/utils/format/masks.mjs.map +1 -0
- package/dist/utils/intl/locales.mjs +12 -0
- package/dist/utils/intl/locales.mjs.map +1 -0
- package/dist/utils/safeServerAction.mjs +22 -0
- package/dist/utils/safeServerAction.mjs.map +1 -0
- package/dist/utils/validators/account.mjs +26 -0
- package/dist/utils/validators/account.mjs.map +1 -0
- package/dist/utils/validators/common.mjs +47 -0
- package/dist/utils/validators/common.mjs.map +1 -0
- package/package.json +1 -1
- package/src/components/layouts/AppNavBar.tsx +0 -4
- package/src/components/layouts/NotificationItem.tsx +2 -2
- package/src/components/layouts/NotificationsPopover.tsx +25 -22
- package/src/index.ts +267 -117
- package/src/modules/auth/actions/login.action.ts +1 -1
- package/src/modules/auth/hooks/login.hook.tsx +6 -1
- package/src/modules/auth/hooks/useUserQuery.ts +2 -1
- package/src/modules/auth/schema.ts +6 -4
- package/src/modules/auth/services/auth.service.ts +2 -2
- package/src/modules/users/action/list-messages.action.ts +10 -0
- package/src/modules/users/action/mark-all-messages-as-read.action.ts +8 -0
- package/src/modules/users/action/mark-message-as-read.action.ts +8 -0
- package/src/modules/users/hooks/messages.hook.ts +39 -0
- package/src/modules/users/schema/messages.schema.ts +46 -0
- package/src/modules/users/services/messages.service.ts +48 -0
- package/src/providers/auth.provider.tsx +6 -9
- package/src/utils/safeServerAction.ts +27 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { ApiError } from "./types";
|
|
2
|
+
import { findWhitelabel } from "../../modules/whitelabel/actions/find-whitelabel.action";
|
|
3
|
+
class ApiClient {
|
|
4
|
+
baseUrl;
|
|
5
|
+
apiVersion = "v1";
|
|
6
|
+
apiLocale = "pt-br";
|
|
7
|
+
constructor(baseUrl) {
|
|
8
|
+
this.baseUrl = baseUrl;
|
|
9
|
+
}
|
|
10
|
+
async buildUrl(endpoint, whiteLabelId) {
|
|
11
|
+
const url = `${this.baseUrl}/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}${endpoint}`;
|
|
12
|
+
console.log("[ApiClient] buildUrl", {
|
|
13
|
+
baseURL: this.baseUrl,
|
|
14
|
+
whiteLabelId,
|
|
15
|
+
endpoint,
|
|
16
|
+
fullUrl: url
|
|
17
|
+
});
|
|
18
|
+
return url;
|
|
19
|
+
}
|
|
20
|
+
async getDefaultHeaders(token) {
|
|
21
|
+
console.log("[ApiClient] getDefaultHeaders", {
|
|
22
|
+
token: token.substring(0, 20) + "..."
|
|
23
|
+
});
|
|
24
|
+
const headers = {
|
|
25
|
+
"Content-Type": "application/json",
|
|
26
|
+
authorization: token
|
|
27
|
+
};
|
|
28
|
+
return headers;
|
|
29
|
+
}
|
|
30
|
+
async request(endpoint, config = {}) {
|
|
31
|
+
console.log("[ApiClient] request called", { endpoint, method: config.method });
|
|
32
|
+
const { timeout = 3e4, ...fetchConfig } = config;
|
|
33
|
+
const controller = new AbortController();
|
|
34
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
35
|
+
try {
|
|
36
|
+
console.log("[ApiClient] Building URL and headers...");
|
|
37
|
+
const { id, token } = await findWhitelabel();
|
|
38
|
+
const [url, defaultHeaders] = await Promise.all([
|
|
39
|
+
this.buildUrl(endpoint, id),
|
|
40
|
+
this.getDefaultHeaders(token)
|
|
41
|
+
]);
|
|
42
|
+
console.log("[ApiClient] Fetching", {
|
|
43
|
+
url,
|
|
44
|
+
method: fetchConfig.method,
|
|
45
|
+
headers: defaultHeaders
|
|
46
|
+
});
|
|
47
|
+
const response = await fetch(url, {
|
|
48
|
+
...fetchConfig,
|
|
49
|
+
headers: {
|
|
50
|
+
...defaultHeaders,
|
|
51
|
+
...fetchConfig.headers
|
|
52
|
+
},
|
|
53
|
+
signal: controller.signal
|
|
54
|
+
});
|
|
55
|
+
console.log("[ApiClient] Response received", { status: response.status, ok: response.ok });
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
const errorData = await response.json().catch(() => ({}));
|
|
58
|
+
console.error("[ApiClient] Request failed", { status: response.status, errorData });
|
|
59
|
+
throw new ApiError(
|
|
60
|
+
errorData.message || `HTTP error ${response.status}`,
|
|
61
|
+
errorData.code || "HTTP_ERROR",
|
|
62
|
+
response.status
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
const data = await response.json();
|
|
66
|
+
console.log("[ApiClient] Request successful", { hasData: !!data });
|
|
67
|
+
return data;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
console.error("[ApiClient] Request error", { error });
|
|
70
|
+
if (error instanceof ApiError) {
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
if (error instanceof Error) {
|
|
74
|
+
if (error.name === "AbortError") {
|
|
75
|
+
throw new ApiError("Tempo de requisi\xE7\xE3o excedido", "TIMEOUT", 408);
|
|
76
|
+
}
|
|
77
|
+
throw new ApiError(error.message, "NETWORK_ERROR", 0);
|
|
78
|
+
}
|
|
79
|
+
throw new ApiError("Erro desconhecido", "UNKNOWN_ERROR", 500);
|
|
80
|
+
} finally {
|
|
81
|
+
clearTimeout(timeoutId);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async get(endpoint, config) {
|
|
85
|
+
return this.request(endpoint, { ...config, method: "GET" });
|
|
86
|
+
}
|
|
87
|
+
async post(endpoint, data, config) {
|
|
88
|
+
return this.request(endpoint, {
|
|
89
|
+
...config,
|
|
90
|
+
method: "POST",
|
|
91
|
+
body: data ? JSON.stringify(data) : void 0
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
async put(endpoint, data, config) {
|
|
95
|
+
return this.request(endpoint, {
|
|
96
|
+
...config,
|
|
97
|
+
method: "PUT",
|
|
98
|
+
body: data ? JSON.stringify(data) : void 0
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
async patch(endpoint, data, config) {
|
|
102
|
+
return this.request(endpoint, {
|
|
103
|
+
...config,
|
|
104
|
+
method: "PATCH",
|
|
105
|
+
body: data ? JSON.stringify(data) : void 0
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
async delete(endpoint, config) {
|
|
109
|
+
return this.request(endpoint, { ...config, method: "DELETE" });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const api = {
|
|
113
|
+
apps: new ApiClient(process.env.GAPPS_R3_API_URL || "https://r3-api.greatapps.dev.br"),
|
|
114
|
+
pages: new ApiClient(process.env.GPAGES_R3_API_URL || "https://r3-api.greatpages.dev.br")
|
|
115
|
+
};
|
|
116
|
+
const apiClient = api.apps;
|
|
117
|
+
export {
|
|
118
|
+
ApiClient,
|
|
119
|
+
api,
|
|
120
|
+
apiClient
|
|
121
|
+
};
|
|
122
|
+
//# sourceMappingURL=client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/api/client.ts"],"sourcesContent":["import { ApiError } from './types';\r\nimport { findWhitelabel } from '../../modules/whitelabel/actions/find-whitelabel.action';\r\n\r\ninterface RequestConfig extends RequestInit {\r\n timeout?: number;\r\n}\r\n\r\nclass ApiClient {\r\n private readonly baseUrl: string;\r\n private readonly apiVersion = 'v1';\r\n private readonly apiLocale = 'pt-br';\r\n\r\n constructor(baseUrl: string) {\r\n this.baseUrl = baseUrl;\r\n }\r\n\r\n private async buildUrl(endpoint: string, whiteLabelId: number): Promise<string> {\r\n const url = `${this.baseUrl}/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}${endpoint}`;\r\n console.log('[ApiClient] buildUrl', {\r\n baseURL: this.baseUrl,\r\n whiteLabelId,\r\n endpoint,\r\n fullUrl: url,\r\n });\r\n return url;\r\n }\r\n\r\n private async getDefaultHeaders(token: string): Promise<HeadersInit> {\r\n console.log('[ApiClient] getDefaultHeaders', {\r\n token: token.substring(0, 20) + '...',\r\n });\r\n\r\n const headers: HeadersInit = {\r\n 'Content-Type': 'application/json',\r\n authorization: token,\r\n };\r\n\r\n return headers;\r\n }\r\n\r\n async request<T>(endpoint: string, config: RequestConfig = {}): Promise<T> {\r\n console.log('[ApiClient] request called', { endpoint, method: config.method });\r\n\r\n const { timeout = 30000, ...fetchConfig } = config;\r\n\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), timeout);\r\n\r\n try {\r\n console.log('[ApiClient] Building URL and headers...');\r\n\r\n const { id, token } = await findWhitelabel();\r\n\r\n const [url, defaultHeaders] = await Promise.all([\r\n this.buildUrl(endpoint, id),\r\n this.getDefaultHeaders(token),\r\n ]);\r\n\r\n console.log('[ApiClient] Fetching', {\r\n url,\r\n method: fetchConfig.method,\r\n headers: defaultHeaders,\r\n });\r\n\r\n const response = await fetch(url, {\r\n ...fetchConfig,\r\n headers: {\r\n ...defaultHeaders,\r\n ...fetchConfig.headers,\r\n },\r\n signal: controller.signal,\r\n });\r\n\r\n console.log('[ApiClient] Response received', { status: response.status, ok: response.ok });\r\n\r\n if (!response.ok) {\r\n const errorData = (await response.json().catch(() => ({}))) as Record<string, unknown>;\r\n console.error('[ApiClient] Request failed', { status: response.status, errorData });\r\n throw new ApiError(\r\n (errorData.message as string) || `HTTP error ${response.status}`,\r\n (errorData.code as string) || 'HTTP_ERROR',\r\n response.status\r\n );\r\n }\r\n\r\n const data = (await response.json()) as T;\r\n console.log('[ApiClient] Request successful', { hasData: !!data });\r\n return data;\r\n } catch (error) {\r\n console.error('[ApiClient] Request error', { error });\r\n\r\n if (error instanceof ApiError) {\r\n throw error;\r\n }\r\n\r\n if (error instanceof Error) {\r\n if (error.name === 'AbortError') {\r\n throw new ApiError('Tempo de requisição excedido', 'TIMEOUT', 408);\r\n }\r\n throw new ApiError(error.message, 'NETWORK_ERROR', 0);\r\n }\r\n\r\n throw new ApiError('Erro desconhecido', 'UNKNOWN_ERROR', 500);\r\n } finally {\r\n clearTimeout(timeoutId);\r\n }\r\n }\r\n\r\n async get<T>(endpoint: string, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, { ...config, method: 'GET' });\r\n }\r\n\r\n async post<T>(endpoint: string, data?: unknown, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: 'POST',\r\n body: data ? JSON.stringify(data) : undefined,\r\n });\r\n }\r\n\r\n async put<T>(endpoint: string, data?: unknown, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: 'PUT',\r\n body: data ? JSON.stringify(data) : undefined,\r\n });\r\n }\r\n\r\n async patch<T>(endpoint: string, data?: unknown, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: 'PATCH',\r\n body: data ? JSON.stringify(data) : undefined,\r\n });\r\n }\r\n\r\n async delete<T>(endpoint: string, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, { ...config, method: 'DELETE' });\r\n }\r\n}\r\n\r\nconst api = {\r\n apps: new ApiClient(process.env.GAPPS_R3_API_URL || 'https://r3-api.greatapps.dev.br'),\r\n pages: new ApiClient(process.env.GPAGES_R3_API_URL || 'https://r3-api.greatpages.dev.br'),\r\n}\r\n\r\n/** @deprecated use api.apps */\r\nexport const apiClient = api.apps;\r\n\r\nexport { api, ApiClient };\r\n"],"mappings":"AAAA,SAAS,gBAAgB;AACzB,SAAS,sBAAsB;AAM/B,MAAM,UAAU;AAAA,EACG;AAAA,EACA,aAAa;AAAA,EACb,YAAY;AAAA,EAE7B,YAAY,SAAiB;AAC3B,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAc,SAAS,UAAkB,cAAuC;AAC9E,UAAM,MAAM,GAAG,KAAK,OAAO,IAAI,KAAK,UAAU,IAAI,KAAK,SAAS,IAAI,YAAY,GAAG,QAAQ;AAC3F,YAAQ,IAAI,wBAAwB;AAAA,MAClC,SAAS,KAAK;AAAA,MACd;AAAA,MACA;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AACD,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBAAkB,OAAqC;AACnE,YAAQ,IAAI,iCAAiC;AAAA,MAC3C,OAAO,MAAM,UAAU,GAAG,EAAE,IAAI;AAAA,IAClC,CAAC;AAED,UAAM,UAAuB;AAAA,MAC3B,gBAAgB;AAAA,MAChB,eAAe;AAAA,IACjB;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAW,UAAkB,SAAwB,CAAC,GAAe;AACzE,YAAQ,IAAI,8BAA8B,EAAE,UAAU,QAAQ,OAAO,OAAO,CAAC;AAE7E,UAAM,EAAE,UAAU,KAAO,GAAG,YAAY,IAAI;AAE5C,UAAM,aAAa,IAAI,gBAAgB;AACvC,UAAM,YAAY,WAAW,MAAM,WAAW,MAAM,GAAG,OAAO;AAE9D,QAAI;AACF,cAAQ,IAAI,yCAAyC;AAErD,YAAM,EAAE,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AI,SAAS,qBAAqB,iBAAiB,GAAG;AAAA,IAC9D,UAAE;AACA,mBAAa,SAAS;AAAA,IACxB;AAAA,EACF;AAAA,EAEA,MAAM,IAAO,UAAkB,QAAoC;AACjE,WAAO,KAAK,QAAW,UAAU,EAAE,GAAG,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAC/D;AAAA,EAEA,MAAM,KAAQ,UAAkB,MAAgB,QAAoC;AAClF,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,IACtC,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,IAAO,UAAkB,MAAgB,QAAoC;AACjF,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,IACtC,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MAAS,UAAkB,MAAgB,QAAoC;AACnF,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,IACtC,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,OAAU,UAAkB,QAAoC;AACpE,WAAO,KAAK,QAAW,UAAU,EAAE,GAAG,QAAQ,QAAQ,SAAS,CAAC;AAAA,EAClE;AACF;AAEA,MAAM,MAAM;AAAA,EACV,MAAM,IAAI,UAAU,QAAQ,IAAI,oBAAoB,iCAAiC;AAAA,EACrF,OAAO,IAAI,UAAU,QAAQ,IAAI,qBAAqB,kCAAkC;AAC1F;AAGO,MAAM,YAAY,IAAI;","names":[]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import z from "zod";
|
|
2
|
+
const PaginationParamsSchema = z.object({
|
|
3
|
+
page: z.number().min(1).optional().default(20),
|
|
4
|
+
limit: z.number().optional().default(20)
|
|
5
|
+
});
|
|
6
|
+
const SearchParamsSchema = z.object({
|
|
7
|
+
search: z.string().optional()
|
|
8
|
+
});
|
|
9
|
+
const SortParamsSchema = z.object({
|
|
10
|
+
sort: z.string().optional()
|
|
11
|
+
});
|
|
12
|
+
class ApiError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
statusCode;
|
|
15
|
+
constructor(message, code = "UNKNOWN_ERROR", statusCode = 500) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "ApiError";
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.statusCode = statusCode;
|
|
20
|
+
}
|
|
21
|
+
static isApiError(error) {
|
|
22
|
+
return error instanceof ApiError;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
ApiError,
|
|
27
|
+
PaginationParamsSchema,
|
|
28
|
+
SearchParamsSchema,
|
|
29
|
+
SortParamsSchema
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=types.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/api/types.ts"],"sourcesContent":["import z from 'zod';\r\n\r\nexport const PaginationParamsSchema = z.object({\r\n page: z.number().min(1).optional().default(20),\r\n limit: z.number().optional().default(20),\r\n});\r\n\r\nexport interface PaginationParams extends z.infer<typeof PaginationParamsSchema> {}\r\n\r\nexport const SearchParamsSchema = z.object({\r\n search: z.string().optional(),\r\n});\r\n\r\nexport interface SearchParams extends z.infer<typeof SearchParamsSchema> {}\r\n\r\nexport const SortParamsSchema = z.object({\r\n sort: z.string().optional(),\r\n});\r\n\r\nexport interface SortParams extends z.infer<typeof SortParamsSchema> {}\r\n\r\nexport interface ApiSuccessResult<T> {\r\n status: 1;\r\n data?: T;\r\n}\r\n\r\nexport interface ApiPaginatedSuccessResult<T> extends Omit<ApiSuccessResult<T>, 'data'> {\r\n data: T[];\r\n total: number;\r\n}\r\n\r\nexport interface ApiErrorResult {\r\n status: 0;\r\n message: string;\r\n}\r\n\r\nexport type ApiActionResult<T> = ApiSuccessResult<T> | ApiErrorResult;\r\nexport type ApiPaginatedActionResult<T> = ApiPaginatedSuccessResult<T> | ApiErrorResult;\r\n\r\nexport interface SuccessResult<T> {\r\n success: true;\r\n data?: T;\r\n total?: number;\r\n}\r\n\r\nexport interface PaginatedSuccessResult<T> extends Omit<SuccessResult<T>, 'data'> {\r\n data: T[];\r\n total: number;\r\n}\r\n\r\nexport interface ErrorResult {\r\n success: false;\r\n error?: string;\r\n}\r\n\r\nexport type ActionResult<T> = SuccessResult<T> | ErrorResult;\r\nexport type PaginatedActionResult<T> = PaginatedSuccessResult<T> | ErrorResult;\r\n\r\nexport class ApiError extends Error {\r\n public readonly code: string;\r\n public readonly statusCode: number;\r\n\r\n constructor(message: string, code: string = 'UNKNOWN_ERROR', statusCode: number = 500) {\r\n super(message);\r\n this.name = 'ApiError';\r\n this.code = code;\r\n this.statusCode = statusCode;\r\n }\r\n\r\n static isApiError(error: unknown): error is ApiError {\r\n return error instanceof ApiError;\r\n }\r\n}\r\n\r\nexport interface ApiResponse<T = unknown> {\r\n status: 0 | 1;\r\n message?: string;\r\n data?: T;\r\n}\r\n"],"mappings":"AAAA,OAAO,OAAO;AAEP,MAAM,yBAAyB,EAAE,OAAO;AAAA,EAC7C,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE;AAAA,EAC7C,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE;AACzC,CAAC;AAIM,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,QAAQ,EAAE,OAAO,EAAE,SAAS;AAC9B,CAAC;AAIM,MAAM,mBAAmB,EAAE,OAAO;AAAA,EACvC,MAAM,EAAE,OAAO,EAAE,SAAS;AAC5B,CAAC;AAyCM,MAAM,iBAAiB,MAAM;AAAA,EAClB;AAAA,EACA;AAAA,EAEhB,YAAY,SAAiB,OAAe,iBAAiB,aAAqB,KAAK;AACrF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,OAAO,WAAW,OAAmC;AACnD,WAAO,iBAAiB;AAAA,EAC1B;AACF;","names":[]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { headers } from "next/headers";
|
|
2
|
+
async function getClientInfoFromRequest(request) {
|
|
3
|
+
let headerStore;
|
|
4
|
+
if (request) {
|
|
5
|
+
headerStore = request.headers;
|
|
6
|
+
} else {
|
|
7
|
+
const nextHeaders = await headers();
|
|
8
|
+
headerStore = nextHeaders;
|
|
9
|
+
}
|
|
10
|
+
return {
|
|
11
|
+
location: {
|
|
12
|
+
continent: headerStore.get("cf-ipcountry") || headerStore.get("x-vercel-ip-country") || "Unknown",
|
|
13
|
+
country: headerStore.get("x-vercel-ip-country") || "Unknown",
|
|
14
|
+
region: headerStore.get("x-vercel-ip-country-region") || "Unknown",
|
|
15
|
+
city: headerStore.get("x-vercel-ip-city") || "Unknown",
|
|
16
|
+
latitude: headerStore.get("x-vercel-ip-latitude") || "0",
|
|
17
|
+
longitude: headerStore.get("x-vercel-ip-longitude") || "0"
|
|
18
|
+
},
|
|
19
|
+
ip: headerStore.get("cf-connecting-ip") || headerStore.get("x-forwarded-for") || headerStore.get("x-real-ip") || "Unknown",
|
|
20
|
+
timezone: headerStore.get("cf-timezone") || "America/Sao_Paulo",
|
|
21
|
+
agent: headerStore.get("user-agent") || "Unknown"
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export {
|
|
25
|
+
getClientInfoFromRequest
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=client-info.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/utils/client-info.ts"],"sourcesContent":["import { headers } from 'next/headers';\r\nimport { NextRequest } from 'next/server';\r\nimport { ClientInfo } from '../../modules/auth/schema';\r\n\r\nexport async function getClientInfoFromRequest(request?: NextRequest): Promise<ClientInfo> {\r\n let headerStore: Headers;\r\n\r\n if (request) {\r\n // Middleware context\r\n headerStore = request.headers;\r\n } else {\r\n // Server action context\r\n const nextHeaders = await headers();\r\n headerStore = nextHeaders as unknown as Headers;\r\n }\r\n\r\n return {\r\n location: {\r\n continent:\r\n headerStore.get('cf-ipcountry') || headerStore.get('x-vercel-ip-country') || 'Unknown',\r\n country: headerStore.get('x-vercel-ip-country') || 'Unknown',\r\n region: headerStore.get('x-vercel-ip-country-region') || 'Unknown',\r\n city: headerStore.get('x-vercel-ip-city') || 'Unknown',\r\n latitude: headerStore.get('x-vercel-ip-latitude') || '0',\r\n longitude: headerStore.get('x-vercel-ip-longitude') || '0',\r\n },\r\n ip:\r\n headerStore.get('cf-connecting-ip') ||\r\n headerStore.get('x-forwarded-for') ||\r\n headerStore.get('x-real-ip') ||\r\n 'Unknown',\r\n timezone: headerStore.get('cf-timezone') || 'America/Sao_Paulo',\r\n agent: headerStore.get('user-agent') || 'Unknown',\r\n };\r\n}\r\n"],"mappings":"AAAA,SAAS,eAAe;AAIxB,eAAsB,yBAAyB,SAA4C;AACzF,MAAI;AAEJ,MAAI,SAAS;AAEX,kBAAc,QAAQ;AAAA,EACxB,OAAO;AAEL,UAAM,cAAc,MAAM,QAAQ;AAClC,kBAAc;AAAA,EAChB;AAEA,SAAO;AAAA,IACL,UAAU;AAAA,MACR,WACE,YAAY,IAAI,cAAc,KAAK,YAAY,IAAI,qBAAqB,KAAK;AAAA,MAC/E,SAAS,YAAY,IAAI,qBAAqB,KAAK;AAAA,MACnD,QAAQ,YAAY,IAAI,4BAA4B,KAAK;AAAA,MACzD,MAAM,YAAY,IAAI,kBAAkB,KAAK;AAAA,MAC7C,UAAU,YAAY,IAAI,sBAAsB,KAAK;AAAA,MACrD,WAAW,YAAY,IAAI,uBAAuB,KAAK;AAAA,IACzD;AAAA,IACA,IACE,YAAY,IAAI,kBAAkB,KAClC,YAAY,IAAI,iBAAiB,KACjC,YAAY,IAAI,WAAW,KAC3B;AAAA,IACF,UAAU,YAAY,IAAI,aAAa,KAAK;AAAA,IAC5C,OAAO,YAAY,IAAI,YAAY,KAAK;AAAA,EAC1C;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/utils/clsx.ts"],"sourcesContent":["import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs))\n}\n"],"mappings":"AAAA,SAAS,YAA6B;AACtC,SAAS,eAAe;AAEjB,SAAS,MAAM,QAAsB;AAC1C,SAAO,QAAQ,KAAK,MAAM,CAAC;AAC7B;","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
function buildQueryParams(params) {
|
|
2
|
+
if (!params) {
|
|
3
|
+
return "";
|
|
4
|
+
}
|
|
5
|
+
const queryParams = new URLSearchParams();
|
|
6
|
+
for (const [key, value] of Object.entries(params)) {
|
|
7
|
+
if (value === null || value === void 0 || value === "") {
|
|
8
|
+
continue;
|
|
9
|
+
}
|
|
10
|
+
if (Array.isArray(value)) {
|
|
11
|
+
queryParams.set(key, value.join(","));
|
|
12
|
+
} else {
|
|
13
|
+
queryParams.set(key, value.toString());
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return queryParams.toString();
|
|
17
|
+
}
|
|
18
|
+
export {
|
|
19
|
+
buildQueryParams
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=params.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/utils/params.ts"],"sourcesContent":["export function buildQueryParams(\r\n params?: Record<\r\n string,\r\n string | number | boolean | Date | null | undefined | string[] | number[] | boolean[] | Date[]\r\n >\r\n) {\r\n if (!params) {\r\n return '';\r\n }\r\n\r\n const queryParams = new URLSearchParams();\r\n\r\n for (const [key, value] of Object.entries(params)) {\r\n if (value === null || value === undefined || value === '') {\r\n continue;\r\n }\r\n\r\n if (Array.isArray(value)) {\r\n queryParams.set(key, value.join(','));\r\n } else {\r\n\r\n queryParams.set(key, value.toString());\r\n }\r\n }\r\n\r\n return queryParams.toString();\r\n}\r\n"],"mappings":"AAAO,SAAS,iBACd,QAIA;AACA,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,IAAI,gBAAgB;AAExC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,QAAI,UAAU,QAAQ,UAAU,UAAa,UAAU,IAAI;AACzD;AAAA,IACF;AAEA,QAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,kBAAY,IAAI,KAAK,MAAM,KAAK,GAAG,CAAC;AAAA,IACtC,OAAO;AAEL,kBAAY,IAAI,KAAK,MAAM,SAAS,CAAC;AAAA,IACvC;AAAA,EACF;AAEA,SAAO,YAAY,SAAS;AAC9B;","names":[]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
function parseSchema(schema, data) {
|
|
2
|
+
if (Array.isArray(data)) {
|
|
3
|
+
return data.map((item) => schema.parse(item));
|
|
4
|
+
}
|
|
5
|
+
return schema.parse(data);
|
|
6
|
+
}
|
|
7
|
+
function parseResult(schema, result) {
|
|
8
|
+
if (!result.data) return result;
|
|
9
|
+
if (Array.isArray(result.data)) {
|
|
10
|
+
return {
|
|
11
|
+
...result,
|
|
12
|
+
data: result.data.map((item) => schema.parse(item))
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
...result,
|
|
17
|
+
data: schema.parse(result.data)
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export {
|
|
21
|
+
parseResult,
|
|
22
|
+
parseSchema
|
|
23
|
+
};
|
|
24
|
+
//# sourceMappingURL=parser.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/utils/parser.ts"],"sourcesContent":["import z, { ZodTypeAny } from \"zod\";\nimport { PaginatedSuccessResult, SuccessResult } from \"../api/types\";\n\n/* Overloads */\nexport function parseSchema<T extends ZodTypeAny>(\n schema: T,\n data: unknown[]\n): z.infer<T>[];\n\nexport function parseSchema<T extends ZodTypeAny>(\n schema: T,\n data: unknown\n): z.infer<T>;\n\nexport function parseSchema<T extends ZodTypeAny>(\n schema: T,\n data: unknown | unknown[]\n) {\n if (Array.isArray(data)) {\n return data.map(item => schema.parse(item));\n }\n\n return schema.parse(data);\n}\n\nexport function parseResult<T extends ZodTypeAny>(\n schema: T,\n result: PaginatedSuccessResult<unknown>\n): PaginatedSuccessResult<z.infer<T>>;\n\nexport function parseResult<T extends ZodTypeAny>(\n schema: T,\n result: SuccessResult<unknown>\n): SuccessResult<z.infer<T>>;\n\nexport function parseResult<T extends ZodTypeAny>(\n schema: T,\n result: SuccessResult<unknown> | PaginatedSuccessResult<unknown>\n) {\n if (!result.data) return result;\n\n if (Array.isArray(result.data)) {\n return {\n ...result,\n data: result.data.map(item => schema.parse(item)),\n };\n }\n\n return {\n ...result,\n data: schema.parse(result.data),\n };\n}"],"mappings":"AAcO,SAAS,YACZ,QACA,MACF;AACE,MAAI,MAAM,QAAQ,IAAI,GAAG;AACrB,WAAO,KAAK,IAAI,UAAQ,OAAO,MAAM,IAAI,CAAC;AAAA,EAC9C;AAEA,SAAO,OAAO,MAAM,IAAI;AAC5B;AAYO,SAAS,YACZ,QACA,QACF;AACE,MAAI,CAAC,OAAO,KAAM,QAAO;AAEzB,MAAI,MAAM,QAAQ,OAAO,IAAI,GAAG;AAC5B,WAAO;AAAA,MACH,GAAG;AAAA,MACH,MAAM,OAAO,KAAK,IAAI,UAAQ,OAAO,MAAM,IAAI,CAAC;AAAA,IACpD;AAAA,EACJ;AAEA,SAAO;AAAA,IACH,GAAG;AAAA,IACH,MAAM,OAAO,MAAM,OAAO,IAAI;AAAA,EAClC;AACJ;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const calculatePercentage = (current, total) => {
|
|
2
|
+
if (total === 0) return 0;
|
|
3
|
+
return current / total * 100;
|
|
4
|
+
};
|
|
5
|
+
const calculateCircumference = (radius) => {
|
|
6
|
+
return 2 * Math.PI * radius;
|
|
7
|
+
};
|
|
8
|
+
const calculateCircularProgressOffset = (percentage, circumference) => {
|
|
9
|
+
return circumference - percentage / 100 * circumference;
|
|
10
|
+
};
|
|
11
|
+
const calculateRadius = (size, strokeWidth) => {
|
|
12
|
+
return (size - strokeWidth) / 2;
|
|
13
|
+
};
|
|
14
|
+
export {
|
|
15
|
+
calculateCircularProgressOffset,
|
|
16
|
+
calculateCircumference,
|
|
17
|
+
calculatePercentage,
|
|
18
|
+
calculateRadius
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=percentage.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/utils/percentage.ts"],"sourcesContent":["/**\n * Calcula percentual de um valor em relação ao total\n * @param current - Valor atual\n * @param total - Valor total\n * @returns Percentual (0-100)\n */\nexport const calculatePercentage = (current: number, total: number): number => {\n if (total === 0) return 0;\n return (current / total) * 100;\n};\n\n/**\n * Calcula a circunferência de um círculo\n * @param radius - Raio do círculo\n * @returns Circunferência\n */\nexport const calculateCircumference = (radius: number): number => {\n return 2 * Math.PI * radius;\n};\n\n/**\n * Calcula o offset para circular progress\n * @param percentage - Percentual de progresso (0-100)\n * @param circumference - Circunferência do círculo\n * @returns Valor do offset\n */\nexport const calculateCircularProgressOffset = (\n percentage: number,\n circumference: number\n): number => {\n return circumference - (percentage / 100) * circumference;\n};\n\n/**\n * Calcula raio de círculo baseado no tamanho e stroke\n * @param size - Tamanho total\n * @param strokeWidth - Largura do stroke\n * @returns Raio calculado\n */\nexport const calculateRadius = (size: number, strokeWidth: number): number => {\n return (size - strokeWidth) / 2;\n};\n"],"mappings":"AAMO,MAAM,sBAAsB,CAAC,SAAiB,UAA0B;AAC7E,MAAI,UAAU,EAAG,QAAO;AACxB,SAAQ,UAAU,QAAS;AAC7B;AAOO,MAAM,yBAAyB,CAAC,WAA2B;AAChE,SAAO,IAAI,KAAK,KAAK;AACvB;AAQO,MAAM,kCAAkC,CAC7C,YACA,kBACW;AACX,SAAO,gBAAiB,aAAa,MAAO;AAC9C;AAQO,MAAM,kBAAkB,CAAC,MAAc,gBAAgC;AAC5E,UAAQ,OAAO,eAAe;AAChC;","names":[]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { NextResponse } from "next/server";
|
|
2
|
+
function shouldProcessPath(pathname, config) {
|
|
3
|
+
const { excludePaths, includePaths } = config;
|
|
4
|
+
if (excludePaths?.length) {
|
|
5
|
+
const isExcluded = excludePaths.some(
|
|
6
|
+
(path) => pathname === path || pathname.startsWith(`${path}/`)
|
|
7
|
+
);
|
|
8
|
+
if (isExcluded) return false;
|
|
9
|
+
}
|
|
10
|
+
if (includePaths?.length) {
|
|
11
|
+
return includePaths.some((path) => pathname === path || pathname.startsWith(`${path}/`));
|
|
12
|
+
}
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
function createMiddlewareChain(middlewares) {
|
|
16
|
+
return async function chainedMiddleware(request) {
|
|
17
|
+
const { pathname } = request.nextUrl;
|
|
18
|
+
let currentRequest = request;
|
|
19
|
+
for (const middleware of middlewares) {
|
|
20
|
+
if (!shouldProcessPath(pathname, middleware)) {
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
const result = await middleware.handler(currentRequest);
|
|
24
|
+
if (result.type === "response") {
|
|
25
|
+
return result.response;
|
|
26
|
+
}
|
|
27
|
+
if (result.request) {
|
|
28
|
+
currentRequest = result.request;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return NextResponse.next();
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
createMiddlewareChain
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=chain.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middlewares/chain.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\r\n\r\nimport { MiddlewareConfig } from './types';\r\n\r\nfunction shouldProcessPath(pathname: string, config: MiddlewareConfig): boolean {\r\n const { excludePaths, includePaths } = config;\r\n\r\n if (excludePaths?.length) {\r\n const isExcluded = excludePaths.some(\r\n (path) => pathname === path || pathname.startsWith(`${path}/`)\r\n );\r\n if (isExcluded) return false;\r\n }\r\n\r\n if (includePaths?.length) {\r\n return includePaths.some((path) => pathname === path || pathname.startsWith(`${path}/`));\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport function createMiddlewareChain(middlewares: MiddlewareConfig[]) {\r\n return async function chainedMiddleware(request: NextRequest): Promise<NextResponse> {\r\n const { pathname } = request.nextUrl;\r\n let currentRequest = request;\r\n\r\n for (const middleware of middlewares) {\r\n if (!shouldProcessPath(pathname, middleware)) {\r\n continue;\r\n }\r\n\r\n const result = await middleware.handler(currentRequest);\r\n\r\n if (result.type === 'response') {\r\n return result.response;\r\n }\r\n\r\n if (result.request) {\r\n currentRequest = result.request;\r\n }\r\n }\r\n\r\n return NextResponse.next();\r\n };\r\n}\r\n"],"mappings":"AAAA,SAAsB,oBAAoB;AAI1C,SAAS,kBAAkB,UAAkB,QAAmC;AAC9E,QAAM,EAAE,cAAc,aAAa,IAAI;AAEvC,MAAI,cAAc,QAAQ;AACxB,UAAM,aAAa,aAAa;AAAA,MAC9B,CAAC,SAAS,aAAa,QAAQ,SAAS,WAAW,GAAG,IAAI,GAAG;AAAA,IAC/D;AACA,QAAI,WAAY,QAAO;AAAA,EACzB;AAEA,MAAI,cAAc,QAAQ;AACxB,WAAO,aAAa,KAAK,CAAC,SAAS,aAAa,QAAQ,SAAS,WAAW,GAAG,IAAI,GAAG,CAAC;AAAA,EACzF;AAEA,SAAO;AACT;AAEO,SAAS,sBAAsB,aAAiC;AACrE,SAAO,eAAe,kBAAkB,SAA6C;AACnF,UAAM,EAAE,SAAS,IAAI,QAAQ;AAC7B,QAAI,iBAAiB;AAErB,eAAW,cAAc,aAAa;AACpC,UAAI,CAAC,kBAAkB,UAAU,UAAU,GAAG;AAC5C;AAAA,MACF;AAEA,YAAM,SAAS,MAAM,WAAW,QAAQ,cAAc;AAEtD,UAAI,OAAO,SAAS,YAAY;AAC9B,eAAO,OAAO;AAAA,MAChB;AAEA,UAAI,OAAO,SAAS;AAClB,yBAAiB,OAAO;AAAA,MAC1B;AAAA,IACF;AAEA,WAAO,aAAa,KAAK;AAAA,EAC3B;AACF;","names":[]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { NextResponse } from "next/server";
|
|
2
|
+
import { continueChain, stopChain } from "./types";
|
|
3
|
+
function isRouteEquals(pathname, routes) {
|
|
4
|
+
return routes.some((route) => pathname === route || pathname.startsWith(`${route}/`));
|
|
5
|
+
}
|
|
6
|
+
function createAuthMiddleware(options) {
|
|
7
|
+
return (request) => {
|
|
8
|
+
const { pathname } = request.nextUrl;
|
|
9
|
+
const token = process.env.DUMMY_AUTH_TOKEN || request.cookies.get("greatapps")?.value;
|
|
10
|
+
const isPublicRoute = isRouteEquals(pathname, options?.publicRoutes || []);
|
|
11
|
+
const isAuthRoute = isRouteEquals(pathname, options?.authRoutes || []);
|
|
12
|
+
if (token && isAuthRoute) {
|
|
13
|
+
return stopChain(NextResponse.redirect(new URL("/", request.url)));
|
|
14
|
+
}
|
|
15
|
+
if (!token && !isPublicRoute && !isAuthRoute) {
|
|
16
|
+
const loginUrl = new URL("/login", request.url);
|
|
17
|
+
if (pathname !== "/") {
|
|
18
|
+
loginUrl.searchParams.set("redirect", pathname);
|
|
19
|
+
}
|
|
20
|
+
return stopChain(NextResponse.redirect(loginUrl));
|
|
21
|
+
}
|
|
22
|
+
return continueChain();
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
createAuthMiddleware
|
|
27
|
+
};
|
|
28
|
+
//# sourceMappingURL=create-auth-middleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middlewares/create-auth-middleware.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\r\n\r\nimport { continueChain, MiddlewareConfig, MiddlewareFunction, MiddlewareResult, stopChain } from './types';\r\n\r\nfunction isRouteEquals(pathname: string, routes: string[]): boolean {\r\n return routes.some((route) => pathname === route || pathname.startsWith(`${route}/`));\r\n}\r\n\r\ninterface CreateAuthMiddlewareOptions {\r\n publicRoutes?: string[];\r\n authRoutes?: string[];\r\n}\r\n\r\nexport function createAuthMiddleware(options?: CreateAuthMiddlewareOptions): MiddlewareFunction {\r\n return (request: NextRequest) => {\r\n const { pathname } = request.nextUrl;\r\n const token = process.env.DUMMY_AUTH_TOKEN || request.cookies.get('greatapps')?.value;\r\n const isPublicRoute = isRouteEquals(pathname, options?.publicRoutes || []);\r\n const isAuthRoute = isRouteEquals(pathname, options?.authRoutes || []);\r\n\r\n if (token && isAuthRoute) {\r\n return stopChain(NextResponse.redirect(new URL('/', request.url)));\r\n }\r\n\r\n if (!token && !isPublicRoute && !isAuthRoute) {\r\n const loginUrl = new URL('/login', request.url);\r\n\r\n if (pathname !== '/') {\r\n loginUrl.searchParams.set('redirect', pathname);\r\n }\r\n\r\n return stopChain(NextResponse.redirect(loginUrl));\r\n }\r\n\r\n return continueChain();\r\n }\r\n}"],"mappings":"AAAA,SAAsB,oBAAoB;AAE1C,SAAS,eAAuE,iBAAiB;AAEjG,SAAS,cAAc,UAAkB,QAA2B;AAClE,SAAO,OAAO,KAAK,CAAC,UAAU,aAAa,SAAS,SAAS,WAAW,GAAG,KAAK,GAAG,CAAC;AACtF;AAOO,SAAS,qBAAqB,SAA2D;AAC9F,SAAO,CAAC,YAAyB;AAC/B,UAAM,EAAE,SAAS,IAAI,QAAQ;AAC7B,UAAM,QAAQ,QAAQ,IAAI,oBAAoB,QAAQ,QAAQ,IAAI,WAAW,GAAG;AAChF,UAAM,gBAAgB,cAAc,UAAU,SAAS,gBAAgB,CAAC,CAAC;AACzE,UAAM,cAAc,cAAc,UAAU,SAAS,cAAc,CAAC,CAAC;AAErE,QAAI,SAAS,aAAa;AACxB,aAAO,UAAU,aAAa,SAAS,IAAI,IAAI,KAAK,QAAQ,GAAG,CAAC,CAAC;AAAA,IACnE;AAEA,QAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,aAAa;AAC5C,YAAM,WAAW,IAAI,IAAI,UAAU,QAAQ,GAAG;AAE9C,UAAI,aAAa,KAAK;AACpB,iBAAS,aAAa,IAAI,YAAY,QAAQ;AAAA,MAChD;AAEA,aAAO,UAAU,aAAa,SAAS,QAAQ,CAAC;AAAA,IAClD;AAEA,WAAO,cAAc;AAAA,EACvB;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middlewares/types.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\r\n\r\nexport type MiddlewareResult =\r\n | { type: 'response'; response: NextResponse }\r\n | { type: 'next'; request?: NextRequest };\r\n\r\nexport type MiddlewareFunction = (\r\n request: NextRequest\r\n) => MiddlewareResult | Promise<MiddlewareResult>;\r\n\r\nexport interface MiddlewareConfig {\r\n name: string;\r\n handler: MiddlewareFunction;\r\n excludePaths?: string[];\r\n includePaths?: string[];\r\n}\r\n\r\nexport function continueChain(request?: NextRequest): MiddlewareResult {\r\n return { type: 'next', request };\r\n}\r\n\r\nexport function stopChain(response: NextResponse): MiddlewareResult {\r\n return { type: 'response', response };\r\n}\r\n"],"mappings":"AAiBO,SAAS,cAAc,SAAyC;AACrE,SAAO,EAAE,MAAM,QAAQ,QAAQ;AACjC;AAEO,SAAS,UAAU,UAA0C;AAClE,SAAO,EAAE,MAAM,YAAY,SAAS;AACtC;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=types.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/modules/auth/actions/login.action.ts"],"sourcesContent":["\"use server\";\r\n\r\nimport { authService } from \"../services/auth.service\";\r\nimport { LoginRequest, LoginResponse } from \"../schema\";\r\nimport { getClientInfoFromRequest } from \"../../../infra/utils/client-info\";\r\nimport { ApiError } from \"../../../infra/api/types\";\r\n\r\nexport async function loginAction(\r\n credentials: LoginRequest\r\n): Promise<LoginResponse> {\r\n try {\r\n const clientInfo = await getClientInfoFromRequest();\r\n return await authService.login(credentials, clientInfo);\r\n } catch (error) {\r\n return {\r\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/modules/auth/actions/login.action.ts"],"sourcesContent":["\"use server\";\r\n\r\nimport { authService } from \"../services/auth.service\";\r\nimport { LoginRequest, LoginResponse } from \"../schema\";\r\nimport { getClientInfoFromRequest } from \"../../../infra/utils/client-info\";\r\nimport { ApiError } from \"../../../infra/api/types\";\r\n\r\nexport async function loginAction(\r\n credentials: LoginRequest\r\n): Promise<LoginResponse> {\r\n try {\r\n const clientInfo = await getClientInfoFromRequest();\r\n return await authService.login(credentials, clientInfo);\r\n } catch (error) {\r\n return {\r\n result: 'error',\r\n message: (error as ApiError).message || \"An error occurred during login\",\r\n };\r\n }\r\n}\r\n"],"mappings":";AAEA,SAAS,mBAAmB;AAE5B,SAAS,gCAAgC;AAGzC,eAAsB,YACpB,aACwB;AACxB,MAAI;AACF,UAAM,aAAa,MAAM,yBAAyB;AAClD,WAAO,MAAM,YAAY,MAAM,aAAa,UAAU;AAAA,EACxD,SAAS,OAAO;AACd,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAU,MAAmB,WAAW;AAAA,IAC1C;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useMutation } from "@tanstack/react-query";
|
|
3
3
|
import { loginAction } from "../actions/login.action";
|
|
4
|
+
import { safeServerAction } from "../../../utils/safeServerAction";
|
|
4
5
|
function useLogin() {
|
|
5
6
|
return useMutation({
|
|
6
|
-
mutationFn:
|
|
7
|
+
mutationFn: async (credentials) => {
|
|
8
|
+
const data = await safeServerAction(loginAction, credentials);
|
|
9
|
+
return data;
|
|
10
|
+
}
|
|
7
11
|
});
|
|
8
12
|
}
|
|
9
13
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/modules/auth/hooks/login.hook.tsx"],"sourcesContent":["\"use client\";\n\nimport { useMutation } from \"@tanstack/react-query\";\nimport { loginAction } from \"../actions/login.action\";\n\nexport function useLogin() {\n return useMutation({\n mutationFn: loginAction,\n });\n}\n"],"mappings":";AAEA,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;
|
|
1
|
+
{"version":3,"sources":["../../../../src/modules/auth/hooks/login.hook.tsx"],"sourcesContent":["\"use client\";\n\nimport { useMutation } from \"@tanstack/react-query\";\nimport { loginAction } from \"../actions/login.action\";\nimport { safeServerAction } from \"../../../utils/safeServerAction\";\nimport { LoginRequest, LoginSuccessResponse } from \"../schema\";\n\nexport function useLogin() {\n return useMutation({\n mutationFn: async (credentials: LoginRequest): Promise<LoginSuccessResponse> => {\n const data = await safeServerAction(loginAction, credentials);\n return data as LoginSuccessResponse;\n },\n });\n}\n"],"mappings":";AAEA,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AAG1B,SAAS,WAAW;AACzB,SAAO,YAAY;AAAA,IACjB,YAAY,OAAO,gBAA6D;AAC9E,YAAM,OAAO,MAAM,iBAAiB,aAAa,WAAW;AAC5D,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
3
|
+
import { safeServerAction } from "../../../utils/safeServerAction";
|
|
3
4
|
const USER_QUERY_KEY = ["user"];
|
|
4
5
|
async function fetchUser() {
|
|
5
6
|
const { findUserById: getUserDataAction } = await import("../../users/action/find-user-by-id.action");
|
|
@@ -35,7 +36,7 @@ function useTwoFactorVerify() {
|
|
|
35
36
|
return useMutation({
|
|
36
37
|
mutationFn: async ({ cookie, code }) => {
|
|
37
38
|
const { verifyTwoFactorAction } = await import("../actions/verify-two-factor.action");
|
|
38
|
-
return verifyTwoFactorAction
|
|
39
|
+
return safeServerAction(verifyTwoFactorAction, cookie, code);
|
|
39
40
|
},
|
|
40
41
|
onSuccess: () => {
|
|
41
42
|
queryClient.invalidateQueries({ queryKey: USER_QUERY_KEY });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/modules/auth/hooks/useUserQuery.ts"],"sourcesContent":["'use client';\r\n\r\nimport { useMutation, useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query';\r\nimport { User } from '../../users/schema';\r\n\r\nexport const USER_QUERY_KEY = ['user'];\r\n\r\nasync function fetchUser(): Promise<User | null> {\r\n const { findUserById: getUserDataAction } = await import('../../users/action/find-user-by-id.action');\r\n const result = await getUserDataAction();\r\n return result.success && result.data ? result.data : null;\r\n}\r\n\r\nasync function validateUserSession(): Promise<boolean> {\r\n const { validateSessionAction } = await import('../actions/validate-session.action');\r\n return await validateSessionAction();\r\n}\r\n\r\nexport function useUserQuery() {\r\n return useQuery({\r\n queryKey: USER_QUERY_KEY,\r\n queryFn: fetchUser,\r\n staleTime: 5 * 60 * 1000,\r\n gcTime: 10 * 60 * 1000,\r\n retry: false,\r\n });\r\n}\r\n\r\nexport function useUserValidateSession(options?: UseQueryOptions) {\r\n return useQuery({\r\n queryKey: ['user-validate-session'],\r\n queryFn: validateUserSession,\r\n retry: false,\r\n staleTime: 5 * 60 * 1000,\r\n ...options,\r\n refetchOnMount: 'always',\r\n refetchOnWindowFocus: true,\r\n });\r\n}\r\n\r\nexport function useTwoFactorVerify() {\r\n const queryClient = useQueryClient();\r\n\r\n return useMutation({\r\n mutationFn: async ({ cookie, code }: { cookie: string; code: string }) => {\r\n const { verifyTwoFactorAction } = await import('../actions/verify-two-factor.action');\r\n return verifyTwoFactorAction
|
|
1
|
+
{"version":3,"sources":["../../../../src/modules/auth/hooks/useUserQuery.ts"],"sourcesContent":["'use client';\r\n\r\nimport { useMutation, useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query';\r\nimport { User } from '../../users/schema';\r\nimport { safeServerAction } from '../../../utils/safeServerAction';\r\n\r\nexport const USER_QUERY_KEY = ['user'];\r\n\r\nasync function fetchUser(): Promise<User | null> {\r\n const { findUserById: getUserDataAction } = await import('../../users/action/find-user-by-id.action');\r\n const result = await getUserDataAction();\r\n return result.success && result.data ? result.data : null;\r\n}\r\n\r\nasync function validateUserSession(): Promise<boolean> {\r\n const { validateSessionAction } = await import('../actions/validate-session.action');\r\n return await validateSessionAction();\r\n}\r\n\r\nexport function useUserQuery() {\r\n return useQuery({\r\n queryKey: USER_QUERY_KEY,\r\n queryFn: fetchUser,\r\n staleTime: 5 * 60 * 1000,\r\n gcTime: 10 * 60 * 1000,\r\n retry: false,\r\n });\r\n}\r\n\r\nexport function useUserValidateSession(options?: UseQueryOptions) {\r\n return useQuery({\r\n queryKey: ['user-validate-session'],\r\n queryFn: validateUserSession,\r\n retry: false,\r\n staleTime: 5 * 60 * 1000,\r\n ...options,\r\n refetchOnMount: 'always',\r\n refetchOnWindowFocus: true,\r\n });\r\n}\r\n\r\nexport function useTwoFactorVerify() {\r\n const queryClient = useQueryClient();\r\n\r\n return useMutation({\r\n mutationFn: async ({ cookie, code }: { cookie: string; code: string }) => {\r\n const { verifyTwoFactorAction } = await import('../actions/verify-two-factor.action');\r\n return safeServerAction(verifyTwoFactorAction, cookie, code);\r\n },\r\n onSuccess: () => {\r\n queryClient.invalidateQueries({ queryKey: USER_QUERY_KEY });\r\n queryClient.invalidateQueries({ queryKey: ['two-factor-pending'] });\r\n },\r\n });\r\n}\r\n\r\nexport function useInvalidateUser() {\r\n const queryClient = useQueryClient();\r\n return () => queryClient.invalidateQueries({ queryKey: USER_QUERY_KEY });\r\n}\r\n\r\nexport function useSetUserData() {\r\n const queryClient = useQueryClient();\r\n return (user: User | null) => queryClient.setQueryData(USER_QUERY_KEY, user);\r\n}\r\n"],"mappings":";AAEA,SAAS,aAAa,UAAU,sBAAuC;AAEvE,SAAS,wBAAwB;AAE1B,MAAM,iBAAiB,CAAC,MAAM;AAErC,eAAe,YAAkC;AAC/C,QAAM,EAAE,cAAc,kBAAkB,IAAI,MAAM,OAAO,2CAA2C;AACpG,QAAM,SAAS,MAAM,kBAAkB;AACvC,SAAO,OAAO,WAAW,OAAO,OAAO,OAAO,OAAO;AACvD;AAEA,eAAe,sBAAwC;AACrD,QAAM,EAAE,sBAAsB,IAAI,MAAM,OAAO,oCAAoC;AACnF,SAAO,MAAM,sBAAsB;AACrC;AAEO,SAAS,eAAe;AAC7B,SAAO,SAAS;AAAA,IACd,UAAU;AAAA,IACV,SAAS;AAAA,IACT,WAAW,IAAI,KAAK;AAAA,IACpB,QAAQ,KAAK,KAAK;AAAA,IAClB,OAAO;AAAA,EACT,CAAC;AACH;AAEO,SAAS,uBAAuB,SAA2B;AAChE,SAAO,SAAS;AAAA,IACd,UAAU,CAAC,uBAAuB;AAAA,IAClC,SAAS;AAAA,IACT,OAAO;AAAA,IACP,WAAW,IAAI,KAAK;AAAA,IACpB,GAAG;AAAA,IACH,gBAAgB;AAAA,IAChB,sBAAsB;AAAA,EACxB,CAAC;AACH;AAEO,SAAS,qBAAqB;AACnC,QAAM,cAAc,eAAe;AAEnC,SAAO,YAAY;AAAA,IACjB,YAAY,OAAO,EAAE,QAAQ,KAAK,MAAwC;AACxE,YAAM,EAAE,sBAAsB,IAAI,MAAM,OAAO,qCAAqC;AACpF,aAAO,iBAAiB,uBAAuB,QAAQ,IAAI;AAAA,IAC7D;AAAA,IACA,WAAW,MAAM;AACf,kBAAY,kBAAkB,EAAE,UAAU,eAAe,CAAC;AAC1D,kBAAY,kBAAkB,EAAE,UAAU,CAAC,oBAAoB,EAAE,CAAC;AAAA,IACpE;AAAA,EACF,CAAC;AACH;AAEO,SAAS,oBAAoB;AAClC,QAAM,cAAc,eAAe;AACnC,SAAO,MAAM,YAAY,kBAAkB,EAAE,UAAU,eAAe,CAAC;AACzE;AAEO,SAAS,iBAAiB;AAC/B,QAAM,cAAc,eAAe;AACnC,SAAO,CAAC,SAAsB,YAAY,aAAa,gBAAgB,IAAI;AAC7E;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=schema.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -36,11 +36,11 @@ class AuthService {
|
|
|
36
36
|
);
|
|
37
37
|
}
|
|
38
38
|
if (response.two_factor_required) {
|
|
39
|
-
return {
|
|
39
|
+
return { result: "two_factor_required", cookie: response.cookie };
|
|
40
40
|
}
|
|
41
41
|
await this.setAuthCookie(response.cookie);
|
|
42
42
|
return {
|
|
43
|
-
|
|
43
|
+
result: "success",
|
|
44
44
|
user: {},
|
|
45
45
|
accessToken: response.cookie,
|
|
46
46
|
refreshToken: "",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/modules/auth/services/auth.service.ts"],"sourcesContent":["import { cookies } from \"next/headers\";\r\n\r\nimport { api } from \"../../../infra/api/client\";\r\nimport { ApiError } from \"../../../infra/api/types\";\r\nimport { User } from \"../../users/schema\";\r\nimport {\r\n ClientInfo,\r\n ForgotPasswordRequest,\r\n ForgotPasswordResponse,\r\n GeoLocation,\r\n LoginApiResponse,\r\n LoginRequest,\r\n LoginResponse,\r\n LogoutApiResponse,\r\n LogoutRequest,\r\n LogoutResponse,\r\n RegisterApiRequest,\r\n RegisterApiResponse,\r\n RegisterRequest,\r\n RegisterResponse,\r\n ResendVerificationRequest,\r\n ResendVerificationResponse,\r\n ResetPasswordRequest,\r\n ResetPasswordResponse,\r\n SessionKeepRequest,\r\n SessionKeepResponse,\r\n TwoFactorApiResponse,\r\n TwoFactorRequest,\r\n TwoFactorResponse,\r\n VerifyEmailRequest,\r\n VerifyEmailResponse,\r\n} from \"../schema\";\r\n\r\nconst AUTH_COOKIE_NAME = \"greatapps\";\r\nconst COOKIE_MAX_AGE = 60 * 60 * 24 * 30;\r\n\r\nconst COOKIE_OPTIONS = {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === \"production\",\r\n sameSite: \"lax\" as const,\r\n path: \"/\",\r\n domain: process.env.DOMAIN_COOKIE,\r\n};\r\n\r\nclass AuthService {\r\n async login(\r\n credentials: LoginRequest,\r\n clientInfo: ClientInfo\r\n ): Promise<LoginResponse> {\r\n const response = await api.apps.post<LoginApiResponse>(\"/auth/login\", {\r\n email: credentials.email,\r\n password: credentials.password,\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n });\r\n\r\n console.log(\"[AuthService.login] response\", JSON.stringify(response));\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\r\n response.message || \"E-mail ou senha incorretos\",\r\n response.code || \"LOGIN_FAILED\",\r\n 401\r\n );\r\n }\r\n\r\n if (!response.cookie) {\r\n throw new ApiError(\r\n \"Resposta de autenticação inválida\",\r\n \"INVALID_RESPONSE\",\r\n 500\r\n );\r\n }\r\n\r\n if (response.two_factor_required) {\r\n return { status: 1, twoFactorRequired: true, cookie: response.cookie };\r\n }\r\n\r\n await this.setAuthCookie(response.cookie);\r\n\r\n return {\r\n status: 1,\r\n user: {} as User,\r\n accessToken: response.cookie,\r\n refreshToken: \"\",\r\n expiresAt: new Date(Date.now() + COOKIE_MAX_AGE * 1000).toISOString(),\r\n };\r\n }\r\n\r\n async verifyTwoFactor(\r\n cookie: string,\r\n code: string,\r\n clientInfo: ClientInfo\r\n ): Promise<TwoFactorResponse> {\r\n const payload: TwoFactorRequest = {\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n cookie,\r\n code,\r\n };\r\n\r\n const response = await api.apps.post<TwoFactorApiResponse>(\r\n \"/auth/code\",\r\n payload\r\n );\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\"Código 2FA inválido\", \"TWO_FACTOR_FAILED\", 401);\r\n }\r\n\r\n if (!response?.data?.cookie) {\r\n throw new ApiError(\r\n \"Resposta de autenticação inválida após 2FA\",\r\n \"INVALID_RESPONSE\",\r\n 500\r\n );\r\n }\r\n\r\n await this.setAuthCookie(response.data.cookie);\r\n\r\n return { status: 1 };\r\n }\r\n async register(data: RegisterRequest): Promise<RegisterResponse> {\r\n const today = new Date();\r\n const trialEndDate = new Date(today);\r\n trialEndDate.setDate(today.getDate() + 7); // 7 dias de trial\r\n\r\n const payload: RegisterApiRequest = {\r\n name: data.accountName,\r\n bussiness_type: data.businessType,\r\n language: \"pt-br\",\r\n timezone: \"America/Sao_Paulo\",\r\n currency: \"BRL\",\r\n user: {\r\n id_api: \"\",\r\n name: data.name,\r\n last_name: data.lastName || \"\",\r\n rg: data.rg || \"\",\r\n cpf: data.cpf || \"\",\r\n gender: data.gender,\r\n email: data.email,\r\n phone: data.phone,\r\n password: data.password,\r\n profile: \"owner\",\r\n language: \"pt-br\",\r\n },\r\n subscription: {\r\n type: \"trial\",\r\n id_cupom: \"\",\r\n id_plan: 1,\r\n due_date: trialEndDate.toISOString().split(\"T\")[0],\r\n id_product: 1,\r\n },\r\n };\r\n\r\n const response = await api.apps.post<RegisterApiResponse>(\r\n \"/accounts\",\r\n payload\r\n );\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\r\n response.message || \"Erro ao criar conta\",\r\n \"REGISTER_FAILED\",\r\n 400\r\n );\r\n }\r\n\r\n if (!response.data || response.data.length === 0) {\r\n throw new ApiError(\r\n \"Resposta de registro inválida\",\r\n \"INVALID_RESPONSE\",\r\n 500\r\n );\r\n }\r\n\r\n const accountData = response.data[0];\r\n\r\n // Retornar sem token pois o registro não retorna cookie diretamente\r\n // O usuário precisará fazer login após o registro\r\n // O usuário completo será carregado após o login\r\n return {\r\n user: {} as User, // Placeholder, será preenchido após login\r\n accessToken: \"\",\r\n refreshToken: \"\",\r\n expiresAt: new Date(Date.now() + COOKIE_MAX_AGE * 1000).toISOString(),\r\n requiresEmailVerification: !accountData.verified,\r\n };\r\n }\r\n\r\n async logout(clientInfo: ClientInfo): Promise<LogoutResponse> {\r\n const cookie = await this.getToken();\r\n\r\n if (!cookie) {\r\n throw new ApiError(\r\n \"Usuário não autenticado\",\r\n \"NOT_AUTHENTICATED_LOGOUT\",\r\n 401\r\n );\r\n }\r\n\r\n const payload: LogoutRequest = {\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n cookie,\r\n };\r\n\r\n try {\r\n const response = await api.apps.post<LogoutApiResponse>(\r\n \"/auth/logout\",\r\n payload\r\n );\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\r\n response.message || \"Erro ao realizar logout\",\r\n response.code || \"LOGOUT_FAILED\",\r\n 400\r\n );\r\n }\r\n } finally {\r\n await this.removeAuthCookie();\r\n }\r\n\r\n return {\r\n success: true,\r\n };\r\n }\r\n\r\n async forgotPassword(\r\n _data: ForgotPasswordRequest\r\n ): Promise<ForgotPasswordResponse> {\r\n throw new ApiError(\r\n \"Recuperação de senha não implementada\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async resetPassword(\r\n _data: ResetPasswordRequest\r\n ): Promise<ResetPasswordResponse> {\r\n throw new ApiError(\r\n \"Redefinição de senha não implementada\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async verifyEmail(_data: VerifyEmailRequest): Promise<VerifyEmailResponse> {\r\n throw new ApiError(\r\n \"Verificação de email não implementada\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async resendVerification(\r\n _data: ResendVerificationRequest\r\n ): Promise<ResendVerificationResponse> {\r\n throw new ApiError(\r\n \"Reenvio de verificação não implementado\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async validateSession(clientInfo: ClientInfo): Promise<boolean> {\r\n const cookie = await this.getToken();\r\n\r\n if (!cookie) {\r\n return false;\r\n }\r\n\r\n try {\r\n const payload: SessionKeepRequest = {\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n cookie,\r\n };\r\n\r\n const response = await api.apps.post<SessionKeepResponse>(\r\n \"/auth/keep\",\r\n payload\r\n );\r\n\r\n return response.status === 1;\r\n } catch (error) {\r\n console.error(\"[AuthService] validateSession error\", error);\r\n return false;\r\n }\r\n }\r\n\r\n async isAuthenticated(): Promise<boolean> {\r\n const token = await this.getToken();\r\n return !!token;\r\n }\r\n\r\n async getToken(): Promise<string | undefined> {\r\n if (process.env.DUMMY_AUTH_TOKEN) return process.env.DUMMY_AUTH_TOKEN;\r\n const cookieStore = await cookies();\r\n return cookieStore.get(AUTH_COOKIE_NAME)?.value;\r\n }\r\n\r\n private async setAuthCookie(token: string): Promise<void> {\r\n const cookieStore = await cookies();\r\n cookieStore.set(AUTH_COOKIE_NAME, token, {\r\n ...COOKIE_OPTIONS,\r\n maxAge: COOKIE_MAX_AGE,\r\n });\r\n }\r\n\r\n async removeAuthCookie(): Promise<void> {\r\n const cookieStore = await cookies();\r\n cookieStore.delete({\r\n name: AUTH_COOKIE_NAME,\r\n ...COOKIE_OPTIONS,\r\n });\r\n }\r\n}\r\n\r\nexport const authService = new AuthService();\r\n\r\nexport type { ClientInfo, GeoLocation };\r\n"],"mappings":"AAAA,SAAS,eAAe;AAExB,SAAS,WAAW;AACpB,SAAS,gBAAgB;AA8BzB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB,KAAK,KAAK,KAAK;AAEtC,MAAM,iBAAiB;AAAA,EACrB,UAAU;AAAA,EACV,QAAQ,QA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services/auth.service.ts"],"sourcesContent":["import { cookies } from \"next/headers\";\r\n\r\nimport { api } from \"../../../infra/api/client\";\r\nimport { ApiError } from \"../../../infra/api/types\";\r\nimport { User } from \"../../users/schema\";\r\nimport {\r\n ClientInfo,\r\n ForgotPasswordRequest,\r\n ForgotPasswordResponse,\r\n GeoLocation,\r\n LoginApiResponse,\r\n LoginRequest,\r\n LoginResponse,\r\n LogoutApiResponse,\r\n LogoutRequest,\r\n LogoutResponse,\r\n RegisterApiRequest,\r\n RegisterApiResponse,\r\n RegisterRequest,\r\n RegisterResponse,\r\n ResendVerificationRequest,\r\n ResendVerificationResponse,\r\n ResetPasswordRequest,\r\n ResetPasswordResponse,\r\n SessionKeepRequest,\r\n SessionKeepResponse,\r\n TwoFactorApiResponse,\r\n TwoFactorRequest,\r\n TwoFactorResponse,\r\n VerifyEmailRequest,\r\n VerifyEmailResponse,\r\n} from \"../schema\";\r\n\r\nconst AUTH_COOKIE_NAME = \"greatapps\";\r\nconst COOKIE_MAX_AGE = 60 * 60 * 24 * 30;\r\n\r\nconst COOKIE_OPTIONS = {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === \"production\",\r\n sameSite: \"lax\" as const,\r\n path: \"/\",\r\n domain: process.env.DOMAIN_COOKIE,\r\n};\r\n\r\nclass AuthService {\r\n async login(\r\n credentials: LoginRequest,\r\n clientInfo: ClientInfo\r\n ): Promise<LoginResponse> {\r\n const response = await api.apps.post<LoginApiResponse>(\"/auth/login\", {\r\n email: credentials.email,\r\n password: credentials.password,\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n });\r\n\r\n console.log(\"[AuthService.login] response\", JSON.stringify(response));\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\r\n response.message || \"E-mail ou senha incorretos\",\r\n response.code || \"LOGIN_FAILED\",\r\n 401\r\n );\r\n }\r\n\r\n if (!response.cookie) {\r\n throw new ApiError(\r\n \"Resposta de autenticação inválida\",\r\n \"INVALID_RESPONSE\",\r\n 500\r\n );\r\n }\r\n\r\n if (response.two_factor_required) {\r\n return { result: 'two_factor_required', cookie: response.cookie };\r\n }\r\n\r\n await this.setAuthCookie(response.cookie);\r\n\r\n return {\r\n result: 'success',\r\n user: {} as User,\r\n accessToken: response.cookie,\r\n refreshToken: \"\",\r\n expiresAt: new Date(Date.now() + COOKIE_MAX_AGE * 1000).toISOString(),\r\n };\r\n }\r\n\r\n async verifyTwoFactor(\r\n cookie: string,\r\n code: string,\r\n clientInfo: ClientInfo\r\n ): Promise<TwoFactorResponse> {\r\n const payload: TwoFactorRequest = {\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n cookie,\r\n code,\r\n };\r\n\r\n const response = await api.apps.post<TwoFactorApiResponse>(\r\n \"/auth/code\",\r\n payload\r\n );\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\"Código 2FA inválido\", \"TWO_FACTOR_FAILED\", 401);\r\n }\r\n\r\n if (!response?.data?.cookie) {\r\n throw new ApiError(\r\n \"Resposta de autenticação inválida após 2FA\",\r\n \"INVALID_RESPONSE\",\r\n 500\r\n );\r\n }\r\n\r\n await this.setAuthCookie(response.data.cookie);\r\n\r\n return { status: 1 };\r\n }\r\n async register(data: RegisterRequest): Promise<RegisterResponse> {\r\n const today = new Date();\r\n const trialEndDate = new Date(today);\r\n trialEndDate.setDate(today.getDate() + 7); // 7 dias de trial\r\n\r\n const payload: RegisterApiRequest = {\r\n name: data.accountName,\r\n bussiness_type: data.businessType,\r\n language: \"pt-br\",\r\n timezone: \"America/Sao_Paulo\",\r\n currency: \"BRL\",\r\n user: {\r\n id_api: \"\",\r\n name: data.name,\r\n last_name: data.lastName || \"\",\r\n rg: data.rg || \"\",\r\n cpf: data.cpf || \"\",\r\n gender: data.gender,\r\n email: data.email,\r\n phone: data.phone,\r\n password: data.password,\r\n profile: \"owner\",\r\n language: \"pt-br\",\r\n },\r\n subscription: {\r\n type: \"trial\",\r\n id_cupom: \"\",\r\n id_plan: 1,\r\n due_date: trialEndDate.toISOString().split(\"T\")[0],\r\n id_product: 1,\r\n },\r\n };\r\n\r\n const response = await api.apps.post<RegisterApiResponse>(\r\n \"/accounts\",\r\n payload\r\n );\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\r\n response.message || \"Erro ao criar conta\",\r\n \"REGISTER_FAILED\",\r\n 400\r\n );\r\n }\r\n\r\n if (!response.data || response.data.length === 0) {\r\n throw new ApiError(\r\n \"Resposta de registro inválida\",\r\n \"INVALID_RESPONSE\",\r\n 500\r\n );\r\n }\r\n\r\n const accountData = response.data[0];\r\n\r\n // Retornar sem token pois o registro não retorna cookie diretamente\r\n // O usuário precisará fazer login após o registro\r\n // O usuário completo será carregado após o login\r\n return {\r\n user: {} as User, // Placeholder, será preenchido após login\r\n accessToken: \"\",\r\n refreshToken: \"\",\r\n expiresAt: new Date(Date.now() + COOKIE_MAX_AGE * 1000).toISOString(),\r\n requiresEmailVerification: !accountData.verified,\r\n };\r\n }\r\n\r\n async logout(clientInfo: ClientInfo): Promise<LogoutResponse> {\r\n const cookie = await this.getToken();\r\n\r\n if (!cookie) {\r\n throw new ApiError(\r\n \"Usuário não autenticado\",\r\n \"NOT_AUTHENTICATED_LOGOUT\",\r\n 401\r\n );\r\n }\r\n\r\n const payload: LogoutRequest = {\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n cookie,\r\n };\r\n\r\n try {\r\n const response = await api.apps.post<LogoutApiResponse>(\r\n \"/auth/logout\",\r\n payload\r\n );\r\n\r\n if (response.status === 0) {\r\n throw new ApiError(\r\n response.message || \"Erro ao realizar logout\",\r\n response.code || \"LOGOUT_FAILED\",\r\n 400\r\n );\r\n }\r\n } finally {\r\n await this.removeAuthCookie();\r\n }\r\n\r\n return {\r\n success: true,\r\n };\r\n }\r\n\r\n async forgotPassword(\r\n _data: ForgotPasswordRequest\r\n ): Promise<ForgotPasswordResponse> {\r\n throw new ApiError(\r\n \"Recuperação de senha não implementada\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async resetPassword(\r\n _data: ResetPasswordRequest\r\n ): Promise<ResetPasswordResponse> {\r\n throw new ApiError(\r\n \"Redefinição de senha não implementada\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async verifyEmail(_data: VerifyEmailRequest): Promise<VerifyEmailResponse> {\r\n throw new ApiError(\r\n \"Verificação de email não implementada\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async resendVerification(\r\n _data: ResendVerificationRequest\r\n ): Promise<ResendVerificationResponse> {\r\n throw new ApiError(\r\n \"Reenvio de verificação não implementado\",\r\n \"NOT_IMPLEMENTED\",\r\n 501\r\n );\r\n }\r\n\r\n async validateSession(clientInfo: ClientInfo): Promise<boolean> {\r\n const cookie = await this.getToken();\r\n\r\n if (!cookie) {\r\n return false;\r\n }\r\n\r\n try {\r\n const payload: SessionKeepRequest = {\r\n location: clientInfo.location,\r\n ip: clientInfo.ip,\r\n timezone: clientInfo.timezone,\r\n agent: clientInfo.agent,\r\n cookie,\r\n };\r\n\r\n const response = await api.apps.post<SessionKeepResponse>(\r\n \"/auth/keep\",\r\n payload\r\n );\r\n\r\n return response.status === 1;\r\n } catch (error) {\r\n console.error(\"[AuthService] validateSession error\", error);\r\n return false;\r\n }\r\n }\r\n\r\n async isAuthenticated(): Promise<boolean> {\r\n const token = await this.getToken();\r\n return !!token;\r\n }\r\n\r\n async getToken(): Promise<string | undefined> {\r\n if (process.env.DUMMY_AUTH_TOKEN) return process.env.DUMMY_AUTH_TOKEN;\r\n const cookieStore = await cookies();\r\n return cookieStore.get(AUTH_COOKIE_NAME)?.value;\r\n }\r\n\r\n private async setAuthCookie(token: string): Promise<void> {\r\n const cookieStore = await cookies();\r\n cookieStore.set(AUTH_COOKIE_NAME, token, {\r\n ...COOKIE_OPTIONS,\r\n maxAge: COOKIE_MAX_AGE,\r\n });\r\n }\r\n\r\n async removeAuthCookie(): Promise<void> {\r\n const cookieStore = await cookies();\r\n cookieStore.delete({\r\n name: AUTH_COOKIE_NAME,\r\n ...COOKIE_OPTIONS,\r\n });\r\n }\r\n}\r\n\r\nexport const authService = new AuthService();\r\n\r\nexport type { ClientInfo, GeoLocation };\r\n"],"mappings":"AAAA,SAAS,eAAe;AAExB,SAAS,WAAW;AACpB,SAAS,gBAAgB;AA8BzB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB,KAAK,KAAK,KAAK;AAEtC,MAAM,iBAAiB;AAAA,EACrB,UAAU;AAAA,EACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,EACjC,UAAU;AAAA,EACV,MAAM;AAAA,EACN,QAAQ,QAAQ,IAAI;AACtB;AAEA,MAAM,YAAY;AAAA,EAChB,MAAM,MACJ,aACA,YACwB;AACxB,UAAM,WAAW,MAAM,IAAI,KAAK,KAAuB,eAAe;AAAA,MACpE,OAAO,YAAY;AAAA,MACnB,UAAU,YAAY;AAAA,MACtB,UAAU,WAAW;AAAA,MACrB,IAAI,WAAW;AAAA,MACf,UAAU,WAAW;AAAA,MACrB,OAAO,WAAW;AAAA,IACpB,CAAC;AAED,YAAQ,IAAI,gCAAgC,KAAK,UAAU,QAAQ,CAAC;AAEpE,QAAI,SAAS,WAAW,GAAG;AACzB,YAAM,IAAI;AAAA,QACR,SAAS,WAAW;AAAA,QACpB,SAAS,QAAQ;AAAA,QACjB;AAAA,MACF;AAAA,IACF;AAEA,QAAI,CAAC,SAAS,QAAQ;AACpB,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,SAAS,qBAAqB;AAChC,aAAO,EAAE,QAAQ,uBAAuB,QAAQ,SAAS,OAAO;AAAA,IAClE;AAEA,UAAM,KAAK,cAAc,SAAS,MAAM;AAExC,WAAO;A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AAQ;AAClC,WAAO,YAAY,IAAI,gBAAgB,GAAG;AAAA,EAC5C;AAAA,EAEA,MAAc,cAAc,OAA8B;AACxD,UAAM,cAAc,MAAM,QAAQ;AAClC,gBAAY,IAAI,kBAAkB,OAAO;AAAA,MACvC,GAAG;AAAA,MACH,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,mBAAkC;AACtC,UAAM,cAAc,MAAM,QAAQ;AAClC,gBAAY,OAAO;AAAA,MACjB,MAAM;AAAA,MACN,GAAG;AAAA,IACL,CAAC;AAAA,EACH;AACF;AAEO,MAAM,cAAc,IAAI,YAAY;","names":[]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import z from "zod";
|
|
2
|
+
const IaCreditOperationSchema = z.object({
|
|
3
|
+
id: z.union([z.number(), z.string()]),
|
|
4
|
+
deleted: z.number(),
|
|
5
|
+
datetime_add: z.string(),
|
|
6
|
+
id_wl: z.number(),
|
|
7
|
+
id_subscription: z.union([z.number(), z.string()]),
|
|
8
|
+
id_addon: z.number(),
|
|
9
|
+
operation: z.string(),
|
|
10
|
+
// 'add' | 'subtract'
|
|
11
|
+
operation_value: z.union([z.number(), z.string()]).transform((v) => Number(v)),
|
|
12
|
+
balance_after_operation: z.union([z.number(), z.string()]).optional(),
|
|
13
|
+
balance_before_operation: z.union([z.number(), z.string()]).optional(),
|
|
14
|
+
operation_ref: z.string().nullable().optional(),
|
|
15
|
+
operation_origin: z.string().nullable().optional(),
|
|
16
|
+
expiration_time: z.string().nullable(),
|
|
17
|
+
has_expired: z.boolean(),
|
|
18
|
+
consumed_from_add_id: z.union([z.number(), z.string()]).nullable(),
|
|
19
|
+
id_user_add: z.union([z.number(), z.string()]).nullable(),
|
|
20
|
+
user_name: z.string().nullable().optional()
|
|
21
|
+
}).passthrough();
|
|
22
|
+
export {
|
|
23
|
+
IaCreditOperationSchema
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=types.mjs.map
|