@vitrindigital/node 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -165,8 +165,63 @@ try {
165
165
  }
166
166
  ```
167
167
 
168
- O cliente faz **retry automático** em `429` e `5xx` com backoff exponencial
169
- (default: 3 tentativas). Erros 4xx (exceto 429) não são retentados.
168
+ O cliente faz **retry automático** com backoff exponencial (default: 3
169
+ tentativas), mas só quando repetir não arrisca cobrar duas vezes:
170
+
171
+ | Situação | `GET` (e `PUT`/`DELETE`) | `POST`/`PATCH` |
172
+ |---|---|---|
173
+ | `429` | repete | repete (o limite barra o pedido antes de qualquer efeito) |
174
+ | `5xx` com `retryable: true` | repete | repete (nada foi cobrado) |
175
+ | `5xx` com `retryable: false` | repete | **não repete** |
176
+ | `5xx` sem `retryable` (ex.: 502/504 do proxy) | repete | só no `/charges/` e `/charges/charge-saved/` com `idempotencyKey` |
177
+ | conexão que nem abriu (DNS, conexão recusada) | repete | repete (nada saiu daqui) |
178
+ | tempo esgotado, conexão caída no meio | repete | só no `/charges/` e `/charges/charge-saved/` com `idempotencyKey` |
179
+ | `4xx` (exceto 429) | não repete | não repete |
180
+
181
+ `retryable: true` num 5xx quer dizer **nada foi cobrado**, em todos os
182
+ caminhos de cartão da API: `/checkout/pay/`, `/charges/`,
183
+ `/charges/charge-saved/`, `/orders/create/`, `/checkout/guest/`,
184
+ `/subscriptions/` e one-click.
185
+
186
+ O `502` com `retryable: false` e `payment_status: "processing"` é o resultado
187
+ incerto de uma cobrança de cartão: a resposta do processador se perdeu e **a
188
+ cobrança pode ter sido feita**. O SDK **nunca reenvia** esse POST. Em
189
+ `charges.create()`, `charges.createWithSavedCard()` e `/checkout/pay/`, ele
190
+ consulta `GET /transactions/{transaction_id}/` por até ~60 s (após 2, 4, 8,
191
+ 15 e 30 s) e devolve o desfecho:
192
+
193
+ | Desfecho da transação | O que a chamada faz |
194
+ |---|---|
195
+ | paga (`received`/`confirmed`) | devolve a transação: o mesmo objeto do sucesso |
196
+ | recusada pelo emissor | lança `VitrinRefusedError`, como o `422` |
197
+ | ainda incerta no fim do prazo (ou consulta falhando) | lança `VitrinServerError` com `payment_status: "processing"` e `transaction_id` no `body` |
198
+
199
+ O prazo é configurável: `new Vitrin({ apiKey, uncertainWaitMs: 30_000 })`;
200
+ `uncertainWaitMs: 0` desliga a consulta e lança o erro na hora. Uma falha na
201
+ consulta não conta como "não cobrado": o SDK segue consultando até o prazo.
202
+
203
+ Em `/orders/create/`, `/checkout/guest/` e `/subscriptions/` o objeto do
204
+ sucesso (pedido, assinatura) não existe quando o pagamento se confirma depois,
205
+ então o erro é lançado na hora, sem consulta. Nos dois casos, não cobre de
206
+ novo: aguarde o webhook ou consulte a transação.
207
+
208
+ ```ts
209
+ try {
210
+ await vitrin.charges.create({ ... });
211
+ } catch (err) {
212
+ const body = (err as VitrinError).body as Record<string, unknown> | undefined;
213
+ if (err instanceof VitrinServerError && body?.payment_status === 'processing') {
214
+ // NÃO cobre de novo: aguarde o webhook de pagamento desta transação.
215
+ await vitrin.charges.retrieve(String(body.transaction_id));
216
+ }
217
+ }
218
+ ```
219
+
220
+ No `/charges/` e no `/charges/charge-saved/`, a Vitrin acha a cobrança pela
221
+ `idempotencyKey` antes de ir ao processador, então ali o SDK repete com
222
+ segurança: a repetição devolve a mesma cobrança (ou o mesmo `502` incerto
223
+ enquanto ela não tem desfecho), nunca uma segunda. Em qualquer outro endpoint a
224
+ chave não impede o segundo efeito, e o SDK não repete.
170
225
 
171
226
  ### Recusa não é erro de validação
172
227
 
package/dist/index.cjs CHANGED
@@ -89,12 +89,13 @@ var VitrinNetworkError = class extends VitrinError {
89
89
 
90
90
  // src/client.ts
91
91
  var DEFAULT_BASE_URL = "https://api.vitrin.digital/api/v1";
92
- var SDK_VERSION = "0.1.0";
92
+ var SDK_VERSION = "0.5.0";
93
93
  var VitrinClient = class {
94
94
  baseUrl;
95
95
  apiKey;
96
96
  timeout;
97
97
  maxRetries;
98
+ uncertainWaitMs;
98
99
  constructor(opts) {
99
100
  if (!opts.apiKey) {
100
101
  throw new Error("apiKey \xE9 obrigat\xF3rio");
@@ -103,6 +104,7 @@ var VitrinClient = class {
103
104
  this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
104
105
  this.timeout = opts.timeout ?? 3e4;
105
106
  this.maxRetries = opts.maxRetries ?? 3;
107
+ this.uncertainWaitMs = Math.max(0, opts.uncertainWaitMs ?? 6e4);
106
108
  }
107
109
  /** Helper público pra resources. */
108
110
  async request(path, options = {}) {
@@ -133,7 +135,7 @@ var VitrinClient = class {
133
135
  lastError = new VitrinNetworkError(
134
136
  netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
135
137
  );
136
- if (attempt < this.maxRetries && canRetryAfterNetworkError(method, idempotencyKey)) {
138
+ if (attempt < this.maxRetries && shouldRetryNetworkError(method, path, idempotencyKey, err2)) {
137
139
  await sleep(backoffMs(attempt));
138
140
  continue;
139
141
  }
@@ -153,8 +155,11 @@ var VitrinClient = class {
153
155
  } catch {
154
156
  }
155
157
  const err = mapErrorResponse(res.status, parsed, requestId);
156
- const retriable = res.status === 429 || res.status >= 500;
157
- if (retriable && attempt < this.maxRetries) {
158
+ const uncertainTxId = uncertainTransactionId(method, path, res.status, parsed);
159
+ if (uncertainTxId && this.uncertainWaitMs > 0) {
160
+ return this.resolveUncertain(uncertainTxId, err);
161
+ }
162
+ if (attempt < this.maxRetries && shouldRetryResponse(method, path, idempotencyKey, res.status, parsed)) {
158
163
  const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
159
164
  await sleep(retryAfter ?? backoffMs(attempt));
160
165
  lastError = err;
@@ -164,6 +169,71 @@ var VitrinClient = class {
164
169
  }
165
170
  throw lastError ?? new VitrinError("Esgotou as tentativas sem erro identificado");
166
171
  }
172
+ /**
173
+ * Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
174
+ * backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
175
+ * desfecho. NUNCA reenvia o POST.
176
+ *
177
+ * O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
178
+ * GET pode levar até o próprio timeout, e sem descontar isso do prazo o
179
+ * pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
180
+ * O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
181
+ * falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
182
+ * tenta mais uma consulta.
183
+ *
184
+ * - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
185
+ * que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
186
+ * `/checkout/pay/` devolve (os três respondem com a transação);
187
+ * - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
188
+ * - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
189
+ * original (`VitrinServerError` com `payment_status: "processing"` e
190
+ * `transaction_id` no `body`). Erro de consulta não prova nada.
191
+ */
192
+ async resolveUncertain(transactionId, original) {
193
+ const deadline = Date.now() + this.uncertainWaitMs;
194
+ for (const step of UNCERTAIN_BACKOFF_MS) {
195
+ const beforeSleep = deadline - Date.now();
196
+ if (beforeSleep <= 0) break;
197
+ await sleep(Math.min(step, beforeSleep));
198
+ const remaining = deadline - Date.now();
199
+ if (remaining < MIN_GET_BUDGET_MS) break;
200
+ let tx;
201
+ try {
202
+ tx = await this.getOnce(
203
+ `/transactions/${encodeURIComponent(transactionId)}/`,
204
+ Math.min(this.timeout, remaining)
205
+ );
206
+ } catch {
207
+ continue;
208
+ }
209
+ const outcome = uncertainOutcome(tx);
210
+ if (outcome === "paid") return tx;
211
+ if (outcome === "refused") throw refusedFromTransaction(tx, original.requestId);
212
+ }
213
+ throw original;
214
+ }
215
+ /** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
216
+ async getOnce(path, timeoutMs = this.timeout) {
217
+ const controller = new AbortController();
218
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
219
+ try {
220
+ const res = await fetch(this.buildUrl(path), {
221
+ method: "GET",
222
+ headers: {
223
+ Authorization: `Bearer ${this.apiKey}`,
224
+ Accept: "application/json",
225
+ "User-Agent": `vitrindigital-node/${SDK_VERSION} node/${process.version}`
226
+ },
227
+ signal: controller.signal
228
+ });
229
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
230
+ const body = await res.json();
231
+ if (!body || typeof body !== "object") throw new Error("corpo inv\xE1lido");
232
+ return body;
233
+ } finally {
234
+ clearTimeout(timer);
235
+ }
236
+ }
167
237
  buildUrl(path, query) {
168
238
  const url = new URL(this.baseUrl + (path.startsWith("/") ? path : `/${path}`));
169
239
  if (query) {
@@ -233,9 +303,83 @@ function parseRetryAfter(header) {
233
303
  return null;
234
304
  }
235
305
  var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
236
- function canRetryAfterNetworkError(method, idempotencyKey) {
237
- if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;
238
- return Boolean(idempotencyKey);
306
+ var DEDUPLICATED_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/"]);
307
+ var NEVER_CONNECTED_CODES = /* @__PURE__ */ new Set([
308
+ "ECONNREFUSED",
309
+ "ENOTFOUND",
310
+ "EAI_AGAIN",
311
+ "EHOSTUNREACH",
312
+ "ENETUNREACH",
313
+ "UND_ERR_CONNECT_TIMEOUT"
314
+ ]);
315
+ function normalizePath(path) {
316
+ const p = path.split("?")[0];
317
+ const withSlash = p.startsWith("/") ? p : `/${p}`;
318
+ return withSlash.endsWith("/") ? withSlash : `${withSlash}/`;
319
+ }
320
+ function isIdempotentMethod(method) {
321
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
322
+ }
323
+ function serverDeduplicates(path, idempotencyKey) {
324
+ return Boolean(idempotencyKey) && DEDUPLICATED_PATHS.has(normalizePath(path));
325
+ }
326
+ function neverConnected(err) {
327
+ const cause = err?.cause;
328
+ if (!cause) return false;
329
+ if (cause.code && NEVER_CONNECTED_CODES.has(cause.code)) return true;
330
+ return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((e) => Boolean(e?.code && NEVER_CONNECTED_CODES.has(e.code)));
331
+ }
332
+ function shouldRetryNetworkError(method, path, idempotencyKey, err) {
333
+ if (isIdempotentMethod(method)) return true;
334
+ if (neverConnected(err)) return true;
335
+ return serverDeduplicates(path, idempotencyKey);
336
+ }
337
+ function shouldRetryResponse(method, path, idempotencyKey, status, body) {
338
+ if (status !== 429 && status < 500) return false;
339
+ if (isIdempotentMethod(method) || status === 429) return true;
340
+ const retryable = body && typeof body === "object" ? body.retryable : void 0;
341
+ if (retryable === true) return true;
342
+ if (retryable === false) return false;
343
+ return serverDeduplicates(path, idempotencyKey);
344
+ }
345
+ var UNCERTAIN_BACKOFF_MS = [2e3, 4e3, 8e3, 15e3, 3e4];
346
+ var MIN_GET_BUDGET_MS = 1e3;
347
+ var TRANSACTION_RESULT_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/", "/checkout/pay/"]);
348
+ var PAID_STATUSES = /* @__PURE__ */ new Set(["received", "confirmed"]);
349
+ var REFUSED_STATUSES = /* @__PURE__ */ new Set(["failed", "canceled", "expired"]);
350
+ var UNCERTAIN_CODE = "VITRIN_PROVIDER_UNCERTAIN";
351
+ function uncertainTransactionId(method, path, status, body) {
352
+ if (isIdempotentMethod(method) || status < 500) return void 0;
353
+ if (!TRANSACTION_RESULT_PATHS.has(normalizePath(path))) return void 0;
354
+ if (!body || typeof body !== "object") return void 0;
355
+ const b = body;
356
+ if (b.payment_status !== "processing" || b.retryable !== false) return void 0;
357
+ return typeof b.transaction_id === "string" && b.transaction_id ? b.transaction_id : void 0;
358
+ }
359
+ function uncertainOutcome(tx) {
360
+ const status = String(tx.status ?? "");
361
+ if (PAID_STATUSES.has(status)) return "paid";
362
+ if (REFUSED_STATUSES.has(status)) {
363
+ const refusal = tx.refusal;
364
+ if (refusal?.code === UNCERTAIN_CODE) return "pending";
365
+ return "refused";
366
+ }
367
+ return "pending";
368
+ }
369
+ function refusedFromTransaction(tx, requestId) {
370
+ const refusal = tx.refusal ?? {};
371
+ const str = (v) => typeof v === "string" && v ? v : void 0;
372
+ const description = str(refusal.description) ?? str(refusal.message);
373
+ return new VitrinRefusedError(description ?? "Pagamento n\xE3o autorizado.", {
374
+ statusCode: 422,
375
+ body: tx,
376
+ requestId,
377
+ code: str(refusal.code),
378
+ codeDescription: description,
379
+ customerMessage: str(refusal.customer_message),
380
+ retryable: refusal.retryable === true,
381
+ transactionId: str(tx.id)
382
+ });
239
383
  }
240
384
  function backoffMs(attempt) {
241
385
  const base = 250 * Math.pow(2, attempt);
package/dist/index.d.cts CHANGED
@@ -5,11 +5,15 @@
5
5
  * - Adicionar headers padrão (Authorization, User-Agent, Content-Type)
6
6
  * - Serializar/deserializar JSON
7
7
  * - Mapear erros HTTP pra `VitrinError`*
8
- * - Retry automático em 429 e 5xx (até 3 tentativas, backoff exponencial)
9
- * - Retry em timeout/erro de rede SÓ quando é seguro: método idempotente
10
- * (GET/HEAD/PUT/DELETE) ou POST/PATCH com Idempotency-Key. Sem isso o
11
- * retry de um POST cria uma segunda cobrança — o timeout não diz que o
12
- * servidor deixou de processar, só que a resposta se perdeu.
8
+ * - Retry automático (até 3 tentativas, backoff exponencial) SÓ quando é
9
+ * seguro — ver `shouldRetryResponse` e `shouldRetryNetworkError`:
10
+ * - GET/HEAD/PUT/DELETE: 429, 5xx, timeout e erro de rede;
11
+ * - POST/PATCH: 429, 5xx com `retryable: true` no corpo, ou conexão
12
+ * que nem abriu. Nunca em timeout de leitura nem em 5xx sem
13
+ * `retryable: true` (o 502 incerto de cartão diz `retryable: false`:
14
+ * a cobrança pode ter saído, e repetir é débito duplo);
15
+ * - exceção: `/charges/` e `/charges/charge-saved/` com
16
+ * Idempotency-Key, que o servidor deduplica pela chave.
13
17
  * - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
14
18
  * retenta uma chamada que já chegou no servidor)
15
19
  */
@@ -22,6 +26,13 @@ interface VitrinClientOptions {
22
26
  timeout?: number;
23
27
  /** Max retries em 429/5xx. Default: 3. */
24
28
  maxRetries?: number;
29
+ /**
30
+ * Quanto tempo (ms) o SDK consulta o desfecho de uma cobrança de cartão com
31
+ * resultado incerto (502 com `payment_status: "processing"`) antes de
32
+ * desistir. Default: 60000. `0` desliga (lança o erro na hora). O POST
33
+ * nunca é reenviado. Ver `resolveUncertain`.
34
+ */
35
+ uncertainWaitMs?: number;
25
36
  }
26
37
  interface RequestOptions {
27
38
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -35,9 +46,33 @@ declare class VitrinClient {
35
46
  private readonly apiKey;
36
47
  private readonly timeout;
37
48
  private readonly maxRetries;
49
+ private readonly uncertainWaitMs;
38
50
  constructor(opts: VitrinClientOptions);
39
51
  /** Helper público pra resources. */
40
52
  request<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
53
+ /**
54
+ * Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
55
+ * backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
56
+ * desfecho. NUNCA reenvia o POST.
57
+ *
58
+ * O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
59
+ * GET pode levar até o próprio timeout, e sem descontar isso do prazo o
60
+ * pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
61
+ * O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
62
+ * falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
63
+ * tenta mais uma consulta.
64
+ *
65
+ * - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
66
+ * que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
67
+ * `/checkout/pay/` devolve (os três respondem com a transação);
68
+ * - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
69
+ * - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
70
+ * original (`VitrinServerError` com `payment_status: "processing"` e
71
+ * `transaction_id` no `body`). Erro de consulta não prova nada.
72
+ */
73
+ private resolveUncertain;
74
+ /** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
75
+ private getOnce;
41
76
  private buildUrl;
42
77
  }
43
78
 
package/dist/index.d.ts CHANGED
@@ -5,11 +5,15 @@
5
5
  * - Adicionar headers padrão (Authorization, User-Agent, Content-Type)
6
6
  * - Serializar/deserializar JSON
7
7
  * - Mapear erros HTTP pra `VitrinError`*
8
- * - Retry automático em 429 e 5xx (até 3 tentativas, backoff exponencial)
9
- * - Retry em timeout/erro de rede SÓ quando é seguro: método idempotente
10
- * (GET/HEAD/PUT/DELETE) ou POST/PATCH com Idempotency-Key. Sem isso o
11
- * retry de um POST cria uma segunda cobrança — o timeout não diz que o
12
- * servidor deixou de processar, só que a resposta se perdeu.
8
+ * - Retry automático (até 3 tentativas, backoff exponencial) SÓ quando é
9
+ * seguro — ver `shouldRetryResponse` e `shouldRetryNetworkError`:
10
+ * - GET/HEAD/PUT/DELETE: 429, 5xx, timeout e erro de rede;
11
+ * - POST/PATCH: 429, 5xx com `retryable: true` no corpo, ou conexão
12
+ * que nem abriu. Nunca em timeout de leitura nem em 5xx sem
13
+ * `retryable: true` (o 502 incerto de cartão diz `retryable: false`:
14
+ * a cobrança pode ter saído, e repetir é débito duplo);
15
+ * - exceção: `/charges/` e `/charges/charge-saved/` com
16
+ * Idempotency-Key, que o servidor deduplica pela chave.
13
17
  * - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
14
18
  * retenta uma chamada que já chegou no servidor)
15
19
  */
@@ -22,6 +26,13 @@ interface VitrinClientOptions {
22
26
  timeout?: number;
23
27
  /** Max retries em 429/5xx. Default: 3. */
24
28
  maxRetries?: number;
29
+ /**
30
+ * Quanto tempo (ms) o SDK consulta o desfecho de uma cobrança de cartão com
31
+ * resultado incerto (502 com `payment_status: "processing"`) antes de
32
+ * desistir. Default: 60000. `0` desliga (lança o erro na hora). O POST
33
+ * nunca é reenviado. Ver `resolveUncertain`.
34
+ */
35
+ uncertainWaitMs?: number;
25
36
  }
26
37
  interface RequestOptions {
27
38
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -35,9 +46,33 @@ declare class VitrinClient {
35
46
  private readonly apiKey;
36
47
  private readonly timeout;
37
48
  private readonly maxRetries;
49
+ private readonly uncertainWaitMs;
38
50
  constructor(opts: VitrinClientOptions);
39
51
  /** Helper público pra resources. */
40
52
  request<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
53
+ /**
54
+ * Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
55
+ * backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
56
+ * desfecho. NUNCA reenvia o POST.
57
+ *
58
+ * O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
59
+ * GET pode levar até o próprio timeout, e sem descontar isso do prazo o
60
+ * pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
61
+ * O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
62
+ * falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
63
+ * tenta mais uma consulta.
64
+ *
65
+ * - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
66
+ * que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
67
+ * `/checkout/pay/` devolve (os três respondem com a transação);
68
+ * - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
69
+ * - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
70
+ * original (`VitrinServerError` com `payment_status: "processing"` e
71
+ * `transaction_id` no `body`). Erro de consulta não prova nada.
72
+ */
73
+ private resolveUncertain;
74
+ /** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
75
+ private getOnce;
41
76
  private buildUrl;
42
77
  }
43
78
 
package/dist/index.js CHANGED
@@ -54,12 +54,13 @@ var VitrinNetworkError = class extends VitrinError {
54
54
 
55
55
  // src/client.ts
56
56
  var DEFAULT_BASE_URL = "https://api.vitrin.digital/api/v1";
57
- var SDK_VERSION = "0.1.0";
57
+ var SDK_VERSION = "0.5.0";
58
58
  var VitrinClient = class {
59
59
  baseUrl;
60
60
  apiKey;
61
61
  timeout;
62
62
  maxRetries;
63
+ uncertainWaitMs;
63
64
  constructor(opts) {
64
65
  if (!opts.apiKey) {
65
66
  throw new Error("apiKey \xE9 obrigat\xF3rio");
@@ -68,6 +69,7 @@ var VitrinClient = class {
68
69
  this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
69
70
  this.timeout = opts.timeout ?? 3e4;
70
71
  this.maxRetries = opts.maxRetries ?? 3;
72
+ this.uncertainWaitMs = Math.max(0, opts.uncertainWaitMs ?? 6e4);
71
73
  }
72
74
  /** Helper público pra resources. */
73
75
  async request(path, options = {}) {
@@ -98,7 +100,7 @@ var VitrinClient = class {
98
100
  lastError = new VitrinNetworkError(
99
101
  netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
100
102
  );
101
- if (attempt < this.maxRetries && canRetryAfterNetworkError(method, idempotencyKey)) {
103
+ if (attempt < this.maxRetries && shouldRetryNetworkError(method, path, idempotencyKey, err2)) {
102
104
  await sleep(backoffMs(attempt));
103
105
  continue;
104
106
  }
@@ -118,8 +120,11 @@ var VitrinClient = class {
118
120
  } catch {
119
121
  }
120
122
  const err = mapErrorResponse(res.status, parsed, requestId);
121
- const retriable = res.status === 429 || res.status >= 500;
122
- if (retriable && attempt < this.maxRetries) {
123
+ const uncertainTxId = uncertainTransactionId(method, path, res.status, parsed);
124
+ if (uncertainTxId && this.uncertainWaitMs > 0) {
125
+ return this.resolveUncertain(uncertainTxId, err);
126
+ }
127
+ if (attempt < this.maxRetries && shouldRetryResponse(method, path, idempotencyKey, res.status, parsed)) {
123
128
  const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
124
129
  await sleep(retryAfter ?? backoffMs(attempt));
125
130
  lastError = err;
@@ -129,6 +134,71 @@ var VitrinClient = class {
129
134
  }
130
135
  throw lastError ?? new VitrinError("Esgotou as tentativas sem erro identificado");
131
136
  }
137
+ /**
138
+ * Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
139
+ * backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
140
+ * desfecho. NUNCA reenvia o POST.
141
+ *
142
+ * O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
143
+ * GET pode levar até o próprio timeout, e sem descontar isso do prazo o
144
+ * pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
145
+ * O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
146
+ * falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
147
+ * tenta mais uma consulta.
148
+ *
149
+ * - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
150
+ * que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
151
+ * `/checkout/pay/` devolve (os três respondem com a transação);
152
+ * - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
153
+ * - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
154
+ * original (`VitrinServerError` com `payment_status: "processing"` e
155
+ * `transaction_id` no `body`). Erro de consulta não prova nada.
156
+ */
157
+ async resolveUncertain(transactionId, original) {
158
+ const deadline = Date.now() + this.uncertainWaitMs;
159
+ for (const step of UNCERTAIN_BACKOFF_MS) {
160
+ const beforeSleep = deadline - Date.now();
161
+ if (beforeSleep <= 0) break;
162
+ await sleep(Math.min(step, beforeSleep));
163
+ const remaining = deadline - Date.now();
164
+ if (remaining < MIN_GET_BUDGET_MS) break;
165
+ let tx;
166
+ try {
167
+ tx = await this.getOnce(
168
+ `/transactions/${encodeURIComponent(transactionId)}/`,
169
+ Math.min(this.timeout, remaining)
170
+ );
171
+ } catch {
172
+ continue;
173
+ }
174
+ const outcome = uncertainOutcome(tx);
175
+ if (outcome === "paid") return tx;
176
+ if (outcome === "refused") throw refusedFromTransaction(tx, original.requestId);
177
+ }
178
+ throw original;
179
+ }
180
+ /** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
181
+ async getOnce(path, timeoutMs = this.timeout) {
182
+ const controller = new AbortController();
183
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
184
+ try {
185
+ const res = await fetch(this.buildUrl(path), {
186
+ method: "GET",
187
+ headers: {
188
+ Authorization: `Bearer ${this.apiKey}`,
189
+ Accept: "application/json",
190
+ "User-Agent": `vitrindigital-node/${SDK_VERSION} node/${process.version}`
191
+ },
192
+ signal: controller.signal
193
+ });
194
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
195
+ const body = await res.json();
196
+ if (!body || typeof body !== "object") throw new Error("corpo inv\xE1lido");
197
+ return body;
198
+ } finally {
199
+ clearTimeout(timer);
200
+ }
201
+ }
132
202
  buildUrl(path, query) {
133
203
  const url = new URL(this.baseUrl + (path.startsWith("/") ? path : `/${path}`));
134
204
  if (query) {
@@ -198,9 +268,83 @@ function parseRetryAfter(header) {
198
268
  return null;
199
269
  }
200
270
  var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
201
- function canRetryAfterNetworkError(method, idempotencyKey) {
202
- if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;
203
- return Boolean(idempotencyKey);
271
+ var DEDUPLICATED_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/"]);
272
+ var NEVER_CONNECTED_CODES = /* @__PURE__ */ new Set([
273
+ "ECONNREFUSED",
274
+ "ENOTFOUND",
275
+ "EAI_AGAIN",
276
+ "EHOSTUNREACH",
277
+ "ENETUNREACH",
278
+ "UND_ERR_CONNECT_TIMEOUT"
279
+ ]);
280
+ function normalizePath(path) {
281
+ const p = path.split("?")[0];
282
+ const withSlash = p.startsWith("/") ? p : `/${p}`;
283
+ return withSlash.endsWith("/") ? withSlash : `${withSlash}/`;
284
+ }
285
+ function isIdempotentMethod(method) {
286
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
287
+ }
288
+ function serverDeduplicates(path, idempotencyKey) {
289
+ return Boolean(idempotencyKey) && DEDUPLICATED_PATHS.has(normalizePath(path));
290
+ }
291
+ function neverConnected(err) {
292
+ const cause = err?.cause;
293
+ if (!cause) return false;
294
+ if (cause.code && NEVER_CONNECTED_CODES.has(cause.code)) return true;
295
+ return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((e) => Boolean(e?.code && NEVER_CONNECTED_CODES.has(e.code)));
296
+ }
297
+ function shouldRetryNetworkError(method, path, idempotencyKey, err) {
298
+ if (isIdempotentMethod(method)) return true;
299
+ if (neverConnected(err)) return true;
300
+ return serverDeduplicates(path, idempotencyKey);
301
+ }
302
+ function shouldRetryResponse(method, path, idempotencyKey, status, body) {
303
+ if (status !== 429 && status < 500) return false;
304
+ if (isIdempotentMethod(method) || status === 429) return true;
305
+ const retryable = body && typeof body === "object" ? body.retryable : void 0;
306
+ if (retryable === true) return true;
307
+ if (retryable === false) return false;
308
+ return serverDeduplicates(path, idempotencyKey);
309
+ }
310
+ var UNCERTAIN_BACKOFF_MS = [2e3, 4e3, 8e3, 15e3, 3e4];
311
+ var MIN_GET_BUDGET_MS = 1e3;
312
+ var TRANSACTION_RESULT_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/", "/checkout/pay/"]);
313
+ var PAID_STATUSES = /* @__PURE__ */ new Set(["received", "confirmed"]);
314
+ var REFUSED_STATUSES = /* @__PURE__ */ new Set(["failed", "canceled", "expired"]);
315
+ var UNCERTAIN_CODE = "VITRIN_PROVIDER_UNCERTAIN";
316
+ function uncertainTransactionId(method, path, status, body) {
317
+ if (isIdempotentMethod(method) || status < 500) return void 0;
318
+ if (!TRANSACTION_RESULT_PATHS.has(normalizePath(path))) return void 0;
319
+ if (!body || typeof body !== "object") return void 0;
320
+ const b = body;
321
+ if (b.payment_status !== "processing" || b.retryable !== false) return void 0;
322
+ return typeof b.transaction_id === "string" && b.transaction_id ? b.transaction_id : void 0;
323
+ }
324
+ function uncertainOutcome(tx) {
325
+ const status = String(tx.status ?? "");
326
+ if (PAID_STATUSES.has(status)) return "paid";
327
+ if (REFUSED_STATUSES.has(status)) {
328
+ const refusal = tx.refusal;
329
+ if (refusal?.code === UNCERTAIN_CODE) return "pending";
330
+ return "refused";
331
+ }
332
+ return "pending";
333
+ }
334
+ function refusedFromTransaction(tx, requestId) {
335
+ const refusal = tx.refusal ?? {};
336
+ const str = (v) => typeof v === "string" && v ? v : void 0;
337
+ const description = str(refusal.description) ?? str(refusal.message);
338
+ return new VitrinRefusedError(description ?? "Pagamento n\xE3o autorizado.", {
339
+ statusCode: 422,
340
+ body: tx,
341
+ requestId,
342
+ code: str(refusal.code),
343
+ codeDescription: description,
344
+ customerMessage: str(refusal.customer_message),
345
+ retryable: refusal.retryable === true,
346
+ transactionId: str(tx.id)
347
+ });
204
348
  }
205
349
  function backoffMs(attempt) {
206
350
  const base = 250 * Math.pow(2, attempt);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitrindigital/node",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "SDK oficial Node.js para a API da Vitrin Digital",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -21,7 +21,8 @@
21
21
  "build": "tsup src/index.ts --format esm,cjs --dts --clean",
22
22
  "test": "vitest run",
23
23
  "test:watch": "vitest",
24
- "lint": "tsc --noEmit"
24
+ "lint": "tsc --noEmit",
25
+ "prepublishOnly": "npm run lint && npm test && npm run build"
25
26
  },
26
27
  "keywords": ["vitrin", "vitrin-digital", "pagamentos", "pix", "boleto", "checkout"],
27
28
  "author": "Vitrin Digital",