@neetru/sdk 3.6.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +66 -1
  3. package/dist/ai.cjs +298 -391
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +298 -391
  7. package/dist/auth.cjs +3717 -5005
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +3714 -5002
  11. package/dist/build-guard.cjs +101 -119
  12. package/dist/build-guard.mjs +91 -109
  13. package/dist/catalog.cjs +220 -225
  14. package/dist/catalog.d.cts +1 -1
  15. package/dist/catalog.d.ts +1 -1
  16. package/dist/catalog.mjs +220 -225
  17. package/dist/checkout.cjs +307 -323
  18. package/dist/checkout.d.cts +1 -1
  19. package/dist/checkout.d.ts +1 -1
  20. package/dist/checkout.mjs +306 -322
  21. package/dist/db-react.cjs +59 -87
  22. package/dist/db-react.d.cts +1 -1
  23. package/dist/db-react.d.ts +1 -1
  24. package/dist/db-react.mjs +56 -84
  25. package/dist/db.cjs +2128 -3014
  26. package/dist/db.d.cts +1 -1
  27. package/dist/db.d.ts +1 -1
  28. package/dist/db.mjs +2141 -3027
  29. package/dist/entitlements.cjs +19 -20
  30. package/dist/entitlements.d.cts +1 -1
  31. package/dist/entitlements.d.ts +1 -1
  32. package/dist/entitlements.mjs +19 -20
  33. package/dist/errors.cjs +16 -12
  34. package/dist/errors.d.cts +59 -3
  35. package/dist/errors.d.ts +59 -3
  36. package/dist/errors.mjs +15 -12
  37. package/dist/firestore-compat.cjs +241 -297
  38. package/dist/firestore-compat.d.cts +1 -1
  39. package/dist/firestore-compat.d.ts +1 -1
  40. package/dist/firestore-compat.mjs +215 -271
  41. package/dist/index.cjs +3942 -5134
  42. package/dist/index.d.cts +181 -5
  43. package/dist/index.d.ts +181 -5
  44. package/dist/index.mjs +4040 -5239
  45. package/dist/mobile.cjs +459 -344
  46. package/dist/mobile.d.cts +59 -4
  47. package/dist/mobile.d.ts +59 -4
  48. package/dist/mobile.mjs +459 -344
  49. package/dist/mocks.cjs +319 -447
  50. package/dist/mocks.d.cts +1 -1
  51. package/dist/mocks.d.ts +1 -1
  52. package/dist/mocks.mjs +313 -441
  53. package/dist/notifications.cjs +296 -317
  54. package/dist/notifications.d.cts +1 -1
  55. package/dist/notifications.d.ts +1 -1
  56. package/dist/notifications.mjs +295 -316
  57. package/dist/react.cjs +557 -707
  58. package/dist/react.d.cts +1 -1
  59. package/dist/react.d.ts +1 -1
  60. package/dist/react.mjs +547 -697
  61. package/dist/support.cjs +402 -328
  62. package/dist/support.d.cts +29 -3
  63. package/dist/support.d.ts +29 -3
  64. package/dist/support.mjs +401 -328
  65. package/dist/telemetry.cjs +267 -304
  66. package/dist/telemetry.d.cts +1 -1
  67. package/dist/telemetry.d.ts +1 -1
  68. package/dist/telemetry.mjs +267 -304
  69. package/dist/{types-Du_iioJ7.d.cts → types-D-9bjlM0.d.cts} +74 -1
  70. package/dist/{types-BPATkXYu.d.ts → types-bVztFQTI.d.ts} +74 -1
  71. package/dist/usage.cjs +233 -230
  72. package/dist/usage.d.cts +1 -1
  73. package/dist/usage.d.ts +1 -1
  74. package/dist/usage.mjs +233 -230
  75. package/dist/webhooks.cjs +328 -362
  76. package/dist/webhooks.d.cts +1 -1
  77. package/dist/webhooks.d.ts +1 -1
  78. package/dist/webhooks.mjs +325 -359
  79. package/package.json +5 -3
  80. package/dist/ai.cjs.map +0 -1
  81. package/dist/ai.mjs.map +0 -1
  82. package/dist/auth.cjs.map +0 -1
  83. package/dist/auth.mjs.map +0 -1
  84. package/dist/build-guard.cjs.map +0 -1
  85. package/dist/build-guard.mjs.map +0 -1
  86. package/dist/catalog.cjs.map +0 -1
  87. package/dist/catalog.mjs.map +0 -1
  88. package/dist/checkout.cjs.map +0 -1
  89. package/dist/checkout.mjs.map +0 -1
  90. package/dist/db-react.cjs.map +0 -1
  91. package/dist/db-react.mjs.map +0 -1
  92. package/dist/db.cjs.map +0 -1
  93. package/dist/db.mjs.map +0 -1
  94. package/dist/entitlements.cjs.map +0 -1
  95. package/dist/entitlements.mjs.map +0 -1
  96. package/dist/errors.cjs.map +0 -1
  97. package/dist/errors.mjs.map +0 -1
  98. package/dist/firestore-compat.cjs.map +0 -1
  99. package/dist/firestore-compat.mjs.map +0 -1
  100. package/dist/index.cjs.map +0 -1
  101. package/dist/index.mjs.map +0 -1
  102. package/dist/mobile.cjs.map +0 -1
  103. package/dist/mobile.mjs.map +0 -1
  104. package/dist/mocks.cjs.map +0 -1
  105. package/dist/mocks.mjs.map +0 -1
  106. package/dist/notifications.cjs.map +0 -1
  107. package/dist/notifications.mjs.map +0 -1
  108. package/dist/react.cjs.map +0 -1
  109. package/dist/react.mjs.map +0 -1
  110. package/dist/support.cjs.map +0 -1
  111. package/dist/support.mjs.map +0 -1
  112. package/dist/telemetry.cjs.map +0 -1
  113. package/dist/telemetry.mjs.map +0 -1
  114. package/dist/usage.cjs.map +0 -1
  115. package/dist/usage.mjs.map +0 -1
  116. package/dist/webhooks.cjs.map +0 -1
  117. package/dist/webhooks.mjs.map +0 -1
