@neetru/sdk 3.7.0 → 3.8.1

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 (73) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +66 -1
  3. package/dist/ai.cjs +221 -177
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +221 -177
  7. package/dist/auth.cjs +1051 -868
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +1048 -865
  11. package/dist/catalog.cjs +164 -97
  12. package/dist/catalog.d.cts +1 -1
  13. package/dist/catalog.d.ts +1 -1
  14. package/dist/catalog.mjs +164 -97
  15. package/dist/checkout.cjs +182 -115
  16. package/dist/checkout.d.cts +1 -1
  17. package/dist/checkout.d.ts +1 -1
  18. package/dist/checkout.mjs +181 -114
  19. package/dist/db-react.d.cts +1 -1
  20. package/dist/db-react.d.ts +1 -1
  21. package/dist/db.cjs +437 -345
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +455 -363
  25. package/dist/entitlements.cjs +17 -10
  26. package/dist/entitlements.d.cts +1 -1
  27. package/dist/entitlements.d.ts +1 -1
  28. package/dist/entitlements.mjs +17 -10
  29. package/dist/errors.cjs +15 -8
  30. package/dist/errors.d.cts +24 -3
  31. package/dist/errors.d.ts +24 -3
  32. package/dist/errors.mjs +14 -7
  33. package/dist/firestore-compat.d.cts +1 -1
  34. package/dist/firestore-compat.d.ts +1 -1
  35. package/dist/index.cjs +1544 -1190
  36. package/dist/index.d.cts +177 -3
  37. package/dist/index.d.ts +177 -3
  38. package/dist/index.mjs +1676 -1329
  39. package/dist/mobile.cjs +400 -181
  40. package/dist/mobile.d.cts +59 -4
  41. package/dist/mobile.d.ts +59 -4
  42. package/dist/mobile.mjs +400 -181
  43. package/dist/mocks.cjs +9 -2
  44. package/dist/mocks.d.cts +1 -1
  45. package/dist/mocks.d.ts +1 -1
  46. package/dist/mocks.mjs +9 -2
  47. package/dist/notifications.cjs +197 -130
  48. package/dist/notifications.d.cts +1 -1
  49. package/dist/notifications.d.ts +1 -1
  50. package/dist/notifications.mjs +196 -129
  51. package/dist/react.cjs +303 -282
  52. package/dist/react.d.cts +1 -1
  53. package/dist/react.d.ts +1 -1
  54. package/dist/react.mjs +295 -274
  55. package/dist/support.cjs +299 -229
  56. package/dist/support.d.cts +8 -4
  57. package/dist/support.d.ts +8 -4
  58. package/dist/support.mjs +298 -228
  59. package/dist/telemetry.cjs +234 -167
  60. package/dist/telemetry.d.cts +1 -1
  61. package/dist/telemetry.d.ts +1 -1
  62. package/dist/telemetry.mjs +234 -167
  63. package/dist/{types-Dx0IrOSF.d.ts → types-BYPk_3HR.d.ts} +104 -17
  64. package/dist/{types-Bx4kTLmk.d.cts → types-yv3EDKg2.d.cts} +104 -17
  65. package/dist/usage.cjs +183 -116
  66. package/dist/usage.d.cts +1 -1
  67. package/dist/usage.d.ts +1 -1
  68. package/dist/usage.mjs +183 -116
  69. package/dist/webhooks.cjs +215 -148
  70. package/dist/webhooks.d.cts +1 -1
  71. package/dist/webhooks.d.ts +1 -1
  72. package/dist/webhooks.mjs +212 -145
  73. package/package.json +2 -1
package/dist/auth.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  import { jwtVerify, createRemoteJWKSet } from 'jose';
2
2
  import { openDB } from 'idb';
3
3
 
