@greatapps/common 1.1.755 → 1.1.757
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/infra/api/client.mjs +36 -0
- package/dist/infra/api/client.mjs.map +1 -1
- package/dist/modules/plans/types/plan.type.mjs +5 -1
- package/dist/modules/plans/types/plan.type.mjs.map +1 -1
- package/package.json +1 -1
- package/src/infra/api/client.ts +309 -263
- package/src/modules/plans/types/plan.type.ts +4 -0
|
@@ -162,6 +162,42 @@ class ApiClient {
|
|
|
162
162
|
async delete(endpoint, config) {
|
|
163
163
|
return this.request(endpoint, { ...config, method: "DELETE" });
|
|
164
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* Requisição cuja resposta é consumida em stream: devolve a `Response` crua, sem ler o
|
|
167
|
+
* corpo e sem timeout.
|
|
168
|
+
*
|
|
169
|
+
* `request()` não serve para isso por dois motivos. Ele faz `await response.json()`, o
|
|
170
|
+
* que espera o corpo inteiro e mata o propósito do stream; e aborta em 30s, que é o
|
|
171
|
+
* tempo que uma operação longa leva justamente por ser longa — gerar o link de uma
|
|
172
|
+
* página com 132 imagens copia 100 MB e passa disso (ID-5112).
|
|
173
|
+
*
|
|
174
|
+
* O corpo é do chamador: quem recebe decide quando ler e quando cancelar.
|
|
175
|
+
*/
|
|
176
|
+
async stream(endpoint, config = {}) {
|
|
177
|
+
const { timeout: _timeout, responseType: _responseType, whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;
|
|
178
|
+
const resolvido = overrideWlId != null && overrideToken != null ? { id: overrideWlId, token: overrideToken } : await findWhitelabel();
|
|
179
|
+
const [url, defaultHeaders] = await Promise.all([
|
|
180
|
+
this.buildUrl(endpoint, overrideWlId ?? resolvido.id),
|
|
181
|
+
this.getDefaultHeaders(overrideToken ?? resolvido.token)
|
|
182
|
+
]);
|
|
183
|
+
const response = await fetch(url, {
|
|
184
|
+
...fetchConfig,
|
|
185
|
+
headers: { ...defaultHeaders, ...fetchConfig.headers },
|
|
186
|
+
// Sem isto o fetch do Next segura o corpo inteiro antes de devolver, e o stream chega
|
|
187
|
+
// completo de uma vez no fim: medido em 32s até o primeiro evento, contra 0,4s com
|
|
188
|
+
// no-store. O progresso existiria no protocolo e não na tela.
|
|
189
|
+
cache: "no-store"
|
|
190
|
+
});
|
|
191
|
+
if (!response.ok || !response.body) {
|
|
192
|
+
const detalhe = await response.text().catch(() => "");
|
|
193
|
+
throw new ApiError(
|
|
194
|
+
detalhe.trim() || `HTTP error ${response.status} ${response.statusText}`,
|
|
195
|
+
"HTTP_ERROR",
|
|
196
|
+
response.status
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
return response;
|
|
200
|
+
}
|
|
165
201
|
}
|
|
166
202
|
const api = {
|
|
167
203
|
apps: new ApiClient(
|
|
@@ -1 +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\nexport interface ApiClientOptions {\r\n /**\r\n * Quando true, monta `{base}/{locale}/{wlId}{endpoint}` (ex.: r2-clone).\r\n * Padrão false: `{base}/v1/{locale}/{wlId}{endpoint}`.\r\n */\r\n omitApiVersion?: boolean;\r\n\r\n /** Habilita logs detalhados das requisições (útil para desenvolvimento) */\r\n emitLogs?: boolean;\r\n}\r\n\r\nexport interface RequestConfig extends RequestInit {\r\n timeout?: number;\r\n /** Padrão `json`. Use `text` quando a API devolve corpo não-JSON. */\r\n responseType?: \"json\" | \"text\";\r\n /** Força um whiteLabelId específico na URL, ignorando o findWhitelabel(). */\r\n whiteLabelId?: number;\r\n /** Força um token específico no header Authorization, ignorando o findWhitelabel(). */\r\n authToken?: string;\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 private readonly omitApiVersion: boolean;\r\n private readonly emitLogs: boolean = false;\r\n\r\n constructor(baseUrl: string, options?: ApiClientOptions) {\r\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\r\n this.omitApiVersion = options?.omitApiVersion ?? false;\r\n this.emitLogs = options?.emitLogs ?? false;\r\n }\r\n\r\n private async buildUrl(\r\n endpoint: string,\r\n whiteLabelId: number,\r\n ): Promise<string> {\r\n const wlPath = this.omitApiVersion\r\n ? `/${this.apiLocale}/${whiteLabelId}`\r\n : `/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}`;\r\n const path = endpoint.startsWith(\"/\") ? endpoint : `/${endpoint}`;\r\n const url = `${this.baseUrl}${wlPath}${path}`;\r\n if (this.emitLogs) {\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 }\r\n return url;\r\n }\r\n\r\n private async getDefaultHeaders(\r\n token: string,\r\n isFormData = false,\r\n ): Promise<HeadersInit> {\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] getDefaultHeaders\", {\r\n token: token.substring(0, 20) + \"...\",\r\n });\r\n }\r\n\r\n const headers: HeadersInit = {\r\n authorization: token,\r\n };\r\n\r\n if (!isFormData) {\r\n headers[\"Content-Type\"] = \"application/json\";\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 if (this.emitLogs) {\r\n console.log(\"[ApiClient] request called\", {\r\n endpoint,\r\n method: config.method,\r\n });\r\n }\r\n\r\n const { timeout = 30000, responseType = \"json\", whiteLabelId: overrideWlId, authToken: overrideToken, ...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 if (this.emitLogs) {\r\n console.log(\"[ApiClient] Building URL and headers...\");\r\n }\r\n\r\n const { id, token } = await findWhitelabel();\r\n\r\n const [url, defaultHeaders] = await Promise.all([\r\n this.buildUrl(endpoint, overrideWlId ?? id),\r\n this.getDefaultHeaders(overrideToken ?? token, fetchConfig.body instanceof FormData),\r\n ]);\r\n\r\n if (this.emitLogs)\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 if (this.emitLogs)\r\n console.log(\"[ApiClient] Response received\", {\r\n status: response.status,\r\n ok: response.ok,\r\n });\r\n\r\n if (!response.ok) {\r\n const errBody = await response.text();\r\n let message = `HTTP error ${response.status} ${response.statusText} ${errBody}`;\r\n let code = \"HTTP_ERROR\";\r\n try {\r\n const errorData = JSON.parse(errBody) as Record<string, unknown>;\r\n // @ts-ignore -- msg pode ser string ou objeto com .message\r\n message = errorData.message?.message ?? errorData.message ?? message;\r\n if (typeof errorData.code === \"string\") code = errorData.code;\r\n } catch {\r\n if (errBody.trim()) message = errBody.trim();\r\n }\r\n const method = fetchConfig.method ?? \"GET\";\r\n let bodyPreview: unknown;\r\n if (method !== \"GET\" && fetchConfig.body != null) {\r\n if (typeof fetchConfig.body === \"string\") {\r\n try {\r\n bodyPreview = JSON.parse(fetchConfig.body);\r\n } catch {\r\n bodyPreview = fetchConfig.body;\r\n }\r\n } else if (fetchConfig.body instanceof FormData) {\r\n bodyPreview = \"[FormData]\";\r\n } else {\r\n bodyPreview = fetchConfig.body;\r\n }\r\n }\r\n console.error(\"[ApiClient] Request failed\", {\r\n from: url,\r\n method,\r\n ...(bodyPreview !== undefined ? { body: bodyPreview } : {}),\r\n status: response.status,\r\n message,\r\n });\r\n throw new ApiError(message, code, response.status);\r\n }\r\n\r\n if (responseType === \"text\") {\r\n return (await response.text()) as T;\r\n }\r\n\r\n const data = (await response.json()) as T;\r\n if (this.emitLogs)\r\n console.log(\"[ApiClient] Request successful\", { hasData: !!data });\r\n return data;\r\n } catch (error) {\r\n if (this.emitLogs) 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>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"POST\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async put<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"PUT\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async patch<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"PATCH\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : 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(\r\n process.env.GAPPS_R3_API_URL || \"https://r3-api.greatapps.dev.br\",\r\n ),\r\n pages: new ApiClient(\r\n process.env.GPAGES_R3_API_URL || \"https://r3-api.greatpages.dev.br\",\r\n ),\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;AAuB/B,MAAM,UAAU;AAAA,EACG;AAAA,EACA,aAAa;AAAA,EACb,YAAY;AAAA,EACZ;AAAA,EACA,WAAoB;AAAA,EAErC,YAAY,SAAiB,SAA4B;AACvD,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AACxC,SAAK,iBAAiB,SAAS,kBAAkB;AACjD,SAAK,WAAW,SAAS,YAAY;AAAA,EACvC;AAAA,EAEA,MAAc,SACZ,UACA,cACiB;AACjB,UAAM,SAAS,KAAK,iBAChB,IAAI,KAAK,SAAS,IAAI,YAAY,KAClC,IAAI,KAAK,UAAU,IAAI,KAAK,SAAS,IAAI,YAAY;AACzD,UAAM,OAAO,SAAS,WAAW,GAAG,IAAI,WAAW,IAAI,QAAQ;AAC/D,UAAM,MAAM,GAAG,KAAK,OAAO,GAAG,MAAM,GAAG,IAAI;AAC3C,QAAI,KAAK,UAAU;AACjB,cAAQ,IAAI,wBAAwB;AAAA,QAClC,SAAS,KAAK;AAAA,QACd;AAAA,QACA;AAAA,QACA,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBACZ,OACA,aAAa,OACS;AACtB,QAAI,KAAK,UAAU;AACjB,cAAQ,IAAI,iCAAiC;AAAA,QAC3C,OAAO,MAAM,UAAU,GAAG,EAAE,IAAI;AAAA,MAClC,CAAC;AAAA,IACH;AAEA,UAAM,UAAuB;AAAA,MAC3B,eAAe;AAAA,IACjB;AAEA,QAAI,CAAC,YAAY;AACf,cAAQ,cAAc,IAAI;AAAA,IAC5B;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAW,UAAkB,SAAwB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;AAEA,YAAM,IAAI,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,KACJ,UACA,MACA,QACY;AACZ,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MACE,gBAAgB,WACZ,OACA,OACE,KAAK,UAAU,IAAI,IACnB;AAAA,IACV,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,IACJ,UACA,MACA,QACY;AACZ,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MACE,gBAAgB,WACZ,OACA,OACE,KAAK,UAAU,IAAI,IACnB;AAAA,IACV,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MACJ,UACA,MACA,QACY;AACZ,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MACE,gBAAgB,WACZ,OACA,OACE,KAAK,UAAU,IAAI,IACnB;AAAA,IACV,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;AAAA,IACR,QAAQ,IAAI,oBAAoB;AAAA,EAClC;AAAA,EACA,OAAO,IAAI;AAAA,IACT,QAAQ,IAAI,qBAAqB;AAAA,EACnC;AACF;AAGO,MAAM,YAAY,IAAI;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/infra/api/client.ts"],"sourcesContent":["import { ApiError } from \"./types\";\nimport { findWhitelabel } from \"../../modules/whitelabel/actions/find-whitelabel.action\";\n\nexport interface ApiClientOptions {\n /**\n * Quando true, monta `{base}/{locale}/{wlId}{endpoint}` (ex.: r2-clone).\n * Padrão false: `{base}/v1/{locale}/{wlId}{endpoint}`.\n */\n omitApiVersion?: boolean;\n\n /** Habilita logs detalhados das requisições (útil para desenvolvimento) */\n emitLogs?: boolean;\n}\n\nexport interface RequestConfig extends RequestInit {\n timeout?: number;\n /** Padrão `json`. Use `text` quando a API devolve corpo não-JSON. */\n responseType?: \"json\" | \"text\";\n /** Força um whiteLabelId específico na URL, ignorando o findWhitelabel(). */\n whiteLabelId?: number;\n /** Força um token específico no header Authorization, ignorando o findWhitelabel(). */\n authToken?: string;\n}\n\nclass ApiClient {\n private readonly baseUrl: string;\n private readonly apiVersion = \"v1\";\n private readonly apiLocale = \"pt-br\";\n private readonly omitApiVersion: boolean;\n private readonly emitLogs: boolean = false;\n\n constructor(baseUrl: string, options?: ApiClientOptions) {\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\n this.omitApiVersion = options?.omitApiVersion ?? false;\n this.emitLogs = options?.emitLogs ?? false;\n }\n\n private async buildUrl(\n endpoint: string,\n whiteLabelId: number,\n ): Promise<string> {\n const wlPath = this.omitApiVersion\n ? `/${this.apiLocale}/${whiteLabelId}`\n : `/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}`;\n const path = endpoint.startsWith(\"/\") ? endpoint : `/${endpoint}`;\n const url = `${this.baseUrl}${wlPath}${path}`;\n if (this.emitLogs) {\n console.log(\"[ApiClient] buildUrl\", {\n baseURL: this.baseUrl,\n whiteLabelId,\n endpoint,\n fullUrl: url,\n });\n }\n return url;\n }\n\n private async getDefaultHeaders(\n token: string,\n isFormData = false,\n ): Promise<HeadersInit> {\n if (this.emitLogs) {\n console.log(\"[ApiClient] getDefaultHeaders\", {\n token: token.substring(0, 20) + \"...\",\n });\n }\n\n const headers: HeadersInit = {\n authorization: token,\n };\n\n if (!isFormData) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n return headers;\n }\n\n async request<T>(endpoint: string, config: RequestConfig = {}): Promise<T> {\n if (this.emitLogs) {\n console.log(\"[ApiClient] request called\", {\n endpoint,\n method: config.method,\n });\n }\n\n const { timeout = 30000, responseType = \"json\", whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n if (this.emitLogs) {\n console.log(\"[ApiClient] Building URL and headers...\");\n }\n\n const { id, token } = await findWhitelabel();\n\n const [url, defaultHeaders] = await Promise.all([\n this.buildUrl(endpoint, overrideWlId ?? id),\n this.getDefaultHeaders(overrideToken ?? token, fetchConfig.body instanceof FormData),\n ]);\n\n if (this.emitLogs)\n console.log(\"[ApiClient] Fetching\", {\n url,\n method: fetchConfig.method,\n headers: defaultHeaders,\n });\n\n const response = await fetch(url, {\n ...fetchConfig,\n headers: {\n ...defaultHeaders,\n ...fetchConfig.headers,\n },\n signal: controller.signal,\n });\n\n if (this.emitLogs)\n console.log(\"[ApiClient] Response received\", {\n status: response.status,\n ok: response.ok,\n });\n\n if (!response.ok) {\n const errBody = await response.text();\n let message = `HTTP error ${response.status} ${response.statusText} ${errBody}`;\n let code = \"HTTP_ERROR\";\n try {\n const errorData = JSON.parse(errBody) as Record<string, unknown>;\n // @ts-ignore -- msg pode ser string ou objeto com .message\n message = errorData.message?.message ?? errorData.message ?? message;\n if (typeof errorData.code === \"string\") code = errorData.code;\n } catch {\n if (errBody.trim()) message = errBody.trim();\n }\n const method = fetchConfig.method ?? \"GET\";\n let bodyPreview: unknown;\n if (method !== \"GET\" && fetchConfig.body != null) {\n if (typeof fetchConfig.body === \"string\") {\n try {\n bodyPreview = JSON.parse(fetchConfig.body);\n } catch {\n bodyPreview = fetchConfig.body;\n }\n } else if (fetchConfig.body instanceof FormData) {\n bodyPreview = \"[FormData]\";\n } else {\n bodyPreview = fetchConfig.body;\n }\n }\n console.error(\"[ApiClient] Request failed\", {\n from: url,\n method,\n ...(bodyPreview !== undefined ? { body: bodyPreview } : {}),\n status: response.status,\n message,\n });\n throw new ApiError(message, code, response.status);\n }\n\n if (responseType === \"text\") {\n return (await response.text()) as T;\n }\n\n const data = (await response.json()) as T;\n if (this.emitLogs)\n console.log(\"[ApiClient] Request successful\", { hasData: !!data });\n return data;\n } catch (error) {\n if (this.emitLogs) console.error(\"[ApiClient] Request error\", { error });\n\n if (error instanceof ApiError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new ApiError(\"Tempo de requisição excedido\", \"TIMEOUT\", 408);\n }\n throw new ApiError(error.message, \"NETWORK_ERROR\", 0);\n }\n\n throw new ApiError(\"Erro desconhecido\", \"UNKNOWN_ERROR\", 500);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n async get<T>(endpoint: string, config?: RequestConfig): Promise<T> {\n return this.request<T>(endpoint, { ...config, method: \"GET\" });\n }\n\n async post<T>(\n endpoint: string,\n data?: unknown,\n config?: RequestConfig,\n ): Promise<T> {\n return this.request<T>(endpoint, {\n ...config,\n method: \"POST\",\n body:\n data instanceof FormData\n ? data\n : data\n ? JSON.stringify(data)\n : undefined,\n });\n }\n\n async put<T>(\n endpoint: string,\n data?: unknown,\n config?: RequestConfig,\n ): Promise<T> {\n return this.request<T>(endpoint, {\n ...config,\n method: \"PUT\",\n body:\n data instanceof FormData\n ? data\n : data\n ? JSON.stringify(data)\n : undefined,\n });\n }\n\n async patch<T>(\n endpoint: string,\n data?: unknown,\n config?: RequestConfig,\n ): Promise<T> {\n return this.request<T>(endpoint, {\n ...config,\n method: \"PATCH\",\n body:\n data instanceof FormData\n ? data\n : data\n ? JSON.stringify(data)\n : undefined,\n });\n }\n\n async delete<T>(endpoint: string, config?: RequestConfig): Promise<T> {\n return this.request<T>(endpoint, { ...config, method: \"DELETE\" });\n }\n\n /**\n * Requisição cuja resposta é consumida em stream: devolve a `Response` crua, sem ler o\n * corpo e sem timeout.\n *\n * `request()` não serve para isso por dois motivos. Ele faz `await response.json()`, o\n * que espera o corpo inteiro e mata o propósito do stream; e aborta em 30s, que é o\n * tempo que uma operação longa leva justamente por ser longa — gerar o link de uma\n * página com 132 imagens copia 100 MB e passa disso (ID-5112).\n *\n * O corpo é do chamador: quem recebe decide quando ler e quando cancelar.\n */\n async stream(endpoint: string, config: RequestConfig = {}): Promise<Response> {\n const { timeout: _timeout, responseType: _responseType, whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;\n\n // Só resolve o whitelabel quando falta algum dos dois: com ambos vindos do chamador, a\n // consulta seria uma ida à rede para descartar o resultado.\n const resolvido = overrideWlId != null && overrideToken != null\n ? { id: overrideWlId, token: overrideToken }\n : await findWhitelabel();\n\n const [url, defaultHeaders] = await Promise.all([\n this.buildUrl(endpoint, overrideWlId ?? resolvido.id),\n this.getDefaultHeaders(overrideToken ?? resolvido.token),\n ]);\n\n const response = await fetch(url, {\n ...fetchConfig,\n headers: { ...defaultHeaders, ...fetchConfig.headers },\n // Sem isto o fetch do Next segura o corpo inteiro antes de devolver, e o stream chega\n // completo de uma vez no fim: medido em 32s até o primeiro evento, contra 0,4s com\n // no-store. O progresso existiria no protocolo e não na tela.\n cache: \"no-store\",\n });\n\n if (!response.ok || !response.body) {\n const detalhe = await response.text().catch(() => \"\");\n throw new ApiError(\n detalhe.trim() || `HTTP error ${response.status} ${response.statusText}`,\n \"HTTP_ERROR\",\n response.status,\n );\n }\n\n return response;\n }\n}\n\nconst api = {\n apps: new ApiClient(\n process.env.GAPPS_R3_API_URL || \"https://r3-api.greatapps.dev.br\",\n ),\n pages: new ApiClient(\n process.env.GPAGES_R3_API_URL || \"https://r3-api.greatpages.dev.br\",\n ),\n};\n\n/** @deprecated use api.apps */\nexport const apiClient = api.apps;\n\nexport { api, ApiClient };\n"],"mappings":"AAAA,SAAS,gBAAgB;AACzB,SAAS,sBAAsB;AAuB/B,MAAM,UAAU;AAAA,EACG;AAAA,EACA,aAAa;AAAA,EACb,YAAY;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AgB,GAAG,YAAY,QAAQ;AAAA;AAAA;AAAA;AAAA,MAIrD,OAAO;AAAA,IACT,CAAC;AAED,QAAI,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM;AAClC,YAAM,UAAU,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,EAAE;AACpD,YAAM,IAAI;AAAA,QACR,QAAQ,KAAK,KAAK,cAAc,SAAS,MAAM,IAAI,SAAS,UAAU;AAAA,QACtE;AAAA,QACA,SAAS;AAAA,MACX;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;AAEA,MAAM,MAAM;AAAA,EACV,MAAM,IAAI;AAAA,IACR,QAAQ,IAAI,oBAAoB;AAAA,EAClC;AAAA,EACA,OAAO,IAAI;AAAA,IACT,QAAQ,IAAI,qBAAqB;AAAA,EACnC;AACF;AAGO,MAAM,YAAY,IAAI;","names":[]}
|
|
@@ -7,7 +7,11 @@ const PlanItemSchema = z.object({
|
|
|
7
7
|
// Maior valor positivo por addon = preço base/original (demais linhas são promos).
|
|
8
8
|
// Derivado por heurística no backend (não há coluna no banco). Ausente em payloads
|
|
9
9
|
// de cache antigos → optional.
|
|
10
|
-
base: z.boolean().optional()
|
|
10
|
+
base: z.boolean().optional(),
|
|
11
|
+
// Faixa por volume: a quantidade EXATA para a qual este `value` unitário vale
|
|
12
|
+
// (créditos de IA em 2.500/5.000/10.000 saem mais baratos por unidade). Ausente/null
|
|
13
|
+
// = unitário padrão, válido para qualquer quantidade.
|
|
14
|
+
tier_quantity: z.number().nullish()
|
|
11
15
|
});
|
|
12
16
|
const PlanPeriodPricingSchema = z.object({
|
|
13
17
|
charged: z.number(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/modules/plans/types/plan.type.ts"],"sourcesContent":["import z from 'zod';\nimport type { BillingPeriod } from '../../subscriptions/types/billing-period.type';\n\nexport const PlanItemSchema = z.object({\n id_addon: z.number(),\n quantity: z.number(),\n value: z.number(),\n value_usd: z.number().nullish(),\n // Maior valor positivo por addon = preço base/original (demais linhas são promos).\n // Derivado por heurística no backend (não há coluna no banco). Ausente em payloads\n // de cache antigos → optional.\n base: z.boolean().optional(),\n});\n\nexport type PlanItem = z.infer<typeof PlanItemSchema>;\n\nexport const PlanPeriodPricingSchema = z.object({\n charged: z.number(),\n list: z.number(),\n discount: z.number(),\n discount_percent: z.number(),\n});\n\nexport const PlanApiPricingSchema = z.object({\n currency: z.enum(['brl', 'usd']),\n monthly: PlanPeriodPricingSchema,\n semester: PlanPeriodPricingSchema,\n annual: PlanPeriodPricingSchema,\n});\n\nexport type PlanApiPricing = z.infer<typeof PlanApiPricingSchema>;\n\nexport const PlanSchema = z.object({\n id: z.number(),\n id_plan: z.number().optional(),\n name: z.string(),\n value: z.number().nullable().default(0),\n // Preço em USD (conta stripe_usd). Operador cadastra no backend; ausente em planos\n // sem suporte internacional. Backend agora resolve por moeda da conta (customer),\n // omitindo value_usd para customer requests e adicionando currency. Admin paths\n // ainda recebem value_usd como número (sem .coerce — backend joga agora como Number).\n value_usd: z.number().nullish(),\n currency: z.enum(['brl', 'usd']).optional(),\n type: z.string().optional(),\n discount_semester: z.number().default(0),\n discount_annual: z.number().default(0),\n pricing: PlanApiPricingSchema.optional(),\n items: z.array(PlanItemSchema).optional().default([]),\n});\n\nexport type Plan = z.infer<typeof PlanSchema>;\n\n// ── UI Plan types (used by list-plans action and consumers) ──\n\nexport type PlanFeature = {\n icon: 'check' | 'x';\n text: string;\n disabled?: boolean;\n tooltip?: keyof PlanTooltips;\n};\n\nexport type PlanMainFeatures = {\n pages: string;\n domains: string;\n users: string;\n};\n\n/** Preços mensais equivalentes por período de cobrança (já com desconto aplicado). */\nexport type PlanPricingByPeriod = {\n monthly: number;\n semiannual: number;\n annual: number;\n};\n\nexport type UiPlan = {\n planId: number;\n name: string;\n isPopular?: boolean;\n isCurrentPlan?: boolean;\n currentPeriodicity?: BillingPeriod | null;\n mainFeatures: PlanMainFeatures;\n features: PlanFeature[];\n originalPrice: string;\n price: string;\n pricingByPeriod?: PlanPricingByPeriod;\n pricing?: PlanApiPricing;\n buttonVariant?: 'brand' | 'default';\n priceUnavailable?: boolean;\n items: PlanItem[];\n};\n\nexport type PlanTooltips = {\n domains: string;\n users: string;\n sharePages: string;\n projectManagement: string;\n};\n"],"mappings":"AAAA,OAAO,OAAO;AAGP,MAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,UAAU,EAAE,OAAO;AAAA,EACnB,UAAU,EAAE,OAAO;AAAA,EACnB,OAAO,EAAE,OAAO;AAAA,EAChB,WAAW,EAAE,OAAO,EAAE,QAAQ;AAAA;AAAA;AAAA;AAAA,EAI9B,MAAM,EAAE,QAAQ,EAAE,SAAS;
|
|
1
|
+
{"version":3,"sources":["../../../../src/modules/plans/types/plan.type.ts"],"sourcesContent":["import z from 'zod';\nimport type { BillingPeriod } from '../../subscriptions/types/billing-period.type';\n\nexport const PlanItemSchema = z.object({\n id_addon: z.number(),\n quantity: z.number(),\n value: z.number(),\n value_usd: z.number().nullish(),\n // Maior valor positivo por addon = preço base/original (demais linhas são promos).\n // Derivado por heurística no backend (não há coluna no banco). Ausente em payloads\n // de cache antigos → optional.\n base: z.boolean().optional(),\n // Faixa por volume: a quantidade EXATA para a qual este `value` unitário vale\n // (créditos de IA em 2.500/5.000/10.000 saem mais baratos por unidade). Ausente/null\n // = unitário padrão, válido para qualquer quantidade.\n tier_quantity: z.number().nullish(),\n});\n\nexport type PlanItem = z.infer<typeof PlanItemSchema>;\n\nexport const PlanPeriodPricingSchema = z.object({\n charged: z.number(),\n list: z.number(),\n discount: z.number(),\n discount_percent: z.number(),\n});\n\nexport const PlanApiPricingSchema = z.object({\n currency: z.enum(['brl', 'usd']),\n monthly: PlanPeriodPricingSchema,\n semester: PlanPeriodPricingSchema,\n annual: PlanPeriodPricingSchema,\n});\n\nexport type PlanApiPricing = z.infer<typeof PlanApiPricingSchema>;\n\nexport const PlanSchema = z.object({\n id: z.number(),\n id_plan: z.number().optional(),\n name: z.string(),\n value: z.number().nullable().default(0),\n // Preço em USD (conta stripe_usd). Operador cadastra no backend; ausente em planos\n // sem suporte internacional. Backend agora resolve por moeda da conta (customer),\n // omitindo value_usd para customer requests e adicionando currency. Admin paths\n // ainda recebem value_usd como número (sem .coerce — backend joga agora como Number).\n value_usd: z.number().nullish(),\n currency: z.enum(['brl', 'usd']).optional(),\n type: z.string().optional(),\n discount_semester: z.number().default(0),\n discount_annual: z.number().default(0),\n pricing: PlanApiPricingSchema.optional(),\n items: z.array(PlanItemSchema).optional().default([]),\n});\n\nexport type Plan = z.infer<typeof PlanSchema>;\n\n// ── UI Plan types (used by list-plans action and consumers) ──\n\nexport type PlanFeature = {\n icon: 'check' | 'x';\n text: string;\n disabled?: boolean;\n tooltip?: keyof PlanTooltips;\n};\n\nexport type PlanMainFeatures = {\n pages: string;\n domains: string;\n users: string;\n};\n\n/** Preços mensais equivalentes por período de cobrança (já com desconto aplicado). */\nexport type PlanPricingByPeriod = {\n monthly: number;\n semiannual: number;\n annual: number;\n};\n\nexport type UiPlan = {\n planId: number;\n name: string;\n isPopular?: boolean;\n isCurrentPlan?: boolean;\n currentPeriodicity?: BillingPeriod | null;\n mainFeatures: PlanMainFeatures;\n features: PlanFeature[];\n originalPrice: string;\n price: string;\n pricingByPeriod?: PlanPricingByPeriod;\n pricing?: PlanApiPricing;\n buttonVariant?: 'brand' | 'default';\n priceUnavailable?: boolean;\n items: PlanItem[];\n};\n\nexport type PlanTooltips = {\n domains: string;\n users: string;\n sharePages: string;\n projectManagement: string;\n};\n"],"mappings":"AAAA,OAAO,OAAO;AAGP,MAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,UAAU,EAAE,OAAO;AAAA,EACnB,UAAU,EAAE,OAAO;AAAA,EACnB,OAAO,EAAE,OAAO;AAAA,EAChB,WAAW,EAAE,OAAO,EAAE,QAAQ;AAAA;AAAA;AAAA;AAAA,EAI9B,MAAM,EAAE,QAAQ,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA,EAI3B,eAAe,EAAE,OAAO,EAAE,QAAQ;AACpC,CAAC;AAIM,MAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,SAAS,EAAE,OAAO;AAAA,EAClB,MAAM,EAAE,OAAO;AAAA,EACf,UAAU,EAAE,OAAO;AAAA,EACnB,kBAAkB,EAAE,OAAO;AAC7B,CAAC;AAEM,MAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,UAAU,EAAE,KAAK,CAAC,OAAO,KAAK,CAAC;AAAA,EAC/B,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AACV,CAAC;AAIM,MAAM,aAAa,EAAE,OAAO;AAAA,EACjC,IAAI,EAAE,OAAO;AAAA,EACb,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,MAAM,EAAE,OAAO;AAAA,EACf,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,EAKtC,WAAW,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC9B,UAAU,EAAE,KAAK,CAAC,OAAO,KAAK,CAAC,EAAE,SAAS;AAAA,EAC1C,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,mBAAmB,EAAE,OAAO,EAAE,QAAQ,CAAC;AAAA,EACvC,iBAAiB,EAAE,OAAO,EAAE,QAAQ,CAAC;AAAA,EACrC,SAAS,qBAAqB,SAAS;AAAA,EACvC,OAAO,EAAE,MAAM,cAAc,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;AACtD,CAAC;","names":[]}
|
package/package.json
CHANGED
package/src/infra/api/client.ts
CHANGED
|
@@ -1,263 +1,309 @@
|
|
|
1
|
-
import { ApiError } from "./types";
|
|
2
|
-
import { findWhitelabel } from "../../modules/whitelabel/actions/find-whitelabel.action";
|
|
3
|
-
|
|
4
|
-
export interface ApiClientOptions {
|
|
5
|
-
/**
|
|
6
|
-
* Quando true, monta `{base}/{locale}/{wlId}{endpoint}` (ex.: r2-clone).
|
|
7
|
-
* Padrão false: `{base}/v1/{locale}/{wlId}{endpoint}`.
|
|
8
|
-
*/
|
|
9
|
-
omitApiVersion?: boolean;
|
|
10
|
-
|
|
11
|
-
/** Habilita logs detalhados das requisições (útil para desenvolvimento) */
|
|
12
|
-
emitLogs?: boolean;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export interface RequestConfig extends RequestInit {
|
|
16
|
-
timeout?: number;
|
|
17
|
-
/** Padrão `json`. Use `text` quando a API devolve corpo não-JSON. */
|
|
18
|
-
responseType?: "json" | "text";
|
|
19
|
-
/** Força um whiteLabelId específico na URL, ignorando o findWhitelabel(). */
|
|
20
|
-
whiteLabelId?: number;
|
|
21
|
-
/** Força um token específico no header Authorization, ignorando o findWhitelabel(). */
|
|
22
|
-
authToken?: string;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
class ApiClient {
|
|
26
|
-
private readonly baseUrl: string;
|
|
27
|
-
private readonly apiVersion = "v1";
|
|
28
|
-
private readonly apiLocale = "pt-br";
|
|
29
|
-
private readonly omitApiVersion: boolean;
|
|
30
|
-
private readonly emitLogs: boolean = false;
|
|
31
|
-
|
|
32
|
-
constructor(baseUrl: string, options?: ApiClientOptions) {
|
|
33
|
-
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
34
|
-
this.omitApiVersion = options?.omitApiVersion ?? false;
|
|
35
|
-
this.emitLogs = options?.emitLogs ?? false;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
private async buildUrl(
|
|
39
|
-
endpoint: string,
|
|
40
|
-
whiteLabelId: number,
|
|
41
|
-
): Promise<string> {
|
|
42
|
-
const wlPath = this.omitApiVersion
|
|
43
|
-
? `/${this.apiLocale}/${whiteLabelId}`
|
|
44
|
-
: `/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}`;
|
|
45
|
-
const path = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
|
|
46
|
-
const url = `${this.baseUrl}${wlPath}${path}`;
|
|
47
|
-
if (this.emitLogs) {
|
|
48
|
-
console.log("[ApiClient] buildUrl", {
|
|
49
|
-
baseURL: this.baseUrl,
|
|
50
|
-
whiteLabelId,
|
|
51
|
-
endpoint,
|
|
52
|
-
fullUrl: url,
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
return url;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
private async getDefaultHeaders(
|
|
59
|
-
token: string,
|
|
60
|
-
isFormData = false,
|
|
61
|
-
): Promise<HeadersInit> {
|
|
62
|
-
if (this.emitLogs) {
|
|
63
|
-
console.log("[ApiClient] getDefaultHeaders", {
|
|
64
|
-
token: token.substring(0, 20) + "...",
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const headers: HeadersInit = {
|
|
69
|
-
authorization: token,
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
if (!isFormData) {
|
|
73
|
-
headers["Content-Type"] = "application/json";
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
return headers;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
async request<T>(endpoint: string, config: RequestConfig = {}): Promise<T> {
|
|
80
|
-
if (this.emitLogs) {
|
|
81
|
-
console.log("[ApiClient] request called", {
|
|
82
|
-
endpoint,
|
|
83
|
-
method: config.method,
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const { timeout = 30000, responseType = "json", whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;
|
|
88
|
-
|
|
89
|
-
const controller = new AbortController();
|
|
90
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
91
|
-
|
|
92
|
-
try {
|
|
93
|
-
if (this.emitLogs) {
|
|
94
|
-
console.log("[ApiClient] Building URL and headers...");
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const { id, token } = await findWhitelabel();
|
|
98
|
-
|
|
99
|
-
const [url, defaultHeaders] = await Promise.all([
|
|
100
|
-
this.buildUrl(endpoint, overrideWlId ?? id),
|
|
101
|
-
this.getDefaultHeaders(overrideToken ?? token, fetchConfig.body instanceof FormData),
|
|
102
|
-
]);
|
|
103
|
-
|
|
104
|
-
if (this.emitLogs)
|
|
105
|
-
console.log("[ApiClient] Fetching", {
|
|
106
|
-
url,
|
|
107
|
-
method: fetchConfig.method,
|
|
108
|
-
headers: defaultHeaders,
|
|
109
|
-
});
|
|
110
|
-
|
|
111
|
-
const response = await fetch(url, {
|
|
112
|
-
...fetchConfig,
|
|
113
|
-
headers: {
|
|
114
|
-
...defaultHeaders,
|
|
115
|
-
...fetchConfig.headers,
|
|
116
|
-
},
|
|
117
|
-
signal: controller.signal,
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
if (this.emitLogs)
|
|
121
|
-
console.log("[ApiClient] Response received", {
|
|
122
|
-
status: response.status,
|
|
123
|
-
ok: response.ok,
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
if (!response.ok) {
|
|
127
|
-
const errBody = await response.text();
|
|
128
|
-
let message = `HTTP error ${response.status} ${response.statusText} ${errBody}`;
|
|
129
|
-
let code = "HTTP_ERROR";
|
|
130
|
-
try {
|
|
131
|
-
const errorData = JSON.parse(errBody) as Record<string, unknown>;
|
|
132
|
-
// @ts-ignore -- msg pode ser string ou objeto com .message
|
|
133
|
-
message = errorData.message?.message ?? errorData.message ?? message;
|
|
134
|
-
if (typeof errorData.code === "string") code = errorData.code;
|
|
135
|
-
} catch {
|
|
136
|
-
if (errBody.trim()) message = errBody.trim();
|
|
137
|
-
}
|
|
138
|
-
const method = fetchConfig.method ?? "GET";
|
|
139
|
-
let bodyPreview: unknown;
|
|
140
|
-
if (method !== "GET" && fetchConfig.body != null) {
|
|
141
|
-
if (typeof fetchConfig.body === "string") {
|
|
142
|
-
try {
|
|
143
|
-
bodyPreview = JSON.parse(fetchConfig.body);
|
|
144
|
-
} catch {
|
|
145
|
-
bodyPreview = fetchConfig.body;
|
|
146
|
-
}
|
|
147
|
-
} else if (fetchConfig.body instanceof FormData) {
|
|
148
|
-
bodyPreview = "[FormData]";
|
|
149
|
-
} else {
|
|
150
|
-
bodyPreview = fetchConfig.body;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
console.error("[ApiClient] Request failed", {
|
|
154
|
-
from: url,
|
|
155
|
-
method,
|
|
156
|
-
...(bodyPreview !== undefined ? { body: bodyPreview } : {}),
|
|
157
|
-
status: response.status,
|
|
158
|
-
message,
|
|
159
|
-
});
|
|
160
|
-
throw new ApiError(message, code, response.status);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
if (responseType === "text") {
|
|
164
|
-
return (await response.text()) as T;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
const data = (await response.json()) as T;
|
|
168
|
-
if (this.emitLogs)
|
|
169
|
-
console.log("[ApiClient] Request successful", { hasData: !!data });
|
|
170
|
-
return data;
|
|
171
|
-
} catch (error) {
|
|
172
|
-
if (this.emitLogs) console.error("[ApiClient] Request error", { error });
|
|
173
|
-
|
|
174
|
-
if (error instanceof ApiError) {
|
|
175
|
-
throw error;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
if (error instanceof Error) {
|
|
179
|
-
if (error.name === "AbortError") {
|
|
180
|
-
throw new ApiError("Tempo de requisição excedido", "TIMEOUT", 408);
|
|
181
|
-
}
|
|
182
|
-
throw new ApiError(error.message, "NETWORK_ERROR", 0);
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
throw new ApiError("Erro desconhecido", "UNKNOWN_ERROR", 500);
|
|
186
|
-
} finally {
|
|
187
|
-
clearTimeout(timeoutId);
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
async get<T>(endpoint: string, config?: RequestConfig): Promise<T> {
|
|
192
|
-
return this.request<T>(endpoint, { ...config, method: "GET" });
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
async post<T>(
|
|
196
|
-
endpoint: string,
|
|
197
|
-
data?: unknown,
|
|
198
|
-
config?: RequestConfig,
|
|
199
|
-
): Promise<T> {
|
|
200
|
-
return this.request<T>(endpoint, {
|
|
201
|
-
...config,
|
|
202
|
-
method: "POST",
|
|
203
|
-
body:
|
|
204
|
-
data instanceof FormData
|
|
205
|
-
? data
|
|
206
|
-
: data
|
|
207
|
-
? JSON.stringify(data)
|
|
208
|
-
: undefined,
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async put<T>(
|
|
213
|
-
endpoint: string,
|
|
214
|
-
data?: unknown,
|
|
215
|
-
config?: RequestConfig,
|
|
216
|
-
): Promise<T> {
|
|
217
|
-
return this.request<T>(endpoint, {
|
|
218
|
-
...config,
|
|
219
|
-
method: "PUT",
|
|
220
|
-
body:
|
|
221
|
-
data instanceof FormData
|
|
222
|
-
? data
|
|
223
|
-
: data
|
|
224
|
-
? JSON.stringify(data)
|
|
225
|
-
: undefined,
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
async patch<T>(
|
|
230
|
-
endpoint: string,
|
|
231
|
-
data?: unknown,
|
|
232
|
-
config?: RequestConfig,
|
|
233
|
-
): Promise<T> {
|
|
234
|
-
return this.request<T>(endpoint, {
|
|
235
|
-
...config,
|
|
236
|
-
method: "PATCH",
|
|
237
|
-
body:
|
|
238
|
-
data instanceof FormData
|
|
239
|
-
? data
|
|
240
|
-
: data
|
|
241
|
-
? JSON.stringify(data)
|
|
242
|
-
: undefined,
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
async delete<T>(endpoint: string, config?: RequestConfig): Promise<T> {
|
|
247
|
-
return this.request<T>(endpoint, { ...config, method: "DELETE" });
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
1
|
+
import { ApiError } from "./types";
|
|
2
|
+
import { findWhitelabel } from "../../modules/whitelabel/actions/find-whitelabel.action";
|
|
3
|
+
|
|
4
|
+
export interface ApiClientOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Quando true, monta `{base}/{locale}/{wlId}{endpoint}` (ex.: r2-clone).
|
|
7
|
+
* Padrão false: `{base}/v1/{locale}/{wlId}{endpoint}`.
|
|
8
|
+
*/
|
|
9
|
+
omitApiVersion?: boolean;
|
|
10
|
+
|
|
11
|
+
/** Habilita logs detalhados das requisições (útil para desenvolvimento) */
|
|
12
|
+
emitLogs?: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface RequestConfig extends RequestInit {
|
|
16
|
+
timeout?: number;
|
|
17
|
+
/** Padrão `json`. Use `text` quando a API devolve corpo não-JSON. */
|
|
18
|
+
responseType?: "json" | "text";
|
|
19
|
+
/** Força um whiteLabelId específico na URL, ignorando o findWhitelabel(). */
|
|
20
|
+
whiteLabelId?: number;
|
|
21
|
+
/** Força um token específico no header Authorization, ignorando o findWhitelabel(). */
|
|
22
|
+
authToken?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
class ApiClient {
|
|
26
|
+
private readonly baseUrl: string;
|
|
27
|
+
private readonly apiVersion = "v1";
|
|
28
|
+
private readonly apiLocale = "pt-br";
|
|
29
|
+
private readonly omitApiVersion: boolean;
|
|
30
|
+
private readonly emitLogs: boolean = false;
|
|
31
|
+
|
|
32
|
+
constructor(baseUrl: string, options?: ApiClientOptions) {
|
|
33
|
+
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
34
|
+
this.omitApiVersion = options?.omitApiVersion ?? false;
|
|
35
|
+
this.emitLogs = options?.emitLogs ?? false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private async buildUrl(
|
|
39
|
+
endpoint: string,
|
|
40
|
+
whiteLabelId: number,
|
|
41
|
+
): Promise<string> {
|
|
42
|
+
const wlPath = this.omitApiVersion
|
|
43
|
+
? `/${this.apiLocale}/${whiteLabelId}`
|
|
44
|
+
: `/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}`;
|
|
45
|
+
const path = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
|
|
46
|
+
const url = `${this.baseUrl}${wlPath}${path}`;
|
|
47
|
+
if (this.emitLogs) {
|
|
48
|
+
console.log("[ApiClient] buildUrl", {
|
|
49
|
+
baseURL: this.baseUrl,
|
|
50
|
+
whiteLabelId,
|
|
51
|
+
endpoint,
|
|
52
|
+
fullUrl: url,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return url;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private async getDefaultHeaders(
|
|
59
|
+
token: string,
|
|
60
|
+
isFormData = false,
|
|
61
|
+
): Promise<HeadersInit> {
|
|
62
|
+
if (this.emitLogs) {
|
|
63
|
+
console.log("[ApiClient] getDefaultHeaders", {
|
|
64
|
+
token: token.substring(0, 20) + "...",
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const headers: HeadersInit = {
|
|
69
|
+
authorization: token,
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
if (!isFormData) {
|
|
73
|
+
headers["Content-Type"] = "application/json";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return headers;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async request<T>(endpoint: string, config: RequestConfig = {}): Promise<T> {
|
|
80
|
+
if (this.emitLogs) {
|
|
81
|
+
console.log("[ApiClient] request called", {
|
|
82
|
+
endpoint,
|
|
83
|
+
method: config.method,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const { timeout = 30000, responseType = "json", whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;
|
|
88
|
+
|
|
89
|
+
const controller = new AbortController();
|
|
90
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
if (this.emitLogs) {
|
|
94
|
+
console.log("[ApiClient] Building URL and headers...");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const { id, token } = await findWhitelabel();
|
|
98
|
+
|
|
99
|
+
const [url, defaultHeaders] = await Promise.all([
|
|
100
|
+
this.buildUrl(endpoint, overrideWlId ?? id),
|
|
101
|
+
this.getDefaultHeaders(overrideToken ?? token, fetchConfig.body instanceof FormData),
|
|
102
|
+
]);
|
|
103
|
+
|
|
104
|
+
if (this.emitLogs)
|
|
105
|
+
console.log("[ApiClient] Fetching", {
|
|
106
|
+
url,
|
|
107
|
+
method: fetchConfig.method,
|
|
108
|
+
headers: defaultHeaders,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
const response = await fetch(url, {
|
|
112
|
+
...fetchConfig,
|
|
113
|
+
headers: {
|
|
114
|
+
...defaultHeaders,
|
|
115
|
+
...fetchConfig.headers,
|
|
116
|
+
},
|
|
117
|
+
signal: controller.signal,
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (this.emitLogs)
|
|
121
|
+
console.log("[ApiClient] Response received", {
|
|
122
|
+
status: response.status,
|
|
123
|
+
ok: response.ok,
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
if (!response.ok) {
|
|
127
|
+
const errBody = await response.text();
|
|
128
|
+
let message = `HTTP error ${response.status} ${response.statusText} ${errBody}`;
|
|
129
|
+
let code = "HTTP_ERROR";
|
|
130
|
+
try {
|
|
131
|
+
const errorData = JSON.parse(errBody) as Record<string, unknown>;
|
|
132
|
+
// @ts-ignore -- msg pode ser string ou objeto com .message
|
|
133
|
+
message = errorData.message?.message ?? errorData.message ?? message;
|
|
134
|
+
if (typeof errorData.code === "string") code = errorData.code;
|
|
135
|
+
} catch {
|
|
136
|
+
if (errBody.trim()) message = errBody.trim();
|
|
137
|
+
}
|
|
138
|
+
const method = fetchConfig.method ?? "GET";
|
|
139
|
+
let bodyPreview: unknown;
|
|
140
|
+
if (method !== "GET" && fetchConfig.body != null) {
|
|
141
|
+
if (typeof fetchConfig.body === "string") {
|
|
142
|
+
try {
|
|
143
|
+
bodyPreview = JSON.parse(fetchConfig.body);
|
|
144
|
+
} catch {
|
|
145
|
+
bodyPreview = fetchConfig.body;
|
|
146
|
+
}
|
|
147
|
+
} else if (fetchConfig.body instanceof FormData) {
|
|
148
|
+
bodyPreview = "[FormData]";
|
|
149
|
+
} else {
|
|
150
|
+
bodyPreview = fetchConfig.body;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
console.error("[ApiClient] Request failed", {
|
|
154
|
+
from: url,
|
|
155
|
+
method,
|
|
156
|
+
...(bodyPreview !== undefined ? { body: bodyPreview } : {}),
|
|
157
|
+
status: response.status,
|
|
158
|
+
message,
|
|
159
|
+
});
|
|
160
|
+
throw new ApiError(message, code, response.status);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (responseType === "text") {
|
|
164
|
+
return (await response.text()) as T;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const data = (await response.json()) as T;
|
|
168
|
+
if (this.emitLogs)
|
|
169
|
+
console.log("[ApiClient] Request successful", { hasData: !!data });
|
|
170
|
+
return data;
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (this.emitLogs) console.error("[ApiClient] Request error", { error });
|
|
173
|
+
|
|
174
|
+
if (error instanceof ApiError) {
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (error instanceof Error) {
|
|
179
|
+
if (error.name === "AbortError") {
|
|
180
|
+
throw new ApiError("Tempo de requisição excedido", "TIMEOUT", 408);
|
|
181
|
+
}
|
|
182
|
+
throw new ApiError(error.message, "NETWORK_ERROR", 0);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
throw new ApiError("Erro desconhecido", "UNKNOWN_ERROR", 500);
|
|
186
|
+
} finally {
|
|
187
|
+
clearTimeout(timeoutId);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async get<T>(endpoint: string, config?: RequestConfig): Promise<T> {
|
|
192
|
+
return this.request<T>(endpoint, { ...config, method: "GET" });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async post<T>(
|
|
196
|
+
endpoint: string,
|
|
197
|
+
data?: unknown,
|
|
198
|
+
config?: RequestConfig,
|
|
199
|
+
): Promise<T> {
|
|
200
|
+
return this.request<T>(endpoint, {
|
|
201
|
+
...config,
|
|
202
|
+
method: "POST",
|
|
203
|
+
body:
|
|
204
|
+
data instanceof FormData
|
|
205
|
+
? data
|
|
206
|
+
: data
|
|
207
|
+
? JSON.stringify(data)
|
|
208
|
+
: undefined,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async put<T>(
|
|
213
|
+
endpoint: string,
|
|
214
|
+
data?: unknown,
|
|
215
|
+
config?: RequestConfig,
|
|
216
|
+
): Promise<T> {
|
|
217
|
+
return this.request<T>(endpoint, {
|
|
218
|
+
...config,
|
|
219
|
+
method: "PUT",
|
|
220
|
+
body:
|
|
221
|
+
data instanceof FormData
|
|
222
|
+
? data
|
|
223
|
+
: data
|
|
224
|
+
? JSON.stringify(data)
|
|
225
|
+
: undefined,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async patch<T>(
|
|
230
|
+
endpoint: string,
|
|
231
|
+
data?: unknown,
|
|
232
|
+
config?: RequestConfig,
|
|
233
|
+
): Promise<T> {
|
|
234
|
+
return this.request<T>(endpoint, {
|
|
235
|
+
...config,
|
|
236
|
+
method: "PATCH",
|
|
237
|
+
body:
|
|
238
|
+
data instanceof FormData
|
|
239
|
+
? data
|
|
240
|
+
: data
|
|
241
|
+
? JSON.stringify(data)
|
|
242
|
+
: undefined,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async delete<T>(endpoint: string, config?: RequestConfig): Promise<T> {
|
|
247
|
+
return this.request<T>(endpoint, { ...config, method: "DELETE" });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Requisição cuja resposta é consumida em stream: devolve a `Response` crua, sem ler o
|
|
252
|
+
* corpo e sem timeout.
|
|
253
|
+
*
|
|
254
|
+
* `request()` não serve para isso por dois motivos. Ele faz `await response.json()`, o
|
|
255
|
+
* que espera o corpo inteiro e mata o propósito do stream; e aborta em 30s, que é o
|
|
256
|
+
* tempo que uma operação longa leva justamente por ser longa — gerar o link de uma
|
|
257
|
+
* página com 132 imagens copia 100 MB e passa disso (ID-5112).
|
|
258
|
+
*
|
|
259
|
+
* O corpo é do chamador: quem recebe decide quando ler e quando cancelar.
|
|
260
|
+
*/
|
|
261
|
+
async stream(endpoint: string, config: RequestConfig = {}): Promise<Response> {
|
|
262
|
+
const { timeout: _timeout, responseType: _responseType, whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;
|
|
263
|
+
|
|
264
|
+
// Só resolve o whitelabel quando falta algum dos dois: com ambos vindos do chamador, a
|
|
265
|
+
// consulta seria uma ida à rede para descartar o resultado.
|
|
266
|
+
const resolvido = overrideWlId != null && overrideToken != null
|
|
267
|
+
? { id: overrideWlId, token: overrideToken }
|
|
268
|
+
: await findWhitelabel();
|
|
269
|
+
|
|
270
|
+
const [url, defaultHeaders] = await Promise.all([
|
|
271
|
+
this.buildUrl(endpoint, overrideWlId ?? resolvido.id),
|
|
272
|
+
this.getDefaultHeaders(overrideToken ?? resolvido.token),
|
|
273
|
+
]);
|
|
274
|
+
|
|
275
|
+
const response = await fetch(url, {
|
|
276
|
+
...fetchConfig,
|
|
277
|
+
headers: { ...defaultHeaders, ...fetchConfig.headers },
|
|
278
|
+
// Sem isto o fetch do Next segura o corpo inteiro antes de devolver, e o stream chega
|
|
279
|
+
// completo de uma vez no fim: medido em 32s até o primeiro evento, contra 0,4s com
|
|
280
|
+
// no-store. O progresso existiria no protocolo e não na tela.
|
|
281
|
+
cache: "no-store",
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
if (!response.ok || !response.body) {
|
|
285
|
+
const detalhe = await response.text().catch(() => "");
|
|
286
|
+
throw new ApiError(
|
|
287
|
+
detalhe.trim() || `HTTP error ${response.status} ${response.statusText}`,
|
|
288
|
+
"HTTP_ERROR",
|
|
289
|
+
response.status,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return response;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const api = {
|
|
298
|
+
apps: new ApiClient(
|
|
299
|
+
process.env.GAPPS_R3_API_URL || "https://r3-api.greatapps.dev.br",
|
|
300
|
+
),
|
|
301
|
+
pages: new ApiClient(
|
|
302
|
+
process.env.GPAGES_R3_API_URL || "https://r3-api.greatpages.dev.br",
|
|
303
|
+
),
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
/** @deprecated use api.apps */
|
|
307
|
+
export const apiClient = api.apps;
|
|
308
|
+
|
|
309
|
+
export { api, ApiClient };
|
|
@@ -10,6 +10,10 @@ export const PlanItemSchema = z.object({
|
|
|
10
10
|
// Derivado por heurística no backend (não há coluna no banco). Ausente em payloads
|
|
11
11
|
// de cache antigos → optional.
|
|
12
12
|
base: z.boolean().optional(),
|
|
13
|
+
// Faixa por volume: a quantidade EXATA para a qual este `value` unitário vale
|
|
14
|
+
// (créditos de IA em 2.500/5.000/10.000 saem mais baratos por unidade). Ausente/null
|
|
15
|
+
// = unitário padrão, válido para qualquer quantidade.
|
|
16
|
+
tier_quantity: z.number().nullish(),
|
|
13
17
|
});
|
|
14
18
|
|
|
15
19
|
export type PlanItem = z.infer<typeof PlanItemSchema>;
|