package/dist/checkout.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/errors.ts
4
- var NeetruError = class _NeetruError extends Error {
4
+ var i = class t extends Error {
5
5
  code;
6
6
  status;
7
7
  requestId;
@@ -14,425 +14,409 @@ var NeetruError = class _NeetruError extends Error {
14
14
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
15
15
  */
16
16
  reason;
17
- constructor(code, message, status, requestId, reason) {
18
- super(message);
19
- this.name = "NeetruError";
20
- this.code = code;
21
- this.status = status;
22
- this.requestId = requestId;
23
- this.reason = reason;
24
- Object.setPrototypeOf(this, _NeetruError.prototype);
17
+ /**
18
+ * 3.8.0: `x-correlation-id` da requisição que falhou. O SDK gera um UUID por
19
+ * chamada (ou usa o que o chamador passou) e manda no header; o Core grava o
20
+ * mesmo id nos logs/auditoria — cite-o ao abrir um ticket de suporte.
21
+ * `undefined` em erros que acontecem antes de qualquer requisição.
22
+ */
23
+ correlationId;
24
+ constructor(e, n, r, o, a, c) {
25
+ super(n), this.name = "NeetruError", this.code = e, this.status = r, this.requestId = o, this.reason = a, this.correlationId = c, Object.setPrototypeOf(this, t.prototype);
25
26
  }
26
27
  };
27
28
 
28
29
  // src/idempotency.ts
29
- function generateIdempotencyKey() {
30
- const cryptoObj = typeof globalThis !== "undefined" && "crypto" in globalThis ? globalThis.crypto : void 0;
31
- if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
32
- return cryptoObj.randomUUID();
33
- }
34
- throw new NeetruError(
30
+ function E() {
31
+ let t = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
32
+ if (t && typeof t.randomUUID == "function")
33
+ return t.randomUUID();
34
+ throw new i(
35
35
  "runtime_unsupported",
36
36
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
37
37
  );
38
38
  }
39
39
 
40
+ // src/correlation.ts
41
+ var A = "x-correlation-id";
42
+ var L = /^[A-Za-z0-9._:\-]+$/;
43
+ function x(t) {
44
+ return typeof t == "string" && t.length > 0 && t.length <= 128 && L.test(t);
45
+ }
46
+ function H() {
47
+ let t = globalThis.crypto;
48
+ try {
49
+ if (t && typeof t.randomUUID == "function") return t.randomUUID();
50
+ } catch {
51
+ }
52
+ let e = new Uint8Array(16), n = false;
53
+ try {
54
+ t && typeof t.getRandomValues == "function" && (t.getRandomValues(e), n = !0);
55
+ } catch {
56
+ n = false;
57
+ }
58
+ if (!n)
59
+ for (let o = 0; o < e.length; o++) e[o] = Math.floor(Math.random() * 256);
60
+ e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
61
+ let r = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
62
+ return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
63
+ }
64
+ function N(t, e) {
65
+ let n, r = {};
66
+ for (let [a, c] of Object.entries(t)) {
67
+ if (a.toLowerCase() === A) {
68
+ x(c) && (n = c);
69
+ continue;
70
+ }
71
+ r[a] = c;
72
+ }
73
+ let o = n ?? (x(e) ? e : void 0) ?? H();
74
+ return r[A] = o, { headers: r, correlationId: o };
75
+ }
76
+
77
+ // src/server-only-key.ts
78
+ function D() {
79
+ try {
80
+ let t = globalThis.navigator;
81
+ if (t && t.product === "ReactNative") return "react-native";
82
+ } catch {
83
+ }
84
+ try {
85
+ let t = globalThis;
86
+ if (typeof t.window < "u" && typeof t.document < "u") return "browser";
87
+ } catch {
88
+ }
89
+ return null;
90
+ }
91
+
40
92
  // src/http.ts
41
- var COMPAT_MATRIX = {
93
+ var B = {
42
94
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
43
95
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
44
96
  3: "2026.05.1"
45
97
  };
46
- function stripRevision(v) {
47
- return v.split("+")[0] ?? v;
98
+ function b(t) {
99
+ return t.split("+")[0] ?? t;
48
100
  }
49
- function compareCalVer(a, b) {
50
- const partsA = stripRevision(a).split(".").map(Number);
51
- const partsB = stripRevision(b).split(".").map(Number);
52
- const len = Math.max(partsA.length, partsB.length);
53
- for (let i = 0; i < len; i++) {
54
- const pa = partsA[i] ?? 0;
55
- const pb = partsB[i] ?? 0;
56
- if (pa !== pb) return pa - pb;
101
+ function G(t, e) {
102
+ let n = b(t).split(".").map(Number), r = b(e).split(".").map(Number), o = Math.max(n.length, r.length);
103
+ for (let a = 0; a < o; a++) {
104
+ let c = n[a] ?? 0, u = r[a] ?? 0;
105
+ if (c !== u) return c - u;
57
106
  }
58
107
  return 0;
59
108
  }
60
- function readInjectedSdkVersion() {
109
+ function M() {
61
110
  try {
62
- return "3.6.0";
111
+ return "3.8.0";
63
112
  } catch {
64
- return void 0;
113
+ return;
65
114
  }
66
115
  }
67
- function getSdkMajor() {
68
- const ver = readInjectedSdkVersion();
69
- if (ver) return parseInt(ver.split(".")[0] ?? "3", 10);
70
- return 3;
116
+ function F() {
117
+ let t = M();
118
+ return t ? parseInt(t.split(".")[0] ?? "3", 10) : 3;
71
119
  }
72
- var _warnedCoreTooOld = /* @__PURE__ */ new Set();
73
- function checkCoreVersionCompat(coreVersion) {
74
- if (!coreVersion) return;
75
- const sdkMajor = getSdkMajor();
76
- const minCore = COMPAT_MATRIX[sdkMajor];
77
- if (!minCore) return;
78
- const stripped = stripRevision(coreVersion);
79
- if (compareCalVer(stripped, minCore) < 0) {
80
- const key = `${sdkMajor}:${stripped}`;
81
- if (!_warnedCoreTooOld.has(key)) {
82
- _warnedCoreTooOld.add(key);
83
- console.warn(
84
- `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${coreVersion}" \xE9 anterior ao m\xEDnimo recomendado "${minCore}" para SDK major ${sdkMajor}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
85
- );
86
- }
120
+ var U = /* @__PURE__ */ new Set();
121
+ function V(t) {
122
+ if (!t) return;
123
+ let e = F(), n = B[e];
124
+ if (!n) return;
125
+ let r = b(t);
126
+ if (G(r, n) < 0) {
127
+ let o = `${e}:${r}`;
128
+ U.has(o) || (U.add(o), console.warn(
129
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${t}" \xE9 anterior ao m\xEDnimo recomendado "${n}" para SDK major ${e}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
130
+ ));
87
131
  }
88
132
  }
89
- var DEFAULT_RETRIES_READ = 2;
90
- var DEFAULT_RETRIES_WRITE = 0;
91
- var READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
92
- var RETRYABLE_CODES = /* @__PURE__ */ new Set([
133
+ function z() {
134
+ let t = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
135
+ return D() ? "Esta opera\xE7\xE3o exige a credencial nrt_ do produto, que \xE9 S\xD3 DE SERVIDOR. No navegador/app, chame a API do seu produto (ex.: https://<produto>.neetru.com/api/v1) com o token do usu\xE1rio \u2014 o backend do produto faz esta chamada com o SDK e a chave. (" + t + ")" : t;
136
+ }
137
+ var X = 2, Y = 0, J = /* @__PURE__ */ new Set(["GET", "HEAD"]), W = /* @__PURE__ */ new Set([
93
138
  "rate_limited",
94
139
  "server_error",
95
140
  "network_error"
96
141
  ]);
97
- function backoffMs(attempt) {
98
- const base = 200 * Math.pow(4, attempt);
99
- const jitter = base * 0.2 * (Math.random() * 2 - 1);
100
- return Math.max(50, Math.round(base + jitter));
142
+ function O(t) {
143
+ let e = 200 * Math.pow(4, t), n = e * 0.2 * (Math.random() * 2 - 1);
144
+ return Math.max(50, Math.round(e + n));
101
145
  }
102
- var MAX_RETRY_AFTER_MS = 6e4;
103
- function parseRetryAfter(value) {
104
- if (!value) return null;
105
- const secs = Number(value);
106
- if (Number.isFinite(secs) && secs >= 0) return Math.min(Math.round(secs * 1e3), MAX_RETRY_AFTER_MS);
107
- const dateMs = Date.parse(value);
108
- if (Number.isFinite(dateMs)) {
109
- const delta = dateMs - Date.now();
110
- if (delta > 0) return Math.min(delta, MAX_RETRY_AFTER_MS);
146
+ var q = 6e4;
147
+ function Z(t) {
148
+ if (!t) return null;
149
+ let e = Number(t);
150
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), q);
151
+ let n = Date.parse(t);
152
+ if (Number.isFinite(n)) {
153
+ let r = n - Date.now();
154
+ if (r > 0) return Math.min(r, q);
111
155
  }
112
156
  return null;
113
157
  }
114
- function sleep(ms) {
115
- return new Promise((resolve) => setTimeout(resolve, ms));
158
+ function K(t) {
159
+ return new Promise((e) => setTimeout(e, t));
116
160
  }
117
- function statusToCode(status) {
118
- if (status === 401) return "unauthorized";
119
- if (status === 403) return "forbidden";
120
- if (status === 404) return "not_found";
121
- if (status === 409) return "conflict";
122
- if (status === 422 || status === 400) return "validation_failed";
123
- if (status === 429) return "rate_limited";
124
- if (status >= 500) return "server_error";
125
- return "unknown";
161
+ function Q(t) {
162
+ return t === 401 ? "unauthorized" : t === 403 ? "forbidden" : t === 404 ? "not_found" : t === 409 ? "conflict" : t === 410 ? "gone" : t === 422 || t === 400 ? "validation_failed" : t === 429 ? "rate_limited" : t >= 500 ? "server_error" : "unknown";
126
163
  }
127
- function buildUrl(baseUrl, path, query) {
128
- const base = baseUrl.replace(/\/+$/, "");
129
- const p = path.startsWith("/") ? path : `/${path}`;
130
- const url = new URL(`${base}${p}`);
131
- if (query) {
132
- for (const [k, v] of Object.entries(query)) {
133
- if (v === void 0) continue;
134
- url.searchParams.set(k, String(v));
164
+ function ee(t, e, n) {
165
+ let r = t.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, a = new URL(`${r}${o}`);
166
+ if (n)
167
+ for (let [c, u] of Object.entries(n))
168
+ u !== void 0 && a.searchParams.set(c, String(u));
169
+ return a.toString();
170
+ }
171
+ async function P(t) {
172
+ let e = await t.text();
173
+ if (e)
174
+ try {
175
+ return JSON.parse(e);
176
+ } catch {
177
+ return;
135
178
  }
136
- }
137
- return url.toString();
138
179
  }
139
- async function safeJson(res) {
140
- const text = await res.text();
141
- if (!text) return void 0;
142
- try {
143
- return JSON.parse(text);
144
- } catch {
145
- return void 0;
180
+ async function y(t, e) {
181
+ let n = e.method ?? "GET", r = ee(t.baseUrl, e.path, e.query), o = J.has(n) ? X : Y, a = e.retries ?? o, { headers: c, correlationId: u } = N(
182
+ { accept: "application/json", ...e.headers },
183
+ e.correlationId
184
+ ), C = M();
185
+ if (C && (c["x-neetru-sdk-version"] = C), e.requireAuth) {
186
+ if (!t.apiKey)
187
+ throw new i("missing_api_key", z());
188
+ c.authorization = `Bearer ${t.apiKey}`;
146
189
  }
147
- }
148
- async function httpRequest(config, opts) {
149
- const method = opts.method ?? "GET";
150
- const url = buildUrl(config.baseUrl, opts.path, opts.query);
151
- const defaultRetries = READ_METHODS.has(method) ? DEFAULT_RETRIES_READ : DEFAULT_RETRIES_WRITE;
152
- const maxRetries = opts.retries ?? defaultRetries;
153
- const headers = {
154
- accept: "application/json",
155
- ...opts.headers
156
- };
157
- const sdkVersion = readInjectedSdkVersion();
158
- if (sdkVersion) {
159
- headers["x-neetru-sdk-version"] = sdkVersion;
190
+ if (e.idempotencyKey) {
191
+ let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : E();
192
+ c["idempotency-key"] = f;
160
193
  }
161
- if (opts.requireAuth) {
162
- if (!config.apiKey) {
163
- throw new NeetruError(
164
- "missing_api_key",
165
- "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
194
+ let I = e.body !== void 0 && n !== "GET" && n !== "DELETE" ? JSON.stringify(e.body) : void 0;
195
+ I !== void 0 && (c["content-type"] = "application/json");
196
+ let g = null, p = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
197
+ for (let f = 0; f <= a; f++) {
198
+ if (p != null && Date.now() >= p)
199
+ throw g ?? new i(
200
+ "network_error",
201
+ "Deadline excedido antes de completar a request",
202
+ void 0,
203
+ void 0,
204
+ void 0,
205
+ u
166
206
  );
167
- }
168
- headers.authorization = `Bearer ${config.apiKey}`;
169
- }
170
- if (opts.idempotencyKey) {
171
- const key = typeof opts.idempotencyKey === "string" ? opts.idempotencyKey : generateIdempotencyKey();
172
- headers["idempotency-key"] = key;
173
- }
174
- const bodyString = opts.body !== void 0 && method !== "GET" && method !== "DELETE" ? JSON.stringify(opts.body) : void 0;
175
- if (bodyString !== void 0) {
176
- headers["content-type"] = "application/json";
177
- }
178
- let lastError = null;
179
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
180
- const init = { method, headers };
181
- if (bodyString !== void 0) init.body = bodyString;
182
- init.signal = AbortSignal.timeout(3e4);
183
- let res;
207
+ let _ = { method: n, headers: c };
208
+ I !== void 0 && (_.body = I);
209
+ let $ = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
210
+ _.signal = AbortSignal.timeout($);
211
+ let d;
184
212
  try {
185
- res = await config.fetch(url, init);
186
- } catch (err2) {
187
- const message2 = err2 instanceof DOMException && err2.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${err2 instanceof Error ? err2.message : "fetch failed"}`;
188
- lastError = new NeetruError("network_error", message2);
189
- if (attempt < maxRetries) {
190
- await sleep(backoffMs(attempt));
191
- continue;
213
+ d = await t.fetch(r, _);
214
+ } catch (s) {
215
+ let m = s instanceof DOMException && s.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${s instanceof Error ? s.message : "fetch failed"}`;
216
+ if (g = new i("network_error", m, void 0, void 0, void 0, u), f < a) {
217
+ let S = O(f);
218
+ if (p == null || Date.now() + S < p) {
219
+ await K(S);
220
+ continue;
221
+ }
192
222
  }
193
- throw lastError;
223
+ throw g;
194
224
  }
195
- const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-correlation-id") ?? void 0;
196
- if (res.ok) {
197
- const coreVersion = res.headers.get("x-neetru-version");
198
- if (coreVersion) checkCoreVersionCompat(coreVersion);
199
- const parsed = await safeJson(res);
200
- return parsed;
225
+ let j = d.headers.get("x-request-id") ?? d.headers.get("x-correlation-id") ?? void 0;
226
+ if (d.ok) {
227
+ let s = d.headers.get("x-neetru-version");
228
+ return s && V(s), await P(d);
201
229
  }
202
- const body = await safeJson(res);
203
- let code = statusToCode(res.status);
204
- let message = `HTTP ${res.status}`;
205
- let reason;
206
- if (body && typeof body === "object") {
207
- const errField = body.error;
208
- if (typeof errField === "string") {
209
- message = errField;
210
- } else if (errField && typeof errField === "object") {
211
- if (typeof errField.code === "string") code = errField.code;
212
- if (typeof errField.message === "string") message = errField.message;
213
- if (typeof errField.reason === "string") reason = errField.reason;
214
- } else {
215
- if (typeof body.code === "string") code = body.code;
216
- if (typeof body.message === "string") message = body.message;
217
- }
218
- if (typeof body.reason === "string") reason = body.reason;
230
+ let l = await P(d), k = Q(d.status), h = `HTTP ${d.status}`, w;
231
+ if (l && typeof l == "object") {
232
+ let s = l.error;
233
+ typeof s == "string" ? h = s : s && typeof s == "object" ? (typeof s.code == "string" && (k = s.code), typeof s.message == "string" && (h = s.message), typeof s.reason == "string" && (w = s.reason)) : (typeof l.code == "string" && (k = l.code), typeof l.message == "string" && (h = l.message)), typeof l.reason == "string" && (w = l.reason);
219
234
  }
220
- const err = new NeetruError(code, message, res.status, requestId, reason);
221
- lastError = err;
222
- const isRetryable = RETRYABLE_CODES.has(code);
223
- if (isRetryable && attempt < maxRetries) {
224
- const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
225
- const delay = retryAfter ?? backoffMs(attempt);
226
- await sleep(delay);
227
- continue;
235
+ if (d.status === 410) {
236
+ let s = d.headers.get("x-neetru-replacement");
237
+ h === `HTTP ${d.status}` && (h = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), s && !h.includes(s) && (h += ` Substituto: ${s}.`);
228
238
  }
229
- throw err;
239
+ let v = new i(k, h, d.status, j, w, u);
240
+ if (g = v, W.has(k) && f < a) {
241
+ let m = Z(d.headers.get("retry-after")) ?? O(f);
242
+ if (p == null || Date.now() + m < p) {
243
+ await K(m);
244
+ continue;
245
+ }
246
+ }
247
+ throw v;
230
248
  }
231
- throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
249
+ throw g ?? new i("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, u);
232
250
  }
233
251
 
234
252
  // src/checkout.ts
235
- function checkoutAuth(auth, method) {
236
- const token = auth?.accessToken || auth?.idToken;
237
- if (!token || typeof token !== "string") {
238
- throw new NeetruError(
253
+ function T(t, e) {
254
+ let n = t?.accessToken || t?.idToken;
255
+ if (!n || typeof n != "string")
256
+ throw new i(
239
257
  "validation_failed",
240
- `checkout.${method} requer o access_token OU o id_token OIDC do usu\xE1rio final (passe \`accessToken\` ou \`idToken\`). A chave de API do SDK (nrt_*) N\xC3O \xE9 aceita pelo endpoint de checkout \u2014 ele autentica a identidade do cliente que est\xE1 assinando (Bearer access_token/id_token OIDC ou cookie de sess\xE3o). No padr\xE3o BFF/cookie, passe o \`idToken\` que seu servidor guardou no cookie httpOnly.`
258
+ `checkout.${e} requer o access_token OU o id_token OIDC do usu\xE1rio final (passe \`accessToken\` ou \`idToken\`). A chave de API do SDK (nrt_*) N\xC3O \xE9 aceita pelo endpoint de checkout \u2014 ele autentica a identidade do cliente que est\xE1 assinando (Bearer access_token/id_token OIDC ou cookie de sess\xE3o). No padr\xE3o BFF/cookie, passe o \`idToken\` que seu servidor guardou no cookie httpOnly.`
241
259
  );
242
- }
243
- return { requireAuth: false, headers: { authorization: `Bearer ${token}` } };
260
+ return { requireAuth: false, headers: { authorization: `Bearer ${n}` } };
244
261
  }
245
- function parseStartResponse(raw) {
246
- if (!raw || typeof raw !== "object") {
247
- throw new NeetruError("invalid_response", "checkout.start response is not an object");
248
- }
249
- const r = raw;
250
- if (typeof r.intentId !== "string" || !r.intentId) {
251
- throw new NeetruError("invalid_response", "checkout.start response missing intentId");
252
- }
253
- if (typeof r.redirectUrl !== "string" || !r.redirectUrl) {
254
- throw new NeetruError("invalid_response", "checkout.start response missing redirectUrl");
255
- }
262
+ function te(t) {
263
+ if (!t || typeof t != "object")
264
+ throw new i("invalid_response", "checkout.start response is not an object");
265
+ let e = t;
266
+ if (typeof e.intentId != "string" || !e.intentId)
267
+ throw new i("invalid_response", "checkout.start response missing intentId");
268
+ if (typeof e.redirectUrl != "string" || !e.redirectUrl)
269
+ throw new i("invalid_response", "checkout.start response missing redirectUrl");
256
270
  return {
257
- intentId: r.intentId,
258
- redirectUrl: r.redirectUrl,
259
- status: r.status ?? "pending",
260
- expiresAt: typeof r.expiresAt === "string" ? r.expiresAt : (/* @__PURE__ */ new Date()).toISOString(),
261
- requiresKyc: r.requiresKyc === true
271
+ intentId: e.intentId,
272
+ redirectUrl: e.redirectUrl,
273
+ status: e.status ?? "pending",
274
+ expiresAt: typeof e.expiresAt == "string" ? e.expiresAt : (/* @__PURE__ */ new Date()).toISOString(),
275
+ requiresKyc: e.requiresKyc === true
262
276
  };
263
277
  }
264
- function parseGetResponse(raw) {
265
- if (!raw || typeof raw !== "object") {
266
- throw new NeetruError("invalid_response", "checkout.get response is not an object");
267
- }
268
- const r = raw;
269
- const intent = r.intent;
270
- if (!intent || typeof intent !== "object") {
271
- throw new NeetruError("invalid_response", "checkout.get response missing intent");
272
- }
273
- if (typeof intent.intentId !== "string") {
274
- throw new NeetruError("invalid_response", "checkout.get response missing intentId");
275
- }
278
+ function ne(t) {
279
+ if (!t || typeof t != "object")
280
+ throw new i("invalid_response", "checkout.get response is not an object");
281
+ let e = t, n = e.intent;
282
+ if (!n || typeof n != "object")
283
+ throw new i("invalid_response", "checkout.get response missing intent");
284
+ if (typeof n.intentId != "string")
285
+ throw new i("invalid_response", "checkout.get response missing intentId");
276
286
  return {
277
- intentId: intent.intentId,
278
- uid: intent.uid ?? "",
279
- targetTenantId: intent.targetTenantId ?? "",
280
- targetTenantType: intent.targetTenantType ?? "pf",
281
- productId: intent.productId ?? "",
282
- planId: intent.planId ?? "",
283
- callbackUrl: intent.callbackUrl ?? "",
284
- status: intent.status ?? "pending",
285
- stripeSessionId: intent.stripeSessionId ?? null,
286
- expiresAt: intent.expiresAt ?? (/* @__PURE__ */ new Date()).toISOString(),
287
- isStale: r.isStale === true
287
+ intentId: n.intentId,
288
+ uid: n.uid ?? "",
289
+ targetTenantId: n.targetTenantId ?? "",
290
+ targetTenantType: n.targetTenantType ?? "pf",
291
+ productId: n.productId ?? "",
292
+ planId: n.planId ?? "",
293
+ callbackUrl: n.callbackUrl ?? "",
294
+ status: n.status ?? "pending",
295
+ stripeSessionId: n.stripeSessionId ?? null,
296
+ expiresAt: n.expiresAt ?? (/* @__PURE__ */ new Date()).toISOString(),
297
+ isStale: e.isStale === true
288
298
  };
289
299
  }
290
- function inBrowser() {
300
+ function re() {
291
301
  try {
292
- return typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined" && typeof globalThis.location !== "undefined" && typeof globalThis.location.assign === "function";
302
+ return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
293
303
  } catch {
294
304
  return false;
295
305
  }
296
306
  }
297
- function performRedirect(url) {
307
+ function oe(t) {
298
308
  try {
299
- globalThis.location.assign(url);
309
+ globalThis.location.assign(t);
300
310
  } catch {
301
311
  }
302
312
  }
303
- function createHttpCheckoutNamespace(config) {
313
+ function ie(t) {
304
314
  return {
305
- async start(input) {
306
- if (!input?.productId) {
307
- throw new NeetruError("validation_failed", "checkout.start: productId is required");
308
- }
309
- if (!input?.planId) {
310
- throw new NeetruError("validation_failed", "checkout.start: planId is required");
311
- }
312
- if (!input?.callbackUrl) {
313
- throw new NeetruError("validation_failed", "checkout.start: callbackUrl is required");
314
- }
315
- const body = {
316
- productId: input.productId,
317
- planId: input.planId,
318
- callbackUrl: input.callbackUrl
315
+ async start(e) {
316
+ if (!e?.productId)
317
+ throw new i("validation_failed", "checkout.start: productId is required");
318
+ if (!e?.planId)
319
+ throw new i("validation_failed", "checkout.start: planId is required");
320
+ if (!e?.callbackUrl)
321
+ throw new i("validation_failed", "checkout.start: callbackUrl is required");
322
+ let n = {
323
+ productId: e.productId,
324
+ planId: e.planId,
325
+ callbackUrl: e.callbackUrl
319
326
  };
320
- if (input.tenantType) body.targetTenantType = input.tenantType;
321
- if (input.tenantId) body.targetTenantId = input.tenantId;
322
- const { requireAuth, headers } = checkoutAuth(
323
- { accessToken: input.accessToken, idToken: input.idToken },
327
+ e.tenantType && (n.targetTenantType = e.tenantType), e.tenantId && (n.targetTenantId = e.tenantId);
328
+ let { requireAuth: r, headers: o } = T(
329
+ { accessToken: e.accessToken, idToken: e.idToken },
324
330
  "start"
325
- );
326
- const raw = await httpRequest(config, {
331
+ ), a = await y(t, {
327
332
  method: "POST",
328
333
  path: "/api/v1/checkout/intents",
329
- body,
330
- requireAuth,
331
- headers,
334
+ body: n,
335
+ requireAuth: r,
336
+ headers: o,
332
337
  idempotencyKey: true
333
- });
334
- const result = parseStartResponse(raw);
335
- const shouldRedirect = input.autoRedirect !== false;
336
- if (shouldRedirect && inBrowser()) {
337
- performRedirect(result.redirectUrl);
338
- }
339
- return result;
338
+ }), c = te(a);
339
+ return e.autoRedirect !== false && re() && oe(c.redirectUrl), c;
340
340
  },
341
- async get(intentId, opts) {
342
- if (!intentId || typeof intentId !== "string") {
343
- throw new NeetruError("validation_failed", "checkout.get: intentId is required");
344
- }
345
- const { requireAuth, headers } = checkoutAuth(
346
- { accessToken: opts?.accessToken, idToken: opts?.idToken },
341
+ async get(e, n) {
342
+ if (!e || typeof e != "string")
343
+ throw new i("validation_failed", "checkout.get: intentId is required");
344
+ let { requireAuth: r, headers: o } = T(
345
+ { accessToken: n?.accessToken, idToken: n?.idToken },
347
346
  "get"
348
- );
349
- const raw = await httpRequest(config, {
347
+ ), a = await y(t, {
350
348
  method: "GET",
351
- path: `/api/v1/checkout/intents/${encodeURIComponent(intentId)}`,
352
- requireAuth,
353
- headers
349
+ path: `/api/v1/checkout/intents/${encodeURIComponent(e)}`,
350
+ requireAuth: r,
351
+ headers: o
354
352
  });
355
- return parseGetResponse(raw);
353
+ return ne(a);
356
354
  },
357
- async cancel(intentId, opts) {
358
- if (!intentId || typeof intentId !== "string") {
359
- throw new NeetruError("validation_failed", "checkout.cancel: intentId is required");
360
- }
361
- const { requireAuth, headers } = checkoutAuth(
362
- { accessToken: opts?.accessToken, idToken: opts?.idToken },
355
+ async cancel(e, n) {
356
+ if (!e || typeof e != "string")
357
+ throw new i("validation_failed", "checkout.cancel: intentId is required");
358
+ let { requireAuth: r, headers: o } = T(
359
+ { accessToken: n?.accessToken, idToken: n?.idToken },
363
360
  "cancel"
364
361
  );
365
- const raw = await httpRequest(config, {
366
- method: "DELETE",
367
- path: `/api/v1/checkout/intents/${encodeURIComponent(intentId)}`,
368
- requireAuth,
369
- headers
370
- });
371
362
  return {
372
363
  ok: true,
373
- alreadyCancelled: raw?.alreadyCancelled === true
364
+ alreadyCancelled: (await y(t, {
365
+ method: "DELETE",
366
+ path: `/api/v1/checkout/intents/${encodeURIComponent(e)}`,
367
+ requireAuth: r,
368
+ headers: o
369
+ }))?.alreadyCancelled === true
374
370
  };
375
371
  }
376
372
  };
377
373
  }
378
- var MockCheckout = class {
374
+ var R = class {
379
375
  intents = /* @__PURE__ */ new Map();
380
- async start(input) {
381
- if (!input?.productId) {
382
- throw new NeetruError("validation_failed", "checkout.start: productId is required");
383
- }
384
- if (!input?.planId) {
385
- throw new NeetruError("validation_failed", "checkout.start: planId is required");
386
- }
387
- if (!input?.callbackUrl) {
388
- throw new NeetruError("validation_failed", "checkout.start: callbackUrl is required");
389
- }
390
- const intentId = `chk_mock_${Math.random().toString(36).slice(2, 10)}`;
391
- const expiresAt = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
392
- const redirectUrl = `https://localhost:9003/portal/checkout/${intentId}`;
393
- this.intents.set(intentId, {
394
- intentId,
376
+ async start(e) {
377
+ if (!e?.productId)
378
+ throw new i("validation_failed", "checkout.start: productId is required");
379
+ if (!e?.planId)
380
+ throw new i("validation_failed", "checkout.start: planId is required");
381
+ if (!e?.callbackUrl)
382
+ throw new i("validation_failed", "checkout.start: callbackUrl is required");
383
+ let n = `chk_mock_${Math.random().toString(36).slice(2, 10)}`, r = new Date(Date.now() + 900 * 1e3).toISOString(), o = `https://localhost:9003/portal/checkout/${n}`;
384
+ return this.intents.set(n, {
385
+ intentId: n,
395
386
  uid: "dev-fixture-uid",
396
- targetTenantId: input.tenantId ?? "dev-fixture-uid",
397
- targetTenantType: input.tenantType ?? "pf",
398
- productId: input.productId,
399
- planId: input.planId,
400
- callbackUrl: input.callbackUrl,
387
+ targetTenantId: e.tenantId ?? "dev-fixture-uid",
388
+ targetTenantType: e.tenantType ?? "pf",
389
+ productId: e.productId,
390
+ planId: e.planId,
391
+ callbackUrl: e.callbackUrl,
401
392
  status: "pending",
402
393
  stripeSessionId: null,
403
- expiresAt
404
- });
405
- return {
406
- intentId,
407
- redirectUrl,
394
+ expiresAt: r
395
+ }), {
396
+ intentId: n,
397
+ redirectUrl: o,
408
398
  status: "pending",
409
- expiresAt,
399
+ expiresAt: r,
410
400
  requiresKyc: false
411
401
  };
412
402
  }
413
- async get(intentId, _opts) {
414
- const found = this.intents.get(intentId);
415
- if (!found) {
416
- throw new NeetruError("not_found", `Mock intent ${intentId} not found`);
417
- }
418
- return { ...found };
403
+ async get(e, n) {
404
+ let r = this.intents.get(e);
405
+ if (!r)
406
+ throw new i("not_found", `Mock intent ${e} not found`);
407
+ return { ...r };
419
408
  }
420
- async cancel(intentId, _opts) {
421
- const found = this.intents.get(intentId);
422
- if (!found) {
423
- throw new NeetruError("not_found", `Mock intent ${intentId} not found`);
424
- }
425
- const alreadyCancelled = found.status === "cancelled";
426
- this.intents.set(intentId, { ...found, status: "cancelled" });
427
- return { ok: true, alreadyCancelled };
409
+ async cancel(e, n) {
410
+ let r = this.intents.get(e);
411
+ if (!r)
412
+ throw new i("not_found", `Mock intent ${e} not found`);
413
+ let o = r.status === "cancelled";
414
+ return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
428
415
  }
429
416
  };
430
- function createCheckoutNamespace(config) {
431
- if (config.env === "dev") return new MockCheckout();
432
- return createHttpCheckoutNamespace(config);
417
+ function Ie(t) {
418
+ return t.env === "dev" ? new R() : ie(t);
433
419
  }
434
420
 
435
- exports.MockCheckout = MockCheckout;
436
- exports.createCheckoutNamespace = createCheckoutNamespace;
437
- //# sourceMappingURL=checkout.cjs.map
438
- //# sourceMappingURL=checkout.cjs.map
421
+ exports.MockCheckout = R;
422
+ exports.createCheckoutNamespace = Ie;