4
- var Nn = Object.defineProperty;
5
- var B = (n, e) => () => (n && (e = n(n = 0)), e);
6
- var Ze = (n, e) => {
4
+ var Qn = Object.defineProperty;
5
+ var $ = (n, e) => () => (n && (e = n(n = 0)), e);
6
+ var ot = (n, e) => {
7
7
  for (var t in e)
8
- Nn(n, t, { get: e[t], enumerable: true });
8
+ Qn(n, t, { get: e[t], enumerable: true });
9
9
  };
10
10
 
11
11
  // src/errors.ts
12
- var c, V, P = B(() => {
12
+ var c, V, I = $(() => {
13
13
  c = class n extends Error {
14
14
  code;
15
15
  status;
@@ -23,18 +23,25 @@ var c, V, P = B(() => {
23
23
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
24
24
  */
25
25
  reason;
26
- constructor(e, t, r, o, i) {
27
- super(t), this.name = "NeetruError", this.code = e, this.status = r, this.requestId = o, this.reason = i, Object.setPrototypeOf(this, n.prototype);
26
+ /**
27
+ * 3.8.0: `x-correlation-id` da requisição que falhou. O SDK gera um UUID por
28
+ * chamada (ou usa o que o chamador passou) e manda no header; o Core grava o
29
+ * mesmo id nos logs/auditoria — cite-o ao abrir um ticket de suporte.
30
+ * `undefined` em erros que acontecem antes de qualquer requisição.
31
+ */
32
+ correlationId;
33
+ constructor(e, t, r, o, i, s) {
34
+ super(t), this.name = "NeetruError", this.code = e, this.status = r, this.requestId = o, this.reason = i, this.correlationId = s, Object.setPrototypeOf(this, n.prototype);
28
35
  }
29
36
  }, V = class n extends c {
30
- constructor(e, t, r, o) {
31
- super("auth_required", e, r, o, t), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, n.prototype);
37
+ constructor(e, t, r, o, i) {
38
+ super("auth_required", e, r, o, t, i), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, n.prototype);
32
39
  }
33
40
  };
34
41
  });
35
42
 
36
43
  // src/idempotency.ts
37
- function ct() {
44
+ function ht() {
38
45
  let n = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
39
46
  if (n && typeof n.randomUUID == "function")
40
47
  return n.randomUUID();
@@ -43,80 +50,164 @@ function ct() {
43
50
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
44
51
  );
45
52
  }
46
- var lt = B(() => {
47
- P();
53
+ var gt = $(() => {
54
+ I();
55
+ });
56
+
57
+ // src/correlation.ts
58
+ function _t(n) {
59
+ return typeof n == "string" && n.length > 0 && n.length <= 128 && tr.test(n);
60
+ }
61
+ function nr() {
62
+ let n = globalThis.crypto;
63
+ try {
64
+ if (n && typeof n.randomUUID == "function") return n.randomUUID();
65
+ } catch {
66
+ }
67
+ let e = new Uint8Array(16), t = false;
68
+ try {
69
+ n && typeof n.getRandomValues == "function" && (n.getRandomValues(e), t = !0);
70
+ } catch {
71
+ t = false;
72
+ }
73
+ if (!t)
74
+ for (let o = 0; o < e.length; o++) e[o] = Math.floor(Math.random() * 256);
75
+ e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
76
+ let r = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
77
+ return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
78
+ }
79
+ function ae(n, e) {
80
+ let t, r = {};
81
+ for (let [i, s] of Object.entries(n)) {
82
+ if (i.toLowerCase() === yt) {
83
+ _t(s) && (t = s);
84
+ continue;
85
+ }
86
+ r[i] = s;
87
+ }
88
+ let o = t ?? (_t(e) ? e : void 0) ?? nr();
89
+ return r[yt] = o, { headers: r, correlationId: o };
90
+ }
91
+ var yt, tr, Me = $(() => {
92
+ yt = "x-correlation-id", tr = /^[A-Za-z0-9._:\-]+$/;
93
+ });
94
+
95
+ // src/server-only-key.ts
96
+ function X() {
97
+ try {
98
+ let n = globalThis.navigator;
99
+ if (n && n.product === "ReactNative") return "react-native";
100
+ } catch {
101
+ }
102
+ try {
103
+ let n = globalThis;
104
+ if (typeof n.window < "u" && typeof n.document < "u") return "browser";
105
+ } catch {
106
+ }
107
+ return null;
108
+ }
109
+ function bt(n, e) {
110
+ let t = rr[n];
111
+ return (`${e ? `[Neetru SDK] Recusado: a credencial nrt_ do produto foi passada ao SDK rodando ${t}.` : `[Neetru SDK] ATEN\xC7\xC3O: a credencial nrt_ do produto est\xE1 sendo usada ${t}.`} Essa chave \xE9 S\xD3 DE SERVIDOR \u2014 quem abrir o DevTools (ou descompactar o app) copia a chave e fala com o Core como se fosse o seu produto. Como corrigir: o site/app chama a API do SEU produto (ex.: https://<produto>.neetru.com/api/v1) com o token do usu\xE1rio (Authorization: Bearer <access_token>); o backend do produto valida com verifyAccessToken() e usa o SDK com a chave (NEETRU_API_KEY, sem prefixo NEXT_PUBLIC_/EXPO_PUBLIC_). ` + (e ? "" : "Nesta vers\xE3o \xE9 s\xF3 um aviso; use strictServerOnlyKey: true para bloquear j\xE1. Na pr\xF3xima vers\xE3o MAJOR do SDK isso passa a falhar sempre.")).trim();
112
+ }
113
+ function wt(n) {
114
+ if (!n.hasApiKey) return;
115
+ let e = n.runtime === void 0 ? X() : n.runtime;
116
+ if (e) {
117
+ if (n.strict)
118
+ throw new c("server_only_key", bt(e, true), void 0, void 0, e);
119
+ if (!vt) {
120
+ vt = true;
121
+ try {
122
+ typeof console < "u" && typeof console.warn == "function" && console.warn(bt(e, !1));
123
+ } catch {
124
+ }
125
+ }
126
+ }
127
+ }
128
+ var rr, vt, qe = $(() => {
129
+ I();
130
+ rr = {
131
+ browser: "no navegador",
132
+ "react-native": "num app React Native"
133
+ };
134
+ vt = false;
48
135
  });
49
136
 
50
137
  // src/http.ts
51
- var X = {};
52
- Ze(X, {
53
- checkCoreVersionCompat: () => ie,
138
+ var Y = {};
139
+ ot(Y, {
140
+ checkCoreVersionCompat: () => ce,
54
141
  httpRequest: () => v,
55
- statusToCode: () => se
142
+ statusToCode: () => le
56
143
  });
57
- function xe(n) {
144
+ function Fe(n) {
58
145
  return n.split("+")[0] ?? n;
59
146
  }
60
- function Fn(n, e) {
61
- let t = xe(n).split(".").map(Number), r = xe(e).split(".").map(Number), o = Math.max(t.length, r.length);
147
+ function ir(n, e) {
148
+ let t = Fe(n).split(".").map(Number), r = Fe(e).split(".").map(Number), o = Math.max(t.length, r.length);
62
149
  for (let i = 0; i < o; i++) {
63
150
  let s = t[i] ?? 0, a = r[i] ?? 0;
64
151
  if (s !== a) return s - a;
65
152
  }
66
153
  return 0;
67
154
  }
68
- function ht() {
155
+ function Ct() {
69
156
  try {
70
- return "3.7.0";
157
+ return "3.8.1";
71
158
  } catch {
72
159
  return;
73
160
  }
74
161
  }
75
- function jn() {
76
- let n = ht();
162
+ function sr() {
163
+ let n = Ct();
77
164
  return n ? parseInt(n.split(".")[0] ?? "3", 10) : 3;
78
165
  }
79
- function ie(n) {
166
+ function ce(n) {
80
167
  if (!n) return;
81
- let e = jn(), t = qn[e];
168
+ let e = sr(), t = or[e];
82
169
  if (!t) return;
83
- let r = xe(n);
84
- if (Fn(r, t) < 0) {
170
+ let r = Fe(n);
171
+ if (ir(r, t) < 0) {
85
172
  let o = `${e}:${r}`;
86
- dt.has(o) || (dt.add(o), console.warn(
173
+ kt.has(o) || (kt.add(o), console.warn(
87
174
  `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${n}" \xE9 anterior ao m\xEDnimo recomendado "${t}" para SDK major ${e}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
88
175
  ));
89
176
  }
90
177
  }
91
- function ut(n) {
178
+ function ar() {
179
+ let n = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
180
+ return X() ? "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. (" + n + ")" : n;
181
+ }
182
+ function St(n) {
92
183
  let e = 200 * Math.pow(4, n), t = e * 0.2 * (Math.random() * 2 - 1);
93
184
  return Math.max(50, Math.round(e + t));
94
185
  }
95
- function zn(n) {
186
+ function pr(n) {
96
187
  if (!n) return null;
97
188
  let e = Number(n);
98
- if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), pt);
189
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), Tt);
99
190
  let t = Date.parse(n);
100
191
  if (Number.isFinite(t)) {
101
192
  let r = t - Date.now();
102
- if (r > 0) return Math.min(r, pt);
193
+ if (r > 0) return Math.min(r, Tt);
103
194
  }
104
195
  return null;
105
196
  }
106
- function ft(n) {
197
+ function Rt(n) {
107
198
  return new Promise((e) => setTimeout(e, n));
108
199
  }
109
- function se(n) {
200
+ function le(n) {
110
201
  return n === 401 ? "unauthorized" : n === 403 ? "forbidden" : n === 404 ? "not_found" : n === 409 ? "conflict" : n === 410 ? "gone" : n === 422 || n === 400 ? "validation_failed" : n === 429 ? "rate_limited" : n >= 500 ? "server_error" : "unknown";
111
202
  }
112
- function Kn(n, e, t) {
203
+ function fr(n, e, t) {
113
204
  let r = n.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, i = new URL(`${r}${o}`);
114
205
  if (t)
115
206
  for (let [s, a] of Object.entries(t))
116
207
  a !== void 0 && i.searchParams.set(s, String(a));
117
208
  return i.toString();
118
209
  }
119
- async function mt(n) {
210
+ async function It(n) {
120
211
  let e = await n.text();
121
212
  if (e)
122
213
  try {
@@ -126,97 +217,103 @@ async function mt(n) {
126
217
  }
127
218
  }
128
219
  async function v(n, e) {
129
- let t = e.method ?? "GET", r = Kn(n.baseUrl, e.path, e.query), o = Bn.has(t) ? Wn : $n, i = e.retries ?? o, s = {
130
- accept: "application/json",
131
- ...e.headers
132
- }, a = ht();
133
- if (a && (s["x-neetru-sdk-version"] = a), e.requireAuth) {
220
+ let t = e.method ?? "GET", r = fr(n.baseUrl, e.path, e.query), o = dr.has(t) ? cr : lr, i = e.retries ?? o, { headers: s, correlationId: a } = ae(
221
+ { accept: "application/json", ...e.headers },
222
+ e.correlationId
223
+ ), l = Ct();
224
+ if (l && (s["x-neetru-sdk-version"] = l), e.requireAuth) {
134
225
  if (!n.apiKey)
135
- throw new c(
136
- "missing_api_key",
137
- "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
138
- );
226
+ throw new c("missing_api_key", ar());
139
227
  s.authorization = `Bearer ${n.apiKey}`;
140
228
  }
141
229
  if (e.idempotencyKey) {
142
- let p = typeof e.idempotencyKey == "string" ? e.idempotencyKey : ct();
143
- s["idempotency-key"] = p;
144
- }
145
- let l = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
146
- l !== void 0 && (s["content-type"] = "application/json");
147
- let d = null, u = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
148
- for (let p = 0; p <= i; p++) {
149
- if (u != null && Date.now() >= u)
150
- throw d ?? new c("network_error", "Deadline excedido antes de completar a request");
151
- let f = { method: t, headers: s };
152
- l !== void 0 && (f.body = l);
153
- let g = u != null ? Math.max(1, Math.min(3e4, u - Date.now())) : 3e4;
154
- f.signal = AbortSignal.timeout(g);
155
- let _;
230
+ let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : ht();
231
+ s["idempotency-key"] = f;
232
+ }
233
+ let d = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
234
+ d !== void 0 && (s["content-type"] = "application/json");
235
+ let u = null, p = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
236
+ for (let f = 0; f <= i; f++) {
237
+ if (p != null && Date.now() >= p)
238
+ throw u ?? new c(
239
+ "network_error",
240
+ "Deadline excedido antes de completar a request",
241
+ void 0,
242
+ void 0,
243
+ void 0,
244
+ a
245
+ );
246
+ let h = { method: t, headers: s };
247
+ d !== void 0 && (h.body = d);
248
+ let y = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
249
+ h.signal = AbortSignal.timeout(y);
250
+ let S;
156
251
  try {
157
- _ = await n.fetch(r, f);
158
- } catch (m) {
159
- let T = m instanceof DOMException && m.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${m instanceof Error ? m.message : "fetch failed"}`;
160
- if (d = new c("network_error", T), p < i) {
161
- let A = ut(p);
162
- if (u == null || Date.now() + A < u) {
163
- await ft(A);
252
+ S = await n.fetch(r, h);
253
+ } catch (g) {
254
+ let C = g instanceof DOMException && g.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${g instanceof Error ? g.message : "fetch failed"}`;
255
+ if (u = new c("network_error", C, void 0, void 0, void 0, a), f < i) {
256
+ let D = St(f);
257
+ if (p == null || Date.now() + D < p) {
258
+ await Rt(D);
164
259
  continue;
165
260
  }
166
261
  }
167
- throw d;
262
+ throw u;
168
263
  }
169
- let M = _.headers.get("x-request-id") ?? _.headers.get("x-correlation-id") ?? void 0;
170
- if (_.ok) {
171
- let m = _.headers.get("x-neetru-version");
172
- return m && ie(m), await mt(_);
264
+ let x = S.headers.get("x-request-id") ?? S.headers.get("x-correlation-id") ?? void 0;
265
+ if (S.ok) {
266
+ let g = S.headers.get("x-neetru-version");
267
+ return g && ce(g), await It(S);
173
268
  }
174
- let R = await mt(_), N = se(_.status), C = `HTTP ${_.status}`, $;
175
- if (R && typeof R == "object") {
176
- let m = R.error;
177
- typeof m == "string" ? C = m : m && typeof m == "object" ? (typeof m.code == "string" && (N = m.code), typeof m.message == "string" && (C = m.message), typeof m.reason == "string" && ($ = m.reason)) : (typeof R.code == "string" && (N = R.code), typeof R.message == "string" && (C = R.message)), typeof R.reason == "string" && ($ = R.reason);
269
+ let T = await It(S), P = le(S.status), q = `HTTP ${S.status}`, m;
270
+ if (T && typeof T == "object") {
271
+ let g = T.error;
272
+ typeof g == "string" ? q = g : g && typeof g == "object" ? (typeof g.code == "string" && (P = g.code), typeof g.message == "string" && (q = g.message), typeof g.reason == "string" && (m = g.reason)) : (typeof T.code == "string" && (P = T.code), typeof T.message == "string" && (q = T.message)), typeof T.reason == "string" && (m = T.reason);
178
273
  }
179
- if (_.status === 410) {
180
- let m = _.headers.get("x-neetru-replacement");
181
- C === `HTTP ${_.status}` && (C = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), m && !C.includes(m) && (C += ` Substituto: ${m}.`);
274
+ if (S.status === 410) {
275
+ let g = S.headers.get("x-neetru-replacement");
276
+ q === `HTTP ${S.status}` && (q = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), g && !q.includes(g) && (q += ` Substituto: ${g}.`);
182
277
  }
183
- let h = new c(N, C, _.status, M, $);
184
- if (d = h, Vn.has(N) && p < i) {
185
- let T = zn(_.headers.get("retry-after")) ?? ut(p);
186
- if (u == null || Date.now() + T < u) {
187
- await ft(T);
278
+ let _ = new c(P, q, S.status, x, m, a);
279
+ if (u = _, ur.has(P) && f < i) {
280
+ let C = pr(S.headers.get("retry-after")) ?? St(f);
281
+ if (p == null || Date.now() + C < p) {
282
+ await Rt(C);
188
283
  continue;
189
284
  }
190
285
  }
191
- throw h;
286
+ throw _;
192
287
  }
193
- throw d ?? new c("unknown", "unexpected httpRequest exit");
288
+ throw u ?? new c("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
194
289
  }
195
- var qn, dt, Wn, $n, Bn, Vn, pt, U = B(() => {
196
- P();
197
- lt();
198
- qn = {
290
+ var or, kt, cr, lr, dr, ur, Tt, M = $(() => {
291
+ I();
292
+ gt();
293
+ Me();
294
+ qe();
295
+ or = {
199
296
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
200
297
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
201
298
  3: "2026.05.1"
202
299
  };
203
- dt = /* @__PURE__ */ new Set();
204
- Wn = 2, $n = 0, Bn = /* @__PURE__ */ new Set(["GET", "HEAD"]), Vn = /* @__PURE__ */ new Set([
300
+ kt = /* @__PURE__ */ new Set();
301
+ cr = 2, lr = 0, dr = /* @__PURE__ */ new Set(["GET", "HEAD"]), ur = /* @__PURE__ */ new Set([
205
302
  "rate_limited",
206
303
  "server_error",
207
304
  "network_error"
208
305
  ]);
209
- pt = 6e4;
306
+ Tt = 6e4;
210
307
  });
211
308
 
212
309
  // src/db-errors.ts
213
- var ir, y, Y = B(() => {
214
- P();
215
- ir = /* @__PURE__ */ new Set([
310
+ var Ir, b, Z = $(() => {
311
+ I();
312
+ Ir = /* @__PURE__ */ new Set([
216
313
  "db_unavailable",
217
314
  "db_conflict",
218
315
  "db_timeout"
219
- ]), y = class n extends c {
316
+ ]), b = class n extends c {
220
317
  /** Código de erro fechado — específico de DB. */
221
318
  code;
222
319
  /**
@@ -230,16 +327,16 @@ var ir, y, Y = B(() => {
230
327
  */
231
328
  dbId;
232
329
  constructor(e, t, r) {
233
- super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = ir.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
330
+ super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Ir.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
234
331
  }
235
332
  };
236
333
  });
237
334
 
238
335
  // src/db/sql/resilient-pool.ts
239
- function ye(n) {
240
- return typeof n == "object" && n !== null && n[We] === true;
336
+ function ve(n) {
337
+ return typeof n == "object" && n !== null && n[He] === true;
241
338
  }
242
- function Cr(n) {
339
+ function Qr(n) {
243
340
  let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
244
341
  if (e === "ECONNREFUSED" || e === "ETIMEDOUT" || e === "ENOTFOUND" || e === "EHOSTUNREACH" || e === "EAI_AGAIN")
245
342
  return true;
@@ -251,67 +348,84 @@ function Cr(n) {
251
348
  let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
252
349
  return r.length === 0 ? false : !!(r.includes("certificate expired") || r.includes("certificate has expired") || r.includes("cert_has_expired") || r.includes("alert certificate expired") || r.includes("err_ssl") || r.includes("sslv3 alert") || r.includes("tlsv1 alert") || r.includes("econnrefused") || r.includes("etimedout") || r.includes("enotfound") || r.includes("ehostunreach") || r.includes("getaddrinfo"));
253
350
  }
254
- function $e(n) {
351
+ function Gt(n) {
352
+ let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
353
+ if (typeof e == "string" && Gr.has(e.toUpperCase()))
354
+ return true;
355
+ let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
356
+ return r.length === 0 ? false : r.includes("password authentication failed") || r.includes("sasl authentication failed");
357
+ }
358
+ function Jr(n) {
359
+ return Qr(n) || Gt(n);
360
+ }
361
+ function Qe(n) {
255
362
  let e = { current: n }, t = null, r = {
256
- __neetruSwapInner(l) {
257
- let d = e.current;
258
- return e.current = l, d;
363
+ __neetruSwapInner(u) {
364
+ let p = e.current;
365
+ return e.current = u, p;
259
366
  },
260
367
  __neetruGetInner() {
261
368
  return e.current;
262
369
  },
263
- __neetruSetReLease(l) {
264
- t = l;
370
+ __neetruSetReLease(u) {
371
+ t = u;
265
372
  }
266
- }, o = (l, d) => l.query(...d), i = (...l) => l.length > 0 && typeof l[l.length - 1] == "function" ? o(e.current, l) : (async () => {
373
+ }, o = (u, p, f) => p[u](
374
+ ...f
375
+ ), i = (u, p) => (...f) => f.length > 0 && typeof f[f.length - 1] == "function" ? o(u, e.current, f) : (async () => {
267
376
  try {
268
- return await o(e.current, l);
269
- } catch (d) {
270
- let u = t;
271
- if (u === null || !Cr(d))
272
- throw d;
377
+ return await o(u, e.current, f);
378
+ } catch (h) {
379
+ let y = t;
380
+ if (y === null || !p(h))
381
+ throw h;
273
382
  try {
274
- await u();
383
+ await y();
275
384
  } catch {
276
- throw d;
385
+ throw h;
277
386
  }
278
- return await o(e.current, l);
387
+ return await o(u, e.current, f);
279
388
  }
280
- })(), s = Object.create(Object.getPrototypeOf(n));
281
- return new Proxy(s, {
282
- get(l, d) {
283
- if (d === We) return true;
284
- if (d === "__neetruSwapInner") return r.__neetruSwapInner;
285
- if (d === "__neetruGetInner") return r.__neetruGetInner;
286
- if (d === "__neetruSetReLease") return r.__neetruSetReLease;
287
- if (d === "query") return i;
288
- if (d === "constructor")
389
+ })(), s = i("query", Jr), a = i("connect", Gt), l = Object.create(Object.getPrototypeOf(n));
390
+ return new Proxy(l, {
391
+ get(u, p) {
392
+ if (p === He) return true;
393
+ if (p === "__neetruSwapInner") return r.__neetruSwapInner;
394
+ if (p === "__neetruGetInner") return r.__neetruGetInner;
395
+ if (p === "__neetruSetReLease") return r.__neetruSetReLease;
396
+ if (p === "query") return s;
397
+ if (p === "connect") {
398
+ let y = e.current;
399
+ return typeof y.connect == "function" ? a : y.connect;
400
+ }
401
+ if (p === "constructor")
289
402
  return e.current.constructor;
290
- let u = e.current, p = Reflect.get(u, d, u);
291
- return typeof p == "function" ? p.bind(u) : p;
403
+ let f = e.current, h = Reflect.get(f, p, f);
404
+ return typeof h == "function" ? h.bind(f) : h;
292
405
  }
293
406
  });
294
407
  }
295
- var We, Be = B(() => {
296
- We = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
408
+ var He, Gr, Ge = $(() => {
409
+ He = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
410
+ Gr = /* @__PURE__ */ new Set(["28P01", "28000"]);
297
411
  });
298
412
 
299
413
  // src/db/sql/lease.ts
300
- function Pr(n, e) {
414
+ function Yr(n, e) {
301
415
  return n ? n.leaseId !== e.leaseId || n.credentialVersion !== e.credentialVersion || n.host !== e.host || n.port !== e.port || n.dbName !== e.dbName || n.user !== e.user || n.password !== e.password || n.sslca !== e.sslca || n.clientCert !== e.clientCert || n.clientKey !== e.clientKey : true;
302
416
  }
303
- function Er(n) {
304
- if (n instanceof y) return n;
417
+ function Zr(n) {
418
+ if (n instanceof b) return n;
305
419
  let e = n instanceof Error ? n.message : String(n), t = n instanceof Error ? n.code : void 0;
306
- return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new y(
420
+ return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new b(
307
421
  "db_unavailable",
308
422
  `Pool connection failed (${t}): ${e}`
309
- ) : e.includes("statement timeout") || e.includes("lock timeout") ? new y("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new y("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new y("db_permission_denied", `Permission denied: ${e}`) : new y("db_unavailable", `Database error: ${e}`);
423
+ ) : e.includes("statement timeout") || e.includes("lock timeout") ? new b("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new b("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new b("db_permission_denied", `Permission denied: ${e}`) : new b("db_unavailable", `Database error: ${e}`);
310
424
  }
311
- var Ar, J, ne, Mt = B(() => {
312
- Y();
313
- Be();
314
- Ar = 0.8, J = 3e4, ne = class {
425
+ var Xr, J, re, Jt = $(() => {
426
+ Z();
427
+ Ge();
428
+ Xr = 0.8, J = 3e4, re = class {
315
429
  /**
316
430
  * Lease atual. `null` no modo LAZY antes da 1ª query (o 1º lease é adiado —
317
431
  * ver `_ensureInitialLease`). Após a 1ª aquisição, sempre não-nulo.
@@ -351,7 +465,7 @@ var Ar, J, ne, Mt = B(() => {
351
465
  isolationLevel: t.isolationLevel
352
466
  }) : await this._orm.transaction(e);
353
467
  } catch (r) {
354
- throw Er(r);
468
+ throw Zr(r);
355
469
  }
356
470
  }
357
471
  async close() {
@@ -374,7 +488,7 @@ var Ar, J, ne, Mt = B(() => {
374
488
  if (!Number.isFinite(e)) return J;
375
489
  let t = this._deps.now(), r = e - t;
376
490
  if (r <= 0) return J;
377
- let o = r * (1 - Ar);
491
+ let o = r * (1 - Xr);
378
492
  return Math.max(J, Math.round(o));
379
493
  }
380
494
  _scheduleRenewal() {
@@ -403,7 +517,7 @@ var Ar, J, ne, Mt = B(() => {
403
517
  this._renewalTimer = setTimeout(() => {
404
518
  this._doRenew();
405
519
  }, J), console.warn(
406
- `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${J}ms (cert TLS ef\xEAmero do servidor expira ~15min ap\xF3s o \xFAltimo swap):`,
520
+ `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${J}ms (o cert de cliente mTLS do lease expira ~15min ap\xF3s o \xFAltimo swap):`,
407
521
  t instanceof Error ? t.message : t
408
522
  );
409
523
  return;
@@ -415,10 +529,13 @@ var Ar, J, ne, Mt = B(() => {
415
529
  /**
416
530
  * Recuperação REATIVA: chamado pelo wrapper resiliente (`resilient-pool.ts`)
417
531
  * quando uma query plana falha num erro de ESTABELECIMENTO de conexão (cert
418
- * TLS efêmero do servidor expirado no meio de uma request, ou timer de
419
- * renovação que não disparou). Emite um lease NOVO e faz o swap do pool interno
420
- * do wrapper com
421
- * o certificado fresco; o wrapper então re-tenta a query 1x no pool novo.
532
+ * TLS de cliente mTLS do lease expirado no meio de uma request, ou timer de
533
+ * renovação que não disparou) ou de AUTENTICAÇÃO (senha rotacionada por
534
+ * `rotate-credentials` antes do próximo renew — SQLSTATE 28P01/28000, ou o
535
+ * 08P01+SASL do PgBouncer; também no `connect()` de uma transação). Emite um
536
+ * lease NOVO e faz o swap do pool interno do wrapper com a credencial e o
537
+ * certificado frescos (o pool velho é drenado com `end()`); o wrapper então
538
+ * re-tenta a operação 1x no pool novo.
422
539
  *
423
540
  * Vai DIRETO ao lease novo (sem `leaseId`) — a conexão falhou porque o
424
541
  * certificado do lease atual está ruim, então `renew` (que depende do lease
@@ -434,7 +551,7 @@ var Ar, J, ne, Mt = B(() => {
434
551
  */
435
552
  async _reactiveReLease() {
436
553
  if (this._closed)
437
- throw new y(
554
+ throw new b(
438
555
  "db_unavailable",
439
556
  "SqlLeaseManager foi fechado \u2014 re-lease reativo abortado."
440
557
  );
@@ -471,30 +588,30 @@ var Ar, J, ne, Mt = B(() => {
471
588
  */
472
589
  async _ensureInitialLease() {
473
590
  if (this._closed)
474
- throw new y(
591
+ throw new b(
475
592
  "db_unavailable",
476
593
  "SqlLeaseManager foi fechado \u2014 aquisi\xE7\xE3o de lease inicial abortada."
477
594
  );
478
595
  if (this._lease)
479
- return ye(this._pool) ? this._pool.__neetruGetInner() : this._pool;
596
+ return ve(this._pool) ? this._pool.__neetruGetInner() : this._pool;
480
597
  if (this._initInFlight !== null) return this._initInFlight;
481
598
  let e = (async () => {
482
599
  let t;
483
600
  try {
484
601
  t = this._deps.database !== void 0 ? await this._deps.fetchLease({ database: this._deps.database }) : await this._deps.fetchLease();
485
602
  } catch (o) {
486
- if (o instanceof y) throw o;
603
+ if (o instanceof b) throw o;
487
604
  let i = o instanceof Error ? o.message : String(o);
488
- throw new y("db_unavailable", `Falha ao obter lease inicial: ${i}`);
605
+ throw new b("db_unavailable", `Falha ao obter lease inicial: ${i}`);
489
606
  }
490
607
  let r;
491
608
  try {
492
609
  r = this._deps.createPool(t);
493
610
  } catch (o) {
494
611
  let i = o instanceof Error ? o.message : String(o);
495
- throw new y("db_unavailable", `Falha ao abrir pool: ${i}`);
612
+ throw new b("db_unavailable", `Falha ao abrir pool: ${i}`);
496
613
  }
497
- return ye(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
614
+ return ve(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
498
615
  }) : this._pool = r, this._lease = t, this._scheduleRenewal(), r;
499
616
  })();
500
617
  this._initInFlight = e;
@@ -510,12 +627,12 @@ var Ar, J, ne, Mt = B(() => {
510
627
  * Exposto como método protegido para testes.
511
628
  */
512
629
  async _swapPool(e) {
513
- if (!Pr(this._lease, e)) {
630
+ if (!Yr(this._lease, e)) {
514
631
  this._lease = e;
515
632
  return;
516
633
  }
517
634
  let t = this._deps.createPool(e);
518
- if (ye(this._pool)) {
635
+ if (ve(this._pool)) {
519
636
  let i = this._pool.__neetruSwapInner(t);
520
637
  this._lease = e, i.end().catch(() => {
521
638
  });
@@ -528,7 +645,7 @@ var Ar, J, ne, Mt = B(() => {
528
645
  // ─── Helpers ───────────────────────────────────────────────────────────────
529
646
  _assertOpen() {
530
647
  if (this._closed)
531
- throw new y(
648
+ throw new b(
532
649
  "db_unavailable",
533
650
  "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
534
651
  );
@@ -537,29 +654,29 @@ var Ar, J, ne, Mt = B(() => {
537
654
  });
538
655
 
539
656
  // src/db/sql/sql-client.ts
540
- var zt = {};
541
- Ze(zt, {
542
- DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => Bt,
543
- DEFAULT_POOL_IDLE_MS: () => $t,
544
- DEFAULT_POOL_MAX: () => Wt,
545
- LEASE_ENDPOINT: () => qt,
546
- LEASE_RENEW_ENDPOINT: () => Ft,
547
- createDrizzleHandle: () => Or,
548
- createHttpLeaseFetcher: () => jt,
549
- createPgPool: () => xr,
550
- createSqlClientFromConfig: () => Ur,
551
- createSqlClientWithDeps: () => Vt,
552
- resolvePoolTuning: () => ze
657
+ var on = {};
658
+ ot(on, {
659
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => nn,
660
+ DEFAULT_POOL_IDLE_MS: () => tn,
661
+ DEFAULT_POOL_MAX: () => en,
662
+ LEASE_ENDPOINT: () => Xt,
663
+ LEASE_RENEW_ENDPOINT: () => Yt,
664
+ createDrizzleHandle: () => ro,
665
+ createHttpLeaseFetcher: () => Zt,
666
+ createPgPool: () => no,
667
+ createSqlClientFromConfig: () => io,
668
+ createSqlClientWithDeps: () => rn,
669
+ resolvePoolTuning: () => Xe
553
670
  });
554
- function Dr(n) {
671
+ function eo(n) {
555
672
  return n === "workspace" ? "staging" : n === "prod" ? "production" : "dev-local";
556
673
  }
557
- function jt(n) {
674
+ function Zt(n) {
558
675
  return async (e) => {
559
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = !!e?.leaseId, o = r ? Ft : qt, i;
676
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = !!e?.leaseId, o = r ? Yt : Xt, i;
560
677
  r ? i = { leaseId: e.leaseId } : (i = {
561
678
  productId: n.productId ?? "",
562
- environment: Dr(n.env ?? "prod")
679
+ environment: eo(n.env ?? "prod")
563
680
  }, e?.database !== void 0 && (i.database = e.database));
564
681
  let s;
565
682
  try {
@@ -575,32 +692,32 @@ function jt(n) {
575
692
  let l = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof c ? a.reason : void 0;
576
693
  if (u === "suspended" || u === "archived" || u === "revoked") {
577
694
  let p = u === "suspended" ? "ambiente suspenso \u2014 a m\xE1quina que o servia parou; ser\xE1 religado quando o ambiente voltar" : u === "archived" ? "ambiente arquivado \u2014 este banco foi arquivado e n\xE3o aceita mais conex\xF5es" : "lease revogado \u2014 as credenciais deste ambiente foram revogadas pelo Core";
578
- throw new y(
695
+ throw new b(
579
696
  "db_suspended",
580
697
  `Falha ao ${l} lease SQL: ${p} (reason=${u}).`
581
698
  );
582
699
  }
583
- throw new y(
700
+ throw new b(
584
701
  "db_unavailable",
585
702
  `Falha ao ${l} lease SQL: ${d}`
586
703
  );
587
704
  }
588
- return Nr(s);
705
+ return to(s);
589
706
  };
590
707
  }
591
- function Nr(n) {
708
+ function to(n) {
592
709
  if (!n || typeof n != "object")
593
- throw new y("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
710
+ throw new b("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
594
711
  let t = n.lease;
595
712
  if (!t || typeof t != "object")
596
- throw new y(
713
+ throw new b(
597
714
  "db_unavailable",
598
715
  'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
599
716
  );
600
717
  let r = t;
601
718
  function o(i, s) {
602
719
  if (typeof r[i] !== s)
603
- throw new y(
720
+ throw new b(
604
721
  "db_unavailable",
605
722
  `Campo obrigat\xF3rio "${i}" ausente ou tipo inv\xE1lido na resposta de lease.`
606
723
  );
@@ -620,22 +737,22 @@ function Nr(n) {
620
737
  expiresAt: o("expiresAt", "string")
621
738
  };
622
739
  }
623
- function Ve(n, e, t, r) {
740
+ function Je(n, e, t, r) {
624
741
  let o = typeof process < "u" ? process.env?.[n] : void 0;
625
742
  if (o === void 0 || o.trim() === "") return e;
626
743
  let i = Number.parseInt(o.trim(), 10);
627
744
  return !Number.isFinite(i) || i < t || i > r ? e : i;
628
745
  }
629
- function ze() {
746
+ function Xe() {
630
747
  return {
631
748
  // Teto 100: bem abaixo do `max_client_conn = 500` do PgBouncer, com folga
632
749
  // para múltiplas instâncias do app dividirem o mesmo front-door.
633
- max: Ve("NEETRU_DB_POOL_MAX", Wt, 1, 100),
750
+ max: Je("NEETRU_DB_POOL_MAX", en, 1, 100),
634
751
  // Teto 15min = janela do cert; piso 1s.
635
- idleTimeoutMillis: Ve("NEETRU_DB_POOL_IDLE_MS", $t, 1e3, 9e5),
636
- connectionTimeoutMillis: Ve(
752
+ idleTimeoutMillis: Je("NEETRU_DB_POOL_IDLE_MS", tn, 1e3, 9e5),
753
+ connectionTimeoutMillis: Je(
637
754
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
638
- Bt,
755
+ nn,
639
756
  1e3,
640
757
  12e4
641
758
  ),
@@ -643,7 +760,7 @@ function ze() {
643
760
  keepAliveInitialDelayMillis: 1e4
644
761
  };
645
762
  }
646
- async function xr(n) {
763
+ async function no(n) {
647
764
  let { Pool: e } = await import(
648
765
  /* webpackIgnore: true */
649
766
  'pg'
@@ -660,17 +777,17 @@ async function xr(n) {
660
777
  user: n.user,
661
778
  password: n.password,
662
779
  ssl: t,
663
- ...ze()
780
+ ...Xe()
664
781
  });
665
782
  }
666
- async function Or(n, e) {
783
+ async function ro(n, e) {
667
784
  let { drizzle: t } = await import(
668
785
  /* webpackIgnore: true */
669
786
  'drizzle-orm/node-postgres'
670
787
  );
671
788
  return t(n, { schema: e });
672
789
  }
673
- function Lr(n, e) {
790
+ function oo(n, e) {
674
791
  let t = null, r = null, o = () => t ? Promise.resolve(t) : (r || (r = e().then((s) => (t = s, r = null, s)).catch((s) => {
675
792
  throw r = null, s;
676
793
  })), r), i = {
@@ -686,52 +803,52 @@ function Lr(n, e) {
686
803
  };
687
804
  return n && Object.setPrototypeOf(i, n), i;
688
805
  }
689
- async function Vt(n, e) {
806
+ async function rn(n, e) {
690
807
  let t = e?.database !== void 0 ? { ...n, database: e.database } : n;
691
808
  if (t.lazy) {
692
- let l = null, d = Lr(t.poolPrototype ?? null, () => {
809
+ let l = null, d = oo(t.poolPrototype ?? null, () => {
693
810
  if (!l)
694
- throw new y("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
811
+ throw new b("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
695
812
  return l._ensureInitialLease();
696
- }), u = $e(d), p;
813
+ }), u = Qe(d), p;
697
814
  try {
698
815
  p = t.createDrizzle(u, t.schema);
699
- } catch (g) {
700
- let _ = g instanceof Error ? g.message : String(g);
701
- throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${_}`);
816
+ } catch (h) {
817
+ let y = h instanceof Error ? h.message : String(h);
818
+ throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${y}`);
702
819
  }
703
- let f = new ne(null, u, p, t);
820
+ let f = new re(null, u, p, t);
704
821
  return l = f, u.__neetruSetReLease(() => f._reactiveReLease()), f;
705
822
  }
706
823
  let r;
707
824
  try {
708
825
  e?.database !== void 0 ? r = await t.fetchLease({ database: e.database }) : r = await t.fetchLease();
709
826
  } catch (l) {
710
- if (l instanceof y) throw l;
827
+ if (l instanceof b) throw l;
711
828
  let d = l instanceof Error ? l.message : String(l);
712
- throw new y("db_unavailable", `Falha ao obter lease inicial: ${d}`);
829
+ throw new b("db_unavailable", `Falha ao obter lease inicial: ${d}`);
713
830
  }
714
831
  let o;
715
832
  try {
716
833
  o = t.createPool(r);
717
834
  } catch (l) {
718
835
  let d = l instanceof Error ? l.message : String(l);
719
- throw new y("db_unavailable", `Falha ao abrir pool: ${d}`);
836
+ throw new b("db_unavailable", `Falha ao abrir pool: ${d}`);
720
837
  }
721
- let i = $e(o), s;
838
+ let i = Qe(o), s;
722
839
  try {
723
840
  s = t.createDrizzle(i, t.schema);
724
841
  } catch (l) {
725
842
  await o.end().catch(() => {
726
843
  });
727
844
  let d = l instanceof Error ? l.message : String(l);
728
- throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
845
+ throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
729
846
  }
730
- let a = new ne(r, i, s, t);
847
+ let a = new re(r, i, s, t);
731
848
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
732
849
  }
733
- async function Ur(n, e, t) {
734
- let r = jt(n), o, i;
850
+ async function io(n, e, t) {
851
+ let r = Zt(n), o, i;
735
852
  try {
736
853
  o = await import(
737
854
  /* webpackIgnore: true */
@@ -741,13 +858,13 @@ async function Ur(n, e, t) {
741
858
  'drizzle-orm/node-postgres'
742
859
  );
743
860
  } catch (d) {
744
- throw new y(
861
+ throw new b(
745
862
  "db_unavailable",
746
863
  `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${d.message})`
747
864
  );
748
865
  }
749
866
  let s = o.Pool ?? o.default?.Pool;
750
- return Vt(
867
+ return rn(
751
868
  {
752
869
  fetchLease: r,
753
870
  createPool: (d) => {
@@ -766,7 +883,7 @@ async function Ur(n, e, t) {
766
883
  ssl: u,
767
884
  // Tuning centralizado (env-tunável) — ver resolvePoolTuning + auditoria
768
885
  // docs/_review/AUDITORIA_DB_CONN_PERF_2026-09-06.md no Core.
769
- ...ze()
886
+ ...Xe()
770
887
  });
771
888
  },
772
889
  createDrizzle: (d, u) => i.drizzle(d, { schema: u }),
@@ -782,28 +899,39 @@ async function Ur(n, e, t) {
782
899
  t
783
900
  );
784
901
  }
785
- var qt, Ft, Wt, $t, Bt, Kt = B(() => {
786
- Y();
787
- P();
788
- Mt();
789
- Be();
790
- qt = "/api/sdk/v1/db/lease", Ft = "/api/sdk/v1/db/lease/renew";
791
- Wt = 10, $t = 6e4, Bt = 1e4;
902
+ var Xt, Yt, en, tn, nn, sn = $(() => {
903
+ Z();
904
+ I();
905
+ Jt();
906
+ Ge();
907
+ Xt = "/api/sdk/v1/db/lease", Yt = "/api/sdk/v1/db/lease/renew";
908
+ en = 10, tn = 6e4, nn = 1e4;
792
909
  });
910
+ var Le = /* @__PURE__ */ new Map(), Ue = 3600 * 1e3;
911
+ function it(n, e = Ue) {
912
+ let t = Date.now(), r = Le.get(n);
913
+ if (r && t - r.createdAt < e)
914
+ return r.jwks;
915
+ let o = createRemoteJWKSet(new URL(n));
916
+ return Le.set(n, { jwks: o, createdAt: t }), o;
917
+ }
918
+ function st() {
919
+ Le.clear();
920
+ }
793
921
 
794
922
  // src/auth.ts
795
- P();
923
+ I();
796
924
 
797
925
  // src/api-key.ts
798
- P();
799
- var et = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
800
- function tt(n) {
926
+ I();
927
+ var at = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
928
+ function ct(n) {
801
929
  if (typeof n != "string" || n.length === 0)
802
930
  throw new c(
803
931
  "invalid_config",
804
932
  "apiKey is required (formato nrt_<keyId>_<secret>)"
805
933
  );
806
- let e = et.exec(n);
934
+ let e = at.exec(n);
807
935
  if (!e)
808
936
  throw new c(
809
937
  "invalid_config",
@@ -811,22 +939,22 @@ function tt(n) {
811
939
  );
812
940
  return { keyId: e[1], secret: e[2] };
813
941
  }
814
- function nt(n) {
942
+ function lt(n) {
815
943
  if (typeof n != "string" || n.length === 0) return null;
816
- let e = et.exec(n);
944
+ let e = at.exec(n);
817
945
  return e ? { keyId: e[1], secret: e[2] } : null;
818
946
  }
819
947
 
820
948
  // src/base-url-allowlist.ts
821
- P();
822
- var rt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), xn = ".neetru.com", On = "neetru.com", Ln = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
823
- function ot(n) {
824
- return Ln.test(n);
949
+ I();
950
+ var dt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), Jn = ".neetru.com", Xn = "neetru.com", Yn = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
951
+ function ut(n) {
952
+ return Yn.test(n);
825
953
  }
826
- function Un(n) {
954
+ function Zn(n) {
827
955
  return n.toLowerCase().replace(/\.+$/, "");
828
956
  }
829
- function it(n, e = []) {
957
+ function pt(n, e = []) {
830
958
  if (typeof n != "string" || n.length === 0)
831
959
  throw new c("invalid_config", "baseUrl is required");
832
960
  let t;
@@ -835,8 +963,8 @@ function it(n, e = []) {
835
963
  } catch {
836
964
  throw new c("invalid_config", `baseUrl is not a valid URL: ${n}`);
837
965
  }
838
- let r = t.protocol, o = Un(t.hostname);
839
- if (Mn())
966
+ let r = t.protocol, o = Zn(t.hostname);
967
+ if (er())
840
968
  return typeof console < "u" && console.warn(
841
969
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${n} aceito sem valida\xE7\xE3o.`
842
970
  ), n.replace(/\/+$/, "");
@@ -846,17 +974,17 @@ function it(n, e = []) {
846
974
  `baseUrl protocol must be http: or https:, got ${r}`
847
975
  );
848
976
  if (r === "http:") {
849
- if (!(rt.has(o) || ot(o)))
977
+ if (!(dt.has(o) || ut(o)))
850
978
  throw new c(
851
979
  "invalid_config",
852
980
  `baseUrl with http: only allowed for localhost/127.0.0.1/*.test/*.localhost. Got: ${o}. Use https: or set NEETRU_ALLOW_INSECURE_BASEURL=1 to bypass.`
853
981
  );
854
982
  return n.replace(/\/+$/, "");
855
983
  }
856
- let i = o === On || o.endsWith(xn), s = e.some((l) => {
984
+ let i = o === Xn || o.endsWith(Jn), s = e.some((l) => {
857
985
  let d = l.toLowerCase();
858
986
  return o === d || o.endsWith(`.${d}`);
859
- }), a = rt.has(o) || ot(o);
987
+ }), a = dt.has(o) || ut(o);
860
988
  if (!i && !s && !a)
861
989
  throw new c(
862
990
  "invalid_config",
@@ -864,7 +992,7 @@ function it(n, e = []) {
864
992
  );
865
993
  return n.replace(/\/+$/, "");
866
994
  }
867
- function Mn() {
995
+ function er() {
868
996
  try {
869
997
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
870
998
  if (e === "1" || e === "true") return !0;
@@ -879,12 +1007,12 @@ function Mn() {
879
1007
  }
880
1008
 
881
1009
  // src/types.ts
882
- var st = "https://api.neetru.com", at = "http://localhost:9003";
1010
+ var ft = "https://api.neetru.com", mt = "http://localhost:9003";
883
1011
 
884
1012
  // src/catalog.ts
885
- P();
886
- U();
887
- function gt(n) {
1013
+ I();
1014
+ M();
1015
+ function At(n) {
888
1016
  if (!n || typeof n != "object")
889
1017
  throw new c("invalid_response", "Catalog response item is not an object");
890
1018
  let e = n;
@@ -903,7 +1031,7 @@ function gt(n) {
903
1031
  return typeof r.amountCents == "number" && (o.amountCents = r.amountCents), Array.isArray(r.features) && r.features.every((i) => typeof i == "string") && (o.features = r.features), o;
904
1032
  })), t;
905
1033
  }
906
- function yt(n) {
1034
+ function Et(n) {
907
1035
  return {
908
1036
  /**
909
1037
  * Lista produtos publicados. Por default só `published=true`; staff
@@ -920,7 +1048,7 @@ function yt(n) {
920
1048
  "Catalog list response missing products array"
921
1049
  );
922
1050
  return {
923
- products: t.products.map(gt),
1051
+ products: t.products.map(At),
924
1052
  fetchedAt: typeof t.fetchedAt == "string" ? t.fetchedAt : (/* @__PURE__ */ new Date()).toISOString()
925
1053
  };
926
1054
  },
@@ -941,32 +1069,32 @@ function yt(n) {
941
1069
  "invalid_response",
942
1070
  "Catalog get response missing product"
943
1071
  );
944
- return gt(t.product);
1072
+ return At(t.product);
945
1073
  }
946
1074
  };
947
1075
  }
948
1076
 
949
1077
  // src/entitlements.ts
950
- P();
951
- var Hn = "client.entitlements.check()/checkDetailed() est\xE3o DEPRECADOS \u2014 apontavam para GET /api/v1/sdk/entitlements/check, um endpoint que o Core nunca escreve (sempre retornava not_subscribed). Use client.usage.check(resource, { productId, tenantId }) no lugar \u2014 mesmo resultado (allowed/reason/remaining/limit/behavior), endpoint real.";
952
- function _t() {
953
- throw new c("validation_failed", Hn);
1078
+ I();
1079
+ var mr = "client.entitlements.check()/checkDetailed() est\xE3o DEPRECADOS \u2014 apontavam para GET /api/v1/sdk/entitlements/check, um endpoint que o Core nunca escreve (sempre retornava not_subscribed). Use client.usage.check(resource, { productId, tenantId }) no lugar \u2014 mesmo resultado (allowed/reason/remaining/limit/behavior), endpoint real.";
1080
+ function Pt() {
1081
+ throw new c("validation_failed", mr);
954
1082
  }
955
- function bt(n) {
1083
+ function Dt(n) {
956
1084
  return {
957
1085
  /**
958
1086
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
959
1087
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
960
1088
  */
961
1089
  async check(e, t, r) {
962
- _t();
1090
+ Pt();
963
1091
  },
964
1092
  /**
965
1093
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
966
1094
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
967
1095
  */
968
1096
  async checkDetailed(e, t, r) {
969
- _t();
1097
+ Pt();
970
1098
  },
971
1099
  /** Test helper legado — no-op (não há mais cache). Mantido por compat. */
972
1100
  __resetCache() {
@@ -975,16 +1103,16 @@ function bt(n) {
975
1103
  }
976
1104
 
977
1105
  // src/telemetry.ts
978
- P();
979
- U();
980
- var vt = ["debug", "info", "warn", "error", "fatal"];
981
- function Qn() {
1106
+ I();
1107
+ M();
1108
+ var Nt = ["debug", "info", "warn", "error", "fatal"];
1109
+ function hr() {
982
1110
  return typeof globalThis < "u" && typeof globalThis.window < "u";
983
1111
  }
984
- function wt() {
985
- return Qn() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1112
+ function xt() {
1113
+ return hr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
986
1114
  }
987
- function Gn(n) {
1115
+ function gr(n) {
988
1116
  switch (n) {
989
1117
  case "debug":
990
1118
  return console.debug.bind(console);
@@ -1000,8 +1128,8 @@ function Gn(n) {
1000
1128
  return console.log.bind(console);
1001
1129
  }
1002
1130
  }
1003
- var Jn = 500, Xn = 50;
1004
- function kt(n) {
1131
+ var yr = 500, _r = 50;
1132
+ function Ot(n) {
1005
1133
  let e = [], t = null, r = null;
1006
1134
  async function o() {
1007
1135
  if (e.length === 0) return;
@@ -1010,7 +1138,7 @@ function kt(n) {
1010
1138
  try {
1011
1139
  let d = { name: l.name }, u = l.productSlug ?? n.productId;
1012
1140
  u && (d.productSlug = u), l.properties && typeof l.properties == "object" && (d.properties = l.properties), l.timestamp && (d.timestamp = l.timestamp);
1013
- let p = wt();
1141
+ let p = xt();
1014
1142
  await v(n, {
1015
1143
  method: "POST",
1016
1144
  path: p.path,
@@ -1034,7 +1162,7 @@ function kt(n) {
1034
1162
  function i() {
1035
1163
  t || (t = setTimeout(() => {
1036
1164
  o();
1037
- }, Jn));
1165
+ }, yr));
1038
1166
  }
1039
1167
  return {
1040
1168
  /**
@@ -1058,7 +1186,7 @@ function kt(n) {
1058
1186
  throw new c("validation_failed", "event.name max 128 chars");
1059
1187
  let a = { name: s.name }, l = s.productSlug ?? n.productId;
1060
1188
  l && (a.productSlug = l), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1061
- let d = wt(), u = await v(n, {
1189
+ let d = xt(), u = await v(n, {
1062
1190
  method: "POST",
1063
1191
  path: d.path,
1064
1192
  body: a,
@@ -1079,7 +1207,7 @@ function kt(n) {
1079
1207
  * ```
1080
1208
  */
1081
1209
  track(s) {
1082
- !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= Xn ? (t && (clearTimeout(t), t = null), o()) : i());
1210
+ !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= _r ? (t && (clearTimeout(t), t = null), o()) : i());
1083
1211
  },
1084
1212
  /**
1085
1213
  * Força flush imediato da queue de `track()`. Resolva antes de
@@ -1106,14 +1234,14 @@ function kt(n) {
1106
1234
  async log(s) {
1107
1235
  if (!s || typeof s != "object")
1108
1236
  throw new c("validation_failed", "log input is required");
1109
- if (!vt.includes(s.level))
1110
- throw new c("validation_failed", `level must be one of ${vt.join(", ")}`);
1237
+ if (!Nt.includes(s.level))
1238
+ throw new c("validation_failed", `level must be one of ${Nt.join(", ")}`);
1111
1239
  if (typeof s.message != "string" || s.message.length === 0)
1112
1240
  throw new c("validation_failed", "message is required");
1113
1241
  if (s.message.length > 4e3)
1114
1242
  throw new c("validation_failed", "message max 4000 chars");
1115
1243
  if (n.env === "dev")
1116
- return Gn(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1244
+ return gr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1117
1245
  let a = {
1118
1246
  level: s.level,
1119
1247
  message: s.message
@@ -1149,22 +1277,22 @@ function kt(n) {
1149
1277
  }
1150
1278
 
1151
1279
  // src/usage.ts
1152
- P();
1153
- U();
1280
+ I();
1281
+ M();
1154
1282
 
1155
1283
  // src/validators.ts
1156
- P();
1157
- var St = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1158
- function x(n, e) {
1159
- if (typeof e != "string" || !St.test(e))
1284
+ I();
1285
+ var Lt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1286
+ function N(n, e) {
1287
+ if (typeof e != "string" || !Lt.test(e))
1160
1288
  throw new c(
1161
1289
  "validation_failed",
1162
- `${n} must match ${St.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1290
+ `${n} must match ${Lt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1163
1291
  );
1164
1292
  }
1165
1293
 
1166
1294
  // src/usage.ts
1167
- function Tt(n) {
1295
+ function Ut(n) {
1168
1296
  return {
1169
1297
  /**
1170
1298
  * Reporta consumo metered de um resource. Hit no endpoint canônico
@@ -1194,7 +1322,7 @@ function Tt(n) {
1194
1322
  "validation_failed",
1195
1323
  "tenantId required (pass to options or set on createNeetruClient)"
1196
1324
  );
1197
- x("productId", o), x("tenantId", i);
1325
+ N("productId", o), N("tenantId", i);
1198
1326
  let s = await v(n, {
1199
1327
  method: "POST",
1200
1328
  path: "/api/sdk/v1/usage/record",
@@ -1228,7 +1356,7 @@ function Tt(n) {
1228
1356
  "validation_failed",
1229
1357
  "productId and tenantId required (pass to options or set on createNeetruClient)"
1230
1358
  );
1231
- x("productId", r), x("tenantId", o);
1359
+ N("productId", r), N("tenantId", o);
1232
1360
  let i = await v(n, {
1233
1361
  method: "GET",
1234
1362
  path: "/api/sdk/v1/entitlements",
@@ -1252,10 +1380,10 @@ function Tt(n) {
1252
1380
  }
1253
1381
 
1254
1382
  // src/support.ts
1255
- P();
1256
- U();
1257
- var Oe = ["low", "normal", "high", "urgent"], Yn = ["open", "pending", "resolved", "closed"], Rt = 50;
1258
- function It(n) {
1383
+ I();
1384
+ M();
1385
+ var je = ["low", "normal", "high", "urgent"], br = ["open", "pending", "resolved", "closed"], Mt = 50;
1386
+ function qt(n) {
1259
1387
  if (!n || typeof n != "object")
1260
1388
  throw new c("invalid_response", "Ticket response is not an object");
1261
1389
  let e = n;
@@ -1266,8 +1394,8 @@ function It(n) {
1266
1394
  id: e.id,
1267
1395
  subject: typeof e.subject == "string" ? e.subject : "",
1268
1396
  message: typeof e.message == "string" ? e.message : "",
1269
- severity: Oe.includes(e.severity) ? e.severity : "normal",
1270
- status: Yn.includes(e.status) ? e.status : "open",
1397
+ severity: je.includes(e.severity) ? e.severity : "normal",
1398
+ status: br.includes(e.status) ? e.status : "open",
1271
1399
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
1272
1400
  updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : void 0,
1273
1401
  productSlug: typeof e.productId == "string" ? e.productId : typeof e.productSlug == "string" ? e.productSlug : void 0,
@@ -1285,60 +1413,63 @@ function It(n) {
1285
1413
  satisfactionComment: typeof e.satisfactionComment == "string" ? e.satisfactionComment : null
1286
1414
  };
1287
1415
  }
1288
- function ae(n) {
1416
+ function de(n) {
1289
1417
  if (!n || typeof n != "string")
1290
1418
  throw new c("validation_failed", "ticketId is required");
1291
1419
  }
1292
- function Ct(n) {
1420
+ function Ft(n) {
1293
1421
  if (typeof n == "string" && n.length > 2e3)
1294
1422
  throw new c("validation_failed", "comment max 2000 chars");
1295
1423
  }
1296
- function At(n, ...e) {
1424
+ function jt(n, ...e) {
1297
1425
  for (let t of e)
1298
1426
  if (typeof t == "string" && t.length > 0)
1299
- return x("productSlug", t), t;
1427
+ return N("productSlug", t), t;
1300
1428
  if (n.productId)
1301
- return x("productId", n.productId), n.productId;
1429
+ return N("productId", n.productId), n.productId;
1302
1430
  throw new c(
1303
1431
  "validation_failed",
1304
1432
  "productId required (pass to input.productSlug or set on createNeetruClient)"
1305
1433
  );
1306
1434
  }
1307
- var Zn = "X-Neetru-End-User-Token", er = "Esta opera\xE7\xE3o de suporte exige um usu\xE1rio final logado: o Core s\xF3 mostra/altera os tickets do pr\xF3prio usu\xE1rio (header X-Neetru-End-User-Token com o id_token OIDC). Fa\xE7a login com client.auth.signIn() e tente de novo.", tr = "O Core exige a identidade do usu\xE1rio final para esta opera\xE7\xE3o (403 end_user_token_required) e nenhum id_token foi aceito. Fa\xE7a login com client.auth.signIn() e tente de novo.", nr = "O Core recusou o token do usu\xE1rio final (401 invalid_end_user_token \u2014 sess\xE3o expirada, usu\xE1rio inativo ou token que n\xE3o \xE9 id_token) e a renova\xE7\xE3o autom\xE1tica n\xE3o resolveu. Fa\xE7a login novamente com client.auth.signIn() e tente de novo.", rr = "O id_token do usu\xE1rio final foi emitido para o client OIDC de OUTRO produto (403 end_user_token_product_mismatch). Confira se o login (client.auth / clientId OIDC) e a apiKey/productId do createNeetruClient s\xE3o do MESMO produto.";
1308
- function Pt(n) {
1435
+ var vr = "X-Neetru-End-User-Token", wr = "Esta opera\xE7\xE3o de suporte exige um usu\xE1rio final logado: o Core s\xF3 mostra/altera os tickets do pr\xF3prio usu\xE1rio (header X-Neetru-End-User-Token com o id_token OIDC). Fa\xE7a login com client.auth.signIn() e tente de novo.", kr = "O Core exige a identidade do usu\xE1rio final para esta opera\xE7\xE3o (403 end_user_token_required) e nenhum id_token foi aceito. Fa\xE7a login com client.auth.signIn() e tente de novo.", Sr = "O Core recusou o token do usu\xE1rio final (401 invalid_end_user_token \u2014 sess\xE3o expirada, usu\xE1rio inativo ou token que n\xE3o \xE9 id_token) e a renova\xE7\xE3o autom\xE1tica n\xE3o resolveu. Fa\xE7a login novamente com client.auth.signIn() e tente de novo.", Tr = "O id_token do usu\xE1rio final foi emitido para o client OIDC de OUTRO produto (403 end_user_token_product_mismatch). Confira se o login (client.auth / clientId OIDC) e a apiKey/productId do createNeetruClient s\xE3o do MESMO produto.";
1436
+ function $t(n) {
1309
1437
  if (n instanceof c && !(n instanceof V)) {
1310
1438
  if (n.code === "end_user_token_required")
1311
1439
  throw new V(
1312
- tr,
1440
+ kr,
1313
1441
  "end_user_token_required",
1314
1442
  n.status,
1315
- n.requestId
1443
+ n.requestId,
1444
+ n.correlationId
1316
1445
  );
1317
1446
  if (n.code === "invalid_end_user_token")
1318
1447
  throw new V(
1319
- nr,
1448
+ Sr,
1320
1449
  "invalid_end_user_token",
1321
1450
  n.status,
1322
- n.requestId
1451
+ n.requestId,
1452
+ n.correlationId
1323
1453
  );
1324
1454
  if (n.code === "end_user_token_product_mismatch")
1325
1455
  throw new c(
1326
1456
  "forbidden",
1327
- rr,
1457
+ Tr,
1328
1458
  n.status,
1329
1459
  n.requestId,
1330
- "end_user_token_product_mismatch"
1460
+ "end_user_token_product_mismatch",
1461
+ n.correlationId
1331
1462
  );
1332
1463
  }
1333
1464
  throw n;
1334
1465
  }
1335
- function or(n) {
1466
+ function Rr(n) {
1336
1467
  return n instanceof c && n.code === "invalid_end_user_token";
1337
1468
  }
1338
- function Et(n, e = {}) {
1339
- function t() {
1469
+ function Wt(n, e = {}) {
1470
+ async function t() {
1340
1471
  try {
1341
- let a = e.getEndUserToken?.();
1472
+ let a = await e.getEndUserToken?.();
1342
1473
  return typeof a == "string" && a.length > 0 ? a : null;
1343
1474
  } catch {
1344
1475
  return null;
@@ -1353,25 +1484,25 @@ function Et(n, e = {}) {
1353
1484
  }
1354
1485
  }
1355
1486
  function o(a) {
1356
- return a ? { [Zn]: a } : {};
1487
+ return a ? { [vr]: a } : {};
1357
1488
  }
1358
1489
  async function i(a, l) {
1359
- let d = t();
1360
- if (!d && a && await r() && (d = t()), !d && a)
1361
- throw new V(er, "no_signed_in_user");
1490
+ let d = await t();
1491
+ if (!d && a && await r() && (d = await t()), !d && a)
1492
+ throw new V(wr, "no_signed_in_user");
1362
1493
  try {
1363
1494
  return await l(o(d));
1364
1495
  } catch (u) {
1365
- if (d && or(u) && await r()) {
1366
- let p = t();
1496
+ if (d && Rr(u) && await r()) {
1497
+ let p = await t();
1367
1498
  if (p)
1368
1499
  try {
1369
1500
  return await l(o(p));
1370
1501
  } catch (f) {
1371
- Pt(f);
1502
+ $t(f);
1372
1503
  }
1373
1504
  }
1374
- Pt(u);
1505
+ $t(u);
1375
1506
  }
1376
1507
  }
1377
1508
  async function s(a, l = {}) {
@@ -1404,13 +1535,13 @@ function Et(n, e = {}) {
1404
1535
  throw new c("validation_failed", "message is required");
1405
1536
  if (a.message.length > 1e4)
1406
1537
  throw new c("validation_failed", "message max 10000 chars");
1407
- if (a.severity && !Oe.includes(a.severity))
1538
+ if (a.severity && !je.includes(a.severity))
1408
1539
  throw new c(
1409
1540
  "validation_failed",
1410
- `severity must be one of ${Oe.join(", ")}`
1541
+ `severity must be one of ${je.join(", ")}`
1411
1542
  );
1412
1543
  let d = {
1413
- productId: At(n, a.productSlug),
1544
+ productId: jt(n, a.productSlug),
1414
1545
  subject: a.subject,
1415
1546
  message: a.message,
1416
1547
  severity: a.severity ?? "normal"
@@ -1427,7 +1558,7 @@ function Et(n, e = {}) {
1427
1558
  headers: f
1428
1559
  })
1429
1560
  ), p = u && typeof u == "object" && "ticket" in u ? u.ticket : u;
1430
- return It(p);
1561
+ return qt(p);
1431
1562
  },
1432
1563
  /**
1433
1564
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
@@ -1435,11 +1566,11 @@ function Et(n, e = {}) {
1435
1566
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
1436
1567
  */
1437
1568
  async listMyTickets(a) {
1438
- let l = At(n, a?.productSlug), d = a?.limit;
1439
- if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Rt))
1569
+ let l = jt(n, a?.productSlug), d = a?.limit;
1570
+ if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Mt))
1440
1571
  throw new c(
1441
1572
  "validation_failed",
1442
- `limit must be an integer 1-${Rt} (Core default 20)`
1573
+ `limit must be an integer 1-${Mt} (Core default 20)`
1443
1574
  );
1444
1575
  let u = await i(
1445
1576
  true,
@@ -1451,7 +1582,7 @@ function Et(n, e = {}) {
1451
1582
  headers: f
1452
1583
  })
1453
1584
  );
1454
- return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(It);
1585
+ return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(qt);
1455
1586
  },
1456
1587
  /**
1457
1588
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
@@ -1459,7 +1590,7 @@ function Et(n, e = {}) {
1459
1590
  * `POST /api/sdk/v1/support/tickets/{id}/resolved-seen`.
1460
1591
  */
1461
1592
  async markResolvedSeen(a) {
1462
- ae(a), await s(
1593
+ de(a), await s(
1463
1594
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/resolved-seen`
1464
1595
  );
1465
1596
  },
@@ -1470,7 +1601,7 @@ function Et(n, e = {}) {
1470
1601
  * `POST /api/sdk/v1/support/tickets/{id}/satisfaction-attempt`.
1471
1602
  */
1472
1603
  async recordSatisfactionAttempt(a) {
1473
- ae(a), await s(
1604
+ de(a), await s(
1474
1605
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/satisfaction-attempt`,
1475
1606
  // Incrementa satisfactionAttempts += 1 no Core — sem idempotencyKey,
1476
1607
  // um retry de rede infla o contador (mesmo padrão de createTicket acima).
@@ -1484,9 +1615,9 @@ function Et(n, e = {}) {
1484
1615
  async submitSatisfaction(a) {
1485
1616
  if (!a || typeof a != "object")
1486
1617
  throw new c("validation_failed", "input is required");
1487
- if (ae(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1618
+ if (de(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1488
1619
  throw new c("validation_failed", "rating must be an integer 1-5 or null");
1489
- Ct(a.comment), await s(
1620
+ Ft(a.comment), await s(
1490
1621
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a.ticketId)}/satisfaction`,
1491
1622
  {
1492
1623
  body: {
@@ -1503,7 +1634,7 @@ function Et(n, e = {}) {
1503
1634
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
1504
1635
  */
1505
1636
  async contestTicket(a, l) {
1506
- ae(a), Ct(l?.comment), await s(
1637
+ de(a), Ft(l?.comment), await s(
1507
1638
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/contest`,
1508
1639
  { body: { comment: l?.comment ?? void 0 } }
1509
1640
  );
@@ -1512,14 +1643,14 @@ function Et(n, e = {}) {
1512
1643
  }
1513
1644
 
1514
1645
  // src/db/client-db.ts
1515
- Y();
1646
+ Z();
1516
1647
 
1517
1648
  // src/db/offline/query-engine.ts
1518
- function Dt(n) {
1649
+ function Bt(n) {
1519
1650
  return n == null ? 0 : typeof n == "number" ? 1 : typeof n == "string" ? 2 : typeof n == "boolean" ? 3 : 4;
1520
1651
  }
1521
- function Z(n, e) {
1522
- let t = Dt(n), r = Dt(e);
1652
+ function ee(n, e) {
1653
+ let t = Bt(n), r = Bt(e);
1523
1654
  if (t !== r) return t - r;
1524
1655
  if (n == null) return 0;
1525
1656
  if (typeof n == "number" && typeof e == "number") return n - e;
@@ -1528,7 +1659,7 @@ function Z(n, e) {
1528
1659
  let o = String(n), i = String(e);
1529
1660
  return o < i ? -1 : o > i ? 1 : 0;
1530
1661
  }
1531
- function Le(n, e) {
1662
+ function $e(n, e) {
1532
1663
  let t = e.split("."), r = n;
1533
1664
  for (let o of t) {
1534
1665
  if (r == null || typeof r != "object")
@@ -1537,8 +1668,8 @@ function Le(n, e) {
1537
1668
  }
1538
1669
  return r;
1539
1670
  }
1540
- function sr(n, e) {
1541
- let t = Le(n, e.field);
1671
+ function Cr(n, e) {
1672
+ let t = $e(n, e.field);
1542
1673
  if (t === void 0) return false;
1543
1674
  let { op: r, value: o } = e;
1544
1675
  switch (r) {
@@ -1547,13 +1678,13 @@ function sr(n, e) {
1547
1678
  case "!=":
1548
1679
  return t !== o;
1549
1680
  case "<":
1550
- return Z(t, o) < 0;
1681
+ return ee(t, o) < 0;
1551
1682
  case "<=":
1552
- return Z(t, o) <= 0;
1683
+ return ee(t, o) <= 0;
1553
1684
  case ">":
1554
- return Z(t, o) > 0;
1685
+ return ee(t, o) > 0;
1555
1686
  case ">=":
1556
- return Z(t, o) >= 0;
1687
+ return ee(t, o) >= 0;
1557
1688
  case "array-contains":
1558
1689
  return Array.isArray(t) && t.includes(o);
1559
1690
  case "in":
@@ -1568,24 +1699,24 @@ function sr(n, e) {
1568
1699
  );
1569
1700
  }
1570
1701
  }
1571
- function ar(n, e) {
1572
- return e.every((t) => sr(n, t));
1702
+ function Ar(n, e) {
1703
+ return e.every((t) => Cr(n, t));
1573
1704
  }
1574
- function cr(n) {
1705
+ function Er(n) {
1575
1706
  return (e, t) => {
1576
1707
  if (n) {
1577
- let r = Le(e.data, n.field), o = Le(t.data, n.field), i = Z(r, o);
1708
+ let r = $e(e.data, n.field), o = $e(t.data, n.field), i = ee(r, o);
1578
1709
  if (i !== 0)
1579
1710
  return n.direction === "desc" ? -i : i;
1580
1711
  }
1581
1712
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
1582
1713
  };
1583
1714
  }
1584
- function lr(n, e) {
1715
+ function Pr(n, e) {
1585
1716
  let t = n.findIndex((r) => r.id === e.docId);
1586
1717
  return t === -1 ? n : e.type === "startAfter" ? n.slice(t + 1) : n.slice(0, t);
1587
1718
  }
1588
- var K = class n {
1719
+ var z = class n {
1589
1720
  /**
1590
1721
  * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
1591
1722
  *
@@ -1599,9 +1730,9 @@ var K = class n {
1599
1730
  evaluate(e, t) {
1600
1731
  let r = e.filter((u) => !u.meta.deleted), o = t.where ?? [];
1601
1732
  o.length > 0 && (r = r.filter(
1602
- (u) => ar(u.data, o)
1733
+ (u) => Ar(u.data, o)
1603
1734
  ));
1604
- let i = cr(t.orderBy), s = [...r].sort(i), a = t.cursor ? lr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1735
+ let i = Er(t.orderBy), s = [...r].sort(i), a = t.cursor ? Pr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1605
1736
  return {
1606
1737
  docs: a.slice(0, l).map((u) => ({ id: u.id, data: u.data })),
1607
1738
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
@@ -1621,7 +1752,7 @@ var K = class n {
1621
1752
  };
1622
1753
 
1623
1754
  // src/db/offline/local-store.ts
1624
- var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_meta", H = "conflict_log", le = class {
1755
+ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_meta", H = "conflict_log", pe = class {
1625
1756
  db = null;
1626
1757
  dbName;
1627
1758
  constructor(e) {
@@ -1633,21 +1764,21 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1633
1764
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
1634
1765
  */
1635
1766
  async open() {
1636
- this.db === null && (this.db = await openDB(this.dbName, ur, {
1767
+ this.db === null && (this.db = await openDB(this.dbName, Nr, {
1637
1768
  upgrade(e) {
1638
- if (!e.objectStoreNames.contains(j)) {
1639
- let t = e.createObjectStore(j, {
1769
+ if (!e.objectStoreNames.contains(W)) {
1770
+ let t = e.createObjectStore(W, {
1640
1771
  keyPath: ["collection", "id"]
1641
1772
  });
1642
1773
  t.createIndex("by_collection", "collection"), t.createIndex("by_collection_state", ["collection", "meta.state"]), t.createIndex("by_updatedAtServer", "meta.updatedAtServer");
1643
1774
  }
1644
- if (!e.objectStoreNames.contains(W)) {
1645
- let t = e.createObjectStore(W, {
1775
+ if (!e.objectStoreNames.contains(B)) {
1776
+ let t = e.createObjectStore(B, {
1646
1777
  keyPath: "mutationId"
1647
1778
  });
1648
1779
  t.createIndex("by_seq", "seq"), t.createIndex("by_status", "status"), t.createIndex("by_doc", ["collection", "docId"]), t.createIndex("by_batch", "batchId");
1649
1780
  }
1650
- if (e.objectStoreNames.contains(ee) || e.createObjectStore(ee, { keyPath: "queryHash" }), e.objectStoreNames.contains(ce) || e.createObjectStore(ce, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1781
+ if (e.objectStoreNames.contains(te) || e.createObjectStore(te, { keyPath: "queryHash" }), e.objectStoreNames.contains(ue) || e.createObjectStore(ue, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1651
1782
  let t = e.createObjectStore(H, {
1652
1783
  keyPath: "id",
1653
1784
  autoIncrement: true
@@ -1690,14 +1821,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1690
1821
  * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
1691
1822
  */
1692
1823
  async getDoc(e, t) {
1693
- return await this.assertOpen().get(j, [e, t]) ?? null;
1824
+ return await this.assertOpen().get(W, [e, t]) ?? null;
1694
1825
  }
1695
1826
  /**
1696
1827
  * Insere ou atualiza um documento na store `documents`.
1697
1828
  * O documento é identificado pelo keyPath composto `[collection, id]`.
1698
1829
  */
1699
1830
  async putDoc(e) {
1700
- await this.assertOpen().put(j, e);
1831
+ await this.assertOpen().put(W, e);
1701
1832
  }
1702
1833
  /**
1703
1834
  * Marca um documento como tombstone (`deleted: true`).
@@ -1705,8 +1836,8 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1705
1836
  * No-op se o documento não existir.
1706
1837
  */
1707
1838
  async deleteDoc(e, t) {
1708
- let r = this.assertOpen(), o = await r.get(j, [e, t]);
1709
- o && await r.put(j, {
1839
+ let r = this.assertOpen(), o = await r.get(W, [e, t]);
1840
+ o && await r.put(W, {
1710
1841
  ...o,
1711
1842
  meta: {
1712
1843
  ...o.meta,
@@ -1722,8 +1853,8 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1722
1853
  * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
1723
1854
  */
1724
1855
  async listDocs(e, t) {
1725
- let o = await this.assertOpen().getAllFromIndex(j, "by_collection", e);
1726
- return K.evaluate(o, t);
1856
+ let o = await this.assertOpen().getAllFromIndex(W, "by_collection", e);
1857
+ return z.evaluate(o, t);
1727
1858
  }
1728
1859
  // ─── Sync meta (key-value) ──────────────────────────────────────────────────
1729
1860
  /**
@@ -1734,14 +1865,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1734
1865
  * 'lastFullResyncAt', 'leaderTabId'.
1735
1866
  */
1736
1867
  async getMeta(e) {
1737
- let r = await this.assertOpen().get(ce, e);
1868
+ let r = await this.assertOpen().get(ue, e);
1738
1869
  return r ? r.value : null;
1739
1870
  }
1740
1871
  /**
1741
1872
  * Armazena ou atualiza um valor na store `sync_meta`.
1742
1873
  */
1743
1874
  async setMeta(e, t) {
1744
- await this.assertOpen().put(ce, { key: e, value: t });
1875
+ await this.assertOpen().put(ue, { key: e, value: t });
1745
1876
  }
1746
1877
  // ─── Conflict log ───────────────────────────────────────────────────────────
1747
1878
  /**
@@ -1773,13 +1904,13 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1773
1904
  * Key: `mutationId`.
1774
1905
  */
1775
1906
  async putMutation(e) {
1776
- await this.assertOpen().put(W, e);
1907
+ await this.assertOpen().put(B, e);
1777
1908
  }
1778
1909
  /**
1779
1910
  * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
1780
1911
  */
1781
1912
  async getMutation(e) {
1782
- return await this.assertOpen().get(W, e) ?? null;
1913
+ return await this.assertOpen().get(B, e) ?? null;
1783
1914
  }
1784
1915
  /**
1785
1916
  * Lista mutações com filtros opcionais.
@@ -1787,14 +1918,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1787
1918
  */
1788
1919
  async listMutations(e) {
1789
1920
  let t = this.assertOpen(), r;
1790
- return e?.status !== void 0 ? r = await t.getAllFromIndex(W, "by_status", e.status) : e?.collection !== void 0 && e.docId !== void 0 ? r = await t.getAllFromIndex(W, "by_doc", [e.collection, e.docId]) : r = await t.getAllFromIndex(W, "by_seq"), r.sort((o, i) => o.seq - i.seq);
1921
+ return e?.status !== void 0 ? r = await t.getAllFromIndex(B, "by_status", e.status) : e?.collection !== void 0 && e.docId !== void 0 ? r = await t.getAllFromIndex(B, "by_doc", [e.collection, e.docId]) : r = await t.getAllFromIndex(B, "by_seq"), r.sort((o, i) => o.seq - i.seq);
1791
1922
  }
1792
1923
  /**
1793
1924
  * Remove uma mutação pelo `mutationId`.
1794
1925
  * No-op se não existir.
1795
1926
  */
1796
1927
  async deleteMutation(e) {
1797
- await this.assertOpen().delete(W, e);
1928
+ await this.assertOpen().delete(B, e);
1798
1929
  }
1799
1930
  // ─── Collection discovery ────────────────────────────────────────────────────
1800
1931
  /**
@@ -1807,7 +1938,7 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1807
1938
  * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
1808
1939
  */
1809
1940
  async listCollections() {
1810
- let t = await this.assertOpen().getAllFromIndex(j, "by_collection"), r = /* @__PURE__ */ new Set();
1941
+ let t = await this.assertOpen().getAllFromIndex(W, "by_collection"), r = /* @__PURE__ */ new Set();
1811
1942
  for (let o of t)
1812
1943
  r.add(o.collection);
1813
1944
  return Array.from(r);
@@ -1817,24 +1948,24 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1817
1948
  * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
1818
1949
  */
1819
1950
  async getQueryCache(e) {
1820
- return await this.assertOpen().get(ee, e) ?? null;
1951
+ return await this.assertOpen().get(te, e) ?? null;
1821
1952
  }
1822
1953
  /**
1823
1954
  * Insere ou atualiza uma entrada de `query_cache`.
1824
1955
  */
1825
1956
  async putQueryCache(e) {
1826
- await this.assertOpen().put(ee, e);
1957
+ await this.assertOpen().put(te, e);
1827
1958
  }
1828
1959
  /**
1829
1960
  * Remove uma entrada de `query_cache` pelo queryHash.
1830
1961
  */
1831
1962
  async deleteQueryCache(e) {
1832
- await this.assertOpen().delete(ee, e);
1963
+ await this.assertOpen().delete(te, e);
1833
1964
  }
1834
1965
  };
1835
1966
 
1836
1967
  // src/db/offline/memory-store.ts
1837
- var de = class {
1968
+ var fe = class {
1838
1969
  // store `documents` — key: `${collection}\0${id}`
1839
1970
  _docs = /* @__PURE__ */ new Map();
1840
1971
  // store `mutations` — key: mutationId
@@ -1882,7 +2013,7 @@ var de = class {
1882
2013
  let r = Array.from(this._docs.values()).filter(
1883
2014
  (o) => o.collection === e
1884
2015
  );
1885
- return K.evaluate(r, t);
2016
+ return z.evaluate(r, t);
1886
2017
  }
1887
2018
  // ─── Sync meta ──────────────────────────────────────────────────────────────
1888
2019
  async getMeta(e) {
@@ -1939,13 +2070,13 @@ var de = class {
1939
2070
  };
1940
2071
 
1941
2072
  // src/db/offline/mutation-queue.ts
1942
- function Ue() {
2073
+ function We() {
1943
2074
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (n) => {
1944
2075
  let e = Math.random() * 16 | 0;
1945
2076
  return (n === "x" ? e : e & 3 | 8).toString(16);
1946
2077
  });
1947
2078
  }
1948
- var ue = class {
2079
+ var me = class {
1949
2080
  store;
1950
2081
  /**
1951
2082
  * Ponteiro de sequência local.
@@ -2041,16 +2172,16 @@ var ue = class {
2041
2172
  * Atômico: a persistência final é uma única operação putMutation.
2042
2173
  */
2043
2174
  async enqueue(e) {
2044
- let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? Ue() : "");
2175
+ let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? We() : "");
2045
2176
  await this.syncSeq();
2046
- let u = (await this.store.listMutations({ collection: t, docId: l })).filter((g) => g.status === "queued").sort((g, _) => _.seq - g.seq)[0];
2177
+ let u = (await this.store.listMutations({ collection: t, docId: l })).filter((h) => h.status === "queued").sort((h, y) => y.seq - h.seq)[0];
2047
2178
  if (u !== void 0) {
2048
- let g = this.tryCoalesce(u, r, o, s, a);
2049
- if (g !== null) {
2050
- if ("removed" in g)
2179
+ let h = this.tryCoalesce(u, r, o, s, a);
2180
+ if (h !== null) {
2181
+ if ("removed" in h)
2051
2182
  return await this.store.deleteMutation(u.mutationId), {
2052
2183
  seq: u.seq,
2053
- mutationId: Ue(),
2184
+ mutationId: We(),
2054
2185
  collection: t,
2055
2186
  docId: l,
2056
2187
  op: "remove",
@@ -2062,13 +2193,13 @@ var ue = class {
2062
2193
  status: "queued",
2063
2194
  batchId: s
2064
2195
  };
2065
- let { coalesced: _ } = g;
2066
- return await this.store.putMutation(_), _;
2196
+ let { coalesced: y } = h;
2197
+ return await this.store.putMutation(y), y;
2067
2198
  }
2068
2199
  }
2069
2200
  let f = {
2070
2201
  seq: this.nextSeq(),
2071
- mutationId: Ue(),
2202
+ mutationId: We(),
2072
2203
  collection: t,
2073
2204
  docId: l,
2074
2205
  op: r,
@@ -2181,45 +2312,45 @@ var ue = class {
2181
2312
  };
2182
2313
 
2183
2314
  // src/db/field-value.ts
2184
- var Nt = "__neetru__";
2315
+ var Vt = "__neetru__";
2185
2316
  function Q(n) {
2186
- return typeof n == "object" && n !== null && Nt in n && typeof n[Nt] == "string";
2317
+ return typeof n == "object" && n !== null && Vt in n && typeof n[Vt] == "string";
2187
2318
  }
2188
- function pr(n) {
2319
+ function xr(n) {
2189
2320
  return Q(n) && n.__neetru__ === "serverTimestamp";
2190
2321
  }
2191
- function fr(n) {
2322
+ function Or(n) {
2192
2323
  return Q(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2193
2324
  }
2194
- function mr(n, e) {
2195
- return pr(n) ? Date.now() : fr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2325
+ function Lr(n, e) {
2326
+ return xr(n) ? Date.now() : Or(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2196
2327
  }
2197
- function z(n, e) {
2328
+ function K(n, e) {
2198
2329
  let t = false, r = {};
2199
2330
  for (let [o, i] of Object.entries(n))
2200
- Q(i) ? (t = true, r[o] = mr(i, e?.[o])) : r[o] = i;
2331
+ Q(i) ? (t = true, r[o] = Lr(i, e?.[o])) : r[o] = i;
2201
2332
  return t ? r : n;
2202
2333
  }
2203
- function Me(n) {
2334
+ function Be(n) {
2204
2335
  for (let e of Object.values(n))
2205
2336
  if (Q(e)) return true;
2206
2337
  return false;
2207
2338
  }
2208
2339
 
2209
2340
  // src/db/offline/sync-engine.ts
2210
- var hr = 8, gr = 1e3, yr = 300 * 1e3, qe = "truncatedCollections";
2211
- function _r(n) {
2212
- return n !== null && Me(n);
2341
+ var Ur = 8, Mr = 1e3, qr = 300 * 1e3, Ve = "truncatedCollections";
2342
+ function Fr(n) {
2343
+ return n !== null && Be(n);
2213
2344
  }
2214
- function br(n) {
2345
+ function jr(n) {
2215
2346
  if (n === null) return null;
2216
- if (!Me(n)) return n;
2347
+ if (!Be(n)) return n;
2217
2348
  let e = {};
2218
2349
  for (let [t, r] of Object.entries(n))
2219
2350
  Q(r) || (e[t] = r);
2220
2351
  return e;
2221
2352
  }
2222
- var pe = class {
2353
+ var he = class {
2223
2354
  _store;
2224
2355
  _queue;
2225
2356
  _resolver;
@@ -2413,13 +2544,13 @@ var pe = class {
2413
2544
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
2414
2545
  return;
2415
2546
  }
2416
- let d = br(i.payload) ?? a?.data ?? {}, u = {
2547
+ let d = jr(i.payload) ?? a?.data ?? {}, u = {
2417
2548
  collection: e,
2418
2549
  id: t,
2419
2550
  data: i.op === "update" ? { ...a?.data ?? {}, ...d } : (
2420
2551
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2421
2552
  // é a fonte de verdade até o pull; senão usa o payload literal.
2422
- _r(i.payload) ? { ...a?.data ?? {}, ...d } : d
2553
+ Fr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2423
2554
  ),
2424
2555
  meta: {
2425
2556
  serverVersion: r,
@@ -2572,7 +2703,7 @@ var pe = class {
2572
2703
  * pending do doc no cache + registra `lastError`/dispara `onError`.
2573
2704
  */
2574
2705
  async _retryOrDeadLetter(e, t, r) {
2575
- if (e.attempts + 1 < hr) {
2706
+ if (e.attempts + 1 < Ur) {
2576
2707
  await this._queue.markRetry(e.mutationId, t);
2577
2708
  return;
2578
2709
  }
@@ -2613,7 +2744,7 @@ var pe = class {
2613
2744
  }
2614
2745
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
2615
2746
  _backoffDelayMs(e) {
2616
- return Math.min(gr * 2 ** (e - 1), yr);
2747
+ return Math.min(Mr * 2 ** (e - 1), qr);
2617
2748
  }
2618
2749
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
2619
2750
  /**
@@ -2646,7 +2777,7 @@ var pe = class {
2646
2777
  let r = [];
2647
2778
  await this._applyServerDocs(t.docs, r, true);
2648
2779
  let o = t.truncatedCollections ?? [], i = new Set(o);
2649
- await this._store.setMeta(qe, o);
2780
+ await this._store.setMeta(Ve, o);
2650
2781
  let s = new Set(
2651
2782
  t.docs.map((a) => `${a.collection}::${a.id}`)
2652
2783
  );
@@ -2865,10 +2996,10 @@ var pe = class {
2865
2996
  };
2866
2997
 
2867
2998
  // src/db/offline/conflict-resolver.ts
2868
- function xt(n, e) {
2999
+ function Kt(n, e) {
2869
3000
  return e === null ? false : n === null ? true : e > n;
2870
3001
  }
2871
- var fe = class n {
3002
+ var ge = class n {
2872
3003
  /**
2873
3004
  * Resolve um conflito com base na operação da mutação (auto-dispatch).
2874
3005
  *
@@ -2902,7 +3033,7 @@ var fe = class n {
2902
3033
  resolvedData: t.data,
2903
3034
  conflictRecord: null
2904
3035
  };
2905
- if (!xt(
3036
+ if (!Kt(
2906
3037
  e.meta.updatedAtServer,
2907
3038
  t.meta.updatedAtServer
2908
3039
  ))
@@ -2949,7 +3080,7 @@ var fe = class n {
2949
3080
  let i = t.data;
2950
3081
  if (e === null)
2951
3082
  return { outcome: "no_conflict", resolvedData: { ...i, ...r.payload ?? {} }, conflictRecord: null };
2952
- if (!xt(
3083
+ if (!Kt(
2953
3084
  e.meta.updatedAtServer,
2954
3085
  t.meta.updatedAtServer
2955
3086
  ))
@@ -3027,10 +3158,10 @@ var fe = class n {
3027
3158
  };
3028
3159
 
3029
3160
  // src/db/offline/change-bus.ts
3030
- function vr(n) {
3161
+ function $r(n) {
3031
3162
  return `${n.collection}::${n.doc.id}`;
3032
3163
  }
3033
- var me = class {
3164
+ var ye = class {
3034
3165
  /** Listeners filtrados por coleção. */
3035
3166
  _collectionListeners = /* @__PURE__ */ new Map();
3036
3167
  /** Listeners globais (todas as coleções). */
@@ -3075,7 +3206,7 @@ var me = class {
3075
3206
  if (e.length === 0) return;
3076
3207
  let t = /* @__PURE__ */ new Map();
3077
3208
  for (let i of e)
3078
- t.set(vr(i), i);
3209
+ t.set($r(i), i);
3079
3210
  let r = Array.from(t.values()), o = /* @__PURE__ */ new Map();
3080
3211
  for (let i of r)
3081
3212
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
@@ -3114,7 +3245,7 @@ var me = class {
3114
3245
  };
3115
3246
 
3116
3247
  // src/db/offline/connectivity-monitor.ts
3117
- var he = class {
3248
+ var _e = class {
3118
3249
  _state;
3119
3250
  _listeners = /* @__PURE__ */ new Set();
3120
3251
  _nav;
@@ -3216,7 +3347,7 @@ var he = class {
3216
3347
  };
3217
3348
 
3218
3349
  // src/db/offline/tab-coordinator.ts
3219
- var te = class {
3350
+ var ne = class {
3220
3351
  _lockName;
3221
3352
  _channelName;
3222
3353
  _lockManager;
@@ -3393,26 +3524,26 @@ var te = class {
3393
3524
  };
3394
3525
 
3395
3526
  // src/db/collection-ref.ts
3396
- Y();
3397
- function wr() {
3527
+ Z();
3528
+ function Wr() {
3398
3529
  return typeof indexedDB > "u" || typeof window > "u";
3399
3530
  }
3400
- var Ot = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3401
- function kr(n) {
3402
- if (!Ot.test(n))
3403
- throw new y(
3531
+ var zt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3532
+ function Br(n) {
3533
+ if (!zt.test(n))
3534
+ throw new b(
3404
3535
  "db_invalid_query",
3405
- `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${Ot}.`
3536
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${zt}.`
3406
3537
  );
3407
3538
  }
3408
3539
  function G(n, e = "id") {
3409
3540
  if (!n || typeof n != "string" || n.trim() === "")
3410
- throw new y(
3541
+ throw new b(
3411
3542
  "db_invalid_query",
3412
3543
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
3413
3544
  );
3414
3545
  }
3415
- function Sr(n) {
3546
+ function Vr(n) {
3416
3547
  let e = {};
3417
3548
  if (n?.where && (e.where = n.where.map((t) => ({
3418
3549
  field: t.field,
@@ -3429,12 +3560,12 @@ function Sr(n) {
3429
3560
  }
3430
3561
  return e;
3431
3562
  }
3432
- function Tr(n, e) {
3563
+ function Kr(n, e) {
3433
3564
  if (n.length < e) return null;
3434
3565
  let t = n[n.length - 1];
3435
3566
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
3436
3567
  }
3437
- var Fe = class {
3568
+ var Ke = class {
3438
3569
  constructor(e, t, r, o, i, s) {
3439
3570
  this._collection = e;
3440
3571
  this._store = t;
@@ -3476,9 +3607,9 @@ var Fe = class {
3476
3607
  }
3477
3608
  /** Constrói um DbListResult para a coleção com query opcional. */
3478
3609
  async _buildListResult(e) {
3479
- let t = Sr(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), l = Tr(o.docs, r), d = await this._store.getMeta(qe), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3610
+ let t = Vr(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), l = Kr(o.docs, r), d = await this._store.getMeta(Ve), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3480
3611
  return {
3481
- docs: o.docs.map((g) => ({ id: g.id, data: g.data })),
3612
+ docs: o.docs.map((h) => ({ id: h.id, data: h.data })),
3482
3613
  nextCursor: l,
3483
3614
  fromCache: f,
3484
3615
  stale: p,
@@ -3495,7 +3626,7 @@ var Fe = class {
3495
3626
  return this._buildListResult(e);
3496
3627
  }
3497
3628
  async add(e) {
3498
- let t = e, r = z(t, void 0), o = await this._queue.enqueue({
3629
+ let t = e, r = K(t, void 0), o = await this._queue.enqueue({
3499
3630
  collection: this._collection,
3500
3631
  op: "add",
3501
3632
  payload: t,
@@ -3523,7 +3654,7 @@ var Fe = class {
3523
3654
  }
3524
3655
  async set(e, t) {
3525
3656
  G(e);
3526
- let r = await this._store.getDoc(this._collection, e), o = t, i = z(o, void 0), s = await this._queue.enqueue({
3657
+ let r = await this._store.getDoc(this._collection, e), o = t, i = K(o, void 0), s = await this._queue.enqueue({
3527
3658
  collection: this._collection,
3528
3659
  docId: e,
3529
3660
  op: "set",
@@ -3552,7 +3683,7 @@ var Fe = class {
3552
3683
  }
3553
3684
  async update(e, t, r) {
3554
3685
  G(e);
3555
- let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = z(i, s), l = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3686
+ let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = K(i, s), l = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3556
3687
  collection: this._collection,
3557
3688
  docId: e,
3558
3689
  op: "update",
@@ -3605,7 +3736,7 @@ var Fe = class {
3605
3736
  for (let o of e) {
3606
3737
  let i = this._collection;
3607
3738
  if (o.kind === "add") {
3608
- let s = o.data, a = z(s, void 0), l = await this._queue.enqueue({
3739
+ let s = o.data, a = K(s, void 0), l = await this._queue.enqueue({
3609
3740
  collection: i,
3610
3741
  op: "add",
3611
3742
  payload: s,
@@ -3627,7 +3758,7 @@ var Fe = class {
3627
3758
  }
3628
3759
  }), r.push({ type: "added", collection: i, doc: { id: d, data: a } });
3629
3760
  } else if (o.kind === "set") {
3630
- let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = z(a, void 0), u = await this._queue.enqueue({
3761
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = K(a, void 0), u = await this._queue.enqueue({
3631
3762
  collection: i,
3632
3763
  docId: s,
3633
3764
  op: "set",
@@ -3654,7 +3785,7 @@ var Fe = class {
3654
3785
  doc: { id: s, data: d }
3655
3786
  });
3656
3787
  } else if (o.kind === "update") {
3657
- let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = l?.meta.deleted ? void 0 : l?.data, u = z(a, d), p = { ...l?.data ?? {}, ...u }, f = await this._queue.enqueue({
3788
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = l?.meta.deleted ? void 0 : l?.data, u = K(a, d), p = { ...l?.data ?? {}, ...u }, f = await this._queue.enqueue({
3658
3789
  collection: i,
3659
3790
  docId: s,
3660
3791
  op: "update",
@@ -3809,7 +3940,7 @@ var Fe = class {
3809
3940
  }
3810
3941
  };
3811
3942
  }
3812
- }, je = class {
3943
+ }, ze = class {
3813
3944
  _store;
3814
3945
  _queue;
3815
3946
  _bus;
@@ -3819,7 +3950,7 @@ var Fe = class {
3819
3950
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3820
3951
  }
3821
3952
  collection(e) {
3822
- return kr(e), new Fe(
3953
+ return Br(e), new Ke(
3823
3954
  e,
3824
3955
  this._store,
3825
3956
  this._queue,
@@ -3848,10 +3979,10 @@ var Fe = class {
3848
3979
  return this._engine.onError(e);
3849
3980
  }
3850
3981
  };
3851
- async function Lt(n) {
3852
- let e = wr() ? new de() : new le(n.dbName);
3982
+ async function Ht(n) {
3983
+ let e = Wr() ? new fe() : new pe(n.dbName);
3853
3984
  await e.open();
3854
- let t = new ue(e), r = new fe(), o = new me(), i = new he({
3985
+ let t = new me(e), r = new ge(), o = new ye(), i = new _e({
3855
3986
  // Se startOnline=false, injeta um navigator falso
3856
3987
  navigator: n.startOnline === false ? { onLine: false } : typeof navigator < "u" ? navigator : void 0
3857
3988
  }), s = n.singleTab ? (
@@ -3861,10 +3992,10 @@ async function Lt(n) {
3861
3992
  onRoleChange: (l) => () => {
3862
3993
  }
3863
3994
  }
3864
- ) : new te({
3995
+ ) : new ne({
3865
3996
  lockName: `neetru-offline:${n.dbName}`,
3866
3997
  channelName: `neetru-offline:${n.dbName}`
3867
- }), a = new pe({
3998
+ }), a = new he({
3868
3999
  store: e,
3869
4000
  queue: t,
3870
4001
  resolver: r,
@@ -3874,7 +4005,7 @@ async function Lt(n) {
3874
4005
  connectivity: i,
3875
4006
  periodicSyncIntervalMs: n.periodicSyncIntervalMs ?? 300 * 1e3
3876
4007
  });
3877
- return i.start(), !n.singleTab && s instanceof te && s.start(), new je({
4008
+ return i.start(), !n.singleTab && s instanceof ne && s.start(), new ze({
3878
4009
  store: e,
3879
4010
  queue: t,
3880
4011
  bus: o,
@@ -3884,11 +4015,11 @@ async function Lt(n) {
3884
4015
  }
3885
4016
 
3886
4017
  // src/db/realtime/realtime-client.ts
3887
- var Rr = 0;
3888
- function Ut() {
3889
- return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++Rr}-${Math.random().toString(36).slice(2)}`;
4018
+ var zr = 0;
4019
+ function Qt() {
4020
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++zr}-${Math.random().toString(36).slice(2)}`;
3890
4021
  }
3891
- var ge = class {
4022
+ var be = class {
3892
4023
  // ── configuração ──────────────────────────────────────────────────────────
3893
4024
  _gatewayUrl;
3894
4025
  _wsFactory;
@@ -3926,7 +4057,7 @@ var ge = class {
3926
4057
  _pendingFrames = [];
3927
4058
  // ── construtor ────────────────────────────────────────────────────────────
3928
4059
  constructor(e) {
3929
- this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? Ir, this._setTimeout = e.setTimeoutFn ?? globalThis.setTimeout.bind(globalThis), this._clearTimeout = e.clearTimeoutFn ?? globalThis.clearTimeout.bind(globalThis), this._backoffBaseMs = e.backoffBaseMs ?? 1e3, this._backoffMaxMs = e.backoffMaxMs ?? 3e4, this._heartbeatIntervalMs = e.heartbeatIntervalMs ?? 25e3, this._ticketProvider = e.ticketProvider, this._dbId = e.dbId, this._connect();
4060
+ this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? Hr, this._setTimeout = e.setTimeoutFn ?? globalThis.setTimeout.bind(globalThis), this._clearTimeout = e.clearTimeoutFn ?? globalThis.clearTimeout.bind(globalThis), this._backoffBaseMs = e.backoffBaseMs ?? 1e3, this._backoffMaxMs = e.backoffMaxMs ?? 3e4, this._heartbeatIntervalMs = e.heartbeatIntervalMs ?? 25e3, this._ticketProvider = e.ticketProvider, this._dbId = e.dbId, this._connect();
3930
4061
  }
3931
4062
  // ── API pública ───────────────────────────────────────────────────────────
3932
4063
  /**
@@ -3940,8 +4071,8 @@ var ge = class {
3940
4071
  */
3941
4072
  subscribe(e, t, r) {
3942
4073
  if (this._closed)
3943
- return Ut();
3944
- let o = Ut();
4074
+ return Qt();
4075
+ let o = Qt();
3945
4076
  this._subscriptions.set(o, {
3946
4077
  subscriptionId: o,
3947
4078
  collection: e,
@@ -4205,7 +4336,7 @@ var ge = class {
4205
4336
  _detachHandlers(e) {
4206
4337
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
4207
4338
  }
4208
- }, Ir = (n) => {
4339
+ }, Hr = (n) => {
4209
4340
  if (typeof WebSocket > "u")
4210
4341
  throw new Error(
4211
4342
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -4214,46 +4345,46 @@ var ge = class {
4214
4345
  };
4215
4346
 
4216
4347
  // src/db/client-db.ts
4217
- var Mr = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, _e = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, Ht = 200;
4218
- function qr(n, e, t) {
4219
- return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? Fr(e.realtimeGatewayUrl, t, e) : Gt(t);
4348
+ var so = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, we = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, an = 200;
4349
+ function ao(n, e, t) {
4350
+ return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? co(e.realtimeGatewayUrl, t, e) : ln(t);
4220
4351
  }
4221
- function Gt(n) {
4352
+ function ln(n) {
4222
4353
  return {
4223
4354
  async pushMutations(e) {
4224
4355
  if (!n)
4225
- throw new y(
4356
+ throw new b(
4226
4357
  "db_unavailable",
4227
4358
  "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
4228
4359
  );
4229
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4360
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4230
4361
  for (let s of e)
4231
4362
  try {
4232
4363
  let a;
4233
4364
  s.op === "add" ? a = await t(n, {
4234
4365
  method: "PUT",
4235
- path: _e(s.collection, s.docId),
4366
+ path: we(s.collection, s.docId),
4236
4367
  body: { data: s.payload ?? {} },
4237
4368
  requireAuth: !0,
4238
4369
  retries: 2,
4239
4370
  headers: i
4240
4371
  }) : s.op === "set" ? a = await t(n, {
4241
4372
  method: "PUT",
4242
- path: _e(s.collection, s.docId),
4373
+ path: we(s.collection, s.docId),
4243
4374
  body: { data: s.payload ?? {} },
4244
4375
  requireAuth: !0,
4245
4376
  retries: 2,
4246
4377
  headers: i
4247
4378
  }) : s.op === "update" ? a = await t(n, {
4248
4379
  method: "PATCH",
4249
- path: _e(s.collection, s.docId),
4380
+ path: we(s.collection, s.docId),
4250
4381
  body: { data: s.payload ?? {}, ...s.upsert ? { upsert: !0 } : {} },
4251
4382
  requireAuth: !0,
4252
4383
  retries: 2,
4253
4384
  headers: i
4254
4385
  }) : a = await t(n, {
4255
4386
  method: "DELETE",
4256
- path: _e(s.collection, s.docId),
4387
+ path: we(s.collection, s.docId),
4257
4388
  requireAuth: !0,
4258
4389
  retries: 2,
4259
4390
  headers: i
@@ -4279,7 +4410,7 @@ function Gt(n) {
4279
4410
  continue;
4280
4411
  }
4281
4412
  if (r.length === 0)
4282
- throw new y("db_unavailable", `pushMutations falhou: ${l}`);
4413
+ throw new b("db_unavailable", `pushMutations falhou: ${l}`);
4283
4414
  break;
4284
4415
  }
4285
4416
  return { results: r };
@@ -4290,13 +4421,13 @@ function Gt(n) {
4290
4421
  async fullResync(e) {
4291
4422
  if (!n)
4292
4423
  return { docs: [], newWatermark: Date.now() };
4293
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4424
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4294
4425
  for (let l of e) {
4295
4426
  let d;
4296
4427
  try {
4297
4428
  d = await t(n, {
4298
4429
  method: "GET",
4299
- path: Mr(l),
4430
+ path: so(l),
4300
4431
  requireAuth: !0,
4301
4432
  retries: 2,
4302
4433
  headers: o,
@@ -4304,37 +4435,37 @@ function Gt(n) {
4304
4435
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
4305
4436
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
4306
4437
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
4307
- query: { limit: Ht }
4438
+ query: { limit: an }
4308
4439
  });
4309
4440
  } catch (f) {
4310
- let g = f instanceof Error ? f.message : String(f);
4311
- throw new y(
4441
+ let h = f instanceof Error ? f.message : String(f);
4442
+ throw new b(
4312
4443
  "db_unavailable",
4313
- `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${g}`
4444
+ `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${h}`
4314
4445
  );
4315
4446
  }
4316
4447
  let u = d, p = Array.isArray(u?.items) ? u.items : [];
4317
- p.length >= Ht && a.push(l);
4448
+ p.length >= an && a.push(l);
4318
4449
  for (let f of p) {
4319
4450
  if (!f || typeof f != "object") continue;
4320
- let g = f, _ = typeof g.id == "string" ? g.id : null;
4321
- if (!_) continue;
4322
- let { id: M, ...R } = g, N = i, C = R._updatedAt;
4323
- if (typeof C == "number")
4324
- N = C;
4325
- else if (C !== null && typeof C == "object" && typeof C._seconds == "number")
4326
- N = C._seconds * 1e3;
4327
- else if (typeof C == "string") {
4328
- let h = Date.parse(C);
4329
- Number.isNaN(h) || (N = h);
4451
+ let h = f, y = typeof h.id == "string" ? h.id : null;
4452
+ if (!y) continue;
4453
+ let { id: S, ...x } = h, T = i, P = x._updatedAt;
4454
+ if (typeof P == "number")
4455
+ T = P;
4456
+ else if (P !== null && typeof P == "object" && typeof P._seconds == "number")
4457
+ T = P._seconds * 1e3;
4458
+ else if (typeof P == "string") {
4459
+ let m = Date.parse(P);
4460
+ Number.isNaN(m) || (T = m);
4330
4461
  }
4331
- let $ = `rest_${_}_${N}`;
4462
+ let q = `rest_${y}_${T}`;
4332
4463
  s.push({
4333
4464
  collection: l,
4334
- id: _,
4335
- data: R,
4336
- serverVersion: $,
4337
- serverTimestamp: N,
4465
+ id: y,
4466
+ data: x,
4467
+ serverVersion: q,
4468
+ serverTimestamp: T,
4338
4469
  deleted: false
4339
4470
  });
4340
4471
  }
@@ -4343,10 +4474,10 @@ function Gt(n) {
4343
4474
  }
4344
4475
  };
4345
4476
  }
4346
- function Fr(n, e, t) {
4347
- let r = Gt(e), o = new ge({
4477
+ function co(n, e, t) {
4478
+ let r = ln(e), o = new be({
4348
4479
  gatewayUrl: n,
4349
- ticketProvider: jr(e, t),
4480
+ ticketProvider: lo(e, t),
4350
4481
  dbId: t.dbId,
4351
4482
  webSocketFactory: t._wsFactory
4352
4483
  });
@@ -4382,9 +4513,9 @@ function Fr(n, e, t) {
4382
4513
  }
4383
4514
  };
4384
4515
  }
4385
- function jr(n, e) {
4516
+ function lo(n, e) {
4386
4517
  return async () => {
4387
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X));
4518
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y));
4388
4519
  return await t(n, {
4389
4520
  method: "POST",
4390
4521
  path: "/api/sdk/v1/db/realtime/ticket",
@@ -4397,21 +4528,21 @@ function jr(n, e) {
4397
4528
  });
4398
4529
  };
4399
4530
  }
4400
- var Qt = false;
4401
- function Wr(n, e) {
4402
- Qt || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (Qt = true, console.warn(
4531
+ var cn = false;
4532
+ function uo(n, e) {
4533
+ cn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (cn = true, console.warn(
4403
4534
  '[neetru/sdk] client.db recebeu `dbId` ("' + e.dbId + '") mas ele N\xC3O roteia nem escopa nada no servidor: as escritas do mundo Documentos (add/set/update/remove/list) SEMPRE caem no datastore gen\xE9rico do Core, escopado s\xF3 por tenant/produto (header x-neetru-tenant). `dbId` apenas nomeia o cache offline LOCAL (IndexedDB). ATEN\xC7\xC3O: usar dbIds distintos no MESMO tenant/produto N\xC3O isola os dados no servidor \u2014 eles se misturam (co-mingling). Veja o JSDoc de NeetruDbOptions.dbId.'
4404
4535
  )));
4405
4536
  }
4406
- function Jt(n, e = {}) {
4407
- Wr(n, e);
4537
+ function dn(n, e = {}) {
4538
+ uo(n, e);
4408
4539
  let t;
4409
4540
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
4410
4541
  '[neetru/sdk] NeetruDbOptions.engine est\xE1 depreciado e ser\xE1 removido em v3.0. Use NeetruDbOptions.transport em vez de engine. Valores v\xE1lidos: "rest" | "firestore" | "nosql-vm". Nota: "engine" no SDK configura o TRANSPORTE (REST/Firestore/WebSocket), n\xE3o o storage engine do admin database (firestore-instance, cloud-sql-postgres, \u2026).'
4411
4542
  ), t = e.engine) : t = "rest";
4412
- let r = qr(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4543
+ let r = ao(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4413
4544
  function l() {
4414
- return s || (s = Lt({
4545
+ return s || (s = Ht({
4415
4546
  dbName: i,
4416
4547
  transport: r,
4417
4548
  singleTab: e.singleTab ?? n.env !== "prod"
@@ -4419,15 +4550,15 @@ function Jt(n, e = {}) {
4419
4550
  }
4420
4551
  return {
4421
4552
  collection(d) {
4422
- return a ? a.collection(d) : $r(d, l);
4553
+ return a ? a.collection(d) : po(d, l);
4423
4554
  },
4424
4555
  async sql(d, u) {
4425
4556
  if (n.env === "dev")
4426
- throw new y(
4557
+ throw new b(
4427
4558
  "db_unavailable",
4428
4559
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4429
4560
  );
4430
- return (await Promise.resolve().then(() => (Kt(), zt))).createSqlClientFromConfig(n, d, u);
4561
+ return (await Promise.resolve().then(() => (sn(), on))).createSqlClientFromConfig(n, d, u);
4431
4562
  },
4432
4563
  get syncState() {
4433
4564
  return a?.syncState ?? {
@@ -4466,7 +4597,7 @@ function Jt(n, e = {}) {
4466
4597
  }
4467
4598
  };
4468
4599
  }
4469
- function $r(n, e) {
4600
+ function po(n, e) {
4470
4601
  async function t() {
4471
4602
  return (await e()).collection(n);
4472
4603
  }
@@ -4545,9 +4676,9 @@ function $r(n, e) {
4545
4676
  }
4546
4677
 
4547
4678
  // src/checkout.ts
4548
- P();
4549
- U();
4550
- function Ke(n, e) {
4679
+ I();
4680
+ M();
4681
+ function Ye(n, e) {
4551
4682
  let t = n?.accessToken || n?.idToken;
4552
4683
  if (!t || typeof t != "string")
4553
4684
  throw new c(
@@ -4556,7 +4687,7 @@ function Ke(n, e) {
4556
4687
  );
4557
4688
  return { requireAuth: false, headers: { authorization: `Bearer ${t}` } };
4558
4689
  }
4559
- function Br(n) {
4690
+ function fo(n) {
4560
4691
  if (!n || typeof n != "object")
4561
4692
  throw new c("invalid_response", "checkout.start response is not an object");
4562
4693
  let e = n;
@@ -4572,7 +4703,7 @@ function Br(n) {
4572
4703
  requiresKyc: e.requiresKyc === true
4573
4704
  };
4574
4705
  }
4575
- function Vr(n) {
4706
+ function mo(n) {
4576
4707
  if (!n || typeof n != "object")
4577
4708
  throw new c("invalid_response", "checkout.get response is not an object");
4578
4709
  let e = n, t = e.intent;
@@ -4594,20 +4725,20 @@ function Vr(n) {
4594
4725
  isStale: e.isStale === true
4595
4726
  };
4596
4727
  }
4597
- function zr() {
4728
+ function ho() {
4598
4729
  try {
4599
4730
  return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
4600
4731
  } catch {
4601
4732
  return false;
4602
4733
  }
4603
4734
  }
4604
- function Kr(n) {
4735
+ function go(n) {
4605
4736
  try {
4606
4737
  globalThis.location.assign(n);
4607
4738
  } catch {
4608
4739
  }
4609
4740
  }
4610
- function Hr(n) {
4741
+ function yo(n) {
4611
4742
  return {
4612
4743
  async start(e) {
4613
4744
  if (!e?.productId)
@@ -4622,7 +4753,7 @@ function Hr(n) {
4622
4753
  callbackUrl: e.callbackUrl
4623
4754
  };
4624
4755
  e.tenantType && (t.targetTenantType = e.tenantType), e.tenantId && (t.targetTenantId = e.tenantId);
4625
- let { requireAuth: r, headers: o } = Ke(
4756
+ let { requireAuth: r, headers: o } = Ye(
4626
4757
  { accessToken: e.accessToken, idToken: e.idToken },
4627
4758
  "start"
4628
4759
  ), i = await v(n, {
@@ -4632,13 +4763,13 @@ function Hr(n) {
4632
4763
  requireAuth: r,
4633
4764
  headers: o,
4634
4765
  idempotencyKey: true
4635
- }), s = Br(i);
4636
- return e.autoRedirect !== false && zr() && Kr(s.redirectUrl), s;
4766
+ }), s = fo(i);
4767
+ return e.autoRedirect !== false && ho() && go(s.redirectUrl), s;
4637
4768
  },
4638
4769
  async get(e, t) {
4639
4770
  if (!e || typeof e != "string")
4640
4771
  throw new c("validation_failed", "checkout.get: intentId is required");
4641
- let { requireAuth: r, headers: o } = Ke(
4772
+ let { requireAuth: r, headers: o } = Ye(
4642
4773
  { accessToken: t?.accessToken, idToken: t?.idToken },
4643
4774
  "get"
4644
4775
  ), i = await v(n, {
@@ -4647,12 +4778,12 @@ function Hr(n) {
4647
4778
  requireAuth: r,
4648
4779
  headers: o
4649
4780
  });
4650
- return Vr(i);
4781
+ return mo(i);
4651
4782
  },
4652
4783
  async cancel(e, t) {
4653
4784
  if (!e || typeof e != "string")
4654
4785
  throw new c("validation_failed", "checkout.cancel: intentId is required");
4655
- let { requireAuth: r, headers: o } = Ke(
4786
+ let { requireAuth: r, headers: o } = Ye(
4656
4787
  { accessToken: t?.accessToken, idToken: t?.idToken },
4657
4788
  "cancel"
4658
4789
  );
@@ -4668,7 +4799,7 @@ function Hr(n) {
4668
4799
  }
4669
4800
  };
4670
4801
  }
4671
- var He = class {
4802
+ var Ze = class {
4672
4803
  intents = /* @__PURE__ */ new Map();
4673
4804
  async start(e) {
4674
4805
  if (!e?.productId)
@@ -4711,14 +4842,14 @@ var He = class {
4711
4842
  return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
4712
4843
  }
4713
4844
  };
4714
- function Xt(n) {
4715
- return n.env === "dev" ? new He() : Hr(n);
4845
+ function un(n) {
4846
+ return n.env === "dev" ? new Ze() : yo(n);
4716
4847
  }
4717
4848
 
4718
4849
  // src/webhooks.ts
4719
- P();
4720
- U();
4721
- var Zt = [
4850
+ I();
4851
+ M();
4852
+ var fn = [
4722
4853
  "subscription.activated",
4723
4854
  "subscription.cancelled",
4724
4855
  "subscription.payment_failed",
@@ -4728,7 +4859,7 @@ var Zt = [
4728
4859
  "account.reactivated",
4729
4860
  "support.ticket_replied"
4730
4861
  ];
4731
- function Yt(n) {
4862
+ function pn(n) {
4732
4863
  if (!n || typeof n != "object")
4733
4864
  throw new c("invalid_response", "Webhook response is not an object");
4734
4865
  let e = n;
@@ -4738,7 +4869,7 @@ function Yt(n) {
4738
4869
  id: e.id,
4739
4870
  url: typeof e.url == "string" ? e.url : "",
4740
4871
  events: Array.isArray(e.events) ? e.events.filter(
4741
- (t) => Zt.includes(t)
4872
+ (t) => fn.includes(t)
4742
4873
  ) : [],
4743
4874
  hasSecret: e.hasSecret === true,
4744
4875
  status: e.status === "active" || e.status === "degraded" || e.status === "disabled" ? e.status : "active",
@@ -4747,7 +4878,7 @@ function Yt(n) {
4747
4878
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString()
4748
4879
  };
4749
4880
  }
4750
- function en(n) {
4881
+ function mn(n) {
4751
4882
  if (!n.url || typeof n.url != "string")
4752
4883
  throw new c("validation_failed", "url \xE9 obrigat\xF3ria");
4753
4884
  try {
@@ -4760,27 +4891,27 @@ function en(n) {
4760
4891
  if (!Array.isArray(n.events) || n.events.length === 0)
4761
4892
  throw new c("validation_failed", "events deve ter pelo menos 1 evento");
4762
4893
  for (let e of n.events)
4763
- if (!Zt.includes(e))
4894
+ if (!fn.includes(e))
4764
4895
  throw new c("validation_failed", `evento desconhecido: ${e}`);
4765
4896
  if (n.secret !== void 0 && n.secret.length < 16)
4766
4897
  throw new c("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4767
4898
  }
4768
- function be(n, ...e) {
4899
+ function ke(n, ...e) {
4769
4900
  for (let t of e)
4770
4901
  if (typeof t == "string" && t.length > 0)
4771
- return x("productId", t), t;
4902
+ return N("productId", t), t;
4772
4903
  if (n.productId)
4773
- return x("productId", n.productId), n.productId;
4904
+ return N("productId", n.productId), n.productId;
4774
4905
  throw new c(
4775
4906
  "validation_failed",
4776
4907
  "productId required (pass to options/input or set on createNeetruClient)"
4777
4908
  );
4778
4909
  }
4779
- function tn(n) {
4910
+ function hn(n) {
4780
4911
  return {
4781
4912
  async register(e) {
4782
- en(e);
4783
- let t = be(n, e.productId), r = await v(n, {
4913
+ mn(e);
4914
+ let t = ke(n, e.productId), r = await v(n, {
4784
4915
  method: "POST",
4785
4916
  path: "/api/sdk/v1/webhooks",
4786
4917
  body: {
@@ -4796,20 +4927,20 @@ function tn(n) {
4796
4927
  // dedup TTL 24h (mesmo padrão de usage.report/support.createTicket).
4797
4928
  idempotencyKey: true
4798
4929
  });
4799
- return Yt(r);
4930
+ return pn(r);
4800
4931
  },
4801
4932
  async list(e) {
4802
- let t = be(n, e?.productId), r = await v(n, {
4933
+ let t = ke(n, e?.productId), r = await v(n, {
4803
4934
  method: "GET",
4804
4935
  path: "/api/sdk/v1/webhooks",
4805
4936
  query: { productId: t },
4806
4937
  requireAuth: true
4807
4938
  });
4808
- return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(Yt);
4939
+ return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(pn);
4809
4940
  },
4810
4941
  async unregister(e, t) {
4811
4942
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4812
- let r = be(n, t?.productId);
4943
+ let r = ke(n, t?.productId);
4813
4944
  return await v(n, {
4814
4945
  method: "DELETE",
4815
4946
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}`,
@@ -4819,7 +4950,7 @@ function tn(n) {
4819
4950
  },
4820
4951
  async test(e, t) {
4821
4952
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4822
- let r = be(n, t?.productId), o = await v(n, {
4953
+ let r = ke(n, t?.productId), o = await v(n, {
4823
4954
  method: "POST",
4824
4955
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}/test`,
4825
4956
  query: { productId: r },
@@ -4838,11 +4969,11 @@ function tn(n) {
4838
4969
  }
4839
4970
  };
4840
4971
  }
4841
- var ve = class {
4972
+ var Se = class {
4842
4973
  endpoints = /* @__PURE__ */ new Map();
4843
4974
  nextId = 1;
4844
4975
  async register(e) {
4845
- en(e);
4976
+ mn(e);
4846
4977
  let t = `mock_wh_${this.nextId++}`, r = {
4847
4978
  id: t,
4848
4979
  url: e.url,
@@ -4869,21 +5000,21 @@ var ve = class {
4869
5000
  };
4870
5001
 
4871
5002
  // src/notifications.ts
4872
- P();
4873
- U();
4874
- var Qe = [
5003
+ I();
5004
+ M();
5005
+ var et = [
4875
5006
  "info",
4876
5007
  "success",
4877
5008
  "warning",
4878
5009
  "error"
4879
5010
  ];
4880
- function nn(n) {
5011
+ function gn(n) {
4881
5012
  if (!n || typeof n != "object")
4882
5013
  throw new c("invalid_response", "Notification response is not an object");
4883
5014
  let e = n;
4884
5015
  if (typeof e.id != "string")
4885
5016
  throw new c("invalid_response", "Notification missing id");
4886
- let t = Qe.includes(e.severity) ? e.severity : "info";
5017
+ let t = et.includes(e.severity) ? e.severity : "info";
4887
5018
  return {
4888
5019
  id: e.id,
4889
5020
  userId: typeof e.userId == "string" ? e.userId : "",
@@ -4898,37 +5029,37 @@ function nn(n) {
4898
5029
  dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
4899
5030
  };
4900
5031
  }
4901
- function rn(n) {
5032
+ function yn(n) {
4902
5033
  if (!n.userId) throw new c("validation_failed", "userId obrigat\xF3rio");
4903
5034
  if (!n.kind) throw new c("validation_failed", "kind obrigat\xF3rio");
4904
5035
  if (!n.title) throw new c("validation_failed", "title obrigat\xF3rio");
4905
- if (n.severity && !Qe.includes(n.severity))
5036
+ if (n.severity && !et.includes(n.severity))
4906
5037
  throw new c(
4907
5038
  "validation_failed",
4908
- `severity inv\xE1lida: ${n.severity} (use ${Qe.join("|")})`
5039
+ `severity inv\xE1lida: ${n.severity} (use ${et.join("|")})`
4909
5040
  );
4910
5041
  if (n.title.length > 200)
4911
5042
  throw new c("validation_failed", "title m\xE1x 200 chars");
4912
5043
  if (n.body && n.body.length > 2e3)
4913
5044
  throw new c("validation_failed", "body m\xE1x 2000 chars");
4914
5045
  }
4915
- function we(n, ...e) {
5046
+ function Te(n, ...e) {
4916
5047
  for (let t of e)
4917
5048
  if (typeof t == "string" && t.length > 0)
4918
- return x("productId", t), t;
5049
+ return N("productId", t), t;
4919
5050
  if (n.productId)
4920
- return x("productId", n.productId), n.productId;
5051
+ return N("productId", n.productId), n.productId;
4921
5052
  throw new c(
4922
5053
  "validation_failed",
4923
5054
  "productId required (pass to options/input or set on createNeetruClient)"
4924
5055
  );
4925
5056
  }
4926
- function on(n) {
5057
+ function _n(n) {
4927
5058
  return {
4928
5059
  async send(e) {
4929
- rn(e);
5060
+ yn(e);
4930
5061
  let r = {
4931
- productId: we(n, e.productId),
5062
+ productId: Te(n, e.productId),
4932
5063
  userId: e.userId,
4933
5064
  kind: e.kind,
4934
5065
  title: e.title,
@@ -4942,12 +5073,12 @@ function on(n) {
4942
5073
  requireAuth: true,
4943
5074
  idempotencyKey: true
4944
5075
  });
4945
- return nn(o);
5076
+ return gn(o);
4946
5077
  },
4947
5078
  async list(e, t) {
4948
5079
  if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
4949
5080
  let o = {
4950
- productId: we(n, t?.productId)
5081
+ productId: Te(n, t?.productId)
4951
5082
  };
4952
5083
  t?.includeDismissed && (o.includeDismissed = true), t?.onlyUnread && (o.onlyUnread = true), t?.limit && (o.limit = Math.min(Math.max(1, t.limit), 200));
4953
5084
  let i = await v(n, {
@@ -4956,11 +5087,11 @@ function on(n) {
4956
5087
  query: o,
4957
5088
  requireAuth: true
4958
5089
  });
4959
- return (Array.isArray(i?.notifications) ? i.notifications : []).map(nn);
5090
+ return (Array.isArray(i?.notifications) ? i.notifications : []).map(gn);
4960
5091
  },
4961
5092
  async markRead(e, t) {
4962
5093
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4963
- let r = we(n, t?.productId);
5094
+ let r = Te(n, t?.productId);
4964
5095
  return await v(n, {
4965
5096
  method: "POST",
4966
5097
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/read`,
@@ -4970,7 +5101,7 @@ function on(n) {
4970
5101
  },
4971
5102
  async dismiss(e, t) {
4972
5103
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4973
- let r = we(n, t?.productId);
5104
+ let r = Te(n, t?.productId);
4974
5105
  return await v(n, {
4975
5106
  method: "POST",
4976
5107
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/dismiss`,
@@ -4980,11 +5111,11 @@ function on(n) {
4980
5111
  }
4981
5112
  };
4982
5113
  }
4983
- var ke = class {
5114
+ var Re = class {
4984
5115
  notifications = /* @__PURE__ */ new Map();
4985
5116
  nextId = 1;
4986
5117
  async send(e) {
4987
- if (rn(e), e.fingerprint) {
5118
+ if (yn(e), e.fingerprint) {
4988
5119
  let o = Date.now() - 864e5;
4989
5120
  for (let i of this.notifications.values())
4990
5121
  if ((i.metadata ?? {}).fingerprint === e.fingerprint && i.userId === e.userId && new Date(i.createdAt).getTime() > o)
@@ -5021,43 +5152,44 @@ var ke = class {
5021
5152
  };
5022
5153
 
5023
5154
  // src/ai.ts
5024
- P();
5025
- U();
5026
- var Qr = "/api/sdk/v1/ai/chat", sn = 12e4, Se = 32768, an = 32, cn = 4194304, ln = 2048, Gr = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, Jr = /^https:\/\/[^\s]+$/, Xr = /* @__PURE__ */ new Set(["low", "high", "auto"]), Yr = /* @__PURE__ */ new Set(["system", "user", "assistant"]), dn = 100, un = 128, pn = 32768, fn = 0, mn = 2, hn = 200, gn = 20, yn = 12 * 1024 * 1024, _n = 5e4, bn = 16, vn = 500, Zr = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), eo = /^[a-zA-Z0-9_-]+$/;
5027
- function w(n) {
5155
+ I();
5156
+ M();
5157
+ Me();
5158
+ var _o = "/api/sdk/v1/ai/chat", bn = 12e4, Ie = 32768, vn = 32, wn = 4194304, kn = 2048, bo = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, vo = /^https:\/\/[^\s]+$/, wo = /* @__PURE__ */ new Set(["low", "high", "auto"]), ko = /* @__PURE__ */ new Set(["system", "user", "assistant"]), Sn = 100, Tn = 128, Rn = 32768, In = 0, Cn = 2, An = 200, En = 20, Pn = 12 * 1024 * 1024, Dn = 5e4, Nn = 16, xn = 500, So = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), To = /^[a-zA-Z0-9_-]+$/;
5159
+ function k(n) {
5028
5160
  throw new c("validation_failed", n);
5029
5161
  }
5030
- function to(n) {
5162
+ function Ro(n) {
5031
5163
  if (n.length === 0 || n.length % 4 !== 0) return false;
5032
5164
  let e = n.endsWith("==") ? 2 : n.endsWith("=") ? 1 : 0;
5033
5165
  return !(e > 0 ? n.slice(0, n.length - e) : n).includes("=");
5034
5166
  }
5035
- function no(n) {
5167
+ function Io(n) {
5036
5168
  let e = n.indexOf(",");
5037
5169
  if (e === -1) return 0;
5038
5170
  let t = n.slice(e + 1), r = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
5039
5171
  return Math.max(0, Math.floor(t.length * 3 / 4) - r);
5040
5172
  }
5041
- function ro(n) {
5173
+ function Co(n) {
5042
5174
  let e = 0, t = 0, r = 0;
5043
5175
  for (let o of n) {
5044
5176
  let i = o?.content;
5045
5177
  if (Array.isArray(i))
5046
5178
  for (let s of i) {
5047
- if (e++, e > hn)
5048
- return `ai: total content parts exceeds ${hn} per request`;
5179
+ if (e++, e > An)
5180
+ return `ai: total content parts exceeds ${An} per request`;
5049
5181
  if (s && typeof s == "object" && s.type === "image_url") {
5050
- if (t++, t > gn)
5051
- return `ai: total images exceeds ${gn} per request`;
5182
+ if (t++, t > En)
5183
+ return `ai: total images exceeds ${En} per request`;
5052
5184
  let a = s.image_url?.url;
5053
- if (typeof a == "string" && a.startsWith("data:") && (r += no(a), r > yn))
5054
- return `ai: aggregate image bytes exceeds ${yn} per request`;
5185
+ if (typeof a == "string" && a.startsWith("data:") && (r += Io(a), r > Pn))
5186
+ return `ai: aggregate image bytes exceeds ${Pn} per request`;
5055
5187
  }
5056
5188
  }
5057
5189
  }
5058
5190
  return null;
5059
5191
  }
5060
- function oo(n) {
5192
+ function Ao(n) {
5061
5193
  if (n === void 0) return null;
5062
5194
  if (n === null || typeof n != "object")
5063
5195
  return "ai: responseFormat json_schema.schema must be an object";
@@ -5068,11 +5200,11 @@ function oo(n) {
5068
5200
  return "ai: responseFormat json_schema.schema is not serializable";
5069
5201
  }
5070
5202
  if (e === void 0) return "ai: responseFormat json_schema.schema is invalid";
5071
- if (e.length > _n)
5072
- return `ai: responseFormat json_schema.schema exceeds ${_n} serialized chars`;
5203
+ if (e.length > Dn)
5204
+ return `ai: responseFormat json_schema.schema exceeds ${Dn} serialized chars`;
5073
5205
  let t = 0, r = (o, i) => {
5074
- if (i > bn)
5075
- return `ai: responseFormat json_schema.schema exceeds max depth ${bn}`;
5206
+ if (i > Nn)
5207
+ return `ai: responseFormat json_schema.schema exceeds max depth ${Nn}`;
5076
5208
  if (Array.isArray(o)) {
5077
5209
  for (let s of o) {
5078
5210
  let a = r(s, i + 1);
@@ -5082,10 +5214,10 @@ function oo(n) {
5082
5214
  }
5083
5215
  if (o && typeof o == "object")
5084
5216
  for (let s of Object.getOwnPropertyNames(o)) {
5085
- if (Zr.has(s))
5217
+ if (So.has(s))
5086
5218
  return `ai: responseFormat json_schema.schema has forbidden key: ${s}`;
5087
- if (t++, t > vn)
5088
- return `ai: responseFormat json_schema.schema exceeds ${vn} keys`;
5219
+ if (t++, t > xn)
5220
+ return `ai: responseFormat json_schema.schema exceeds ${xn} keys`;
5089
5221
  let a = r(o[s], i + 1);
5090
5222
  if (a) return a;
5091
5223
  }
@@ -5093,80 +5225,80 @@ function oo(n) {
5093
5225
  };
5094
5226
  return r(n, 0);
5095
5227
  }
5096
- function io(n) {
5097
- (typeof n != "string" || n.length === 0) && w("ai: image_url.url must be a non-empty string");
5228
+ function Eo(n) {
5229
+ (typeof n != "string" || n.length === 0) && k("ai: image_url.url must be a non-empty string");
5098
5230
  let e = n;
5099
5231
  if (e.startsWith("data:")) {
5100
- e.length > cn && w(`ai: image_url.url (data:) exceeds ${cn} chars`), Gr.test(e) || w("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5232
+ e.length > wn && k(`ai: image_url.url (data:) exceeds ${wn} chars`), bo.test(e) || k("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5101
5233
  let t = e.slice(e.indexOf(",") + 1);
5102
- to(t) || w("ai: image_url.url data: has invalid base64 (length/padding)");
5234
+ Ro(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5103
5235
  return;
5104
5236
  }
5105
5237
  if (e.startsWith("https://")) {
5106
- e.length > ln && w(`ai: image_url.url (https:) exceeds ${ln} chars`), Jr.test(e) || w("ai: image_url.url https: is invalid");
5238
+ e.length > kn && k(`ai: image_url.url (https:) exceeds ${kn} chars`), vo.test(e) || k("ai: image_url.url https: is invalid");
5107
5239
  return;
5108
5240
  }
5109
- w("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5241
+ k("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5110
5242
  }
5111
- function so(n, e) {
5243
+ function Po(n, e) {
5112
5244
  if (typeof n == "string") {
5113
- n.length === 0 && w("ai: message content string must be non-empty"), n.length > Se && w(`ai: message content exceeds ${Se} chars`);
5245
+ n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ie && k(`ai: message content exceeds ${Ie} chars`);
5114
5246
  return;
5115
5247
  }
5116
- (!Array.isArray(n) || n.length === 0) && w("ai: message content must be a non-empty string or array of parts"), n.length > an && w(`ai: message content has more than ${an} parts`);
5248
+ (!Array.isArray(n) || n.length === 0) && k("ai: message content must be a non-empty string or array of parts"), n.length > vn && k(`ai: message content has more than ${vn} parts`);
5117
5249
  for (let t of n) {
5118
- (!t || typeof t != "object") && w("ai: each content part must be an object");
5250
+ (!t || typeof t != "object") && k("ai: each content part must be an object");
5119
5251
  let r = t.type;
5120
5252
  if (r === "text") {
5121
5253
  let o = t.text;
5122
- (typeof o != "string" || o.length === 0) && w("ai: text part must have non-empty { text: string }"), o.length > Se && w(`ai: text part exceeds ${Se} chars`);
5254
+ (typeof o != "string" || o.length === 0) && k("ai: text part must have non-empty { text: string }"), o.length > Ie && k(`ai: text part exceeds ${Ie} chars`);
5123
5255
  } else if (r === "image_url") {
5124
- e !== "user" && w(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5256
+ e !== "user" && k(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5125
5257
  let o = t.image_url;
5126
- (!o || typeof o != "object") && w("ai: image_url part must have { image_url: { url } }"), io(o.url);
5258
+ (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Eo(o.url);
5127
5259
  let i = o.detail;
5128
- i !== void 0 && (typeof i != "string" || !Xr.has(i)) && w("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5260
+ i !== void 0 && (typeof i != "string" || !wo.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5129
5261
  } else
5130
- w("ai: content part type must be 'text' or 'image_url'");
5262
+ k("ai: content part type must be 'text' or 'image_url'");
5131
5263
  }
5132
5264
  }
5133
- function ao(n) {
5134
- (!n || typeof n != "object") && w("ai: responseFormat must be an object");
5265
+ function Do(n) {
5266
+ (!n || typeof n != "object") && k("ai: responseFormat must be an object");
5135
5267
  let e = n.type;
5136
5268
  if (!(e === "text" || e === "json_object")) {
5137
5269
  if (e === "json_schema") {
5138
5270
  let t = n.json_schema;
5139
- (!t || typeof t != "object") && w("ai: responseFormat json_schema requires { json_schema: { name } }");
5271
+ (!t || typeof t != "object") && k("ai: responseFormat json_schema requires { json_schema: { name } }");
5140
5272
  let r = t, o = r.name;
5141
- if ((typeof o != "string" || o.length === 0) && w("ai: responseFormat json_schema.name is required"), o.length > 64 && w("ai: responseFormat json_schema.name exceeds 64 chars"), eo.test(o) || w("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && w("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && w("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && w("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5142
- let i = oo(r.schema);
5143
- i && w(i);
5273
+ if ((typeof o != "string" || o.length === 0) && k("ai: responseFormat json_schema.name is required"), o.length > 64 && k("ai: responseFormat json_schema.name exceeds 64 chars"), To.test(o) || k("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && k("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && k("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && k("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5274
+ let i = Ao(r.schema);
5275
+ i && k(i);
5144
5276
  }
5145
5277
  return;
5146
5278
  }
5147
- w("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5279
+ k("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5148
5280
  }
5149
5281
  }
5150
- function wn(n, e, t) {
5282
+ function On(n, e, t) {
5151
5283
  if (!e || typeof e != "object")
5152
5284
  throw new c("validation_failed", "ai: options object is required");
5153
5285
  if (typeof e.model != "string" || e.model.length === 0)
5154
5286
  throw new c("validation_failed", "ai: model is required");
5155
- if (e.model.length > un)
5156
- throw new c("validation_failed", `ai: model exceeds ${un} chars`);
5287
+ if (e.model.length > Tn)
5288
+ throw new c("validation_failed", `ai: model exceeds ${Tn} chars`);
5157
5289
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5158
5290
  throw new c("validation_failed", "ai: messages must be a non-empty array");
5159
- if (e.messages.length > dn)
5160
- throw new c("validation_failed", `ai: messages exceeds ${dn} per request`);
5291
+ if (e.messages.length > Sn)
5292
+ throw new c("validation_failed", `ai: messages exceeds ${Sn} per request`);
5161
5293
  for (let a of e.messages) {
5162
- if (!a || typeof a != "object" || typeof a.role != "string" || !Yr.has(a.role))
5294
+ if (!a || typeof a != "object" || typeof a.role != "string" || !ko.has(a.role))
5163
5295
  throw new c(
5164
5296
  "validation_failed",
5165
5297
  "ai: each message role must be 'system' | 'user' | 'assistant'"
5166
5298
  );
5167
- so(a.content, a.role);
5299
+ Po(a.content, a.role);
5168
5300
  }
5169
- let r = ro(e.messages);
5301
+ let r = Co(e.messages);
5170
5302
  if (r) throw new c("validation_failed", r);
5171
5303
  let o = e.productId ?? n.productId, i = e.tenantId ?? n.tenantId;
5172
5304
  if (!o)
@@ -5179,7 +5311,7 @@ function wn(n, e, t) {
5179
5311
  "validation_failed",
5180
5312
  "ai: tenantId required (pass to options or set on createNeetruClient)"
5181
5313
  );
5182
- x("productId", o), x("tenantId", i);
5314
+ N("productId", o), N("tenantId", i);
5183
5315
  let s = {
5184
5316
  productId: o,
5185
5317
  tenantId: i,
@@ -5188,24 +5320,24 @@ function wn(n, e, t) {
5188
5320
  stream: t
5189
5321
  };
5190
5322
  if (e.maxTokens !== void 0) {
5191
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > pn)
5323
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Rn)
5192
5324
  throw new c(
5193
5325
  "validation_failed",
5194
- `ai: maxTokens must be a positive integer <= ${pn}`
5326
+ `ai: maxTokens must be a positive integer <= ${Rn}`
5195
5327
  );
5196
5328
  s.maxTokens = e.maxTokens;
5197
5329
  }
5198
5330
  if (e.temperature !== void 0) {
5199
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < fn || e.temperature > mn)
5331
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < In || e.temperature > Cn)
5200
5332
  throw new c(
5201
5333
  "validation_failed",
5202
- `ai: temperature must be a finite number between ${fn} and ${mn}`
5334
+ `ai: temperature must be a finite number between ${In} and ${Cn}`
5203
5335
  );
5204
5336
  s.temperature = e.temperature;
5205
5337
  }
5206
- return e.responseFormat !== void 0 && (ao(e.responseFormat), s.responseFormat = e.responseFormat), s;
5338
+ return e.responseFormat !== void 0 && (Do(e.responseFormat), s.responseFormat = e.responseFormat), s;
5207
5339
  }
5208
- async function Rn(n) {
5340
+ async function qn(n) {
5209
5341
  try {
5210
5342
  let e = await n.text();
5211
5343
  return e ? JSON.parse(e) : void 0;
@@ -5213,48 +5345,48 @@ async function Rn(n) {
5213
5345
  return;
5214
5346
  }
5215
5347
  }
5216
- function co(n, e) {
5348
+ function No(n, e) {
5217
5349
  let t = n.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
5218
5350
  return `${t}${r}`;
5219
5351
  }
5220
- async function kn(n, e, t, r) {
5352
+ async function Ln(n, e, t, r) {
5221
5353
  if (!n.apiKey)
5222
5354
  throw new c(
5223
5355
  "missing_api_key",
5224
5356
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
5225
5357
  );
5226
- let o = co(n.baseUrl, Qr), s = { method: "POST", headers: {
5358
+ let o = No(n.baseUrl, _o), { headers: i, correlationId: s } = ae({
5227
5359
  "content-type": "application/json",
5228
5360
  accept: r ? "text/event-stream" : "application/json",
5229
5361
  authorization: `Bearer ${n.apiKey}`
5230
- }, body: JSON.stringify(e) };
5231
- r ? t && (s.signal = t) : s.signal = t ?? AbortSignal.timeout(sn);
5232
- let a;
5362
+ }), a = { method: "POST", headers: i, body: JSON.stringify(e) };
5363
+ r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(bn);
5364
+ let l;
5233
5365
  try {
5234
- a = await n.fetch(o, s);
5235
- } catch (u) {
5236
- let p = u instanceof DOMException && u.name === "TimeoutError" ? `Network error: timeout after ${sn / 1e3}s` : u instanceof DOMException && u.name === "AbortError" ? "Network error: request aborted" : `Network error: ${u instanceof Error ? u.message : "fetch failed"}`;
5237
- throw new c("network_error", p);
5238
- }
5239
- let l = a.headers.get("x-request-id") ?? a.headers.get("x-correlation-id") ?? void 0;
5240
- if (!a.ok) {
5241
- let u = await Rn(a), p = se(a.status), f = `HTTP ${a.status}`;
5242
- if (u && typeof u == "object" && "error" in u) {
5243
- let g = u.error;
5244
- typeof g == "string" ? f = g : g && typeof g == "object" && (typeof g.code == "string" && (p = g.code), typeof g.message == "string" && (f = g.message));
5366
+ l = await n.fetch(o, a);
5367
+ } catch (p) {
5368
+ let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${bn / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5369
+ throw new c("network_error", f, void 0, void 0, void 0, s);
5370
+ }
5371
+ let d = l.headers.get("x-request-id") ?? l.headers.get("x-correlation-id") ?? void 0;
5372
+ if (!l.ok) {
5373
+ let p = await qn(l), f = le(l.status), h = `HTTP ${l.status}`;
5374
+ if (p && typeof p == "object" && "error" in p) {
5375
+ let y = p.error;
5376
+ typeof y == "string" ? h = y : y && typeof y == "object" && (typeof y.code == "string" && (f = y.code), typeof y.message == "string" && (h = y.message));
5245
5377
  }
5246
- throw new c(p, f, a.status, l);
5378
+ throw new c(f, h, l.status, d, void 0, s);
5247
5379
  }
5248
- let d = a.headers.get("x-neetru-version");
5249
- return d && ie(d), a;
5380
+ let u = l.headers.get("x-neetru-version");
5381
+ return u && ce(u), l;
5250
5382
  }
5251
- function Sn(n) {
5383
+ function Un(n) {
5252
5384
  return {
5253
5385
  provider: n.headers.get("x-neetru-provider") ?? "",
5254
5386
  usageWarning: n.headers.get("x-neetru-ai-usage-warning") === "1"
5255
5387
  };
5256
5388
  }
5257
- function Tn(n) {
5389
+ function Mn(n) {
5258
5390
  let e = [];
5259
5391
  for (let r of n.split(`
5260
5392
  `)) {
@@ -5275,10 +5407,10 @@ function Tn(n) {
5275
5407
  return null;
5276
5408
  }
5277
5409
  }
5278
- function In(n) {
5410
+ function Fn(n) {
5279
5411
  return {
5280
5412
  async chat(e) {
5281
- let t = wn(n, e, false), r = await kn(n, t, e.signal, false), { provider: o, usageWarning: i } = Sn(r), s = await Rn(r);
5413
+ let t = On(n, e, false), r = await Ln(n, t, e.signal, false), { provider: o, usageWarning: i } = Un(r), s = await qn(r);
5282
5414
  if (!s || s.ok !== true || !Array.isArray(s.choices))
5283
5415
  throw new c("invalid_response", "ai.chat response missing ok/choices");
5284
5416
  return {
@@ -5290,7 +5422,7 @@ function In(n) {
5290
5422
  };
5291
5423
  },
5292
5424
  stream(e) {
5293
- let t = wn(n, e, true), r = kn(n, t, e.signal, true), o = r.then(Sn);
5425
+ let t = On(n, e, true), r = Ln(n, t, e.signal, true), o = r.then(Un);
5294
5426
  o.catch(() => {
5295
5427
  });
5296
5428
  async function* i() {
@@ -5300,23 +5432,23 @@ function In(n) {
5300
5432
  let l = a.getReader(), d = new TextDecoder(), u = "";
5301
5433
  try {
5302
5434
  for (; ; ) {
5303
- let { done: f, value: g } = await l.read();
5435
+ let { done: f, value: h } = await l.read();
5304
5436
  if (f) break;
5305
- u += d.decode(g, { stream: !0 });
5306
- let _;
5307
- for (; (_ = u.indexOf(`
5437
+ u += d.decode(h, { stream: !0 });
5438
+ let y;
5439
+ for (; (y = u.indexOf(`
5308
5440
 
5309
5441
  `)) !== -1; ) {
5310
- let M = u.slice(0, _);
5311
- u = u.slice(_ + 2);
5312
- let R = Tn(M);
5313
- if (R && "done" in R) return;
5314
- R && "content" in R && (yield R.content);
5442
+ let S = u.slice(0, y);
5443
+ u = u.slice(y + 2);
5444
+ let x = Mn(S);
5445
+ if (x && "done" in x) return;
5446
+ x && "content" in x && (yield x.content);
5315
5447
  }
5316
5448
  }
5317
5449
  let p = u.trim();
5318
5450
  if (p) {
5319
- let f = Tn(p);
5451
+ let f = Mn(p);
5320
5452
  f && "content" in f && (yield f.content);
5321
5453
  }
5322
5454
  } finally {
@@ -5339,10 +5471,10 @@ function In(n) {
5339
5471
  }
5340
5472
 
5341
5473
  // src/mocks.ts
5342
- P();
5474
+ I();
5343
5475
 
5344
5476
  // src/runtime-env.ts
5345
- function Te() {
5477
+ function Ce() {
5346
5478
  try {
5347
5479
  if (typeof process < "u" && process.env)
5348
5480
  return process.env.NODE_ENV === "production";
@@ -5352,19 +5484,19 @@ function Te() {
5352
5484
  }
5353
5485
 
5354
5486
  // src/mocks.ts
5355
- var Ge = Object.freeze({
5487
+ var tt = Object.freeze({
5356
5488
  uid: "dev-fixture-uid-0001",
5357
5489
  email: "dev@neetru.local",
5358
5490
  emailVerified: true,
5359
5491
  displayName: "Dev Fixture",
5360
5492
  isCustomer: true,
5361
5493
  isStaff: false
5362
- }), Re = class {
5494
+ }), Ae = class {
5363
5495
  _user;
5364
5496
  _listeners;
5365
5497
  _allowUnsignedDecode;
5366
5498
  constructor(e = null, t) {
5367
- if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Te())
5499
+ if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Ce())
5368
5500
  throw new c(
5369
5501
  "invalid_config",
5370
5502
  "MockAuth com allowUnsignedDecode=true \xE9 PROIBIDO em produ\xE7\xE3o (NODE_ENV=production): decodificar JWT sem verificar assinatura \xE9 bypass de autentica\xE7\xE3o. Este modo existe exclusivamente para testes."
@@ -5374,7 +5506,7 @@ var Ge = Object.freeze({
5374
5506
  );
5375
5507
  }
5376
5508
  async signIn(e) {
5377
- return this._user || (this._user = { ...Ge }), this._notify(), this._user;
5509
+ return this._user || (this._user = { ...tt }), this._notify(), this._user;
5378
5510
  }
5379
5511
  async signOut() {
5380
5512
  this._user = null, this._notify();
@@ -5495,7 +5627,7 @@ var Ge = Object.freeze({
5495
5627
  } catch {
5496
5628
  }
5497
5629
  }
5498
- }, Ie = class {
5630
+ }, Ee = class {
5499
5631
  _reports = [];
5500
5632
  _quotas;
5501
5633
  _counters = /* @__PURE__ */ new Map();
@@ -5557,7 +5689,7 @@ var Ge = Object.freeze({
5557
5689
  __reset() {
5558
5690
  this._reports = [], this._quotas.clear(), this._counters.clear();
5559
5691
  }
5560
- }, Ce = class {
5692
+ }, Pe = class {
5561
5693
  _tickets = [];
5562
5694
  _ticketSeq = 0;
5563
5695
  async createTicket(e) {
@@ -5634,7 +5766,7 @@ var Ge = Object.freeze({
5634
5766
  __reset() {
5635
5767
  this._tickets = [], this._ticketSeq = 0;
5636
5768
  }
5637
- }, Ae = class {
5769
+ }, De = class {
5638
5770
  _denied = /* @__PURE__ */ new Set();
5639
5771
  async check(e, t) {
5640
5772
  return !this._denied.has(`${e}:${t}`);
@@ -5657,7 +5789,7 @@ var Ge = Object.freeze({
5657
5789
  this._denied.clear();
5658
5790
  }
5659
5791
  };
5660
- var Pe = class {
5792
+ var Ne = class {
5661
5793
  _calls = [];
5662
5794
  /** Extrai texto de um content string OU array multimodal (imagens ignoradas). */
5663
5795
  _contentToText(e) {
@@ -5705,8 +5837,8 @@ var Pe = class {
5705
5837
  };
5706
5838
 
5707
5839
  // src/auth-pkce-shared.ts
5708
- P();
5709
- function Cn() {
5840
+ I();
5841
+ function jn() {
5710
5842
  let n = globalThis.crypto;
5711
5843
  if (!n || typeof n.getRandomValues != "function" || !n.subtle)
5712
5844
  throw new c(
@@ -5715,36 +5847,36 @@ function Cn() {
5715
5847
  );
5716
5848
  return n;
5717
5849
  }
5718
- function An(n) {
5850
+ function $n(n) {
5719
5851
  let e = "";
5720
5852
  for (let r of n) e += String.fromCharCode(r);
5721
5853
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
5722
5854
  }
5723
- function Ee(n, e) {
5855
+ function xe(n, e) {
5724
5856
  let t = new Uint8Array(e);
5725
- return n.getRandomValues(t), An(t);
5857
+ return n.getRandomValues(t), $n(t);
5726
5858
  }
5727
- async function Pn(n, e) {
5859
+ async function Wn(n, e) {
5728
5860
  let t = new TextEncoder().encode(e), r = await n.subtle.digest("SHA-256", t);
5729
- return An(new Uint8Array(r));
5861
+ return $n(new Uint8Array(r));
5730
5862
  }
5731
- function De(n) {
5863
+ function oe(n) {
5732
5864
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.replace(/^https?:\/\/api\./, "https://auth.");
5733
5865
  }
5734
- function En(n) {
5866
+ function Bn(n) {
5735
5867
  let e = n.oidcClientId;
5736
- if (!e && n.apiKey && (e = tt(n.apiKey).keyId), !e)
5868
+ if (!e && n.apiKey && (e = ct(n.apiKey).keyId), !e)
5737
5869
  throw new c(
5738
5870
  "invalid_config",
5739
5871
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
5740
5872
  );
5741
5873
  return e;
5742
5874
  }
5743
- function Dn(n) {
5875
+ function Vn(n) {
5744
5876
  let e = new URL("/api/v1/oauth/authorize", n.idpOrigin);
5745
5877
  return e.searchParams.set("response_type", "code"), e.searchParams.set("client_id", n.clientId), e.searchParams.set("redirect_uri", n.redirectUri), e.searchParams.set("scope", n.scope), e.searchParams.set("state", n.state), e.searchParams.set("nonce", n.nonce), e.searchParams.set("code_challenge", n.codeChallenge), e.searchParams.set("code_challenge_method", "S256"), e;
5746
5878
  }
5747
- function Je(n) {
5879
+ function nt(n) {
5748
5880
  let e = n.split(".");
5749
5881
  if (e.length !== 3) return null;
5750
5882
  try {
@@ -5754,8 +5886,8 @@ function Je(n) {
5754
5886
  return null;
5755
5887
  }
5756
5888
  }
5757
- function re(n) {
5758
- let e = Je(n);
5889
+ function ie(n) {
5890
+ let e = nt(n);
5759
5891
  return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
5760
5892
  uid: e.sub,
5761
5893
  email: typeof e.email == "string" ? e.email : "",
@@ -5768,9 +5900,68 @@ function re(n) {
5768
5900
  ...e
5769
5901
  };
5770
5902
  }
5903
+ var xo = "/api/v1/oauth/revoke";
5904
+ async function Kn(n, e, t, r) {
5905
+ let o = `${e}${xo}`, i = true;
5906
+ for (let s of r) {
5907
+ if (!s.token) continue;
5908
+ let a = new URLSearchParams({
5909
+ token: s.token,
5910
+ token_type_hint: s.hint,
5911
+ client_id: t
5912
+ }).toString(), l = false;
5913
+ for (let d = 0; d < 2 && !l; d++)
5914
+ try {
5915
+ if (l = (await n(o, {
5916
+ method: "POST",
5917
+ headers: { "content-type": "application/x-www-form-urlencoded" },
5918
+ body: a
5919
+ })).ok, !l) break;
5920
+ } catch {
5921
+ d === 0 && await new Promise((u) => setTimeout(u, 500));
5922
+ }
5923
+ l || (i = false);
5924
+ }
5925
+ return i;
5926
+ }
5771
5927
 
5772
5928
  // src/auth.ts
5773
- function po() {
5929
+ qe();
5930
+
5931
+ // src/end-user-token.ts
5932
+ var Oo = /* @__PURE__ */ new WeakMap();
5933
+ function zn(n, e) {
5934
+ Oo.set(n, e);
5935
+ }
5936
+
5937
+ // src/unsupported-db.ts
5938
+ I();
5939
+ var Lo = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O app n\xE3o acessa o banco do produto diretamente: chame a API do SEU produto (ex.: https://<produto>.neetru.com/api/v1) com o access_token do usu\xE1rio (Authorization: Bearer) \u2014 o backend do produto usa client.db no servidor. (At\xE9 a 3.7.x o db ca\xEDa em mem\xF3ria em sil\xEAncio e os dados sumiam ao fechar o app.)", Uo = /* @__PURE__ */ new Set([
5940
+ "then",
5941
+ "toJSON",
5942
+ "valueOf",
5943
+ "constructor",
5944
+ "$$typeof",
5945
+ "asymmetricMatch",
5946
+ "nodeType"
5947
+ ]);
5948
+ function Hn() {
5949
+ let n = () => {
5950
+ throw new c("runtime_unsupported", Lo, void 0, void 0, "react-native");
5951
+ }, e = {};
5952
+ return new Proxy(e, {
5953
+ get(t, r) {
5954
+ if (!(typeof r == "symbol" || Uo.has(r)))
5955
+ return r === "toString" ? () => "[NeetruDb indispon\xEDvel em React Native]" : n;
5956
+ },
5957
+ set() {
5958
+ return n(), false;
5959
+ }
5960
+ });
5961
+ }
5962
+
5963
+ // src/auth.ts
5964
+ function qo() {
5774
5965
  try {
5775
5966
  let e = globalThis.process?.env?.NEETRU_API_KEY;
5776
5967
  return typeof e == "string" && e.length > 0 ? e : void 0;
@@ -5778,7 +5969,7 @@ function po() {
5778
5969
  return;
5779
5970
  }
5780
5971
  }
5781
- function fo(n) {
5972
+ function Fo(n) {
5782
5973
  if (n) return n;
5783
5974
  try {
5784
5975
  let t = globalThis.process?.env?.NEETRU_ENV;
@@ -5792,18 +5983,11 @@ function fo(n) {
5792
5983
  }
5793
5984
  return "prod";
5794
5985
  }
5795
- var Ye = /* @__PURE__ */ new Map(), mo = 3600 * 1e3;
5796
- function ho(n, e) {
5797
- let t = Date.now(), r = Ye.get(n);
5798
- if (r && t - r.createdAt < e)
5799
- return r.jwks;
5800
- let o = createRemoteJWKSet(new URL(n));
5801
- return Ye.set(n, { jwks: o, createdAt: t }), o;
5802
- }
5803
- function vs() {
5804
- Ye.clear();
5986
+ var jo = it;
5987
+ function sa() {
5988
+ st();
5805
5989
  }
5806
- function go(n) {
5990
+ function $o(n) {
5807
5991
  let e = n.sub ?? "", t = typeof n.email == "string" ? n.email : "";
5808
5992
  return {
5809
5993
  uid: e,
@@ -5818,8 +6002,8 @@ function go(n) {
5818
6002
  ...n
5819
6003
  };
5820
6004
  }
5821
- var oe = "neetru_oauth_tx";
5822
- function Xe(n) {
6005
+ var se = "neetru_oauth_tx";
6006
+ function rt(n) {
5823
6007
  try {
5824
6008
  let e = globalThis.history;
5825
6009
  if (!e || typeof e.replaceState != "function") return;
@@ -5830,7 +6014,7 @@ function Xe(n) {
5830
6014
  } catch {
5831
6015
  }
5832
6016
  }
5833
- function yo(n) {
6017
+ function Wo(n) {
5834
6018
  let e = "neetru_id_token", t = "neetru_refresh_token", r = /* @__PURE__ */ new Set(), o = null, i = null, s = null;
5835
6019
  function a() {
5836
6020
  try {
@@ -5848,21 +6032,21 @@ function yo(n) {
5848
6032
  }
5849
6033
  function d() {
5850
6034
  if (o) {
5851
- let T = o.exp;
5852
- return typeof T == "number" && T * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), M(), null) : o;
6035
+ let g = o.exp;
6036
+ return typeof g == "number" && g * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), S(), null) : o;
5853
6037
  }
5854
- let h = a();
5855
- if (!h) return null;
5856
- let b = h.getItem(e);
5857
- if (!b)
5858
- return M(), null;
5859
- let m = re(b);
5860
- return m ? (o = m, R(m), o) : (h.removeItem(e), M(), null);
6038
+ let m = a();
6039
+ if (!m) return null;
6040
+ let _ = m.getItem(e);
6041
+ if (!_)
6042
+ return S(), null;
6043
+ let w = ie(_);
6044
+ return w ? (o = w, x(w), o) : (m.removeItem(e), S(), null);
5861
6045
  }
5862
6046
  function u() {
5863
- for (let h of r)
6047
+ for (let m of r)
5864
6048
  try {
5865
- h(o);
6049
+ m(o);
5866
6050
  } catch {
5867
6051
  }
5868
6052
  }
@@ -5872,216 +6056,216 @@ function yo(n) {
5872
6056
  function f() {
5873
6057
  return a()?.getItem(t) ?? null;
5874
6058
  }
5875
- function g() {
6059
+ function h() {
5876
6060
  o = null;
5877
- let h = a();
5878
- h?.removeItem(e), h?.removeItem(t), u();
6061
+ let m = a();
6062
+ m?.removeItem(e), m?.removeItem(t), u();
5879
6063
  }
5880
- function _() {
6064
+ function y() {
5881
6065
  return s || (s = (async () => {
5882
- let h = f();
5883
- if (!h) return false;
5884
- let b;
6066
+ let m = f();
6067
+ if (!m) return false;
6068
+ let _;
5885
6069
  try {
5886
- b = N();
6070
+ _ = T();
5887
6071
  } catch {
5888
6072
  return false;
5889
6073
  }
5890
- let T = `${De(n.baseUrl)}/api/v1/oauth/token`, A = new URLSearchParams({
6074
+ let g = `${oe(n.baseUrl)}/api/v1/oauth/token`, C = new URLSearchParams({
5891
6075
  grant_type: "refresh_token",
5892
- refresh_token: h,
5893
- client_id: b
5894
- }), E;
6076
+ refresh_token: m,
6077
+ client_id: _
6078
+ }), D;
5895
6079
  try {
5896
- E = await n.fetch(T, {
6080
+ D = await n.fetch(g, {
5897
6081
  method: "POST",
5898
6082
  headers: { "content-type": "application/x-www-form-urlencoded" },
5899
- body: A.toString()
6083
+ body: C.toString()
5900
6084
  });
5901
6085
  } catch {
5902
6086
  return false;
5903
6087
  }
5904
- let S = null;
6088
+ let E = null;
5905
6089
  try {
5906
- S = await E.json();
6090
+ E = await D.json();
5907
6091
  } catch {
5908
- S = null;
6092
+ E = null;
5909
6093
  }
5910
- if (!E.ok || typeof S?.error == "string") return false;
5911
- let k = S?.id_token;
5912
- if (typeof k != "string" || k.length === 0) return false;
5913
- let D = re(k);
5914
- if (!D) return false;
5915
- let I = a();
5916
- I?.setItem(e, k);
5917
- let L = S?.refresh_token;
5918
- return typeof L == "string" && L.length > 0 && I?.setItem(t, L), o = D, R(D), u(), true;
6094
+ if (!D.ok || typeof E?.error == "string") return false;
6095
+ let R = E?.id_token;
6096
+ if (typeof R != "string" || R.length === 0) return false;
6097
+ let O = ie(R);
6098
+ if (!O) return false;
6099
+ let A = a();
6100
+ A?.setItem(e, R);
6101
+ let U = E?.refresh_token;
6102
+ return typeof U == "string" && U.length > 0 && A?.setItem(t, U), o = O, x(O), u(), true;
5919
6103
  })().finally(() => {
5920
6104
  s = null;
5921
6105
  }), s);
5922
6106
  }
5923
- function M() {
5924
- f() && _().then((h) => {
5925
- h || g();
6107
+ function S() {
6108
+ f() && y().then((m) => {
6109
+ m || h();
5926
6110
  });
5927
6111
  }
5928
- function R(h) {
6112
+ function x(m) {
5929
6113
  p();
5930
- let b = h.exp;
5931
- if (typeof b != "number") return;
5932
- let m = b * 1e3 - Date.now();
5933
- if (!(m <= 0)) {
6114
+ let _ = m.exp;
6115
+ if (typeof _ != "number") return;
6116
+ let w = _ * 1e3 - Date.now();
6117
+ if (!(w <= 0)) {
5934
6118
  if (f()) {
5935
- let T = Math.min(m, Math.max(3e4, m * 0.2)), A = Math.max(1, m - T);
6119
+ let g = Math.min(w, Math.max(3e4, w * 0.2)), C = Math.max(1, w - g);
5936
6120
  i = setTimeout(() => {
5937
- i = null, _().then((E) => {
5938
- E || g();
6121
+ i = null, y().then((D) => {
6122
+ D || h();
5939
6123
  });
5940
- }, A);
6124
+ }, C);
5941
6125
  return;
5942
6126
  }
5943
6127
  i = setTimeout(() => {
5944
6128
  i = null, d();
5945
- }, m + 1);
6129
+ }, w + 1);
5946
6130
  }
5947
6131
  }
5948
- function N() {
5949
- return En(n);
6132
+ function T() {
6133
+ return Bn(n);
5950
6134
  }
5951
- async function C(h) {
5952
- let b = h ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
5953
- if (!b) return null;
5954
- let m;
6135
+ async function P(m) {
6136
+ let _ = m ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6137
+ if (!_) return null;
6138
+ let w;
5955
6139
  try {
5956
- m = new URL(b);
6140
+ w = new URL(_);
5957
6141
  } catch {
5958
6142
  return null;
5959
6143
  }
5960
- let T = m.searchParams, A = T.get("error");
5961
- if (A) {
5962
- let L = T.get("error_description") ?? A;
5963
- throw l()?.removeItem(oe), Xe(m), new c(A, `OIDC authorize falhou: ${L}`);
6144
+ let g = w.searchParams, C = g.get("error");
6145
+ if (C) {
6146
+ let U = g.get("error_description") ?? C;
6147
+ throw l()?.removeItem(se), rt(w), new c(C, `OIDC authorize falhou: ${U}`);
5964
6148
  }
5965
- let E = T.get("code");
5966
- if (!E) return null;
5967
- let S = T.get("state"), k = l(), D = k?.getItem(oe) ?? null, I = null;
5968
- if (D)
6149
+ let D = g.get("code");
6150
+ if (!D) return null;
6151
+ let E = g.get("state"), R = l(), O = R?.getItem(se) ?? null, A = null;
6152
+ if (O)
5969
6153
  try {
5970
- I = JSON.parse(D);
6154
+ A = JSON.parse(O);
5971
6155
  } catch {
5972
- I = null;
6156
+ A = null;
5973
6157
  }
5974
- if (!I)
6158
+ if (!A)
5975
6159
  throw new c(
5976
6160
  "oidc_state_mismatch",
5977
6161
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado nesta sess\xE3o (ou j\xE1 consumido)."
5978
6162
  );
5979
- if (!S || S !== I.state)
5980
- throw k?.removeItem(oe), Xe(m), new c(
6163
+ if (!E || E !== A.state)
6164
+ throw R?.removeItem(se), rt(w), new c(
5981
6165
  "oidc_state_mismatch",
5982
6166
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
5983
6167
  );
5984
- return k?.removeItem(oe), Xe(m), {
5985
- code: E,
5986
- codeVerifier: I.codeVerifier,
5987
- redirectUri: I.redirectUri,
5988
- nonce: I.nonce,
5989
- state: I.state,
5990
- postLoginRedirect: I.postLoginRedirect
6168
+ return R?.removeItem(se), rt(w), {
6169
+ code: D,
6170
+ codeVerifier: A.codeVerifier,
6171
+ redirectUri: A.redirectUri,
6172
+ nonce: A.nonce,
6173
+ state: A.state,
6174
+ postLoginRedirect: A.postLoginRedirect
5991
6175
  };
5992
6176
  }
5993
- async function $(h) {
5994
- let b = await C(h);
5995
- if (!b) return null;
5996
- let m = N(), A = `${De(n.baseUrl)}/api/v1/oauth/token`, E = new URLSearchParams({
6177
+ async function q(m) {
6178
+ let _ = await P(m);
6179
+ if (!_) return null;
6180
+ let w = T(), C = `${oe(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
5997
6181
  grant_type: "authorization_code",
5998
- code: b.code,
5999
- redirect_uri: b.redirectUri,
6000
- client_id: m,
6001
- code_verifier: b.codeVerifier
6002
- }), S;
6182
+ code: _.code,
6183
+ redirect_uri: _.redirectUri,
6184
+ client_id: w,
6185
+ code_verifier: _.codeVerifier
6186
+ }), E;
6003
6187
  try {
6004
- S = await n.fetch(A, {
6188
+ E = await n.fetch(C, {
6005
6189
  method: "POST",
6006
6190
  headers: { "content-type": "application/x-www-form-urlencoded" },
6007
- body: E.toString()
6191
+ body: D.toString()
6008
6192
  });
6009
- } catch (O) {
6193
+ } catch (L) {
6010
6194
  throw new c(
6011
6195
  "network_error",
6012
- `POST ${A} falhou (network): ${O?.message ?? String(O)}`
6196
+ `POST ${C} falhou (network): ${L?.message ?? String(L)}`
6013
6197
  );
6014
6198
  }
6015
- let k = null;
6199
+ let R = null;
6016
6200
  try {
6017
- k = await S.json();
6201
+ R = await E.json();
6018
6202
  } catch {
6019
- k = null;
6203
+ R = null;
6020
6204
  }
6021
- if (!S.ok || typeof k?.error == "string") {
6022
- let O = typeof k?.error_description == "string" && k.error_description || typeof k?.error == "string" && k.error || `HTTP ${S.status}`;
6205
+ if (!E.ok || typeof R?.error == "string") {
6206
+ let L = typeof R?.error_description == "string" && R.error_description || typeof R?.error == "string" && R.error || `HTTP ${E.status}`;
6023
6207
  throw new c(
6024
6208
  "token_exchange_failed",
6025
- `Troca do authorization_code por tokens falhou no /token: ${O}`,
6026
- S.status
6209
+ `Troca do authorization_code por tokens falhou no /token: ${L}`,
6210
+ E.status
6027
6211
  );
6028
6212
  }
6029
- let D = k?.id_token;
6030
- if (typeof D != "string" || D.length === 0)
6213
+ let O = R?.id_token;
6214
+ if (typeof O != "string" || O.length === 0)
6031
6215
  throw new c(
6032
6216
  "token_exchange_failed",
6033
6217
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado.",
6034
- S.status
6218
+ E.status
6035
6219
  );
6036
- let I = Je(D);
6037
- if (!I)
6220
+ let A = nt(O);
6221
+ if (!A)
6038
6222
  throw new c(
6039
6223
  "token_exchange_failed",
6040
6224
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
6041
6225
  );
6042
- if (I.nonce !== b.nonce)
6226
+ if (A.nonce !== _.nonce)
6043
6227
  throw new c(
6044
6228
  "oidc_nonce_mismatch",
6045
6229
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
6046
6230
  );
6047
- let L = re(D);
6048
- if (!L)
6231
+ let U = ie(O);
6232
+ if (!U)
6049
6233
  throw new c(
6050
6234
  "token_exchange_failed",
6051
6235
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
6052
6236
  );
6053
- let q = a();
6054
- q?.setItem(e, D);
6055
- let F = k?.refresh_token;
6056
- return typeof F == "string" && F.length > 0 && q?.setItem(t, F), o = L, R(L), u(), { user: L, postLoginRedirect: b.postLoginRedirect };
6237
+ let F = a();
6238
+ F?.setItem(e, O);
6239
+ let j = R?.refresh_token;
6240
+ return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = U, x(U), u(), { user: U, postLoginRedirect: _.postLoginRedirect };
6057
6241
  }
6058
6242
  return {
6059
- async signIn(h) {
6243
+ async signIn(m) {
6060
6244
  if (typeof globalThis.location < "u" && typeof globalThis.location.assign == "function") {
6061
- let b = Cn(), m = h?.redirectUri ?? globalThis.location.origin, T = h?.scope ?? "openid profile email", A = N(), E = Ee(b, 16), S = Ee(b, 16), k = Ee(b, 32), D = await Pn(b, k), I = l();
6062
- if (!I)
6245
+ let _ = jn(), w = m?.redirectUri ?? globalThis.location.origin, g = m?.scope ?? "openid profile email", C = T(), D = xe(_, 16), E = xe(_, 16), R = xe(_, 32), O = await Wn(_, R), A = l();
6246
+ if (!A)
6063
6247
  throw new c(
6064
6248
  "runtime_unsupported",
6065
6249
  "auth.signIn requer sessionStorage para guardar a transa\xE7\xE3o PKCE entre o redirect e o callback."
6066
6250
  );
6067
- let L = {
6068
- state: E,
6069
- nonce: S,
6070
- codeVerifier: k,
6071
- redirectUri: m,
6072
- postLoginRedirect: h?.postLoginRedirect
6251
+ let U = {
6252
+ state: D,
6253
+ nonce: E,
6254
+ codeVerifier: R,
6255
+ redirectUri: w,
6256
+ postLoginRedirect: m?.postLoginRedirect
6073
6257
  };
6074
- I.setItem(oe, JSON.stringify(L));
6075
- let q = De(n.baseUrl), F = Dn({
6076
- idpOrigin: q,
6077
- clientId: A,
6078
- redirectUri: m,
6079
- scope: T,
6080
- state: E,
6081
- nonce: S,
6082
- codeChallenge: D
6258
+ A.setItem(se, JSON.stringify(U));
6259
+ let F = oe(n.baseUrl), j = Vn({
6260
+ idpOrigin: F,
6261
+ clientId: C,
6262
+ redirectUri: w,
6263
+ scope: g,
6264
+ state: D,
6265
+ nonce: E,
6266
+ codeChallenge: O
6083
6267
  });
6084
- globalThis.location.assign(F.toString());
6268
+ globalThis.location.assign(j.toString());
6085
6269
  return;
6086
6270
  }
6087
6271
  throw new c(
@@ -6089,80 +6273,79 @@ function yo(n) {
6089
6273
  "auth.signIn requires a browser context or mocks. Use NEETRU_ENV=dev or pass mocks.auth."
6090
6274
  );
6091
6275
  },
6092
- handleRedirectCallback: C,
6093
- completeSignIn: $,
6276
+ handleRedirectCallback: P,
6277
+ completeSignIn: q,
6094
6278
  // 3.7.0: exposto pro client.support renovar a sessão 1x num 401
6095
6279
  // invalid_end_user_token (mesma função do refresh proativo, com dedup).
6096
- refreshTokens: _,
6280
+ refreshTokens: y,
6097
6281
  getIdToken() {
6098
- let b = a()?.getItem(e) ?? null;
6099
- return b && re(b) ? b : null;
6282
+ let _ = a()?.getItem(e) ?? null;
6283
+ return _ && ie(_) ? _ : null;
6100
6284
  },
6101
6285
  async signOut() {
6102
- let h = a(), b = h?.getItem(e) ?? null;
6103
- h && (h.removeItem(e), h.removeItem(t)), p(), o = null;
6104
- let A = `${(typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth.")}/api/v1/oauth/revoke`, E = b ? JSON.stringify({ token: b }) : null, S = null;
6105
- for (let k = 0; k < 2; k++)
6286
+ let m = a(), _ = m?.getItem(t) ?? null;
6287
+ if (m && (m.removeItem(e), m.removeItem(t)), p(), o = null, _) {
6288
+ let w = null;
6106
6289
  try {
6107
- E && await n.fetch(A, {
6108
- method: "POST",
6109
- headers: { "content-type": "application/json" },
6110
- body: E
6111
- }), S = null;
6112
- break;
6113
- } catch (D) {
6114
- S = D, k === 0 && await new Promise((I) => setTimeout(I, 500));
6290
+ w = T();
6291
+ } catch {
6292
+ w = null;
6115
6293
  }
6116
- S && typeof console < "u" && console.warn(
6117
- "[neetru-sdk] signOut: server-side revoke falhou (2 tentativas). Refresh token pode estar stale.",
6118
- S
6119
- ), u();
6294
+ !(w && await Kn(n.fetch, oe(n.baseUrl), w, [
6295
+ { token: _, hint: "refresh_token" }
6296
+ ])) && typeof console < "u" && console.warn(
6297
+ "[neetru-sdk] signOut: a revoga\xE7\xE3o do refresh_token no servidor n\xE3o foi confirmada. A sess\xE3o local foi encerrada, mas o refresh_token pode seguir v\xE1lido at\xE9 expirar."
6298
+ );
6299
+ }
6300
+ u();
6120
6301
  },
6121
6302
  getUser() {
6122
6303
  return d();
6123
6304
  },
6124
- onAuthStateChanged(h) {
6125
- r.add(h);
6305
+ onAuthStateChanged(m) {
6306
+ r.add(m);
6126
6307
  try {
6127
- h(d());
6308
+ m(d());
6128
6309
  } catch {
6129
6310
  }
6130
6311
  return () => {
6131
- r.delete(h);
6312
+ r.delete(m);
6132
6313
  };
6133
6314
  },
6134
- async verifyToken(h, b) {
6135
- if (!h || typeof h != "string")
6315
+ async verifyToken(m, _) {
6316
+ if (!m || typeof m != "string")
6136
6317
  throw new c("token_invalid_signature", "token must be a non-empty string");
6137
- let T = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), A = T, E = `${T}/api/v1/oauth/.well-known/jwks`, S = b?.jwksCacheTtlMs ?? mo, k = b?.audience, D = nt(n.apiKey), I = k ?? n.oidcClientId ?? D?.keyId;
6138
- if (!I)
6318
+ let g = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), C = g, D = `${g}/api/v1/oauth/.well-known/jwks`, E = _?.jwksCacheTtlMs ?? Ue, R = _?.audience, O = lt(n.apiKey), A = R ?? n.oidcClientId ?? O?.keyId;
6319
+ if (!A)
6139
6320
  throw new c(
6140
6321
  "invalid_config",
6141
6322
  "verifyToken requires an audience: provide oidcClientId/apiKey on the client or pass options.audience. Calling jwtVerify without an audience allows tokens issued for other OIDC clients to pass."
6142
6323
  );
6143
- let L = ho(E, S);
6324
+ let U = jo(D, E);
6144
6325
  try {
6145
- let { payload: q } = await jwtVerify(h, L, {
6146
- issuer: A,
6147
- audience: I,
6326
+ let { payload: F } = await jwtVerify(m, U, {
6327
+ issuer: C,
6328
+ audience: A,
6148
6329
  algorithms: ["RS256"]
6149
6330
  });
6150
- return go(q);
6151
- } catch (q) {
6152
- let F = q?.code ?? q?.name ?? "", O = q?.message ?? String(q);
6153
- throw F === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${O}`) : F === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${O}`) : F === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? O.includes('"aud"') || O.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${O}`) : O.includes('"iss"') || O.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${O}`) : new c("token_invalid_signature", `Token claim validation failed: ${O}`) : new c("token_invalid_signature", `Token verification failed: ${O}`);
6331
+ return $o(F);
6332
+ } catch (F) {
6333
+ let j = F?.code ?? F?.name ?? "", L = F?.message ?? String(F);
6334
+ throw j === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${L}`) : j === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${L}`) : j === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? L.includes('"aud"') || L.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${L}`) : L.includes('"iss"') || L.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${L}`) : new c("token_invalid_signature", `Token claim validation failed: ${L}`) : new c("token_invalid_signature", `Token verification failed: ${L}`);
6154
6335
  }
6155
6336
  }
6156
6337
  };
6157
6338
  }
6158
- function _o(n = {}) {
6339
+ function Bo(n = {}) {
6159
6340
  let e = n.fetch ?? globalThis.fetch;
6160
6341
  if (typeof e != "function")
6161
6342
  throw new c(
6162
6343
  "invalid_config",
6163
6344
  "fetch is not available in this runtime. Pass `fetch` explicitly to createNeetruClient."
6164
6345
  );
6165
- let t = n.apiKey ?? po(), r = fo(n.env), o = n.baseUrl ?? (r === "dev-local" ? at : st), i = it(o, n.allowedHosts ?? []), s = Object.freeze({
6346
+ let t = n.apiKey ?? qo();
6347
+ wt({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6348
+ let r = Fo(n.env), o = n.baseUrl ?? (r === "dev-local" ? mt : ft), i = pt(o, n.allowedHosts ?? []), s = Object.freeze({
6166
6349
  apiKey: t,
6167
6350
  oidcClientId: n.oidcClientId,
6168
6351
  baseUrl: i,
@@ -6170,36 +6353,36 @@ function _o(n = {}) {
6170
6353
  env: r,
6171
6354
  productId: n.productId,
6172
6355
  tenantId: n.tenantId
6173
- }), a = r === "dev" && !Te(), l = n.mocks?.auth ?? (a ? new Re({ ...Ge }) : yo(s)), d = n.mocks?.usage ?? (a ? new Ie() : Tt(s)), u = n.mocks?.support ?? (a ? new Ce() : Et(s, {
6174
- getEndUserToken: () => l.getIdToken(),
6175
- // `refreshTokens` é opcional no AuthNamespace (MockAuth/mocks próprios omitem).
6356
+ }), a = r === "dev" && !Ce(), l = n.mocks?.auth ?? (a ? new Ae({ ...tt }) : Wo(s)), d = n.mocks?.usage ?? (a ? new Ee() : Ut(s)), u = n.endUserAuth ?? l, p = n.mocks?.support ?? (a ? new Pe() : Wt(s, {
6357
+ getEndUserToken: () => u.getIdToken(),
6358
+ // `refreshTokens` é opcional (MockAuth/mocks próprios omitem).
6176
6359
  refreshEndUserToken: (() => {
6177
- let N = l.refreshTokens;
6178
- return typeof N == "function" ? () => N.call(l) : void 0;
6360
+ let P = u.refreshTokens;
6361
+ return typeof P == "function" ? () => P.call(u) : void 0;
6179
6362
  })()
6180
- })), p = n.mocks?.entitlements ?? (a ? new Ae() : bt()), f = n.mocks?.db ?? Jt(s, n.db), g = n.mocks?.webhooks ?? (a ? new ve() : tn(s)), _ = n.mocks?.notifications ?? (a ? new ke() : on(s)), M = n.mocks?.ai ?? (a ? new Pe() : In(s));
6181
- return Object.freeze({
6363
+ })), f = n.mocks?.entitlements ?? (a ? new De() : Dt()), h = n.mocks?.db ?? (X() === "react-native" ? Hn() : dn(s, n.db)), y = n.mocks?.webhooks ?? (a ? new Se() : hn(s)), S = n.mocks?.notifications ?? (a ? new Re() : _n(s)), x = n.mocks?.ai ?? (a ? new Ne() : Fn(s)), T = Object.freeze({
6182
6364
  config: s,
6183
6365
  auth: l,
6184
- catalog: yt(s),
6185
- entitlements: p,
6186
- telemetry: kt(s),
6366
+ catalog: Et(s),
6367
+ entitlements: f,
6368
+ telemetry: Ot(s),
6187
6369
  usage: d,
6188
- support: u,
6189
- db: f,
6190
- checkout: Xt(s),
6191
- webhooks: g,
6192
- notifications: _,
6193
- ai: M
6370
+ support: p,
6371
+ db: h,
6372
+ checkout: un(s),
6373
+ webhooks: y,
6374
+ notifications: S,
6375
+ ai: x
6194
6376
  });
6377
+ return n.endUserAuth && zn(T, n.endUserAuth), T;
6195
6378
  }
6196
- var Ne = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6197
- function ws(n = {}) {
6379
+ var Oe = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6380
+ function aa(n = {}) {
6198
6381
  let e = globalThis;
6199
- return e[Ne] || (e[Ne] = _o(n)), e[Ne];
6382
+ return e[Oe] || (e[Oe] = Bo(n)), e[Oe];
6200
6383
  }
6201
- function ks() {
6202
- delete globalThis[Ne];
6384
+ function ca() {
6385
+ delete globalThis[Oe];
6203
6386
  }
6204
6387
 
6205
- export { vs as __resetJwksCacheForTests, ks as __resetServerNeetruClientForTests, _o as createNeetruClient, ws as getServerNeetruClient };
6388
+ export { sa as __resetJwksCacheForTests, ca as __resetServerNeetruClientForTests, Bo as createNeetruClient, aa as getServerNeetruClient };