@neetru/sdk 3.8.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 (60) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/ai.cjs +1 -1
  3. package/dist/ai.d.cts +1 -1
  4. package/dist/ai.d.ts +1 -1
  5. package/dist/ai.mjs +1 -1
  6. package/dist/auth.cjs +708 -688
  7. package/dist/auth.d.cts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.mjs +705 -685
  10. package/dist/catalog.cjs +1 -1
  11. package/dist/catalog.d.cts +1 -1
  12. package/dist/catalog.d.ts +1 -1
  13. package/dist/catalog.mjs +1 -1
  14. package/dist/checkout.cjs +1 -1
  15. package/dist/checkout.d.cts +1 -1
  16. package/dist/checkout.d.ts +1 -1
  17. package/dist/checkout.mjs +1 -1
  18. package/dist/db-react.d.cts +1 -1
  19. package/dist/db-react.d.ts +1 -1
  20. package/dist/db.cjs +242 -222
  21. package/dist/db.d.cts +1 -1
  22. package/dist/db.d.ts +1 -1
  23. package/dist/db.mjs +263 -243
  24. package/dist/entitlements.d.cts +1 -1
  25. package/dist/entitlements.d.ts +1 -1
  26. package/dist/firestore-compat.d.cts +1 -1
  27. package/dist/firestore-compat.d.ts +1 -1
  28. package/dist/index.cjs +730 -710
  29. package/dist/index.d.cts +2 -2
  30. package/dist/index.d.ts +2 -2
  31. package/dist/index.mjs +874 -854
  32. package/dist/mobile.d.cts +1 -1
  33. package/dist/mobile.d.ts +1 -1
  34. package/dist/mocks.d.cts +1 -1
  35. package/dist/mocks.d.ts +1 -1
  36. package/dist/notifications.cjs +1 -1
  37. package/dist/notifications.d.cts +1 -1
  38. package/dist/notifications.d.ts +1 -1
  39. package/dist/notifications.mjs +1 -1
  40. package/dist/react.d.cts +1 -1
  41. package/dist/react.d.ts +1 -1
  42. package/dist/support.cjs +1 -1
  43. package/dist/support.d.cts +1 -1
  44. package/dist/support.d.ts +1 -1
  45. package/dist/support.mjs +1 -1
  46. package/dist/telemetry.cjs +1 -1
  47. package/dist/telemetry.d.cts +1 -1
  48. package/dist/telemetry.d.ts +1 -1
  49. package/dist/telemetry.mjs +1 -1
  50. package/dist/{types-bVztFQTI.d.ts → types-BYPk_3HR.d.ts} +56 -16
  51. package/dist/{types-D-9bjlM0.d.cts → types-yv3EDKg2.d.cts} +56 -16
  52. package/dist/usage.cjs +1 -1
  53. package/dist/usage.d.cts +1 -1
  54. package/dist/usage.d.ts +1 -1
  55. package/dist/usage.mjs +1 -1
  56. package/dist/webhooks.cjs +1 -1
  57. package/dist/webhooks.d.cts +1 -1
  58. package/dist/webhooks.d.ts +1 -1
  59. package/dist/webhooks.mjs +1 -1
  60. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
1
  import { jwtVerify, createRemoteJWKSet } from 'jose';
2
2
  import { openDB } from 'idb';
3
3
 
4
- var ir = Object.defineProperty;
4
+ var sr = Object.defineProperty;
5
5
  var W = (n, e) => () => (n && (e = n(n = 0)), e);
6
6
  var ft = (n, e) => {
7
7
  for (var t in e)
8
- ir(n, t, { get: e[t], enumerable: true });
8
+ sr(n, t, { get: e[t], enumerable: true });
9
9
  };
10
10
 
11
11
  // src/errors.ts
12
- var l, $, C = W(() => {
13
- l = class n extends Error {
12
+ var c, $, C = W(() => {
13
+ c = class n extends Error {
14
14
  code;
15
15
  status;
16
16
  requestId;
@@ -33,7 +33,7 @@ var l, $, C = W(() => {
33
33
  constructor(e, t, r, o, i, s) {
34
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);
35
35
  }
36
- }, $ = class n extends l {
36
+ }, $ = class n extends c {
37
37
  constructor(e, t, r, o, i) {
38
38
  super("auth_required", e, r, o, t, i), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, n.prototype);
39
39
  }
@@ -45,7 +45,7 @@ function kt() {
45
45
  let n = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
46
46
  if (n && typeof n.randomUUID == "function")
47
47
  return n.randomUUID();
48
- throw new l(
48
+ throw new c(
49
49
  "runtime_unsupported",
50
50
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
51
51
  );
@@ -56,9 +56,9 @@ var St = W(() => {
56
56
 
57
57
  // src/correlation.ts
58
58
  function Rt(n) {
59
- return typeof n == "string" && n.length > 0 && n.length <= 128 && pr.test(n);
59
+ return typeof n == "string" && n.length > 0 && n.length <= 128 && fr.test(n);
60
60
  }
61
- function fr() {
61
+ function mr() {
62
62
  let n = globalThis.crypto;
63
63
  try {
64
64
  if (n && typeof n.randomUUID == "function") return n.randomUUID();
@@ -85,11 +85,11 @@ function _e(n, e) {
85
85
  }
86
86
  r[i] = s;
87
87
  }
88
- let o = t ?? (Rt(e) ? e : void 0) ?? fr();
88
+ let o = t ?? (Rt(e) ? e : void 0) ?? mr();
89
89
  return r[Tt] = o, { headers: r, correlationId: o };
90
90
  }
91
- var Tt, pr, We = W(() => {
92
- Tt = "x-correlation-id", pr = /^[A-Za-z0-9._:\-]+$/;
91
+ var Tt, fr, We = W(() => {
92
+ Tt = "x-correlation-id", fr = /^[A-Za-z0-9._:\-]+$/;
93
93
  });
94
94
 
95
95
  // src/server-only-key.ts
@@ -107,7 +107,7 @@ function Q() {
107
107
  return null;
108
108
  }
109
109
  function It(n, e) {
110
- let t = mr[n];
110
+ let t = hr[n];
111
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
112
  }
113
113
  function At(n) {
@@ -115,7 +115,7 @@ function At(n) {
115
115
  let e = n.runtime === void 0 ? Q() : n.runtime;
116
116
  if (e) {
117
117
  if (n.strict)
118
- throw new l("server_only_key", It(e, true), void 0, void 0, e);
118
+ throw new c("server_only_key", It(e, true), void 0, void 0, e);
119
119
  if (!Ct) {
120
120
  Ct = true;
121
121
  try {
@@ -125,9 +125,9 @@ function At(n) {
125
125
  }
126
126
  }
127
127
  }
128
- var mr, Ct, be = W(() => {
128
+ var hr, Ct, be = W(() => {
129
129
  C();
130
- mr = {
130
+ hr = {
131
131
  browser: "no navegador",
132
132
  "react-native": "num app React Native"
133
133
  };
@@ -144,7 +144,7 @@ ft(ne, {
144
144
  function $e(n) {
145
145
  return n.split("+")[0] ?? n;
146
146
  }
147
- function gr(n, e) {
147
+ function yr(n, e) {
148
148
  let t = $e(n).split(".").map(Number), r = $e(e).split(".").map(Number), o = Math.max(t.length, r.length);
149
149
  for (let i = 0; i < o; i++) {
150
150
  let s = t[i] ?? 0, a = r[i] ?? 0;
@@ -154,28 +154,28 @@ function gr(n, e) {
154
154
  }
155
155
  function Ot() {
156
156
  try {
157
- return "3.8.0";
157
+ return "3.8.1";
158
158
  } catch {
159
159
  return;
160
160
  }
161
161
  }
162
- function yr() {
162
+ function _r() {
163
163
  let n = Ot();
164
164
  return n ? parseInt(n.split(".")[0] ?? "3", 10) : 3;
165
165
  }
166
166
  function te(n) {
167
167
  if (!n) return;
168
- let e = yr(), t = hr[e];
168
+ let e = _r(), t = gr[e];
169
169
  if (!t) return;
170
170
  let r = $e(n);
171
- if (gr(r, t) < 0) {
171
+ if (yr(r, t) < 0) {
172
172
  let o = `${e}:${r}`;
173
173
  Et.has(o) || (Et.add(o), console.warn(
174
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.`
175
175
  ));
176
176
  }
177
177
  }
178
- function _r() {
178
+ function br() {
179
179
  let n = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
180
180
  return Q() ? "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
181
  }
@@ -183,7 +183,7 @@ function Pt(n) {
183
183
  let e = 200 * Math.pow(4, n), t = e * 0.2 * (Math.random() * 2 - 1);
184
184
  return Math.max(50, Math.round(e + t));
185
185
  }
186
- function Sr(n) {
186
+ function Tr(n) {
187
187
  if (!n) return null;
188
188
  let e = Number(n);
189
189
  if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), Dt);
@@ -200,7 +200,7 @@ function Nt(n) {
200
200
  function ve(n) {
201
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";
202
202
  }
203
- function Tr(n, e, t) {
203
+ function Rr(n, e, t) {
204
204
  let r = n.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, i = new URL(`${r}${o}`);
205
205
  if (t)
206
206
  for (let [s, a] of Object.entries(t))
@@ -217,25 +217,25 @@ async function xt(n) {
217
217
  }
218
218
  }
219
219
  async function S(n, e) {
220
- let t = e.method ?? "GET", r = Tr(n.baseUrl, e.path, e.query), o = wr.has(t) ? br : vr, i = e.retries ?? o, { headers: s, correlationId: a } = _e(
220
+ let t = e.method ?? "GET", r = Rr(n.baseUrl, e.path, e.query), o = kr.has(t) ? vr : wr, i = e.retries ?? o, { headers: s, correlationId: a } = _e(
221
221
  { accept: "application/json", ...e.headers },
222
222
  e.correlationId
223
- ), c = Ot();
224
- if (c && (s["x-neetru-sdk-version"] = c), e.requireAuth) {
223
+ ), d = Ot();
224
+ if (d && (s["x-neetru-sdk-version"] = d), e.requireAuth) {
225
225
  if (!n.apiKey)
226
- throw new l("missing_api_key", _r());
226
+ throw new c("missing_api_key", br());
227
227
  s.authorization = `Bearer ${n.apiKey}`;
228
228
  }
229
229
  if (e.idempotencyKey) {
230
230
  let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : kt();
231
231
  s["idempotency-key"] = f;
232
232
  }
233
- let u = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
234
- u !== void 0 && (s["content-type"] = "application/json");
235
- let d = null, p = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
233
+ let p = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
234
+ p !== void 0 && (s["content-type"] = "application/json");
235
+ let l = null, u = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
236
236
  for (let f = 0; f <= i; f++) {
237
- if (p != null && Date.now() >= p)
238
- throw d ?? new l(
237
+ if (u != null && Date.now() >= u)
238
+ throw l ?? new c(
239
239
  "network_error",
240
240
  "Deadline excedido antes de completar a request",
241
241
  void 0,
@@ -244,22 +244,22 @@ async function S(n, e) {
244
244
  a
245
245
  );
246
246
  let m = { method: t, headers: s };
247
- u !== void 0 && (m.body = u);
248
- let h = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
247
+ p !== void 0 && (m.body = p);
248
+ let h = u != null ? Math.max(1, Math.min(3e4, u - Date.now())) : 3e4;
249
249
  m.signal = AbortSignal.timeout(h);
250
250
  let y;
251
251
  try {
252
252
  y = await n.fetch(r, m);
253
253
  } catch (b) {
254
254
  let E = b instanceof DOMException && b.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${b instanceof Error ? b.message : "fetch failed"}`;
255
- if (d = new l("network_error", E, void 0, void 0, void 0, a), f < i) {
255
+ if (l = new c("network_error", E, void 0, void 0, void 0, a), f < i) {
256
256
  let x = Pt(f);
257
- if (p == null || Date.now() + x < p) {
257
+ if (u == null || Date.now() + x < u) {
258
258
  await Nt(x);
259
259
  continue;
260
260
  }
261
261
  }
262
- throw d;
262
+ throw l;
263
263
  }
264
264
  let I = y.headers.get("x-request-id") ?? y.headers.get("x-correlation-id") ?? void 0;
265
265
  if (y.ok) {
@@ -275,30 +275,30 @@ async function S(n, e) {
275
275
  let b = y.headers.get("x-neetru-replacement");
276
276
  N === `HTTP ${y.status}` && (N = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), b && !N.includes(b) && (N += ` Substituto: ${b}.`);
277
277
  }
278
- let _ = new l(k, N, y.status, I, g, a);
279
- if (d = _, kr.has(k) && f < i) {
280
- let E = Sr(y.headers.get("retry-after")) ?? Pt(f);
281
- if (p == null || Date.now() + E < p) {
278
+ let _ = new c(k, N, y.status, I, g, a);
279
+ if (l = _, Sr.has(k) && f < i) {
280
+ let E = Tr(y.headers.get("retry-after")) ?? Pt(f);
281
+ if (u == null || Date.now() + E < u) {
282
282
  await Nt(E);
283
283
  continue;
284
284
  }
285
285
  }
286
286
  throw _;
287
287
  }
288
- throw d ?? new l("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
288
+ throw l ?? new c("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
289
289
  }
290
- var hr, Et, br, vr, wr, kr, Dt, q = W(() => {
290
+ var gr, Et, vr, wr, kr, Sr, Dt, q = W(() => {
291
291
  C();
292
292
  St();
293
293
  We();
294
294
  be();
295
- hr = {
295
+ gr = {
296
296
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
297
297
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
298
298
  3: "2026.05.1"
299
299
  };
300
300
  Et = /* @__PURE__ */ new Set();
301
- br = 2, vr = 0, wr = /* @__PURE__ */ new Set(["GET", "HEAD"]), kr = /* @__PURE__ */ new Set([
301
+ vr = 2, wr = 0, kr = /* @__PURE__ */ new Set(["GET", "HEAD"]), Sr = /* @__PURE__ */ new Set([
302
302
  "rate_limited",
303
303
  "server_error",
304
304
  "network_error"
@@ -307,13 +307,13 @@ var hr, Et, br, vr, wr, kr, Dt, q = W(() => {
307
307
  });
308
308
 
309
309
  // src/db-errors.ts
310
- var Mr, v, z = W(() => {
310
+ var qr, v, z = W(() => {
311
311
  C();
312
- Mr = /* @__PURE__ */ new Set([
312
+ qr = /* @__PURE__ */ new Set([
313
313
  "db_unavailable",
314
314
  "db_conflict",
315
315
  "db_timeout"
316
- ]), v = class n extends l {
316
+ ]), v = class n extends c {
317
317
  /** Código de erro fechado — específico de DB. */
318
318
  code;
319
319
  /**
@@ -327,7 +327,7 @@ var Mr, v, z = W(() => {
327
327
  */
328
328
  dbId;
329
329
  constructor(e, t, r) {
330
- super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Mr.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
330
+ super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = qr.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
331
331
  }
332
332
  };
333
333
  });
@@ -336,7 +336,7 @@ var Mr, v, z = W(() => {
336
336
  function De(n) {
337
337
  return typeof n == "object" && n !== null && n[Xe] === true;
338
338
  }
339
- function io(n) {
339
+ function so(n) {
340
340
  let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
341
341
  if (e === "ECONNREFUSED" || e === "ETIMEDOUT" || e === "ENOTFOUND" || e === "EHOSTUNREACH" || e === "EAI_AGAIN")
342
342
  return true;
@@ -348,56 +348,73 @@ function io(n) {
348
348
  let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
349
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"));
350
350
  }
351
+ function rn(n) {
352
+ let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
353
+ if (typeof e == "string" && ao.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 co(n) {
359
+ return so(n) || rn(n);
360
+ }
351
361
  function Ye(n) {
352
362
  let e = { current: n }, t = null, r = {
353
- __neetruSwapInner(c) {
363
+ __neetruSwapInner(l) {
354
364
  let u = e.current;
355
- return e.current = c, u;
365
+ return e.current = l, u;
356
366
  },
357
367
  __neetruGetInner() {
358
368
  return e.current;
359
369
  },
360
- __neetruSetReLease(c) {
361
- t = c;
370
+ __neetruSetReLease(l) {
371
+ t = l;
362
372
  }
363
- }, o = (c, u) => c.query(...u), i = (...c) => c.length > 0 && typeof c[c.length - 1] == "function" ? o(e.current, c) : (async () => {
373
+ }, o = (l, u, f) => u[l](
374
+ ...f
375
+ ), i = (l, u) => (...f) => f.length > 0 && typeof f[f.length - 1] == "function" ? o(l, e.current, f) : (async () => {
364
376
  try {
365
- return await o(e.current, c);
366
- } catch (u) {
367
- let d = t;
368
- if (d === null || !io(u))
369
- throw u;
377
+ return await o(l, e.current, f);
378
+ } catch (m) {
379
+ let h = t;
380
+ if (h === null || !u(m))
381
+ throw m;
370
382
  try {
371
- await d();
383
+ await h();
372
384
  } catch {
373
- throw u;
385
+ throw m;
374
386
  }
375
- return await o(e.current, c);
387
+ return await o(l, e.current, f);
376
388
  }
377
- })(), s = Object.create(Object.getPrototypeOf(n));
378
- return new Proxy(s, {
379
- get(c, u) {
389
+ })(), s = i("query", co), a = i("connect", rn), d = Object.create(Object.getPrototypeOf(n));
390
+ return new Proxy(d, {
391
+ get(l, u) {
380
392
  if (u === Xe) return true;
381
393
  if (u === "__neetruSwapInner") return r.__neetruSwapInner;
382
394
  if (u === "__neetruGetInner") return r.__neetruGetInner;
383
395
  if (u === "__neetruSetReLease") return r.__neetruSetReLease;
384
- if (u === "query") return i;
396
+ if (u === "query") return s;
397
+ if (u === "connect") {
398
+ let h = e.current;
399
+ return typeof h.connect == "function" ? a : h.connect;
400
+ }
385
401
  if (u === "constructor")
386
402
  return e.current.constructor;
387
- let d = e.current, p = Reflect.get(d, u, d);
388
- return typeof p == "function" ? p.bind(d) : p;
403
+ let f = e.current, m = Reflect.get(f, u, f);
404
+ return typeof m == "function" ? m.bind(f) : m;
389
405
  }
390
406
  });
391
407
  }
392
- var Xe, Ze = W(() => {
408
+ var Xe, ao, Ze = W(() => {
393
409
  Xe = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
410
+ ao = /* @__PURE__ */ new Set(["28P01", "28000"]);
394
411
  });
395
412
 
396
413
  // src/db/sql/lease.ts
397
- function ao(n, e) {
414
+ function uo(n, e) {
398
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;
399
416
  }
400
- function co(n) {
417
+ function po(n) {
401
418
  if (n instanceof v) return n;
402
419
  let e = n instanceof Error ? n.message : String(n), t = n instanceof Error ? n.code : void 0;
403
420
  return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new v(
@@ -405,10 +422,10 @@ function co(n) {
405
422
  `Pool connection failed (${t}): ${e}`
406
423
  ) : e.includes("statement timeout") || e.includes("lock timeout") ? new v("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new v("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new v("db_permission_denied", `Permission denied: ${e}`) : new v("db_unavailable", `Database error: ${e}`);
407
424
  }
408
- var so, Z, se, rn = W(() => {
425
+ var lo, Z, se, on = W(() => {
409
426
  z();
410
427
  Ze();
411
- so = 0.8, Z = 3e4, se = class {
428
+ lo = 0.8, Z = 3e4, se = class {
412
429
  /**
413
430
  * Lease atual. `null` no modo LAZY antes da 1ª query (o 1º lease é adiado —
414
431
  * ver `_ensureInitialLease`). Após a 1ª aquisição, sempre não-nulo.
@@ -448,7 +465,7 @@ var so, Z, se, rn = W(() => {
448
465
  isolationLevel: t.isolationLevel
449
466
  }) : await this._orm.transaction(e);
450
467
  } catch (r) {
451
- throw co(r);
468
+ throw po(r);
452
469
  }
453
470
  }
454
471
  async close() {
@@ -471,7 +488,7 @@ var so, Z, se, rn = W(() => {
471
488
  if (!Number.isFinite(e)) return Z;
472
489
  let t = this._deps.now(), r = e - t;
473
490
  if (r <= 0) return Z;
474
- let o = r * (1 - so);
491
+ let o = r * (1 - lo);
475
492
  return Math.max(Z, Math.round(o));
476
493
  }
477
494
  _scheduleRenewal() {
@@ -500,7 +517,7 @@ var so, Z, se, rn = W(() => {
500
517
  this._renewalTimer = setTimeout(() => {
501
518
  this._doRenew();
502
519
  }, Z), console.warn(
503
- `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${Z}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 ${Z}ms (o cert de cliente mTLS do lease expira ~15min ap\xF3s o \xFAltimo swap):`,
504
521
  t instanceof Error ? t.message : t
505
522
  );
506
523
  return;
@@ -512,10 +529,13 @@ var so, Z, se, rn = W(() => {
512
529
  /**
513
530
  * Recuperação REATIVA: chamado pelo wrapper resiliente (`resilient-pool.ts`)
514
531
  * quando uma query plana falha num erro de ESTABELECIMENTO de conexão (cert
515
- * TLS efêmero do servidor expirado no meio de uma request, ou timer de
516
- * renovação que não disparou). Emite um lease NOVO e faz o swap do pool interno
517
- * do wrapper com
518
- * 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.
519
539
  *
520
540
  * Vai DIRETO ao lease novo (sem `leaseId`) — a conexão falhou porque o
521
541
  * certificado do lease atual está ruim, então `renew` (que depende do lease
@@ -607,7 +627,7 @@ var so, Z, se, rn = W(() => {
607
627
  * Exposto como método protegido para testes.
608
628
  */
609
629
  async _swapPool(e) {
610
- if (!ao(this._lease, e)) {
630
+ if (!uo(this._lease, e)) {
611
631
  this._lease = e;
612
632
  return;
613
633
  }
@@ -634,29 +654,29 @@ var so, Z, se, rn = W(() => {
634
654
  });
635
655
 
636
656
  // src/db/sql/sql-client.ts
637
- var pn = {};
638
- ft(pn, {
639
- DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => dn,
640
- DEFAULT_POOL_IDLE_MS: () => ln,
641
- DEFAULT_POOL_MAX: () => cn,
642
- LEASE_ENDPOINT: () => on,
643
- LEASE_RENEW_ENDPOINT: () => sn,
644
- createDrizzleHandle: () => fo,
645
- createHttpLeaseFetcher: () => an,
646
- createPgPool: () => po,
647
- createSqlClientFromConfig: () => ho,
648
- createSqlClientWithDeps: () => un,
657
+ var fn = {};
658
+ ft(fn, {
659
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => un,
660
+ DEFAULT_POOL_IDLE_MS: () => dn,
661
+ DEFAULT_POOL_MAX: () => ln,
662
+ LEASE_ENDPOINT: () => sn,
663
+ LEASE_RENEW_ENDPOINT: () => an,
664
+ createDrizzleHandle: () => go,
665
+ createHttpLeaseFetcher: () => cn,
666
+ createPgPool: () => ho,
667
+ createSqlClientFromConfig: () => _o,
668
+ createSqlClientWithDeps: () => pn,
649
669
  resolvePoolTuning: () => tt
650
670
  });
651
- function lo(n) {
671
+ function fo(n) {
652
672
  return n === "workspace" ? "staging" : n === "prod" ? "production" : "dev-local";
653
673
  }
654
- function an(n) {
674
+ function cn(n) {
655
675
  return async (e) => {
656
- let { httpRequest: t } = await Promise.resolve().then(() => (q(), ne)), r = !!e?.leaseId, o = r ? sn : on, i;
676
+ let { httpRequest: t } = await Promise.resolve().then(() => (q(), ne)), r = !!e?.leaseId, o = r ? an : sn, i;
657
677
  r ? i = { leaseId: e.leaseId } : (i = {
658
678
  productId: n.productId ?? "",
659
- environment: lo(n.env ?? "prod")
679
+ environment: fo(n.env ?? "prod")
660
680
  }, e?.database !== void 0 && (i.database = e.database));
661
681
  let s;
662
682
  try {
@@ -669,23 +689,23 @@ function an(n) {
669
689
  retries: 2
670
690
  });
671
691
  } catch (a) {
672
- let c = r ? "renovar" : "obter", u = a instanceof Error ? a.message : String(a), d = a instanceof l ? a.reason : void 0;
673
- if (d === "suspended" || d === "archived" || d === "revoked") {
674
- let p = d === "suspended" ? "ambiente suspenso \u2014 a m\xE1quina que o servia parou; ser\xE1 religado quando o ambiente voltar" : d === "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";
692
+ let d = r ? "renovar" : "obter", p = a instanceof Error ? a.message : String(a), l = a instanceof c ? a.reason : void 0;
693
+ if (l === "suspended" || l === "archived" || l === "revoked") {
694
+ let u = l === "suspended" ? "ambiente suspenso \u2014 a m\xE1quina que o servia parou; ser\xE1 religado quando o ambiente voltar" : l === "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";
675
695
  throw new v(
676
696
  "db_suspended",
677
- `Falha ao ${c} lease SQL: ${p} (reason=${d}).`
697
+ `Falha ao ${d} lease SQL: ${u} (reason=${l}).`
678
698
  );
679
699
  }
680
700
  throw new v(
681
701
  "db_unavailable",
682
- `Falha ao ${c} lease SQL: ${u}`
702
+ `Falha ao ${d} lease SQL: ${p}`
683
703
  );
684
704
  }
685
- return uo(s);
705
+ return mo(s);
686
706
  };
687
707
  }
688
- function uo(n) {
708
+ function mo(n) {
689
709
  if (!n || typeof n != "object")
690
710
  throw new v("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
691
711
  let t = n.lease;
@@ -727,12 +747,12 @@ function tt() {
727
747
  return {
728
748
  // Teto 100: bem abaixo do `max_client_conn = 500` do PgBouncer, com folga
729
749
  // para múltiplas instâncias do app dividirem o mesmo front-door.
730
- max: et("NEETRU_DB_POOL_MAX", cn, 1, 100),
750
+ max: et("NEETRU_DB_POOL_MAX", ln, 1, 100),
731
751
  // Teto 15min = janela do cert; piso 1s.
732
- idleTimeoutMillis: et("NEETRU_DB_POOL_IDLE_MS", ln, 1e3, 9e5),
752
+ idleTimeoutMillis: et("NEETRU_DB_POOL_IDLE_MS", dn, 1e3, 9e5),
733
753
  connectionTimeoutMillis: et(
734
754
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
735
- dn,
755
+ un,
736
756
  1e3,
737
757
  12e4
738
758
  ),
@@ -740,7 +760,7 @@ function tt() {
740
760
  keepAliveInitialDelayMillis: 1e4
741
761
  };
742
762
  }
743
- async function po(n) {
763
+ async function ho(n) {
744
764
  let { Pool: e } = await import(
745
765
  /* webpackIgnore: true */
746
766
  'pg'
@@ -760,14 +780,14 @@ async function po(n) {
760
780
  ...tt()
761
781
  });
762
782
  }
763
- async function fo(n, e) {
783
+ async function go(n, e) {
764
784
  let { drizzle: t } = await import(
765
785
  /* webpackIgnore: true */
766
786
  'drizzle-orm/node-postgres'
767
787
  );
768
788
  return t(n, { schema: e });
769
789
  }
770
- function mo(n, e) {
790
+ function yo(n, e) {
771
791
  let t = null, r = null, o = () => t ? Promise.resolve(t) : (r || (r = e().then((s) => (t = s, r = null, s)).catch((s) => {
772
792
  throw r = null, s;
773
793
  })), r), i = {
@@ -783,52 +803,52 @@ function mo(n, e) {
783
803
  };
784
804
  return n && Object.setPrototypeOf(i, n), i;
785
805
  }
786
- async function un(n, e) {
806
+ async function pn(n, e) {
787
807
  let t = e?.database !== void 0 ? { ...n, database: e.database } : n;
788
808
  if (t.lazy) {
789
- let c = null, u = mo(t.poolPrototype ?? null, () => {
790
- if (!c)
809
+ let d = null, p = yo(t.poolPrototype ?? null, () => {
810
+ if (!d)
791
811
  throw new v("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
792
- return c._ensureInitialLease();
793
- }), d = Ye(u), p;
812
+ return d._ensureInitialLease();
813
+ }), l = Ye(p), u;
794
814
  try {
795
- p = t.createDrizzle(d, t.schema);
815
+ u = t.createDrizzle(l, t.schema);
796
816
  } catch (m) {
797
817
  let h = m instanceof Error ? m.message : String(m);
798
818
  throw new v("db_unavailable", `Falha ao criar handle Drizzle: ${h}`);
799
819
  }
800
- let f = new se(null, d, p, t);
801
- return c = f, d.__neetruSetReLease(() => f._reactiveReLease()), f;
820
+ let f = new se(null, l, u, t);
821
+ return d = f, l.__neetruSetReLease(() => f._reactiveReLease()), f;
802
822
  }
803
823
  let r;
804
824
  try {
805
825
  e?.database !== void 0 ? r = await t.fetchLease({ database: e.database }) : r = await t.fetchLease();
806
- } catch (c) {
807
- if (c instanceof v) throw c;
808
- let u = c instanceof Error ? c.message : String(c);
809
- throw new v("db_unavailable", `Falha ao obter lease inicial: ${u}`);
826
+ } catch (d) {
827
+ if (d instanceof v) throw d;
828
+ let p = d instanceof Error ? d.message : String(d);
829
+ throw new v("db_unavailable", `Falha ao obter lease inicial: ${p}`);
810
830
  }
811
831
  let o;
812
832
  try {
813
833
  o = t.createPool(r);
814
- } catch (c) {
815
- let u = c instanceof Error ? c.message : String(c);
816
- throw new v("db_unavailable", `Falha ao abrir pool: ${u}`);
834
+ } catch (d) {
835
+ let p = d instanceof Error ? d.message : String(d);
836
+ throw new v("db_unavailable", `Falha ao abrir pool: ${p}`);
817
837
  }
818
838
  let i = Ye(o), s;
819
839
  try {
820
840
  s = t.createDrizzle(i, t.schema);
821
- } catch (c) {
841
+ } catch (d) {
822
842
  await o.end().catch(() => {
823
843
  });
824
- let u = c instanceof Error ? c.message : String(c);
825
- throw new v("db_unavailable", `Falha ao criar handle Drizzle: ${u}`);
844
+ let p = d instanceof Error ? d.message : String(d);
845
+ throw new v("db_unavailable", `Falha ao criar handle Drizzle: ${p}`);
826
846
  }
827
847
  let a = new se(r, i, s, t);
828
848
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
829
849
  }
830
- async function ho(n, e, t) {
831
- let r = an(n), o, i;
850
+ async function _o(n, e, t) {
851
+ let r = cn(n), o, i;
832
852
  try {
833
853
  o = await import(
834
854
  /* webpackIgnore: true */
@@ -837,36 +857,36 @@ async function ho(n, e, t) {
837
857
  /* webpackIgnore: true */
838
858
  'drizzle-orm/node-postgres'
839
859
  );
840
- } catch (u) {
860
+ } catch (p) {
841
861
  throw new v(
842
862
  "db_unavailable",
843
- `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${u.message})`
863
+ `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${p.message})`
844
864
  );
845
865
  }
846
866
  let s = o.Pool ?? o.default?.Pool;
847
- return un(
867
+ return pn(
848
868
  {
849
869
  fetchLease: r,
850
- createPool: (u) => {
851
- let d = u.sslca ? {
852
- ca: u.sslca,
853
- cert: u.clientCert ?? void 0,
854
- key: u.clientKey ?? void 0,
870
+ createPool: (p) => {
871
+ let l = p.sslca ? {
872
+ ca: p.sslca,
873
+ cert: p.clientCert ?? void 0,
874
+ key: p.clientKey ?? void 0,
855
875
  rejectUnauthorized: true
856
876
  } : false;
857
877
  return new s({
858
- host: u.host,
859
- port: u.port,
860
- database: u.dbName,
861
- user: u.user,
862
- password: u.password,
863
- ssl: d,
878
+ host: p.host,
879
+ port: p.port,
880
+ database: p.dbName,
881
+ user: p.user,
882
+ password: p.password,
883
+ ssl: l,
864
884
  // Tuning centralizado (env-tunável) — ver resolvePoolTuning + auditoria
865
885
  // docs/_review/AUDITORIA_DB_CONN_PERF_2026-09-06.md no Core.
866
886
  ...tt()
867
887
  });
868
888
  },
869
- createDrizzle: (u, d) => i.drizzle(u, { schema: d }),
889
+ createDrizzle: (p, l) => i.drizzle(p, { schema: l }),
870
890
  schema: e,
871
891
  // Lease inicial LAZY (motor de ambientes suspenso): `client.db.sql()` não
872
892
  // pode explodir o `import` do módulo do produto quando o ambiente está
@@ -879,13 +899,13 @@ async function ho(n, e, t) {
879
899
  t
880
900
  );
881
901
  }
882
- var on, sn, cn, ln, dn, fn = W(() => {
902
+ var sn, an, ln, dn, un, mn = W(() => {
883
903
  z();
884
904
  C();
885
- rn();
905
+ on();
886
906
  Ze();
887
- on = "/api/sdk/v1/db/lease", sn = "/api/sdk/v1/db/lease/renew";
888
- cn = 10, ln = 6e4, dn = 1e4;
907
+ sn = "/api/sdk/v1/db/lease", an = "/api/sdk/v1/db/lease/renew";
908
+ ln = 10, dn = 6e4, un = 1e4;
889
909
  });
890
910
  var mt = /* @__PURE__ */ new Map(), ee = 3600 * 1e3;
891
911
  function ye(n, e = ee) {
@@ -904,13 +924,13 @@ C();
904
924
  var ht = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
905
925
  function gt(n) {
906
926
  if (typeof n != "string" || n.length === 0)
907
- throw new l(
927
+ throw new c(
908
928
  "invalid_config",
909
929
  "apiKey is required (formato nrt_<keyId>_<secret>)"
910
930
  );
911
931
  let e = ht.exec(n);
912
932
  if (!e)
913
- throw new l(
933
+ throw new c(
914
934
  "invalid_config",
915
935
  "apiKey malformado - esperado formato nrt_<keyId>_<secret>"
916
936
  );
@@ -924,52 +944,52 @@ function yt(n) {
924
944
 
925
945
  // src/base-url-allowlist.ts
926
946
  C();
927
- var _t = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), ar = ".neetru.com", cr = "neetru.com", lr = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
947
+ var _t = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), cr = ".neetru.com", lr = "neetru.com", dr = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
928
948
  function bt(n) {
929
- return lr.test(n);
949
+ return dr.test(n);
930
950
  }
931
- function dr(n) {
951
+ function ur(n) {
932
952
  return n.toLowerCase().replace(/\.+$/, "");
933
953
  }
934
954
  function vt(n, e = []) {
935
955
  if (typeof n != "string" || n.length === 0)
936
- throw new l("invalid_config", "baseUrl is required");
956
+ throw new c("invalid_config", "baseUrl is required");
937
957
  let t;
938
958
  try {
939
959
  t = new URL(n);
940
960
  } catch {
941
- throw new l("invalid_config", `baseUrl is not a valid URL: ${n}`);
961
+ throw new c("invalid_config", `baseUrl is not a valid URL: ${n}`);
942
962
  }
943
- let r = t.protocol, o = dr(t.hostname);
944
- if (ur())
963
+ let r = t.protocol, o = ur(t.hostname);
964
+ if (pr())
945
965
  return typeof console < "u" && console.warn(
946
966
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${n} aceito sem valida\xE7\xE3o.`
947
967
  ), n.replace(/\/+$/, "");
948
968
  if (r !== "https:" && r !== "http:")
949
- throw new l(
969
+ throw new c(
950
970
  "invalid_config",
951
971
  `baseUrl protocol must be http: or https:, got ${r}`
952
972
  );
953
973
  if (r === "http:") {
954
974
  if (!(_t.has(o) || bt(o)))
955
- throw new l(
975
+ throw new c(
956
976
  "invalid_config",
957
977
  `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.`
958
978
  );
959
979
  return n.replace(/\/+$/, "");
960
980
  }
961
- let i = o === cr || o.endsWith(ar), s = e.some((c) => {
962
- let u = c.toLowerCase();
963
- return o === u || o.endsWith(`.${u}`);
981
+ let i = o === lr || o.endsWith(cr), s = e.some((d) => {
982
+ let p = d.toLowerCase();
983
+ return o === p || o.endsWith(`.${p}`);
964
984
  }), a = _t.has(o) || bt(o);
965
985
  if (!i && !s && !a)
966
- throw new l(
986
+ throw new c(
967
987
  "invalid_config",
968
988
  `baseUrl ${o} is not in the allowlist. Allowed: *.neetru.com, localhost, or configure { allowedHosts: ['...'] }. Bypass: NEETRU_ALLOW_INSECURE_BASEURL=1.`
969
989
  );
970
990
  return n.replace(/\/+$/, "");
971
991
  }
972
- function ur() {
992
+ function pr() {
973
993
  try {
974
994
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
975
995
  if (e === "1" || e === "true") return !0;
@@ -991,12 +1011,12 @@ C();
991
1011
  q();
992
1012
  function Lt(n) {
993
1013
  if (!n || typeof n != "object")
994
- throw new l("invalid_response", "Catalog response item is not an object");
1014
+ throw new c("invalid_response", "Catalog response item is not an object");
995
1015
  let e = n;
996
1016
  if (typeof e.slug != "string" || !e.slug)
997
- throw new l("invalid_response", "Catalog product missing slug");
1017
+ throw new c("invalid_response", "Catalog product missing slug");
998
1018
  if (typeof e.name != "string" || !e.name)
999
- throw new l("invalid_response", "Catalog product missing name");
1019
+ throw new c("invalid_response", "Catalog product missing name");
1000
1020
  let t = {
1001
1021
  slug: e.slug,
1002
1022
  name: e.name
@@ -1020,7 +1040,7 @@ function Ut(n) {
1020
1040
  path: "/api/sdk/v1/catalog"
1021
1041
  });
1022
1042
  if (!t || !Array.isArray(t.products))
1023
- throw new l(
1043
+ throw new c(
1024
1044
  "invalid_response",
1025
1045
  "Catalog list response missing products array"
1026
1046
  );
@@ -1036,13 +1056,13 @@ function Ut(n) {
1036
1056
  */
1037
1057
  async get(e) {
1038
1058
  if (!e || typeof e != "string")
1039
- throw new l("validation_failed", "slug is required");
1059
+ throw new c("validation_failed", "slug is required");
1040
1060
  let t = await S(n, {
1041
1061
  method: "GET",
1042
1062
  path: `/api/sdk/v1/catalog/${encodeURIComponent(e)}`
1043
1063
  });
1044
1064
  if (!t || !t.product)
1045
- throw new l(
1065
+ throw new c(
1046
1066
  "invalid_response",
1047
1067
  "Catalog get response missing product"
1048
1068
  );
@@ -1053,9 +1073,9 @@ function Ut(n) {
1053
1073
 
1054
1074
  // src/entitlements.ts
1055
1075
  C();
1056
- var Rr = "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.";
1076
+ var Ir = "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.";
1057
1077
  function Mt() {
1058
- throw new l("validation_failed", Rr);
1078
+ throw new c("validation_failed", Ir);
1059
1079
  }
1060
1080
  function qt(n) {
1061
1081
  return {
@@ -1083,13 +1103,13 @@ function qt(n) {
1083
1103
  C();
1084
1104
  q();
1085
1105
  var Ft = ["debug", "info", "warn", "error", "fatal"];
1086
- function Ir() {
1106
+ function Cr() {
1087
1107
  return typeof globalThis < "u" && typeof globalThis.window < "u";
1088
1108
  }
1089
1109
  function jt() {
1090
- return Ir() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1110
+ return Cr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1091
1111
  }
1092
- function Cr(n) {
1112
+ function Ar(n) {
1093
1113
  switch (n) {
1094
1114
  case "debug":
1095
1115
  return console.debug.bind(console);
@@ -1105,30 +1125,30 @@ function Cr(n) {
1105
1125
  return console.log.bind(console);
1106
1126
  }
1107
1127
  }
1108
- var Ar = 500, Er = 50;
1128
+ var Er = 500, Pr = 50;
1109
1129
  function Wt(n) {
1110
1130
  let e = [], t = null, r = null;
1111
1131
  async function o() {
1112
1132
  if (e.length === 0) return;
1113
1133
  let s = e.splice(0, e.length), a = Promise.allSettled(
1114
- s.map(async (c) => {
1134
+ s.map(async (d) => {
1115
1135
  try {
1116
- let u = { name: c.name }, d = c.productSlug ?? n.productId;
1117
- d && (u.productSlug = d), c.properties && typeof c.properties == "object" && (u.properties = c.properties), c.timestamp && (u.timestamp = c.timestamp);
1118
- let p = jt();
1136
+ let p = { name: d.name }, l = d.productSlug ?? n.productId;
1137
+ l && (p.productSlug = l), d.properties && typeof d.properties == "object" && (p.properties = d.properties), d.timestamp && (p.timestamp = d.timestamp);
1138
+ let u = jt();
1119
1139
  await S(n, {
1120
1140
  method: "POST",
1121
- path: p.path,
1122
- body: u,
1123
- requireAuth: p.requireAuth,
1141
+ path: u.path,
1142
+ body: p,
1143
+ requireAuth: u.requireAuth,
1124
1144
  retries: 1,
1125
1145
  // caça-bruxas: retry sem Idempotency-Key duplicava o evento se o
1126
1146
  // servidor já tinha persistido antes da falha transiente. Mesmo
1127
1147
  // padrão do usage.report (key estável por chamada, reusada no retry).
1128
1148
  idempotencyKey: !0
1129
1149
  });
1130
- } catch (u) {
1131
- typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", c.name, u);
1150
+ } catch (p) {
1151
+ typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", d.name, p);
1132
1152
  }
1133
1153
  })
1134
1154
  );
@@ -1139,7 +1159,7 @@ function Wt(n) {
1139
1159
  function i() {
1140
1160
  t || (t = setTimeout(() => {
1141
1161
  o();
1142
- }, Ar));
1162
+ }, Er));
1143
1163
  }
1144
1164
  return {
1145
1165
  /**
@@ -1156,22 +1176,22 @@ function Wt(n) {
1156
1176
  */
1157
1177
  async event(s) {
1158
1178
  if (!s || typeof s != "object")
1159
- throw new l("validation_failed", "event input is required");
1179
+ throw new c("validation_failed", "event input is required");
1160
1180
  if (typeof s.name != "string" || s.name.length === 0)
1161
- throw new l("validation_failed", "event.name is required");
1181
+ throw new c("validation_failed", "event.name is required");
1162
1182
  if (s.name.length > 128)
1163
- throw new l("validation_failed", "event.name max 128 chars");
1164
- let a = { name: s.name }, c = s.productSlug ?? n.productId;
1165
- c && (a.productSlug = c), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1166
- let u = jt(), d = await S(n, {
1183
+ throw new c("validation_failed", "event.name max 128 chars");
1184
+ let a = { name: s.name }, d = s.productSlug ?? n.productId;
1185
+ d && (a.productSlug = d), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1186
+ let p = jt(), l = await S(n, {
1167
1187
  method: "POST",
1168
- path: u.path,
1188
+ path: p.path,
1169
1189
  body: a,
1170
- requireAuth: u.requireAuth
1190
+ requireAuth: p.requireAuth
1171
1191
  });
1172
- if (!d || d.ok !== true || typeof d.eventId != "string")
1173
- throw new l("invalid_response", "Telemetry response missing eventId");
1174
- return { ok: true, eventId: d.eventId };
1192
+ if (!l || l.ok !== true || typeof l.eventId != "string")
1193
+ throw new c("invalid_response", "Telemetry response missing eventId");
1194
+ return { ok: true, eventId: l.eventId };
1175
1195
  },
1176
1196
  /**
1177
1197
  * Fire-and-forget: enqueue + flush 500ms debounce. Não retorna `eventId`
@@ -1184,7 +1204,7 @@ function Wt(n) {
1184
1204
  * ```
1185
1205
  */
1186
1206
  track(s) {
1187
- !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= Er ? (t && (clearTimeout(t), t = null), o()) : i());
1207
+ !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= Pr ? (t && (clearTimeout(t), t = null), o()) : i());
1188
1208
  },
1189
1209
  /**
1190
1210
  * Força flush imediato da queue de `track()`. Resolva antes de
@@ -1210,43 +1230,43 @@ function Wt(n) {
1210
1230
  */
1211
1231
  async log(s) {
1212
1232
  if (!s || typeof s != "object")
1213
- throw new l("validation_failed", "log input is required");
1233
+ throw new c("validation_failed", "log input is required");
1214
1234
  if (!Ft.includes(s.level))
1215
- throw new l("validation_failed", `level must be one of ${Ft.join(", ")}`);
1235
+ throw new c("validation_failed", `level must be one of ${Ft.join(", ")}`);
1216
1236
  if (typeof s.message != "string" || s.message.length === 0)
1217
- throw new l("validation_failed", "message is required");
1237
+ throw new c("validation_failed", "message is required");
1218
1238
  if (s.message.length > 4e3)
1219
- throw new l("validation_failed", "message max 4000 chars");
1239
+ throw new c("validation_failed", "message max 4000 chars");
1220
1240
  if (n.env === "dev")
1221
- return Cr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1241
+ return Ar(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1222
1242
  let a = {
1223
1243
  level: s.level,
1224
1244
  message: s.message
1225
1245
  };
1226
1246
  s.metadata && (a.metadata = s.metadata);
1227
- let c = s.productSlug ?? n.productId;
1228
- c && (a.productSlug = c);
1229
- let u = s.correlationId;
1230
- if (!u)
1247
+ let d = s.productSlug ?? n.productId;
1248
+ d && (a.productSlug = d);
1249
+ let p = s.correlationId;
1250
+ if (!p)
1231
1251
  try {
1232
1252
  let f = globalThis.NEETRU_CORRELATION_ID;
1233
- typeof f == "string" && f.length > 0 && (u = f);
1253
+ typeof f == "string" && f.length > 0 && (p = f);
1234
1254
  } catch {
1235
1255
  }
1236
- let d = {};
1237
- u && (d["x-correlation-id"] = u);
1238
- let p = await S(n, {
1256
+ let l = {};
1257
+ p && (l["x-correlation-id"] = p);
1258
+ let u = await S(n, {
1239
1259
  method: "POST",
1240
1260
  path: "/api/sdk/v1/telemetry/log",
1241
1261
  body: a,
1242
1262
  requireAuth: true,
1243
- headers: d
1263
+ headers: l
1244
1264
  });
1245
- if (!p || p.ok !== true)
1246
- throw new l("invalid_response", "Telemetry log response missing ok");
1265
+ if (!u || u.ok !== true)
1266
+ throw new c("invalid_response", "Telemetry log response missing ok");
1247
1267
  return {
1248
1268
  ok: true,
1249
- logId: typeof p.logId == "string" ? p.logId : void 0,
1269
+ logId: typeof u.logId == "string" ? u.logId : void 0,
1250
1270
  mode: "http"
1251
1271
  };
1252
1272
  }
@@ -1262,7 +1282,7 @@ C();
1262
1282
  var $t = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1263
1283
  function O(n, e) {
1264
1284
  if (typeof e != "string" || !$t.test(e))
1265
- throw new l(
1285
+ throw new c(
1266
1286
  "validation_failed",
1267
1287
  `${n} must match ${$t.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1268
1288
  );
@@ -1285,17 +1305,17 @@ function Vt(n) {
1285
1305
  */
1286
1306
  async report(e, t = 1, r) {
1287
1307
  if (!e || typeof e != "string")
1288
- throw new l("validation_failed", "resource is required");
1308
+ throw new c("validation_failed", "resource is required");
1289
1309
  if (!Number.isFinite(t) || t <= 0 || !Number.isInteger(t))
1290
- throw new l("validation_failed", "qty must be a positive integer");
1310
+ throw new c("validation_failed", "qty must be a positive integer");
1291
1311
  let o = r?.productId ?? n.productId, i = r?.tenantId ?? n.tenantId;
1292
1312
  if (!o)
1293
- throw new l(
1313
+ throw new c(
1294
1314
  "validation_failed",
1295
1315
  "productId required (pass to options or set on createNeetruClient)"
1296
1316
  );
1297
1317
  if (!i)
1298
- throw new l(
1318
+ throw new c(
1299
1319
  "validation_failed",
1300
1320
  "tenantId required (pass to options or set on createNeetruClient)"
1301
1321
  );
@@ -1308,7 +1328,7 @@ function Vt(n) {
1308
1328
  idempotencyKey: true
1309
1329
  });
1310
1330
  if (!s || s.ok !== true)
1311
- throw new l("invalid_response", "usage.report response missing ok");
1331
+ throw new c("invalid_response", "usage.report response missing ok");
1312
1332
  return {
1313
1333
  ok: true,
1314
1334
  counterId: s.counterId,
@@ -1326,10 +1346,10 @@ function Vt(n) {
1326
1346
  */
1327
1347
  async check(e, t) {
1328
1348
  if (!e || typeof e != "string")
1329
- throw new l("validation_failed", "resource is required");
1349
+ throw new c("validation_failed", "resource is required");
1330
1350
  let r = t?.productId ?? n.productId, o = t?.tenantId ?? n.tenantId;
1331
1351
  if (!r || !o)
1332
- throw new l(
1352
+ throw new c(
1333
1353
  "validation_failed",
1334
1354
  "productId and tenantId required (pass to options or set on createNeetruClient)"
1335
1355
  );
@@ -1341,7 +1361,7 @@ function Vt(n) {
1341
1361
  requireAuth: true
1342
1362
  });
1343
1363
  if (!i || typeof i.allowed != "boolean")
1344
- throw new l("invalid_response", "usage.check response missing allowed");
1364
+ throw new c("invalid_response", "usage.check response missing allowed");
1345
1365
  let s = i.behavior ?? (i.reason === "limit_exceeded" ? "readonly" : null);
1346
1366
  return {
1347
1367
  allowed: i.allowed,
@@ -1359,20 +1379,20 @@ function Vt(n) {
1359
1379
  // src/support.ts
1360
1380
  C();
1361
1381
  q();
1362
- var Ve = ["low", "normal", "high", "urgent"], Pr = ["open", "pending", "resolved", "closed"], Bt = 50;
1382
+ var Ve = ["low", "normal", "high", "urgent"], Dr = ["open", "pending", "resolved", "closed"], Bt = 50;
1363
1383
  function Kt(n) {
1364
1384
  if (!n || typeof n != "object")
1365
- throw new l("invalid_response", "Ticket response is not an object");
1385
+ throw new c("invalid_response", "Ticket response is not an object");
1366
1386
  let e = n;
1367
1387
  if (typeof e.id != "string")
1368
- throw new l("invalid_response", "Ticket missing id");
1388
+ throw new c("invalid_response", "Ticket missing id");
1369
1389
  let t = Array.isArray(e.attachments) && typeof e.attachments[0] == "string" ? e.attachments[0] : void 0, r = typeof e.screenshotUrl == "string" ? e.screenshotUrl : t ?? null;
1370
1390
  return {
1371
1391
  id: e.id,
1372
1392
  subject: typeof e.subject == "string" ? e.subject : "",
1373
1393
  message: typeof e.message == "string" ? e.message : "",
1374
1394
  severity: Ve.includes(e.severity) ? e.severity : "normal",
1375
- status: Pr.includes(e.status) ? e.status : "open",
1395
+ status: Dr.includes(e.status) ? e.status : "open",
1376
1396
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
1377
1397
  updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : void 0,
1378
1398
  productSlug: typeof e.productId == "string" ? e.productId : typeof e.productSlug == "string" ? e.productSlug : void 0,
@@ -1392,11 +1412,11 @@ function Kt(n) {
1392
1412
  }
1393
1413
  function we(n) {
1394
1414
  if (!n || typeof n != "string")
1395
- throw new l("validation_failed", "ticketId is required");
1415
+ throw new c("validation_failed", "ticketId is required");
1396
1416
  }
1397
1417
  function zt(n) {
1398
1418
  if (typeof n == "string" && n.length > 2e3)
1399
- throw new l("validation_failed", "comment max 2000 chars");
1419
+ throw new c("validation_failed", "comment max 2000 chars");
1400
1420
  }
1401
1421
  function Ht(n, ...e) {
1402
1422
  for (let t of e)
@@ -1404,17 +1424,17 @@ function Ht(n, ...e) {
1404
1424
  return O("productSlug", t), t;
1405
1425
  if (n.productId)
1406
1426
  return O("productId", n.productId), n.productId;
1407
- throw new l(
1427
+ throw new c(
1408
1428
  "validation_failed",
1409
1429
  "productId required (pass to input.productSlug or set on createNeetruClient)"
1410
1430
  );
1411
1431
  }
1412
- var Dr = "X-Neetru-End-User-Token", Nr = "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.", xr = "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.", Or = "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.", Lr = "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.";
1432
+ var Nr = "X-Neetru-End-User-Token", xr = "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.", Or = "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.", Lr = "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.", Ur = "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.";
1413
1433
  function Gt(n) {
1414
- if (n instanceof l && !(n instanceof $)) {
1434
+ if (n instanceof c && !(n instanceof $)) {
1415
1435
  if (n.code === "end_user_token_required")
1416
1436
  throw new $(
1417
- xr,
1437
+ Or,
1418
1438
  "end_user_token_required",
1419
1439
  n.status,
1420
1440
  n.requestId,
@@ -1422,16 +1442,16 @@ function Gt(n) {
1422
1442
  );
1423
1443
  if (n.code === "invalid_end_user_token")
1424
1444
  throw new $(
1425
- Or,
1445
+ Lr,
1426
1446
  "invalid_end_user_token",
1427
1447
  n.status,
1428
1448
  n.requestId,
1429
1449
  n.correlationId
1430
1450
  );
1431
1451
  if (n.code === "end_user_token_product_mismatch")
1432
- throw new l(
1452
+ throw new c(
1433
1453
  "forbidden",
1434
- Lr,
1454
+ Ur,
1435
1455
  n.status,
1436
1456
  n.requestId,
1437
1457
  "end_user_token_product_mismatch",
@@ -1440,8 +1460,8 @@ function Gt(n) {
1440
1460
  }
1441
1461
  throw n;
1442
1462
  }
1443
- function Ur(n) {
1444
- return n instanceof l && n.code === "invalid_end_user_token";
1463
+ function Mr(n) {
1464
+ return n instanceof c && n.code === "invalid_end_user_token";
1445
1465
  }
1446
1466
  function Qt(n, e = {}) {
1447
1467
  async function t() {
@@ -1461,36 +1481,36 @@ function Qt(n, e = {}) {
1461
1481
  }
1462
1482
  }
1463
1483
  function o(a) {
1464
- return a ? { [Dr]: a } : {};
1484
+ return a ? { [Nr]: a } : {};
1465
1485
  }
1466
- async function i(a, c) {
1467
- let u = await t();
1468
- if (!u && a && await r() && (u = await t()), !u && a)
1469
- throw new $(Nr, "no_signed_in_user");
1486
+ async function i(a, d) {
1487
+ let p = await t();
1488
+ if (!p && a && await r() && (p = await t()), !p && a)
1489
+ throw new $(xr, "no_signed_in_user");
1470
1490
  try {
1471
- return await c(o(u));
1472
- } catch (d) {
1473
- if (u && Ur(d) && await r()) {
1474
- let p = await t();
1475
- if (p)
1491
+ return await d(o(p));
1492
+ } catch (l) {
1493
+ if (p && Mr(l) && await r()) {
1494
+ let u = await t();
1495
+ if (u)
1476
1496
  try {
1477
- return await c(o(p));
1497
+ return await d(o(u));
1478
1498
  } catch (f) {
1479
1499
  Gt(f);
1480
1500
  }
1481
1501
  }
1482
- Gt(d);
1502
+ Gt(l);
1483
1503
  }
1484
1504
  }
1485
- async function s(a, c = {}) {
1505
+ async function s(a, d = {}) {
1486
1506
  await i(
1487
1507
  true,
1488
- (u) => S(n, {
1508
+ (p) => S(n, {
1489
1509
  method: "POST",
1490
1510
  path: a,
1491
1511
  requireAuth: !0,
1492
- headers: u,
1493
- ...c
1512
+ headers: p,
1513
+ ...d
1494
1514
  })
1495
1515
  );
1496
1516
  }
@@ -1503,39 +1523,39 @@ function Qt(n, e = {}) {
1503
1523
  */
1504
1524
  async createTicket(a) {
1505
1525
  if (!a || typeof a != "object")
1506
- throw new l("validation_failed", "input is required");
1526
+ throw new c("validation_failed", "input is required");
1507
1527
  if (!a.subject || typeof a.subject != "string")
1508
- throw new l("validation_failed", "subject is required");
1528
+ throw new c("validation_failed", "subject is required");
1509
1529
  if (a.subject.length > 200)
1510
- throw new l("validation_failed", "subject max 200 chars");
1530
+ throw new c("validation_failed", "subject max 200 chars");
1511
1531
  if (!a.message || typeof a.message != "string")
1512
- throw new l("validation_failed", "message is required");
1532
+ throw new c("validation_failed", "message is required");
1513
1533
  if (a.message.length > 1e4)
1514
- throw new l("validation_failed", "message max 10000 chars");
1534
+ throw new c("validation_failed", "message max 10000 chars");
1515
1535
  if (a.severity && !Ve.includes(a.severity))
1516
- throw new l(
1536
+ throw new c(
1517
1537
  "validation_failed",
1518
1538
  `severity must be one of ${Ve.join(", ")}`
1519
1539
  );
1520
- let u = {
1540
+ let p = {
1521
1541
  productId: Ht(n, a.productSlug),
1522
1542
  subject: a.subject,
1523
1543
  message: a.message,
1524
1544
  severity: a.severity ?? "normal"
1525
1545
  };
1526
- a.metadata && typeof a.metadata == "object" && (u.metadata = a.metadata), typeof a.pageUrl == "string" && (u.pageUrl = a.pageUrl), typeof a.screenshotBase64 == "string" && (u.screenshotBase64 = a.screenshotBase64), typeof a.consoleLogs == "string" && (u.consoleLogs = a.consoleLogs);
1527
- let d = await i(
1546
+ a.metadata && typeof a.metadata == "object" && (p.metadata = a.metadata), typeof a.pageUrl == "string" && (p.pageUrl = a.pageUrl), typeof a.screenshotBase64 == "string" && (p.screenshotBase64 = a.screenshotBase64), typeof a.consoleLogs == "string" && (p.consoleLogs = a.consoleLogs);
1547
+ let l = await i(
1528
1548
  false,
1529
1549
  (f) => S(n, {
1530
1550
  method: "POST",
1531
1551
  path: "/api/sdk/v1/support/tickets",
1532
- body: u,
1552
+ body: p,
1533
1553
  requireAuth: !0,
1534
1554
  idempotencyKey: !0,
1535
1555
  headers: f
1536
1556
  })
1537
- ), p = d && typeof d == "object" && "ticket" in d ? d.ticket : d;
1538
- return Kt(p);
1557
+ ), u = l && typeof l == "object" && "ticket" in l ? l.ticket : l;
1558
+ return Kt(u);
1539
1559
  },
1540
1560
  /**
1541
1561
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
@@ -1543,23 +1563,23 @@ function Qt(n, e = {}) {
1543
1563
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
1544
1564
  */
1545
1565
  async listMyTickets(a) {
1546
- let c = Ht(n, a?.productSlug), u = a?.limit;
1547
- if (u !== void 0 && (!Number.isInteger(u) || u < 1 || u > Bt))
1548
- throw new l(
1566
+ let d = Ht(n, a?.productSlug), p = a?.limit;
1567
+ if (p !== void 0 && (!Number.isInteger(p) || p < 1 || p > Bt))
1568
+ throw new c(
1549
1569
  "validation_failed",
1550
1570
  `limit must be an integer 1-${Bt} (Core default 20)`
1551
1571
  );
1552
- let d = await i(
1572
+ let l = await i(
1553
1573
  true,
1554
1574
  (f) => S(n, {
1555
1575
  method: "GET",
1556
1576
  path: "/api/sdk/v1/support/tickets",
1557
- query: { productId: c, limit: u },
1577
+ query: { productId: d, limit: p },
1558
1578
  requireAuth: !0,
1559
1579
  headers: f
1560
1580
  })
1561
1581
  );
1562
- return (Array.isArray(d) ? d : d && typeof d == "object" && "tickets" in d ? d.tickets ?? [] : []).map(Kt);
1582
+ return (Array.isArray(l) ? l : l && typeof l == "object" && "tickets" in l ? l.tickets ?? [] : []).map(Kt);
1563
1583
  },
1564
1584
  /**
1565
1585
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
@@ -1591,9 +1611,9 @@ function Qt(n, e = {}) {
1591
1611
  */
1592
1612
  async submitSatisfaction(a) {
1593
1613
  if (!a || typeof a != "object")
1594
- throw new l("validation_failed", "input is required");
1614
+ throw new c("validation_failed", "input is required");
1595
1615
  if (we(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1596
- throw new l("validation_failed", "rating must be an integer 1-5 or null");
1616
+ throw new c("validation_failed", "rating must be an integer 1-5 or null");
1597
1617
  zt(a.comment), await s(
1598
1618
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a.ticketId)}/satisfaction`,
1599
1619
  {
@@ -1610,10 +1630,10 @@ function Qt(n, e = {}) {
1610
1630
  * satisfação/notificação. Endpoint canonical:
1611
1631
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
1612
1632
  */
1613
- async contestTicket(a, c) {
1614
- we(a), zt(c?.comment), await s(
1633
+ async contestTicket(a, d) {
1634
+ we(a), zt(d?.comment), await s(
1615
1635
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/contest`,
1616
- { body: { comment: c?.comment ?? void 0 } }
1636
+ { body: { comment: d?.comment ?? void 0 } }
1617
1637
  );
1618
1638
  }
1619
1639
  };
@@ -1645,7 +1665,7 @@ function Be(n, e) {
1645
1665
  }
1646
1666
  return r;
1647
1667
  }
1648
- function qr(n, e) {
1668
+ function Fr(n, e) {
1649
1669
  let t = Be(n, e.field);
1650
1670
  if (t === void 0) return false;
1651
1671
  let { op: r, value: o } = e;
@@ -1676,10 +1696,10 @@ function qr(n, e) {
1676
1696
  );
1677
1697
  }
1678
1698
  }
1679
- function Fr(n, e) {
1680
- return e.every((t) => qr(n, t));
1699
+ function jr(n, e) {
1700
+ return e.every((t) => Fr(n, t));
1681
1701
  }
1682
- function jr(n) {
1702
+ function Wr(n) {
1683
1703
  return (e, t) => {
1684
1704
  if (n) {
1685
1705
  let r = Be(e.data, n.field), o = Be(t.data, n.field), i = re(r, o);
@@ -1689,7 +1709,7 @@ function jr(n) {
1689
1709
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
1690
1710
  };
1691
1711
  }
1692
- function Wr(n, e) {
1712
+ function $r(n, e) {
1693
1713
  let t = n.findIndex((r) => r.id === e.docId);
1694
1714
  return t === -1 ? n : e.type === "startAfter" ? n.slice(t + 1) : n.slice(0, t);
1695
1715
  }
@@ -1705,13 +1725,13 @@ var J = class n {
1705
1725
  * 5. Corta em `limit`.
1706
1726
  */
1707
1727
  evaluate(e, t) {
1708
- let r = e.filter((d) => !d.meta.deleted), o = t.where ?? [];
1728
+ let r = e.filter((l) => !l.meta.deleted), o = t.where ?? [];
1709
1729
  o.length > 0 && (r = r.filter(
1710
- (d) => Fr(d.data, o)
1730
+ (l) => jr(l.data, o)
1711
1731
  ));
1712
- let i = jr(t.orderBy), s = [...r].sort(i), a = t.cursor ? Wr(s, t.cursor) : s, c = Math.min(t.limit ?? 20, 500);
1732
+ let i = Wr(t.orderBy), s = [...r].sort(i), a = t.cursor ? $r(s, t.cursor) : s, d = Math.min(t.limit ?? 20, 500);
1713
1733
  return {
1714
- docs: a.slice(0, c).map((d) => ({ id: d.id, data: d.data })),
1734
+ docs: a.slice(0, d).map((l) => ({ id: l.id, data: l.data })),
1715
1735
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
1716
1736
  // tem todos os docs da coleção. É responsabilidade do chamador (LocalStore)
1717
1737
  // injetar o flag de completude baseado nos metadados do query_cache.
@@ -1729,7 +1749,7 @@ var J = class n {
1729
1749
  };
1730
1750
 
1731
1751
  // src/db/offline/local-store.ts
1732
- var Vr = 1, V = "documents", B = "mutations", oe = "query_cache", ke = "sync_meta", X = "conflict_log", Se = class {
1752
+ var Br = 1, V = "documents", B = "mutations", oe = "query_cache", ke = "sync_meta", X = "conflict_log", Se = class {
1733
1753
  db = null;
1734
1754
  dbName;
1735
1755
  constructor(e) {
@@ -1741,7 +1761,7 @@ var Vr = 1, V = "documents", B = "mutations", oe = "query_cache", ke = "sync_met
1741
1761
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
1742
1762
  */
1743
1763
  async open() {
1744
- this.db === null && (this.db = await openDB(this.dbName, Vr, {
1764
+ this.db === null && (this.db = await openDB(this.dbName, Br, {
1745
1765
  upgrade(e) {
1746
1766
  if (!e.objectStoreNames.contains(V)) {
1747
1767
  let t = e.createObjectStore(V, {
@@ -2149,18 +2169,18 @@ var Re = class {
2149
2169
  * Atômico: a persistência final é uma única operação putMutation.
2150
2170
  */
2151
2171
  async enqueue(e) {
2152
- let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, c = e.docId ?? (r === "add" ? Ke() : "");
2172
+ let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, d = e.docId ?? (r === "add" ? Ke() : "");
2153
2173
  await this.syncSeq();
2154
- let d = (await this.store.listMutations({ collection: t, docId: c })).filter((m) => m.status === "queued").sort((m, h) => h.seq - m.seq)[0];
2155
- if (d !== void 0) {
2156
- let m = this.tryCoalesce(d, r, o, s, a);
2174
+ let l = (await this.store.listMutations({ collection: t, docId: d })).filter((m) => m.status === "queued").sort((m, h) => h.seq - m.seq)[0];
2175
+ if (l !== void 0) {
2176
+ let m = this.tryCoalesce(l, r, o, s, a);
2157
2177
  if (m !== null) {
2158
2178
  if ("removed" in m)
2159
- return await this.store.deleteMutation(d.mutationId), {
2160
- seq: d.seq,
2179
+ return await this.store.deleteMutation(l.mutationId), {
2180
+ seq: l.seq,
2161
2181
  mutationId: Ke(),
2162
2182
  collection: t,
2163
- docId: c,
2183
+ docId: d,
2164
2184
  op: "remove",
2165
2185
  payload: null,
2166
2186
  baseVersion: i,
@@ -2178,7 +2198,7 @@ var Re = class {
2178
2198
  seq: this.nextSeq(),
2179
2199
  mutationId: Ke(),
2180
2200
  collection: t,
2181
- docId: c,
2201
+ docId: d,
2182
2202
  op: r,
2183
2203
  payload: o,
2184
2204
  baseVersion: i,
@@ -2290,10 +2310,10 @@ var Re = class {
2290
2310
 
2291
2311
  // src/db/field-value.ts
2292
2312
  var ze = "__neetru__";
2293
- function Br() {
2313
+ function Kr() {
2294
2314
  return { __neetru__: "serverTimestamp" };
2295
2315
  }
2296
- function Kr(n) {
2316
+ function zr(n) {
2297
2317
  if (typeof n != "number" || !Number.isFinite(n))
2298
2318
  throw new TypeError(
2299
2319
  `increment(n): n deve ser um n\xFAmero finito (recebido: ${String(n)}).`
@@ -2309,13 +2329,13 @@ function Xt(n) {
2309
2329
  function Yt(n) {
2310
2330
  return H(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2311
2331
  }
2312
- function zr(n, e) {
2332
+ function Hr(n, e) {
2313
2333
  return Xt(n) ? Date.now() : Yt(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2314
2334
  }
2315
2335
  function G(n, e) {
2316
2336
  let t = false, r = {};
2317
2337
  for (let [o, i] of Object.entries(n))
2318
- H(i) ? (t = true, r[o] = zr(i, e?.[o])) : r[o] = i;
2338
+ H(i) ? (t = true, r[o] = Hr(i, e?.[o])) : r[o] = i;
2319
2339
  return t ? r : n;
2320
2340
  }
2321
2341
  function He(n) {
@@ -2325,11 +2345,11 @@ function He(n) {
2325
2345
  }
2326
2346
 
2327
2347
  // src/db/offline/sync-engine.ts
2328
- var Hr = 8, Gr = 1e3, Qr = 300 * 1e3, Ge = "truncatedCollections";
2329
- function Jr(n) {
2348
+ var Gr = 8, Qr = 1e3, Jr = 300 * 1e3, Ge = "truncatedCollections";
2349
+ function Xr(n) {
2330
2350
  return n !== null && He(n);
2331
2351
  }
2332
- function Xr(n) {
2352
+ function Yr(n) {
2333
2353
  if (n === null) return null;
2334
2354
  if (!He(n)) return n;
2335
2355
  let e = {};
@@ -2481,16 +2501,16 @@ var Ie = class {
2481
2501
  try {
2482
2502
  t = await this._transport.pushMutations(e);
2483
2503
  } catch (s) {
2484
- let a = s instanceof Error ? s.message : String(s), c = [], [u, ...d] = e;
2485
- await this._retryOrDeadLetter(u, a, c);
2486
- for (let p of d)
2487
- await this._queue.requeueInflight(p.mutationId);
2488
- return c.length > 0 && this._bus.emit(c), this._refreshPendingWrites().catch(() => {
2504
+ let a = s instanceof Error ? s.message : String(s), d = [], [p, ...l] = e;
2505
+ await this._retryOrDeadLetter(p, a, d);
2506
+ for (let u of l)
2507
+ await this._queue.requeueInflight(u.mutationId);
2508
+ return d.length > 0 && this._bus.emit(d), this._refreshPendingWrites().catch(() => {
2489
2509
  }), false;
2490
2510
  }
2491
2511
  let r = [];
2492
2512
  for (let s of t.results) {
2493
- let a = e.find((c) => c.mutationId === s.mutationId);
2513
+ let a = e.find((d) => d.mutationId === s.mutationId);
2494
2514
  a && (s.outcome === "confirmed" ? (await this._queue.markApplied(a.mutationId), await this._applySyncedDoc(
2495
2515
  a.collection,
2496
2516
  a.docId,
@@ -2508,8 +2528,8 @@ var Ie = class {
2508
2528
  "partial_push: muta\xE7\xE3o n\xE3o processada no lote",
2509
2529
  r
2510
2530
  );
2511
- for (let c of a)
2512
- await this._queue.requeueInflight(c.mutationId);
2531
+ for (let d of a)
2532
+ await this._queue.requeueInflight(d.mutationId);
2513
2533
  }
2514
2534
  return r.length > 0 && this._bus.emit(r), i.length === 0;
2515
2535
  }
@@ -2531,13 +2551,13 @@ var Ie = class {
2531
2551
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
2532
2552
  return;
2533
2553
  }
2534
- let u = Xr(i.payload) ?? a?.data ?? {}, d = {
2554
+ let p = Yr(i.payload) ?? a?.data ?? {}, l = {
2535
2555
  collection: e,
2536
2556
  id: t,
2537
- data: i.op === "update" ? { ...a?.data ?? {}, ...u } : (
2557
+ data: i.op === "update" ? { ...a?.data ?? {}, ...p } : (
2538
2558
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2539
2559
  // é a fonte de verdade até o pull; senão usa o payload literal.
2540
- Jr(i.payload) ? { ...a?.data ?? {}, ...u } : u
2560
+ Xr(i.payload) ? { ...a?.data ?? {}, ...p } : p
2541
2561
  ),
2542
2562
  meta: {
2543
2563
  serverVersion: r,
@@ -2549,10 +2569,10 @@ var Ie = class {
2549
2569
  ownerId: a?.meta.ownerId ?? null
2550
2570
  }
2551
2571
  };
2552
- await this._store.putDoc(d), s.push({
2572
+ await this._store.putDoc(l), s.push({
2553
2573
  type: a ? "modified" : "added",
2554
2574
  collection: e,
2555
- doc: { id: t, data: d.data }
2575
+ doc: { id: t, data: l.data }
2556
2576
  });
2557
2577
  }
2558
2578
  /** Processa resultado 'superseded' (LWW: servidor venceu). */
@@ -2584,7 +2604,7 @@ var Ie = class {
2584
2604
  deleted: false,
2585
2605
  ownerId: null
2586
2606
  }
2587
- }, c = this._resolver.resolve(
2607
+ }, d = this._resolver.resolve(
2588
2608
  s,
2589
2609
  i,
2590
2610
  e
@@ -2598,8 +2618,8 @@ var Ie = class {
2598
2618
  detectedAt: Date.now(),
2599
2619
  delivered: false
2600
2620
  };
2601
- await this._store.appendConflict(c);
2602
- let u = {
2621
+ await this._store.appendConflict(d);
2622
+ let p = {
2603
2623
  collection: e.collection,
2604
2624
  id: e.docId,
2605
2625
  data: t.serverData,
@@ -2613,7 +2633,7 @@ var Ie = class {
2613
2633
  ownerId: o?.meta.ownerId ?? null
2614
2634
  }
2615
2635
  };
2616
- await this._store.putDoc(u), r.push({
2636
+ await this._store.putDoc(p), r.push({
2617
2637
  type: o ? "modified" : "added",
2618
2638
  collection: e.collection,
2619
2639
  doc: { id: e.docId, data: t.serverData }
@@ -2641,7 +2661,7 @@ var Ie = class {
2641
2661
  ...i.meta,
2642
2662
  serverVersion: t.serverVersion ?? i.meta.serverVersion
2643
2663
  }
2644
- } : null, c = this._resolver.resolveRejected(
2664
+ } : null, d = this._resolver.resolveRejected(
2645
2665
  i,
2646
2666
  s,
2647
2667
  e,
@@ -2656,7 +2676,7 @@ var Ie = class {
2656
2676
  detectedAt: Date.now(),
2657
2677
  delivered: false
2658
2678
  };
2659
- await this._store.appendConflict(c), t.serverData ? (await this._store.putDoc({
2679
+ await this._store.appendConflict(d), t.serverData ? (await this._store.putDoc({
2660
2680
  ...i,
2661
2681
  data: t.serverData,
2662
2682
  meta: {
@@ -2690,7 +2710,7 @@ var Ie = class {
2690
2710
  * pending do doc no cache + registra `lastError`/dispara `onError`.
2691
2711
  */
2692
2712
  async _retryOrDeadLetter(e, t, r) {
2693
- if (e.attempts + 1 < Hr) {
2713
+ if (e.attempts + 1 < Gr) {
2694
2714
  await this._queue.markRetry(e.mutationId, t);
2695
2715
  return;
2696
2716
  }
@@ -2731,7 +2751,7 @@ var Ie = class {
2731
2751
  }
2732
2752
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
2733
2753
  _backoffDelayMs(e) {
2734
- return Math.min(Gr * 2 ** (e - 1), Qr);
2754
+ return Math.min(Qr * 2 ** (e - 1), Jr);
2735
2755
  }
2736
2756
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
2737
2757
  /**
@@ -2770,15 +2790,15 @@ var Ie = class {
2770
2790
  );
2771
2791
  for (let a of e) {
2772
2792
  if (i.has(a)) continue;
2773
- let c = await this._store.listDocs(a, {});
2774
- for (let { id: u } of c.docs) {
2775
- let d = `${a}::${u}`;
2776
- if (!s.has(d)) {
2777
- let p = await this._store.getDoc(a, u);
2778
- p && !p.meta.deleted && (await this._store.putDoc({
2779
- ...p,
2793
+ let d = await this._store.listDocs(a, {});
2794
+ for (let { id: p } of d.docs) {
2795
+ let l = `${a}::${p}`;
2796
+ if (!s.has(l)) {
2797
+ let u = await this._store.getDoc(a, p);
2798
+ u && !u.meta.deleted && (await this._store.putDoc({
2799
+ ...u,
2780
2800
  meta: {
2781
- ...p.meta,
2801
+ ...u.meta,
2782
2802
  deleted: true,
2783
2803
  updatedAtLocal: Date.now(),
2784
2804
  state: "synced"
@@ -2786,7 +2806,7 @@ var Ie = class {
2786
2806
  }), r.push({
2787
2807
  type: "removed",
2788
2808
  collection: a,
2789
- doc: { id: u, data: p.data }
2809
+ doc: { id: p, data: u.data }
2790
2810
  }));
2791
2811
  }
2792
2812
  }
@@ -2821,7 +2841,7 @@ var Ie = class {
2821
2841
  continue;
2822
2842
  }
2823
2843
  if (i && i.meta.state === "pending") {
2824
- let c = {
2844
+ let d = {
2825
2845
  collection: o.collection,
2826
2846
  id: o.id,
2827
2847
  data: o.data,
@@ -2834,12 +2854,12 @@ var Ie = class {
2834
2854
  deleted: false,
2835
2855
  ownerId: i.meta.ownerId
2836
2856
  }
2837
- }, d = (await this._queue.listAll()).find(
2838
- (p) => p.collection === o.collection && p.docId === o.id
2857
+ }, l = (await this._queue.listAll()).find(
2858
+ (u) => u.collection === o.collection && u.docId === o.id
2839
2859
  );
2840
- if (d) {
2841
- let p = this._resolver.resolve(i, c, d);
2842
- p.conflictRecord && await this._store.appendConflict(p.conflictRecord), await this._store.putDoc({
2860
+ if (l) {
2861
+ let u = this._resolver.resolve(i, d, l);
2862
+ u.conflictRecord && await this._store.appendConflict(u.conflictRecord), await this._store.putDoc({
2843
2863
  ...i,
2844
2864
  meta: { ...i.meta, state: "conflict" }
2845
2865
  });
@@ -3073,9 +3093,9 @@ var Ce = class n {
3073
3093
  ))
3074
3094
  return { outcome: "local_wins", resolvedData: { ...i, ...r.payload ?? {} }, conflictRecord: null };
3075
3095
  let a = {};
3076
- for (let u of o)
3077
- a[u] = e.data[u];
3078
- let c = {
3096
+ for (let p of o)
3097
+ a[p] = e.data[p];
3098
+ let d = {
3079
3099
  collection: r.collection,
3080
3100
  docId: r.docId,
3081
3101
  mutationId: r.mutationId,
@@ -3088,7 +3108,7 @@ var Ce = class n {
3088
3108
  return {
3089
3109
  outcome: "server_wins",
3090
3110
  resolvedData: i,
3091
- conflictRecord: c
3111
+ conflictRecord: d
3092
3112
  };
3093
3113
  }
3094
3114
  /**
@@ -3145,7 +3165,7 @@ var Ce = class n {
3145
3165
  };
3146
3166
 
3147
3167
  // src/db/offline/change-bus.ts
3148
- function Yr(n) {
3168
+ function Zr(n) {
3149
3169
  return `${n.collection}::${n.doc.id}`;
3150
3170
  }
3151
3171
  var Ae = class {
@@ -3193,15 +3213,15 @@ var Ae = class {
3193
3213
  if (e.length === 0) return;
3194
3214
  let t = /* @__PURE__ */ new Map();
3195
3215
  for (let i of e)
3196
- t.set(Yr(i), i);
3216
+ t.set(Zr(i), i);
3197
3217
  let r = Array.from(t.values()), o = /* @__PURE__ */ new Map();
3198
3218
  for (let i of r)
3199
3219
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
3200
3220
  for (let [i, s] of o) {
3201
3221
  let a = this._collectionListeners.get(i);
3202
3222
  if (a)
3203
- for (let c of a)
3204
- this._safeCall(c, s);
3223
+ for (let d of a)
3224
+ this._safeCall(d, s);
3205
3225
  }
3206
3226
  for (let i of this._globalListeners)
3207
3227
  this._safeCall(i, r);
@@ -3512,11 +3532,11 @@ var ie = class {
3512
3532
 
3513
3533
  // src/db/collection-ref.ts
3514
3534
  z();
3515
- function Zr() {
3535
+ function eo() {
3516
3536
  return typeof indexedDB > "u" || typeof window > "u";
3517
3537
  }
3518
3538
  var en = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3519
- function eo(n) {
3539
+ function to(n) {
3520
3540
  if (!en.test(n))
3521
3541
  throw new v(
3522
3542
  "db_invalid_query",
@@ -3530,7 +3550,7 @@ function Y(n, e = "id") {
3530
3550
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
3531
3551
  );
3532
3552
  }
3533
- function to(n) {
3553
+ function no(n) {
3534
3554
  let e = {};
3535
3555
  if (n?.where && (e.where = n.where.map((t) => ({
3536
3556
  field: t.field,
@@ -3547,7 +3567,7 @@ function to(n) {
3547
3567
  }
3548
3568
  return e;
3549
3569
  }
3550
- function no(n, e) {
3570
+ function ro(n, e) {
3551
3571
  if (n.length < e) return null;
3552
3572
  let t = n[n.length - 1];
3553
3573
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
@@ -3594,15 +3614,15 @@ var Qe = class {
3594
3614
  }
3595
3615
  /** Constrói um DbListResult para a coleção com query opcional. */
3596
3616
  async _buildListResult(e) {
3597
- let t = to(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), c = no(o.docs, r), u = await this._store.getMeta(Ge), d = Array.isArray(u) && u.includes(this._collection), p = !s || a.status === "offline" || d, f = i || a.lastSyncedAt === null || p;
3617
+ let t = no(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), d = ro(o.docs, r), p = await this._store.getMeta(Ge), l = Array.isArray(p) && p.includes(this._collection), u = !s || a.status === "offline" || l, f = i || a.lastSyncedAt === null || u;
3598
3618
  return {
3599
3619
  docs: o.docs.map((m) => ({ id: m.id, data: m.data })),
3600
- nextCursor: c,
3620
+ nextCursor: d,
3601
3621
  fromCache: f,
3602
- stale: p,
3622
+ stale: u,
3603
3623
  hasPendingWrites: i,
3604
3624
  changes: [],
3605
- truncated: d
3625
+ truncated: l
3606
3626
  };
3607
3627
  }
3608
3628
  // ── CRUD ────────────────────────────────────────────────────────────────────
@@ -3670,7 +3690,7 @@ var Qe = class {
3670
3690
  }
3671
3691
  async update(e, t, r) {
3672
3692
  Y(e);
3673
- let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = G(i, s), c = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, u = await this._queue.enqueue({
3693
+ let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = G(i, s), d = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, p = await this._queue.enqueue({
3674
3694
  collection: this._collection,
3675
3695
  docId: e,
3676
3696
  op: "update",
@@ -3683,7 +3703,7 @@ var Qe = class {
3683
3703
  return await this._store.putDoc({
3684
3704
  collection: this._collection,
3685
3705
  id: e,
3686
- data: c,
3706
+ data: d,
3687
3707
  meta: {
3688
3708
  serverVersion: o?.meta.serverVersion ?? null,
3689
3709
  updatedAtServer: o?.meta.updatedAtServer ?? null,
@@ -3691,7 +3711,7 @@ var Qe = class {
3691
3711
  state: "pending",
3692
3712
  pendingMutationIds: [
3693
3713
  ...o?.meta.pendingMutationIds ?? [],
3694
- u.mutationId
3714
+ p.mutationId
3695
3715
  ],
3696
3716
  deleted: false,
3697
3717
  ownerId: o?.meta.ownerId ?? null
@@ -3699,7 +3719,7 @@ var Qe = class {
3699
3719
  }), this._bus.emit([{
3700
3720
  type: "modified",
3701
3721
  collection: this._collection,
3702
- doc: { id: e, data: c }
3722
+ doc: { id: e, data: d }
3703
3723
  }]), { ok: true };
3704
3724
  }
3705
3725
  async remove(e) {
@@ -3723,61 +3743,61 @@ var Qe = class {
3723
3743
  for (let o of e) {
3724
3744
  let i = this._collection;
3725
3745
  if (o.kind === "add") {
3726
- let s = o.data, a = G(s, void 0), c = await this._queue.enqueue({
3746
+ let s = o.data, a = G(s, void 0), d = await this._queue.enqueue({
3727
3747
  collection: i,
3728
3748
  op: "add",
3729
3749
  payload: s,
3730
3750
  baseVersion: null,
3731
3751
  batchId: t
3732
- }), u = c.docId;
3752
+ }), p = d.docId;
3733
3753
  await this._store.putDoc({
3734
3754
  collection: i,
3735
- id: u,
3755
+ id: p,
3736
3756
  data: a,
3737
3757
  meta: {
3738
3758
  serverVersion: null,
3739
3759
  updatedAtServer: null,
3740
3760
  updatedAtLocal: Date.now(),
3741
3761
  state: "pending",
3742
- pendingMutationIds: [c.mutationId],
3762
+ pendingMutationIds: [d.mutationId],
3743
3763
  deleted: false,
3744
3764
  ownerId: null
3745
3765
  }
3746
- }), r.push({ type: "added", collection: i, doc: { id: u, data: a } });
3766
+ }), r.push({ type: "added", collection: i, doc: { id: p, data: a } });
3747
3767
  } else if (o.kind === "set") {
3748
- let s = o.id, a = o.data, c = await this._store.getDoc(i, s), u = G(a, void 0), d = await this._queue.enqueue({
3768
+ let s = o.id, a = o.data, d = await this._store.getDoc(i, s), p = G(a, void 0), l = await this._queue.enqueue({
3749
3769
  collection: i,
3750
3770
  docId: s,
3751
3771
  op: "set",
3752
3772
  payload: a,
3753
- baseVersion: c?.meta.serverVersion ?? null,
3773
+ baseVersion: d?.meta.serverVersion ?? null,
3754
3774
  batchId: t
3755
3775
  });
3756
3776
  await this._store.putDoc({
3757
3777
  collection: i,
3758
3778
  id: s,
3759
- data: u,
3779
+ data: p,
3760
3780
  meta: {
3761
- serverVersion: c?.meta.serverVersion ?? null,
3762
- updatedAtServer: c?.meta.updatedAtServer ?? null,
3781
+ serverVersion: d?.meta.serverVersion ?? null,
3782
+ updatedAtServer: d?.meta.updatedAtServer ?? null,
3763
3783
  updatedAtLocal: Date.now(),
3764
3784
  state: "pending",
3765
- pendingMutationIds: [d.mutationId],
3785
+ pendingMutationIds: [l.mutationId],
3766
3786
  deleted: false,
3767
3787
  ownerId: null
3768
3788
  }
3769
3789
  }), r.push({
3770
- type: c && !c.meta.deleted ? "modified" : "added",
3790
+ type: d && !d.meta.deleted ? "modified" : "added",
3771
3791
  collection: i,
3772
- doc: { id: s, data: u }
3792
+ doc: { id: s, data: p }
3773
3793
  });
3774
3794
  } else if (o.kind === "update") {
3775
- let s = o.id, a = o.data, c = await this._store.getDoc(i, s), u = c?.meta.deleted ? void 0 : c?.data, d = G(a, u), p = { ...c?.data ?? {}, ...d }, f = await this._queue.enqueue({
3795
+ let s = o.id, a = o.data, d = await this._store.getDoc(i, s), p = d?.meta.deleted ? void 0 : d?.data, l = G(a, p), u = { ...d?.data ?? {}, ...l }, f = await this._queue.enqueue({
3776
3796
  collection: i,
3777
3797
  docId: s,
3778
3798
  op: "update",
3779
3799
  payload: a,
3780
- baseVersion: c?.meta.serverVersion ?? null,
3800
+ baseVersion: d?.meta.serverVersion ?? null,
3781
3801
  batchId: t,
3782
3802
  // bug_0273e4dd: propaga merge-upsert (writeBatch.set(merge) cria-se-ausente).
3783
3803
  upsert: o.upsert
@@ -3785,20 +3805,20 @@ var Qe = class {
3785
3805
  await this._store.putDoc({
3786
3806
  collection: i,
3787
3807
  id: s,
3788
- data: p,
3808
+ data: u,
3789
3809
  meta: {
3790
- serverVersion: c?.meta.serverVersion ?? null,
3791
- updatedAtServer: c?.meta.updatedAtServer ?? null,
3810
+ serverVersion: d?.meta.serverVersion ?? null,
3811
+ updatedAtServer: d?.meta.updatedAtServer ?? null,
3792
3812
  updatedAtLocal: Date.now(),
3793
3813
  state: "pending",
3794
3814
  pendingMutationIds: [
3795
- ...c?.meta.pendingMutationIds ?? [],
3815
+ ...d?.meta.pendingMutationIds ?? [],
3796
3816
  f.mutationId
3797
3817
  ],
3798
3818
  deleted: false,
3799
- ownerId: c?.meta.ownerId ?? null
3819
+ ownerId: d?.meta.ownerId ?? null
3800
3820
  }
3801
- }), r.push({ type: "modified", collection: i, doc: { id: s, data: p } });
3821
+ }), r.push({ type: "modified", collection: i, doc: { id: s, data: u } });
3802
3822
  } else if (o.kind === "remove") {
3803
3823
  let s = o.id, a = await this._store.getDoc(i, s);
3804
3824
  await this._queue.enqueue({
@@ -3827,11 +3847,11 @@ var Qe = class {
3827
3847
  });
3828
3848
  let r = this._bus.subscribe(this._collection, async (s) => {
3829
3849
  try {
3830
- let a = await this._buildListResult(e), c = s.map((u) => ({
3831
- type: u.type,
3832
- doc: { id: u.doc.id, data: u.doc.data }
3850
+ let a = await this._buildListResult(e), d = s.map((p) => ({
3851
+ type: p.type,
3852
+ doc: { id: p.doc.id, data: p.doc.data }
3833
3853
  }));
3834
- t({ ...a, changes: c });
3854
+ t({ ...a, changes: d });
3835
3855
  } catch {
3836
3856
  }
3837
3857
  }), o = this._engine.onSyncStateChange(async () => {
@@ -3845,15 +3865,15 @@ var Qe = class {
3845
3865
  this._collection,
3846
3866
  async (s, a) => {
3847
3867
  if (!a)
3848
- for (let c of s)
3849
- c.type === "removed" || c.data === null ? (await this._store.deleteDoc(this._collection, c.docId), this._bus.emit([{
3868
+ for (let d of s)
3869
+ d.type === "removed" || d.data === null ? (await this._store.deleteDoc(this._collection, d.docId), this._bus.emit([{
3850
3870
  type: "removed",
3851
3871
  collection: this._collection,
3852
- doc: { id: c.docId, data: {} }
3872
+ doc: { id: d.docId, data: {} }
3853
3873
  }])) : (await this._store.putDoc({
3854
3874
  collection: this._collection,
3855
- id: c.docId,
3856
- data: c.data,
3875
+ id: d.docId,
3876
+ data: d.data,
3857
3877
  meta: {
3858
3878
  serverVersion: `rt_${Date.now()}`,
3859
3879
  updatedAtServer: Date.now(),
@@ -3864,9 +3884,9 @@ var Qe = class {
3864
3884
  ownerId: null
3865
3885
  }
3866
3886
  }), this._bus.emit([{
3867
- type: c.type,
3887
+ type: d.type,
3868
3888
  collection: this._collection,
3869
- doc: { id: c.docId, data: c.data }
3889
+ doc: { id: d.docId, data: d.data }
3870
3890
  }]));
3871
3891
  }
3872
3892
  )), () => {
@@ -3901,14 +3921,14 @@ var Qe = class {
3901
3921
  onSnapshot(r) {
3902
3922
  t._buildGetResult(e).then((s) => r(s)).catch(() => r(null));
3903
3923
  let o = t._bus.subscribe(t._collection, async (s) => {
3904
- let a = s.find((c) => c.doc.id === e);
3924
+ let a = s.find((d) => d.doc.id === e);
3905
3925
  if (a)
3906
3926
  try {
3907
3927
  if (a.type === "removed")
3908
3928
  r(null);
3909
3929
  else {
3910
- let c = await t._buildGetResult(e);
3911
- r(c);
3930
+ let d = await t._buildGetResult(e);
3931
+ r(d);
3912
3932
  }
3913
3933
  } catch {
3914
3934
  r(null);
@@ -3937,7 +3957,7 @@ var Qe = class {
3937
3957
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3938
3958
  }
3939
3959
  collection(e) {
3940
- return eo(e), new Qe(
3960
+ return to(e), new Qe(
3941
3961
  e,
3942
3962
  this._store,
3943
3963
  this._queue,
@@ -3967,7 +3987,7 @@ var Qe = class {
3967
3987
  }
3968
3988
  };
3969
3989
  async function tn(n) {
3970
- let e = Zr() ? new Te() : new Se(n.dbName);
3990
+ let e = eo() ? new Te() : new Se(n.dbName);
3971
3991
  await e.open();
3972
3992
  let t = new Re(e), r = new Ce(), o = new Ae(), i = new Ee({
3973
3993
  // Se startOnline=false, injeta um navigator falso
@@ -3976,7 +3996,7 @@ async function tn(n) {
3976
3996
  // Fake tab coordinator para single-tab mode (sempre líder)
3977
3997
  {
3978
3998
  isLeader: () => true,
3979
- onRoleChange: (c) => () => {
3999
+ onRoleChange: (d) => () => {
3980
4000
  }
3981
4001
  }
3982
4002
  ) : new ie({
@@ -4002,9 +4022,9 @@ async function tn(n) {
4002
4022
  }
4003
4023
 
4004
4024
  // src/db/realtime/realtime-client.ts
4005
- var ro = 0;
4025
+ var oo = 0;
4006
4026
  function nn() {
4007
- return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++ro}-${Math.random().toString(36).slice(2)}`;
4027
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++oo}-${Math.random().toString(36).slice(2)}`;
4008
4028
  }
4009
4029
  var Pe = class {
4010
4030
  // ── configuração ──────────────────────────────────────────────────────────
@@ -4044,7 +4064,7 @@ var Pe = class {
4044
4064
  _pendingFrames = [];
4045
4065
  // ── construtor ────────────────────────────────────────────────────────────
4046
4066
  constructor(e) {
4047
- this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? oo, 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();
4067
+ this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? io, 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();
4048
4068
  }
4049
4069
  // ── API pública ───────────────────────────────────────────────────────────
4050
4070
  /**
@@ -4323,7 +4343,7 @@ var Pe = class {
4323
4343
  _detachHandlers(e) {
4324
4344
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
4325
4345
  }
4326
- }, oo = (n) => {
4346
+ }, io = (n) => {
4327
4347
  if (typeof WebSocket > "u")
4328
4348
  throw new Error(
4329
4349
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -4332,11 +4352,11 @@ var Pe = class {
4332
4352
  };
4333
4353
 
4334
4354
  // src/db/client-db.ts
4335
- var go = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, Ne = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, mn = 200;
4336
- function yo(n, e, t) {
4337
- return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? _o(e.realtimeGatewayUrl, t, e) : gn(t);
4355
+ var bo = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, Ne = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, hn = 200;
4356
+ function vo(n, e, t) {
4357
+ return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? wo(e.realtimeGatewayUrl, t, e) : yn(t);
4338
4358
  }
4339
- function gn(n) {
4359
+ function yn(n) {
4340
4360
  return {
4341
4361
  async pushMutations(e) {
4342
4362
  if (!n)
@@ -4376,17 +4396,17 @@ function gn(n) {
4376
4396
  retries: 2,
4377
4397
  headers: i
4378
4398
  });
4379
- let c = a;
4399
+ let d = a;
4380
4400
  r.push({
4381
4401
  mutationId: s.mutationId,
4382
4402
  outcome: "confirmed",
4383
- serverVersion: c?.serverVersion ?? c?.id ?? `rest_${Date.now()}`,
4403
+ serverVersion: d?.serverVersion ?? d?.id ?? `rest_${Date.now()}`,
4384
4404
  serverTimestamp: Date.now()
4385
4405
  });
4386
4406
  } catch (a) {
4387
- let c = a instanceof Error ? a.message : String(a), u = a?.code, d = a?.status;
4388
- if (u === "forbidden" || u === "unauthorized" || u === "not_found" || u === "conflict" || u === "validation_failed" || typeof d == "number" && d >= 400 && d < 500 && d !== 408 && d !== 429) {
4389
- let f = u === "forbidden" || u === "unauthorized" ? "rejected_permission" : "rejected_validation";
4407
+ let d = a instanceof Error ? a.message : String(a), p = a?.code, l = a?.status;
4408
+ if (p === "forbidden" || p === "unauthorized" || p === "not_found" || p === "conflict" || p === "validation_failed" || typeof l == "number" && l >= 400 && l < 500 && l !== 408 && l !== 429) {
4409
+ let f = p === "forbidden" || p === "unauthorized" ? "rejected_permission" : "rejected_validation";
4390
4410
  r.push({
4391
4411
  mutationId: s.mutationId,
4392
4412
  outcome: "rejected",
@@ -4397,7 +4417,7 @@ function gn(n) {
4397
4417
  continue;
4398
4418
  }
4399
4419
  if (r.length === 0)
4400
- throw new v("db_unavailable", `pushMutations falhou: ${c}`);
4420
+ throw new v("db_unavailable", `pushMutations falhou: ${d}`);
4401
4421
  break;
4402
4422
  }
4403
4423
  return { results: r };
@@ -4409,12 +4429,12 @@ function gn(n) {
4409
4429
  if (!n)
4410
4430
  return { docs: [], newWatermark: Date.now() };
4411
4431
  let { httpRequest: t } = await Promise.resolve().then(() => (q(), ne)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4412
- for (let c of e) {
4413
- let u;
4432
+ for (let d of e) {
4433
+ let p;
4414
4434
  try {
4415
- u = await t(n, {
4435
+ p = await t(n, {
4416
4436
  method: "GET",
4417
- path: go(c),
4437
+ path: bo(d),
4418
4438
  requireAuth: !0,
4419
4439
  retries: 2,
4420
4440
  headers: o,
@@ -4422,18 +4442,18 @@ function gn(n) {
4422
4442
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
4423
4443
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
4424
4444
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
4425
- query: { limit: mn }
4445
+ query: { limit: hn }
4426
4446
  });
4427
4447
  } catch (f) {
4428
4448
  let m = f instanceof Error ? f.message : String(f);
4429
4449
  throw new v(
4430
4450
  "db_unavailable",
4431
- `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${c}": ${m}`
4451
+ `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${d}": ${m}`
4432
4452
  );
4433
4453
  }
4434
- let d = u, p = Array.isArray(d?.items) ? d.items : [];
4435
- p.length >= mn && a.push(c);
4436
- for (let f of p) {
4454
+ let l = p, u = Array.isArray(l?.items) ? l.items : [];
4455
+ u.length >= hn && a.push(d);
4456
+ for (let f of u) {
4437
4457
  if (!f || typeof f != "object") continue;
4438
4458
  let m = f, h = typeof m.id == "string" ? m.id : null;
4439
4459
  if (!h) continue;
@@ -4448,7 +4468,7 @@ function gn(n) {
4448
4468
  }
4449
4469
  let N = `rest_${h}_${w}`;
4450
4470
  s.push({
4451
- collection: c,
4471
+ collection: d,
4452
4472
  id: h,
4453
4473
  data: I,
4454
4474
  serverVersion: N,
@@ -4461,10 +4481,10 @@ function gn(n) {
4461
4481
  }
4462
4482
  };
4463
4483
  }
4464
- function _o(n, e, t) {
4465
- let r = gn(e), o = new Pe({
4484
+ function wo(n, e, t) {
4485
+ let r = yn(e), o = new Pe({
4466
4486
  gatewayUrl: n,
4467
- ticketProvider: bo(e, t),
4487
+ ticketProvider: ko(e, t),
4468
4488
  dbId: t.dbId,
4469
4489
  webSocketFactory: t._wsFactory
4470
4490
  });
@@ -4476,22 +4496,22 @@ function _o(n, e, t) {
4476
4496
  // quando o engine é nosql-vm. Registra a subscription no NeetruRealtimeClient
4477
4497
  // e traduz os frames inbound para o contrato de `onChange`.
4478
4498
  subscribeCollection(i, s) {
4479
- let a = o.subscribe(i, {}, (c) => {
4480
- if (c.op === "resync") {
4499
+ let a = o.subscribe(i, {}, (d) => {
4500
+ if (d.op === "resync") {
4481
4501
  s([], true);
4482
4502
  return;
4483
4503
  }
4484
- if (c.op === "stale") {
4504
+ if (d.op === "stale") {
4485
4505
  s([], true);
4486
4506
  return;
4487
4507
  }
4488
- if (c.op === "delta" && c.changes) {
4489
- let u = c.changes.map((d) => ({
4490
- type: d.type === "insert" ? "added" : d.type === "delete" ? "removed" : "modified",
4491
- docId: d.documentId,
4492
- data: d.data ?? null
4508
+ if (d.op === "delta" && d.changes) {
4509
+ let p = d.changes.map((l) => ({
4510
+ type: l.type === "insert" ? "added" : l.type === "delete" ? "removed" : "modified",
4511
+ docId: l.documentId,
4512
+ data: l.data ?? null
4493
4513
  }));
4494
- u.length > 0 && s(u, false);
4514
+ p.length > 0 && s(p, false);
4495
4515
  }
4496
4516
  });
4497
4517
  return () => {
@@ -4500,7 +4520,7 @@ function _o(n, e, t) {
4500
4520
  }
4501
4521
  };
4502
4522
  }
4503
- function bo(n, e) {
4523
+ function ko(n, e) {
4504
4524
  return async () => {
4505
4525
  let { httpRequest: t } = await Promise.resolve().then(() => (q(), ne));
4506
4526
  return await t(n, {
@@ -4515,37 +4535,37 @@ function bo(n, e) {
4515
4535
  });
4516
4536
  };
4517
4537
  }
4518
- var hn = false;
4519
- function vo(n, e) {
4520
- hn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (hn = true, console.warn(
4538
+ var gn = false;
4539
+ function So(n, e) {
4540
+ gn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (gn = true, console.warn(
4521
4541
  '[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.'
4522
4542
  )));
4523
4543
  }
4524
4544
  function nt(n, e = {}) {
4525
- vo(n, e);
4545
+ So(n, e);
4526
4546
  let t;
4527
4547
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
4528
4548
  '[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).'
4529
4549
  ), t = e.engine) : t = "rest";
4530
- let r = yo(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4531
- function c() {
4550
+ let r = vo(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4551
+ function d() {
4532
4552
  return s || (s = tn({
4533
4553
  dbName: i,
4534
4554
  transport: r,
4535
4555
  singleTab: e.singleTab ?? n.env !== "prod"
4536
- }).then((u) => (a = u, u))), s;
4556
+ }).then((p) => (a = p, p))), s;
4537
4557
  }
4538
4558
  return {
4539
- collection(u) {
4540
- return a ? a.collection(u) : wo(u, c);
4559
+ collection(p) {
4560
+ return a ? a.collection(p) : To(p, d);
4541
4561
  },
4542
- async sql(u, d) {
4562
+ async sql(p, l) {
4543
4563
  if (n.env === "dev")
4544
4564
  throw new v(
4545
4565
  "db_unavailable",
4546
4566
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4547
4567
  );
4548
- return (await Promise.resolve().then(() => (fn(), pn))).createSqlClientFromConfig(n, u, d);
4568
+ return (await Promise.resolve().then(() => (mn(), fn))).createSqlClientFromConfig(n, p, l);
4549
4569
  },
4550
4570
  get syncState() {
4551
4571
  return a?.syncState ?? {
@@ -4555,36 +4575,36 @@ function nt(n, e = {}) {
4555
4575
  isLeaderTab: false
4556
4576
  };
4557
4577
  },
4558
- onSyncStateChanged(u) {
4559
- if (a) return a.onSyncStateChanged(u);
4560
- let d = null, p = false;
4561
- return c().then((f) => {
4562
- p || (d = f.onSyncStateChanged(u));
4578
+ onSyncStateChanged(p) {
4579
+ if (a) return a.onSyncStateChanged(p);
4580
+ let l = null, u = false;
4581
+ return d().then((f) => {
4582
+ u || (l = f.onSyncStateChanged(p));
4563
4583
  }), () => {
4564
- p = true, d?.();
4584
+ u = true, l?.();
4565
4585
  };
4566
4586
  },
4567
4587
  async flush() {
4568
- return (await c()).flush();
4588
+ return (await d()).flush();
4569
4589
  },
4570
4590
  async clearCache() {
4571
- return (await c()).clearCache();
4591
+ return (await d()).clearCache();
4572
4592
  },
4573
4593
  async getConflicts() {
4574
- return (await c()).getConflicts();
4594
+ return (await d()).getConflicts();
4575
4595
  },
4576
- onError(u) {
4577
- if (a) return a.onError(u);
4578
- let d = null, p = false;
4579
- return c().then((f) => {
4580
- p || (d = f.onError(u));
4596
+ onError(p) {
4597
+ if (a) return a.onError(p);
4598
+ let l = null, u = false;
4599
+ return d().then((f) => {
4600
+ u || (l = f.onError(p));
4581
4601
  }), () => {
4582
- p = true, d?.();
4602
+ u = true, l?.();
4583
4603
  };
4584
4604
  }
4585
4605
  };
4586
4606
  }
4587
- function wo(n, e) {
4607
+ function To(n, e) {
4588
4608
  async function t() {
4589
4609
  return (await e()).collection(n);
4590
4610
  }
@@ -4668,20 +4688,20 @@ q();
4668
4688
  function rt(n, e) {
4669
4689
  let t = n?.accessToken || n?.idToken;
4670
4690
  if (!t || typeof t != "string")
4671
- throw new l(
4691
+ throw new c(
4672
4692
  "validation_failed",
4673
4693
  `checkout.${e} requer o access_token OU o id_token OIDC do usu\xE1rio final (passe \`accessToken\` ou \`idToken\`). A chave de API do SDK (nrt_*) N\xC3O \xE9 aceita pelo endpoint de checkout \u2014 ele autentica a identidade do cliente que est\xE1 assinando (Bearer access_token/id_token OIDC ou cookie de sess\xE3o). No padr\xE3o BFF/cookie, passe o \`idToken\` que seu servidor guardou no cookie httpOnly.`
4674
4694
  );
4675
4695
  return { requireAuth: false, headers: { authorization: `Bearer ${t}` } };
4676
4696
  }
4677
- function ko(n) {
4697
+ function Ro(n) {
4678
4698
  if (!n || typeof n != "object")
4679
- throw new l("invalid_response", "checkout.start response is not an object");
4699
+ throw new c("invalid_response", "checkout.start response is not an object");
4680
4700
  let e = n;
4681
4701
  if (typeof e.intentId != "string" || !e.intentId)
4682
- throw new l("invalid_response", "checkout.start response missing intentId");
4702
+ throw new c("invalid_response", "checkout.start response missing intentId");
4683
4703
  if (typeof e.redirectUrl != "string" || !e.redirectUrl)
4684
- throw new l("invalid_response", "checkout.start response missing redirectUrl");
4704
+ throw new c("invalid_response", "checkout.start response missing redirectUrl");
4685
4705
  return {
4686
4706
  intentId: e.intentId,
4687
4707
  redirectUrl: e.redirectUrl,
@@ -4690,14 +4710,14 @@ function ko(n) {
4690
4710
  requiresKyc: e.requiresKyc === true
4691
4711
  };
4692
4712
  }
4693
- function So(n) {
4713
+ function Io(n) {
4694
4714
  if (!n || typeof n != "object")
4695
- throw new l("invalid_response", "checkout.get response is not an object");
4715
+ throw new c("invalid_response", "checkout.get response is not an object");
4696
4716
  let e = n, t = e.intent;
4697
4717
  if (!t || typeof t != "object")
4698
- throw new l("invalid_response", "checkout.get response missing intent");
4718
+ throw new c("invalid_response", "checkout.get response missing intent");
4699
4719
  if (typeof t.intentId != "string")
4700
- throw new l("invalid_response", "checkout.get response missing intentId");
4720
+ throw new c("invalid_response", "checkout.get response missing intentId");
4701
4721
  return {
4702
4722
  intentId: t.intentId,
4703
4723
  uid: t.uid ?? "",
@@ -4712,28 +4732,28 @@ function So(n) {
4712
4732
  isStale: e.isStale === true
4713
4733
  };
4714
4734
  }
4715
- function To() {
4735
+ function Co() {
4716
4736
  try {
4717
4737
  return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
4718
4738
  } catch {
4719
4739
  return false;
4720
4740
  }
4721
4741
  }
4722
- function Ro(n) {
4742
+ function Ao(n) {
4723
4743
  try {
4724
4744
  globalThis.location.assign(n);
4725
4745
  } catch {
4726
4746
  }
4727
4747
  }
4728
- function Io(n) {
4748
+ function Eo(n) {
4729
4749
  return {
4730
4750
  async start(e) {
4731
4751
  if (!e?.productId)
4732
- throw new l("validation_failed", "checkout.start: productId is required");
4752
+ throw new c("validation_failed", "checkout.start: productId is required");
4733
4753
  if (!e?.planId)
4734
- throw new l("validation_failed", "checkout.start: planId is required");
4754
+ throw new c("validation_failed", "checkout.start: planId is required");
4735
4755
  if (!e?.callbackUrl)
4736
- throw new l("validation_failed", "checkout.start: callbackUrl is required");
4756
+ throw new c("validation_failed", "checkout.start: callbackUrl is required");
4737
4757
  let t = {
4738
4758
  productId: e.productId,
4739
4759
  planId: e.planId,
@@ -4750,12 +4770,12 @@ function Io(n) {
4750
4770
  requireAuth: r,
4751
4771
  headers: o,
4752
4772
  idempotencyKey: true
4753
- }), s = ko(i);
4754
- return e.autoRedirect !== false && To() && Ro(s.redirectUrl), s;
4773
+ }), s = Ro(i);
4774
+ return e.autoRedirect !== false && Co() && Ao(s.redirectUrl), s;
4755
4775
  },
4756
4776
  async get(e, t) {
4757
4777
  if (!e || typeof e != "string")
4758
- throw new l("validation_failed", "checkout.get: intentId is required");
4778
+ throw new c("validation_failed", "checkout.get: intentId is required");
4759
4779
  let { requireAuth: r, headers: o } = rt(
4760
4780
  { accessToken: t?.accessToken, idToken: t?.idToken },
4761
4781
  "get"
@@ -4765,11 +4785,11 @@ function Io(n) {
4765
4785
  requireAuth: r,
4766
4786
  headers: o
4767
4787
  });
4768
- return So(i);
4788
+ return Io(i);
4769
4789
  },
4770
4790
  async cancel(e, t) {
4771
4791
  if (!e || typeof e != "string")
4772
- throw new l("validation_failed", "checkout.cancel: intentId is required");
4792
+ throw new c("validation_failed", "checkout.cancel: intentId is required");
4773
4793
  let { requireAuth: r, headers: o } = rt(
4774
4794
  { accessToken: t?.accessToken, idToken: t?.idToken },
4775
4795
  "cancel"
@@ -4790,11 +4810,11 @@ var xe = class {
4790
4810
  intents = /* @__PURE__ */ new Map();
4791
4811
  async start(e) {
4792
4812
  if (!e?.productId)
4793
- throw new l("validation_failed", "checkout.start: productId is required");
4813
+ throw new c("validation_failed", "checkout.start: productId is required");
4794
4814
  if (!e?.planId)
4795
- throw new l("validation_failed", "checkout.start: planId is required");
4815
+ throw new c("validation_failed", "checkout.start: planId is required");
4796
4816
  if (!e?.callbackUrl)
4797
- throw new l("validation_failed", "checkout.start: callbackUrl is required");
4817
+ throw new c("validation_failed", "checkout.start: callbackUrl is required");
4798
4818
  let t = `chk_mock_${Math.random().toString(36).slice(2, 10)}`, r = new Date(Date.now() + 900 * 1e3).toISOString(), o = `https://localhost:9003/portal/checkout/${t}`;
4799
4819
  return this.intents.set(t, {
4800
4820
  intentId: t,
@@ -4818,61 +4838,61 @@ var xe = class {
4818
4838
  async get(e, t) {
4819
4839
  let r = this.intents.get(e);
4820
4840
  if (!r)
4821
- throw new l("not_found", `Mock intent ${e} not found`);
4841
+ throw new c("not_found", `Mock intent ${e} not found`);
4822
4842
  return { ...r };
4823
4843
  }
4824
4844
  async cancel(e, t) {
4825
4845
  let r = this.intents.get(e);
4826
4846
  if (!r)
4827
- throw new l("not_found", `Mock intent ${e} not found`);
4847
+ throw new c("not_found", `Mock intent ${e} not found`);
4828
4848
  let o = r.status === "cancelled";
4829
4849
  return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
4830
4850
  }
4831
4851
  };
4832
4852
  function ot(n) {
4833
- return n.env === "dev" ? new xe() : Io(n);
4853
+ return n.env === "dev" ? new xe() : Eo(n);
4834
4854
  }
4835
4855
 
4836
4856
  // src/webhooks.ts
4837
4857
  C();
4838
4858
  q();
4839
- async function _n(n, e, t, r) {
4859
+ async function bn(n, e, t, r) {
4840
4860
  if (!e || !t) return false;
4841
4861
  let o = e.startsWith("sha256=") ? e.slice(7) : e;
4842
4862
  if (!/^[0-9a-f]+$/i.test(o)) return false;
4843
4863
  let i = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto?.subtle : void 0;
4844
4864
  if (!i)
4845
- throw new l(
4865
+ throw new c(
4846
4866
  "runtime_unsupported",
4847
4867
  "verifyWebhookSignature requires globalThis.crypto.subtle (Node \u226520, modern browser, or Edge runtime)."
4848
4868
  );
4849
- let s = new TextEncoder(), a = s.encode(t), c = typeof n == "string" ? s.encode(n) : n, u = c;
4869
+ let s = new TextEncoder(), a = s.encode(t), d = typeof n == "string" ? s.encode(n) : n, p = d;
4850
4870
  if (r !== void 0) {
4851
- let y = s.encode(`${r}.`), I = new Uint8Array(y.length + c.length);
4852
- I.set(y, 0), I.set(c, y.length), u = I;
4871
+ let y = s.encode(`${r}.`), I = new Uint8Array(y.length + d.length);
4872
+ I.set(y, 0), I.set(d, y.length), p = I;
4853
4873
  }
4854
- let d = await i.importKey(
4874
+ let l = await i.importKey(
4855
4875
  "raw",
4856
4876
  a,
4857
4877
  { name: "HMAC", hash: "SHA-256" },
4858
4878
  false,
4859
4879
  ["sign"]
4860
- ), p = await i.sign(
4880
+ ), u = await i.sign(
4861
4881
  "HMAC",
4862
- d,
4863
- u
4864
- ), f = new Uint8Array(p), m = Ao(o.toLowerCase());
4882
+ l,
4883
+ p
4884
+ ), f = new Uint8Array(u), m = Do(o.toLowerCase());
4865
4885
  if (!m || m.length !== f.length) return false;
4866
4886
  let h = 0;
4867
4887
  for (let y = 0; y < f.length; y++)
4868
4888
  h |= f[y] ^ m[y];
4869
4889
  return h === 0;
4870
4890
  }
4871
- async function Co(n, e, t, r = {}) {
4872
- let o = r.toleranceMs ?? 3e5, i = (p) => {
4891
+ async function Po(n, e, t, r = {}) {
4892
+ let o = r.toleranceMs ?? 3e5, i = (u) => {
4873
4893
  if (typeof e.get == "function")
4874
- return e.get(p);
4875
- let f = e, m = p.toLowerCase();
4894
+ return e.get(u);
4895
+ let f = e, m = u.toLowerCase();
4876
4896
  for (let h of Object.keys(f))
4877
4897
  if (h.toLowerCase() === m) return f[h] ?? null;
4878
4898
  return null;
@@ -4884,10 +4904,10 @@ async function Co(n, e, t, r = {}) {
4884
4904
  return { ok: false, reason: "timestamp_missing" };
4885
4905
  if (Math.abs(Date.now() - a) > o)
4886
4906
  return { ok: false, reason: "timestamp_expired" };
4887
- let u = i("x-neetru-signature");
4888
- return await _n(n, u, t, s) ? { ok: true } : { ok: false, reason: "invalid_signature" };
4907
+ let p = i("x-neetru-signature");
4908
+ return await bn(n, p, t, s) ? { ok: true } : { ok: false, reason: "invalid_signature" };
4889
4909
  }
4890
- function Ao(n) {
4910
+ function Do(n) {
4891
4911
  if (n.length % 2 !== 0) return null;
4892
4912
  let e = new Uint8Array(n.length / 2);
4893
4913
  for (let t = 0; t < e.length; t++) {
@@ -4897,7 +4917,7 @@ function Ao(n) {
4897
4917
  }
4898
4918
  return e;
4899
4919
  }
4900
- var bn = [
4920
+ var vn = [
4901
4921
  "subscription.activated",
4902
4922
  "subscription.cancelled",
4903
4923
  "subscription.payment_failed",
@@ -4907,17 +4927,17 @@ var bn = [
4907
4927
  "account.reactivated",
4908
4928
  "support.ticket_replied"
4909
4929
  ];
4910
- function yn(n) {
4930
+ function _n(n) {
4911
4931
  if (!n || typeof n != "object")
4912
- throw new l("invalid_response", "Webhook response is not an object");
4932
+ throw new c("invalid_response", "Webhook response is not an object");
4913
4933
  let e = n;
4914
4934
  if (typeof e.id != "string")
4915
- throw new l("invalid_response", "Webhook missing id");
4935
+ throw new c("invalid_response", "Webhook missing id");
4916
4936
  return {
4917
4937
  id: e.id,
4918
4938
  url: typeof e.url == "string" ? e.url : "",
4919
4939
  events: Array.isArray(e.events) ? e.events.filter(
4920
- (t) => bn.includes(t)
4940
+ (t) => vn.includes(t)
4921
4941
  ) : [],
4922
4942
  hasSecret: e.hasSecret === true,
4923
4943
  status: e.status === "active" || e.status === "degraded" || e.status === "disabled" ? e.status : "active",
@@ -4926,23 +4946,23 @@ function yn(n) {
4926
4946
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString()
4927
4947
  };
4928
4948
  }
4929
- function vn(n) {
4949
+ function wn(n) {
4930
4950
  if (!n.url || typeof n.url != "string")
4931
- throw new l("validation_failed", "url \xE9 obrigat\xF3ria");
4951
+ throw new c("validation_failed", "url \xE9 obrigat\xF3ria");
4932
4952
  try {
4933
4953
  let e = new URL(n.url);
4934
4954
  if (e.protocol !== "https:" && e.protocol !== "http:")
4935
4955
  throw new Error("invalid protocol");
4936
4956
  } catch {
4937
- throw new l("validation_failed", `url inv\xE1lida: ${n.url}`);
4957
+ throw new c("validation_failed", `url inv\xE1lida: ${n.url}`);
4938
4958
  }
4939
4959
  if (!Array.isArray(n.events) || n.events.length === 0)
4940
- throw new l("validation_failed", "events deve ter pelo menos 1 evento");
4960
+ throw new c("validation_failed", "events deve ter pelo menos 1 evento");
4941
4961
  for (let e of n.events)
4942
- if (!bn.includes(e))
4943
- throw new l("validation_failed", `evento desconhecido: ${e}`);
4962
+ if (!vn.includes(e))
4963
+ throw new c("validation_failed", `evento desconhecido: ${e}`);
4944
4964
  if (n.secret !== void 0 && n.secret.length < 16)
4945
- throw new l("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4965
+ throw new c("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4946
4966
  }
4947
4967
  function Oe(n, ...e) {
4948
4968
  for (let t of e)
@@ -4950,7 +4970,7 @@ function Oe(n, ...e) {
4950
4970
  return O("productId", t), t;
4951
4971
  if (n.productId)
4952
4972
  return O("productId", n.productId), n.productId;
4953
- throw new l(
4973
+ throw new c(
4954
4974
  "validation_failed",
4955
4975
  "productId required (pass to options/input or set on createNeetruClient)"
4956
4976
  );
@@ -4958,7 +4978,7 @@ function Oe(n, ...e) {
4958
4978
  function it(n) {
4959
4979
  return {
4960
4980
  async register(e) {
4961
- vn(e);
4981
+ wn(e);
4962
4982
  let t = Oe(n, e.productId), r = await S(n, {
4963
4983
  method: "POST",
4964
4984
  path: "/api/sdk/v1/webhooks",
@@ -4975,7 +4995,7 @@ function it(n) {
4975
4995
  // dedup TTL 24h (mesmo padrão de usage.report/support.createTicket).
4976
4996
  idempotencyKey: true
4977
4997
  });
4978
- return yn(r);
4998
+ return _n(r);
4979
4999
  },
4980
5000
  async list(e) {
4981
5001
  let t = Oe(n, e?.productId), r = await S(n, {
@@ -4984,10 +5004,10 @@ function it(n) {
4984
5004
  query: { productId: t },
4985
5005
  requireAuth: true
4986
5006
  });
4987
- return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(yn);
5007
+ return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(_n);
4988
5008
  },
4989
5009
  async unregister(e, t) {
4990
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5010
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4991
5011
  let r = Oe(n, t?.productId);
4992
5012
  return await S(n, {
4993
5013
  method: "DELETE",
@@ -4997,7 +5017,7 @@ function it(n) {
4997
5017
  }), { ok: true };
4998
5018
  },
4999
5019
  async test(e, t) {
5000
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5020
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5001
5021
  let r = Oe(n, t?.productId), o = await S(n, {
5002
5022
  method: "POST",
5003
5023
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}/test`,
@@ -5021,7 +5041,7 @@ var ae = class {
5021
5041
  endpoints = /* @__PURE__ */ new Map();
5022
5042
  nextId = 1;
5023
5043
  async register(e) {
5024
- vn(e);
5044
+ wn(e);
5025
5045
  let t = `mock_wh_${this.nextId++}`, r = {
5026
5046
  id: t,
5027
5047
  url: e.url,
@@ -5037,12 +5057,12 @@ var ae = class {
5037
5057
  }
5038
5058
  async unregister(e, t) {
5039
5059
  if (!this.endpoints.has(e))
5040
- throw new l("not_found", `Webhook ${e} n\xE3o encontrado`);
5060
+ throw new c("not_found", `Webhook ${e} n\xE3o encontrado`);
5041
5061
  return this.endpoints.delete(e), { ok: true };
5042
5062
  }
5043
5063
  async test(e, t) {
5044
5064
  if (!this.endpoints.has(e))
5045
- throw new l("not_found", `Webhook ${e} n\xE3o encontrado`);
5065
+ throw new c("not_found", `Webhook ${e} n\xE3o encontrado`);
5046
5066
  return { ok: true, statusCode: 200, durationMs: 42 };
5047
5067
  }
5048
5068
  };
@@ -5056,12 +5076,12 @@ var st = [
5056
5076
  "warning",
5057
5077
  "error"
5058
5078
  ];
5059
- function wn(n) {
5079
+ function kn(n) {
5060
5080
  if (!n || typeof n != "object")
5061
- throw new l("invalid_response", "Notification response is not an object");
5081
+ throw new c("invalid_response", "Notification response is not an object");
5062
5082
  let e = n;
5063
5083
  if (typeof e.id != "string")
5064
- throw new l("invalid_response", "Notification missing id");
5084
+ throw new c("invalid_response", "Notification missing id");
5065
5085
  let t = st.includes(e.severity) ? e.severity : "info";
5066
5086
  return {
5067
5087
  id: e.id,
@@ -5077,19 +5097,19 @@ function wn(n) {
5077
5097
  dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
5078
5098
  };
5079
5099
  }
5080
- function kn(n) {
5081
- if (!n.userId) throw new l("validation_failed", "userId obrigat\xF3rio");
5082
- if (!n.kind) throw new l("validation_failed", "kind obrigat\xF3rio");
5083
- if (!n.title) throw new l("validation_failed", "title obrigat\xF3rio");
5100
+ function Sn(n) {
5101
+ if (!n.userId) throw new c("validation_failed", "userId obrigat\xF3rio");
5102
+ if (!n.kind) throw new c("validation_failed", "kind obrigat\xF3rio");
5103
+ if (!n.title) throw new c("validation_failed", "title obrigat\xF3rio");
5084
5104
  if (n.severity && !st.includes(n.severity))
5085
- throw new l(
5105
+ throw new c(
5086
5106
  "validation_failed",
5087
5107
  `severity inv\xE1lida: ${n.severity} (use ${st.join("|")})`
5088
5108
  );
5089
5109
  if (n.title.length > 200)
5090
- throw new l("validation_failed", "title m\xE1x 200 chars");
5110
+ throw new c("validation_failed", "title m\xE1x 200 chars");
5091
5111
  if (n.body && n.body.length > 2e3)
5092
- throw new l("validation_failed", "body m\xE1x 2000 chars");
5112
+ throw new c("validation_failed", "body m\xE1x 2000 chars");
5093
5113
  }
5094
5114
  function Le(n, ...e) {
5095
5115
  for (let t of e)
@@ -5097,7 +5117,7 @@ function Le(n, ...e) {
5097
5117
  return O("productId", t), t;
5098
5118
  if (n.productId)
5099
5119
  return O("productId", n.productId), n.productId;
5100
- throw new l(
5120
+ throw new c(
5101
5121
  "validation_failed",
5102
5122
  "productId required (pass to options/input or set on createNeetruClient)"
5103
5123
  );
@@ -5105,7 +5125,7 @@ function Le(n, ...e) {
5105
5125
  function at(n) {
5106
5126
  return {
5107
5127
  async send(e) {
5108
- kn(e);
5128
+ Sn(e);
5109
5129
  let r = {
5110
5130
  productId: Le(n, e.productId),
5111
5131
  userId: e.userId,
@@ -5121,10 +5141,10 @@ function at(n) {
5121
5141
  requireAuth: true,
5122
5142
  idempotencyKey: true
5123
5143
  });
5124
- return wn(o);
5144
+ return kn(o);
5125
5145
  },
5126
5146
  async list(e, t) {
5127
- if (!e) throw new l("validation_failed", "userId obrigat\xF3rio");
5147
+ if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5128
5148
  let o = {
5129
5149
  productId: Le(n, t?.productId)
5130
5150
  };
@@ -5135,10 +5155,10 @@ function at(n) {
5135
5155
  query: o,
5136
5156
  requireAuth: true
5137
5157
  });
5138
- return (Array.isArray(i?.notifications) ? i.notifications : []).map(wn);
5158
+ return (Array.isArray(i?.notifications) ? i.notifications : []).map(kn);
5139
5159
  },
5140
5160
  async markRead(e, t) {
5141
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5161
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5142
5162
  let r = Le(n, t?.productId);
5143
5163
  return await S(n, {
5144
5164
  method: "POST",
@@ -5148,7 +5168,7 @@ function at(n) {
5148
5168
  }), { ok: true };
5149
5169
  },
5150
5170
  async dismiss(e, t) {
5151
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5171
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5152
5172
  let r = Le(n, t?.productId);
5153
5173
  return await S(n, {
5154
5174
  method: "POST",
@@ -5163,7 +5183,7 @@ var ce = class {
5163
5183
  notifications = /* @__PURE__ */ new Map();
5164
5184
  nextId = 1;
5165
5185
  async send(e) {
5166
- if (kn(e), e.fingerprint) {
5186
+ if (Sn(e), e.fingerprint) {
5167
5187
  let o = Date.now() - 864e5;
5168
5188
  for (let i of this.notifications.values())
5169
5189
  if ((i.metadata ?? {}).fingerprint === e.fingerprint && i.userId === e.userId && new Date(i.createdAt).getTime() > o)
@@ -5183,18 +5203,18 @@ var ce = class {
5183
5203
  return this.notifications.set(t, r), r;
5184
5204
  }
5185
5205
  async list(e, t) {
5186
- if (!e) throw new l("validation_failed", "userId obrigat\xF3rio");
5206
+ if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5187
5207
  let r = Math.min(Math.max(1, t?.limit ?? 50), 200);
5188
5208
  return [...this.notifications.values()].filter((o) => o.userId === e).filter((o) => t?.includeDismissed || !o.dismissedAt).filter((o) => !t?.onlyUnread || !o.readAt).sort((o, i) => i.createdAt.localeCompare(o.createdAt)).slice(0, r);
5189
5209
  }
5190
5210
  async markRead(e, t) {
5191
5211
  let r = this.notifications.get(e);
5192
- if (!r) throw new l("not_found", `Notification ${e} n\xE3o encontrada`);
5212
+ if (!r) throw new c("not_found", `Notification ${e} n\xE3o encontrada`);
5193
5213
  return r.readAt || (r.readAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, r)), { ok: true };
5194
5214
  }
5195
5215
  async dismiss(e, t) {
5196
5216
  let r = this.notifications.get(e);
5197
- if (!r) throw new l("not_found", `Notification ${e} n\xE3o encontrada`);
5217
+ if (!r) throw new c("not_found", `Notification ${e} n\xE3o encontrada`);
5198
5218
  return r.dismissedAt || (r.dismissedAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, r)), { ok: true };
5199
5219
  }
5200
5220
  };
@@ -5203,41 +5223,41 @@ var ce = class {
5203
5223
  C();
5204
5224
  q();
5205
5225
  We();
5206
- var Eo = "/api/sdk/v1/ai/chat", Sn = 12e4, Ue = 32768, Tn = 32, Rn = 4194304, In = 2048, Po = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, Do = /^https:\/\/[^\s]+$/, No = /* @__PURE__ */ new Set(["low", "high", "auto"]), xo = /* @__PURE__ */ new Set(["system", "user", "assistant"]), Cn = 100, An = 128, En = 32768, Pn = 0, Dn = 2, Nn = 200, xn = 20, On = 12 * 1024 * 1024, Ln = 5e4, Un = 16, Mn = 500, Oo = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), Lo = /^[a-zA-Z0-9_-]+$/;
5226
+ var No = "/api/sdk/v1/ai/chat", Tn = 12e4, Ue = 32768, Rn = 32, In = 4194304, Cn = 2048, xo = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, Oo = /^https:\/\/[^\s]+$/, Lo = /* @__PURE__ */ new Set(["low", "high", "auto"]), Uo = /* @__PURE__ */ new Set(["system", "user", "assistant"]), An = 100, En = 128, Pn = 32768, Dn = 0, Nn = 2, xn = 200, On = 20, Ln = 12 * 1024 * 1024, Un = 5e4, Mn = 16, qn = 500, Mo = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), qo = /^[a-zA-Z0-9_-]+$/;
5207
5227
  function R(n) {
5208
- throw new l("validation_failed", n);
5228
+ throw new c("validation_failed", n);
5209
5229
  }
5210
- function Uo(n) {
5230
+ function Fo(n) {
5211
5231
  if (n.length === 0 || n.length % 4 !== 0) return false;
5212
5232
  let e = n.endsWith("==") ? 2 : n.endsWith("=") ? 1 : 0;
5213
5233
  return !(e > 0 ? n.slice(0, n.length - e) : n).includes("=");
5214
5234
  }
5215
- function Mo(n) {
5235
+ function jo(n) {
5216
5236
  let e = n.indexOf(",");
5217
5237
  if (e === -1) return 0;
5218
5238
  let t = n.slice(e + 1), r = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
5219
5239
  return Math.max(0, Math.floor(t.length * 3 / 4) - r);
5220
5240
  }
5221
- function qo(n) {
5241
+ function Wo(n) {
5222
5242
  let e = 0, t = 0, r = 0;
5223
5243
  for (let o of n) {
5224
5244
  let i = o?.content;
5225
5245
  if (Array.isArray(i))
5226
5246
  for (let s of i) {
5227
- if (e++, e > Nn)
5228
- return `ai: total content parts exceeds ${Nn} per request`;
5247
+ if (e++, e > xn)
5248
+ return `ai: total content parts exceeds ${xn} per request`;
5229
5249
  if (s && typeof s == "object" && s.type === "image_url") {
5230
- if (t++, t > xn)
5231
- return `ai: total images exceeds ${xn} per request`;
5250
+ if (t++, t > On)
5251
+ return `ai: total images exceeds ${On} per request`;
5232
5252
  let a = s.image_url?.url;
5233
- if (typeof a == "string" && a.startsWith("data:") && (r += Mo(a), r > On))
5234
- return `ai: aggregate image bytes exceeds ${On} per request`;
5253
+ if (typeof a == "string" && a.startsWith("data:") && (r += jo(a), r > Ln))
5254
+ return `ai: aggregate image bytes exceeds ${Ln} per request`;
5235
5255
  }
5236
5256
  }
5237
5257
  }
5238
5258
  return null;
5239
5259
  }
5240
- function Fo(n) {
5260
+ function $o(n) {
5241
5261
  if (n === void 0) return null;
5242
5262
  if (n === null || typeof n != "object")
5243
5263
  return "ai: responseFormat json_schema.schema must be an object";
@@ -5248,11 +5268,11 @@ function Fo(n) {
5248
5268
  return "ai: responseFormat json_schema.schema is not serializable";
5249
5269
  }
5250
5270
  if (e === void 0) return "ai: responseFormat json_schema.schema is invalid";
5251
- if (e.length > Ln)
5252
- return `ai: responseFormat json_schema.schema exceeds ${Ln} serialized chars`;
5271
+ if (e.length > Un)
5272
+ return `ai: responseFormat json_schema.schema exceeds ${Un} serialized chars`;
5253
5273
  let t = 0, r = (o, i) => {
5254
- if (i > Un)
5255
- return `ai: responseFormat json_schema.schema exceeds max depth ${Un}`;
5274
+ if (i > Mn)
5275
+ return `ai: responseFormat json_schema.schema exceeds max depth ${Mn}`;
5256
5276
  if (Array.isArray(o)) {
5257
5277
  for (let s of o) {
5258
5278
  let a = r(s, i + 1);
@@ -5262,10 +5282,10 @@ function Fo(n) {
5262
5282
  }
5263
5283
  if (o && typeof o == "object")
5264
5284
  for (let s of Object.getOwnPropertyNames(o)) {
5265
- if (Oo.has(s))
5285
+ if (Mo.has(s))
5266
5286
  return `ai: responseFormat json_schema.schema has forbidden key: ${s}`;
5267
- if (t++, t > Mn)
5268
- return `ai: responseFormat json_schema.schema exceeds ${Mn} keys`;
5287
+ if (t++, t > qn)
5288
+ return `ai: responseFormat json_schema.schema exceeds ${qn} keys`;
5269
5289
  let a = r(o[s], i + 1);
5270
5290
  if (a) return a;
5271
5291
  }
@@ -5273,27 +5293,27 @@ function Fo(n) {
5273
5293
  };
5274
5294
  return r(n, 0);
5275
5295
  }
5276
- function jo(n) {
5296
+ function Vo(n) {
5277
5297
  (typeof n != "string" || n.length === 0) && R("ai: image_url.url must be a non-empty string");
5278
5298
  let e = n;
5279
5299
  if (e.startsWith("data:")) {
5280
- e.length > Rn && R(`ai: image_url.url (data:) exceeds ${Rn} chars`), Po.test(e) || R("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5300
+ e.length > In && R(`ai: image_url.url (data:) exceeds ${In} chars`), xo.test(e) || R("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5281
5301
  let t = e.slice(e.indexOf(",") + 1);
5282
- Uo(t) || R("ai: image_url.url data: has invalid base64 (length/padding)");
5302
+ Fo(t) || R("ai: image_url.url data: has invalid base64 (length/padding)");
5283
5303
  return;
5284
5304
  }
5285
5305
  if (e.startsWith("https://")) {
5286
- e.length > In && R(`ai: image_url.url (https:) exceeds ${In} chars`), Do.test(e) || R("ai: image_url.url https: is invalid");
5306
+ e.length > Cn && R(`ai: image_url.url (https:) exceeds ${Cn} chars`), Oo.test(e) || R("ai: image_url.url https: is invalid");
5287
5307
  return;
5288
5308
  }
5289
5309
  R("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5290
5310
  }
5291
- function Wo(n, e) {
5311
+ function Bo(n, e) {
5292
5312
  if (typeof n == "string") {
5293
5313
  n.length === 0 && R("ai: message content string must be non-empty"), n.length > Ue && R(`ai: message content exceeds ${Ue} chars`);
5294
5314
  return;
5295
5315
  }
5296
- (!Array.isArray(n) || n.length === 0) && R("ai: message content must be a non-empty string or array of parts"), n.length > Tn && R(`ai: message content has more than ${Tn} parts`);
5316
+ (!Array.isArray(n) || n.length === 0) && R("ai: message content must be a non-empty string or array of parts"), n.length > Rn && R(`ai: message content has more than ${Rn} parts`);
5297
5317
  for (let t of n) {
5298
5318
  (!t || typeof t != "object") && R("ai: each content part must be an object");
5299
5319
  let r = t.type;
@@ -5303,14 +5323,14 @@ function Wo(n, e) {
5303
5323
  } else if (r === "image_url") {
5304
5324
  e !== "user" && R(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5305
5325
  let o = t.image_url;
5306
- (!o || typeof o != "object") && R("ai: image_url part must have { image_url: { url } }"), jo(o.url);
5326
+ (!o || typeof o != "object") && R("ai: image_url part must have { image_url: { url } }"), Vo(o.url);
5307
5327
  let i = o.detail;
5308
- i !== void 0 && (typeof i != "string" || !No.has(i)) && R("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5328
+ i !== void 0 && (typeof i != "string" || !Lo.has(i)) && R("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5309
5329
  } else
5310
5330
  R("ai: content part type must be 'text' or 'image_url'");
5311
5331
  }
5312
5332
  }
5313
- function $o(n) {
5333
+ function Ko(n) {
5314
5334
  (!n || typeof n != "object") && R("ai: responseFormat must be an object");
5315
5335
  let e = n.type;
5316
5336
  if (!(e === "text" || e === "json_object")) {
@@ -5318,8 +5338,8 @@ function $o(n) {
5318
5338
  let t = n.json_schema;
5319
5339
  (!t || typeof t != "object") && R("ai: responseFormat json_schema requires { json_schema: { name } }");
5320
5340
  let r = t, o = r.name;
5321
- if ((typeof o != "string" || o.length === 0) && R("ai: responseFormat json_schema.name is required"), o.length > 64 && R("ai: responseFormat json_schema.name exceeds 64 chars"), Lo.test(o) || R("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && R("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && R("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && R("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5322
- let i = Fo(r.schema);
5341
+ if ((typeof o != "string" || o.length === 0) && R("ai: responseFormat json_schema.name is required"), o.length > 64 && R("ai: responseFormat json_schema.name exceeds 64 chars"), qo.test(o) || R("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && R("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && R("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && R("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5342
+ let i = $o(r.schema);
5323
5343
  i && R(i);
5324
5344
  }
5325
5345
  return;
@@ -5327,35 +5347,35 @@ function $o(n) {
5327
5347
  R("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5328
5348
  }
5329
5349
  }
5330
- function qn(n, e, t) {
5350
+ function Fn(n, e, t) {
5331
5351
  if (!e || typeof e != "object")
5332
- throw new l("validation_failed", "ai: options object is required");
5352
+ throw new c("validation_failed", "ai: options object is required");
5333
5353
  if (typeof e.model != "string" || e.model.length === 0)
5334
- throw new l("validation_failed", "ai: model is required");
5335
- if (e.model.length > An)
5336
- throw new l("validation_failed", `ai: model exceeds ${An} chars`);
5354
+ throw new c("validation_failed", "ai: model is required");
5355
+ if (e.model.length > En)
5356
+ throw new c("validation_failed", `ai: model exceeds ${En} chars`);
5337
5357
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5338
- throw new l("validation_failed", "ai: messages must be a non-empty array");
5339
- if (e.messages.length > Cn)
5340
- throw new l("validation_failed", `ai: messages exceeds ${Cn} per request`);
5358
+ throw new c("validation_failed", "ai: messages must be a non-empty array");
5359
+ if (e.messages.length > An)
5360
+ throw new c("validation_failed", `ai: messages exceeds ${An} per request`);
5341
5361
  for (let a of e.messages) {
5342
- if (!a || typeof a != "object" || typeof a.role != "string" || !xo.has(a.role))
5343
- throw new l(
5362
+ if (!a || typeof a != "object" || typeof a.role != "string" || !Uo.has(a.role))
5363
+ throw new c(
5344
5364
  "validation_failed",
5345
5365
  "ai: each message role must be 'system' | 'user' | 'assistant'"
5346
5366
  );
5347
- Wo(a.content, a.role);
5367
+ Bo(a.content, a.role);
5348
5368
  }
5349
- let r = qo(e.messages);
5350
- if (r) throw new l("validation_failed", r);
5369
+ let r = Wo(e.messages);
5370
+ if (r) throw new c("validation_failed", r);
5351
5371
  let o = e.productId ?? n.productId, i = e.tenantId ?? n.tenantId;
5352
5372
  if (!o)
5353
- throw new l(
5373
+ throw new c(
5354
5374
  "validation_failed",
5355
5375
  "ai: productId required (pass to options or set on createNeetruClient)"
5356
5376
  );
5357
5377
  if (!i)
5358
- throw new l(
5378
+ throw new c(
5359
5379
  "validation_failed",
5360
5380
  "ai: tenantId required (pass to options or set on createNeetruClient)"
5361
5381
  );
@@ -5368,24 +5388,24 @@ function qn(n, e, t) {
5368
5388
  stream: t
5369
5389
  };
5370
5390
  if (e.maxTokens !== void 0) {
5371
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > En)
5372
- throw new l(
5391
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Pn)
5392
+ throw new c(
5373
5393
  "validation_failed",
5374
- `ai: maxTokens must be a positive integer <= ${En}`
5394
+ `ai: maxTokens must be a positive integer <= ${Pn}`
5375
5395
  );
5376
5396
  s.maxTokens = e.maxTokens;
5377
5397
  }
5378
5398
  if (e.temperature !== void 0) {
5379
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < Pn || e.temperature > Dn)
5380
- throw new l(
5399
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < Dn || e.temperature > Nn)
5400
+ throw new c(
5381
5401
  "validation_failed",
5382
- `ai: temperature must be a finite number between ${Pn} and ${Dn}`
5402
+ `ai: temperature must be a finite number between ${Dn} and ${Nn}`
5383
5403
  );
5384
5404
  s.temperature = e.temperature;
5385
5405
  }
5386
- return e.responseFormat !== void 0 && ($o(e.responseFormat), s.responseFormat = e.responseFormat), s;
5406
+ return e.responseFormat !== void 0 && (Ko(e.responseFormat), s.responseFormat = e.responseFormat), s;
5387
5407
  }
5388
- async function $n(n) {
5408
+ async function Vn(n) {
5389
5409
  try {
5390
5410
  let e = await n.text();
5391
5411
  return e ? JSON.parse(e) : void 0;
@@ -5393,48 +5413,48 @@ async function $n(n) {
5393
5413
  return;
5394
5414
  }
5395
5415
  }
5396
- function Vo(n, e) {
5416
+ function zo(n, e) {
5397
5417
  let t = n.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
5398
5418
  return `${t}${r}`;
5399
5419
  }
5400
- async function Fn(n, e, t, r) {
5420
+ async function jn(n, e, t, r) {
5401
5421
  if (!n.apiKey)
5402
- throw new l(
5422
+ throw new c(
5403
5423
  "missing_api_key",
5404
5424
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
5405
5425
  );
5406
- let o = Vo(n.baseUrl, Eo), { headers: i, correlationId: s } = _e({
5426
+ let o = zo(n.baseUrl, No), { headers: i, correlationId: s } = _e({
5407
5427
  "content-type": "application/json",
5408
5428
  accept: r ? "text/event-stream" : "application/json",
5409
5429
  authorization: `Bearer ${n.apiKey}`
5410
5430
  }), a = { method: "POST", headers: i, body: JSON.stringify(e) };
5411
- r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(Sn);
5412
- let c;
5431
+ r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(Tn);
5432
+ let d;
5413
5433
  try {
5414
- c = await n.fetch(o, a);
5415
- } catch (p) {
5416
- let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${Sn / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5417
- throw new l("network_error", f, void 0, void 0, void 0, s);
5418
- }
5419
- let u = c.headers.get("x-request-id") ?? c.headers.get("x-correlation-id") ?? void 0;
5420
- if (!c.ok) {
5421
- let p = await $n(c), f = ve(c.status), m = `HTTP ${c.status}`;
5422
- if (p && typeof p == "object" && "error" in p) {
5423
- let h = p.error;
5434
+ d = await n.fetch(o, a);
5435
+ } catch (u) {
5436
+ let f = u instanceof DOMException && u.name === "TimeoutError" ? `Network error: timeout after ${Tn / 1e3}s` : u instanceof DOMException && u.name === "AbortError" ? "Network error: request aborted" : `Network error: ${u instanceof Error ? u.message : "fetch failed"}`;
5437
+ throw new c("network_error", f, void 0, void 0, void 0, s);
5438
+ }
5439
+ let p = d.headers.get("x-request-id") ?? d.headers.get("x-correlation-id") ?? void 0;
5440
+ if (!d.ok) {
5441
+ let u = await Vn(d), f = ve(d.status), m = `HTTP ${d.status}`;
5442
+ if (u && typeof u == "object" && "error" in u) {
5443
+ let h = u.error;
5424
5444
  typeof h == "string" ? m = h : h && typeof h == "object" && (typeof h.code == "string" && (f = h.code), typeof h.message == "string" && (m = h.message));
5425
5445
  }
5426
- throw new l(f, m, c.status, u, void 0, s);
5446
+ throw new c(f, m, d.status, p, void 0, s);
5427
5447
  }
5428
- let d = c.headers.get("x-neetru-version");
5429
- return d && te(d), c;
5448
+ let l = d.headers.get("x-neetru-version");
5449
+ return l && te(l), d;
5430
5450
  }
5431
- function jn(n) {
5451
+ function Wn(n) {
5432
5452
  return {
5433
5453
  provider: n.headers.get("x-neetru-provider") ?? "",
5434
5454
  usageWarning: n.headers.get("x-neetru-ai-usage-warning") === "1"
5435
5455
  };
5436
5456
  }
5437
- function Wn(n) {
5457
+ function $n(n) {
5438
5458
  let e = [];
5439
5459
  for (let r of n.split(`
5440
5460
  `)) {
@@ -5458,9 +5478,9 @@ function Wn(n) {
5458
5478
  function ct(n) {
5459
5479
  return {
5460
5480
  async chat(e) {
5461
- let t = qn(n, e, false), r = await Fn(n, t, e.signal, false), { provider: o, usageWarning: i } = jn(r), s = await $n(r);
5481
+ let t = Fn(n, e, false), r = await jn(n, t, e.signal, false), { provider: o, usageWarning: i } = Wn(r), s = await Vn(r);
5462
5482
  if (!s || s.ok !== true || !Array.isArray(s.choices))
5463
- throw new l("invalid_response", "ai.chat response missing ok/choices");
5483
+ throw new c("invalid_response", "ai.chat response missing ok/choices");
5464
5484
  return {
5465
5485
  choices: s.choices,
5466
5486
  usage: s.usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
@@ -5470,38 +5490,38 @@ function ct(n) {
5470
5490
  };
5471
5491
  },
5472
5492
  stream(e) {
5473
- let t = qn(n, e, true), r = Fn(n, t, e.signal, true), o = r.then(jn);
5493
+ let t = Fn(n, e, true), r = jn(n, t, e.signal, true), o = r.then(Wn);
5474
5494
  o.catch(() => {
5475
5495
  });
5476
5496
  async function* i() {
5477
5497
  let a = (await r).body;
5478
5498
  if (!a)
5479
- throw new l("invalid_response", "ai.stream: response has no body");
5480
- let c = a.getReader(), u = new TextDecoder(), d = "";
5499
+ throw new c("invalid_response", "ai.stream: response has no body");
5500
+ let d = a.getReader(), p = new TextDecoder(), l = "";
5481
5501
  try {
5482
5502
  for (; ; ) {
5483
- let { done: f, value: m } = await c.read();
5503
+ let { done: f, value: m } = await d.read();
5484
5504
  if (f) break;
5485
- d += u.decode(m, { stream: !0 });
5505
+ l += p.decode(m, { stream: !0 });
5486
5506
  let h;
5487
- for (; (h = d.indexOf(`
5507
+ for (; (h = l.indexOf(`
5488
5508
 
5489
5509
  `)) !== -1; ) {
5490
- let y = d.slice(0, h);
5491
- d = d.slice(h + 2);
5492
- let I = Wn(y);
5510
+ let y = l.slice(0, h);
5511
+ l = l.slice(h + 2);
5512
+ let I = $n(y);
5493
5513
  if (I && "done" in I) return;
5494
5514
  I && "content" in I && (yield I.content);
5495
5515
  }
5496
5516
  }
5497
- let p = d.trim();
5498
- if (p) {
5499
- let f = Wn(p);
5517
+ let u = l.trim();
5518
+ if (u) {
5519
+ let f = $n(u);
5500
5520
  f && "content" in f && (yield f.content);
5501
5521
  }
5502
5522
  } finally {
5503
5523
  try {
5504
- c.releaseLock();
5524
+ d.releaseLock();
5505
5525
  } catch {
5506
5526
  }
5507
5527
  try {
@@ -5546,7 +5566,7 @@ var qe = Object.freeze({
5546
5566
  _allowUnsignedDecode;
5547
5567
  constructor(e = null, t) {
5548
5568
  if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Me())
5549
- throw new l(
5569
+ throw new c(
5550
5570
  "invalid_config",
5551
5571
  "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."
5552
5572
  );
@@ -5587,9 +5607,9 @@ var qe = Object.freeze({
5587
5607
  if (this._verifyTokenOverride)
5588
5608
  return this._verifyTokenOverride(e);
5589
5609
  if (!e)
5590
- throw new l("token_invalid_signature", "Token inv\xE1lido: string vazia");
5610
+ throw new c("token_invalid_signature", "Token inv\xE1lido: string vazia");
5591
5611
  if (!this._allowUnsignedDecode)
5592
- throw new l(
5612
+ throw new c(
5593
5613
  "unauthorized",
5594
5614
  "MockAuth.verifyToken n\xE3o verifica assinaturas JWT e N\xC3O deve ser usado como security boundary em c\xF3digo deployado. Em testes, use new MockAuth(user, { allowUnsignedDecode: true }) para habilitar decodifica\xE7\xE3o sem assinatura, ou __mockVerifyToken(fn) para injetar resultado customizado."
5595
5615
  );
@@ -5615,7 +5635,7 @@ var qe = Object.freeze({
5615
5635
  } catch {
5616
5636
  }
5617
5637
  if (this._user) return this._user;
5618
- throw new l("token_invalid_signature", "Nenhum user mock dispon\xEDvel e JWT sem sub v\xE1lido");
5638
+ throw new c("token_invalid_signature", "Nenhum user mock dispon\xEDvel e JWT sem sub v\xE1lido");
5619
5639
  }
5620
5640
  /**
5621
5641
  * Mock de `handleRedirectCallback` (Bug 2 / 3.1.3) — não há redirect real no
@@ -5693,14 +5713,14 @@ var qe = Object.freeze({
5693
5713
  tenantId: r?.tenantId,
5694
5714
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
5695
5715
  });
5696
- let c = this._quotas.get(e)?.limit ?? -1;
5716
+ let d = this._quotas.get(e)?.limit ?? -1;
5697
5717
  return {
5698
5718
  ok: true,
5699
5719
  counterId: `mock_${e}`,
5700
5720
  value: s,
5701
- limit: c,
5702
- remaining: c < 0 ? -1 : Math.max(0, c - s),
5703
- status: c > 0 && s >= c ? "read_only_overlimit" : "ok"
5721
+ limit: d,
5722
+ remaining: d < 0 ? -1 : Math.max(0, d - s),
5723
+ status: d > 0 && s >= d ? "read_only_overlimit" : "ok"
5704
5724
  };
5705
5725
  }
5706
5726
  async check(e, t) {
@@ -5742,10 +5762,10 @@ var qe = Object.freeze({
5742
5762
  _tickets = [];
5743
5763
  _ticketSeq = 0;
5744
5764
  async createTicket(e) {
5745
- if (!e?.subject) throw new l("validation_failed", "subject required");
5746
- if (!e?.message) throw new l("validation_failed", "message required");
5765
+ if (!e?.subject) throw new c("validation_failed", "subject required");
5766
+ if (!e?.message) throw new c("validation_failed", "message required");
5747
5767
  if (!e?.productSlug)
5748
- throw new l(
5768
+ throw new c(
5749
5769
  "validation_failed",
5750
5770
  "productSlug required (3.0 breaking \u2014 pass to input or set on createNeetruClient)"
5751
5771
  );
@@ -5777,10 +5797,10 @@ var qe = Object.freeze({
5777
5797
  }
5778
5798
  _find(e) {
5779
5799
  if (!e || typeof e != "string")
5780
- throw new l("validation_failed", "ticketId is required");
5800
+ throw new c("validation_failed", "ticketId is required");
5781
5801
  let t = this._tickets.find((r) => r.id === e);
5782
5802
  if (!t)
5783
- throw new l("not_found", `ticket ${e} not found`);
5803
+ throw new c("not_found", `ticket ${e} not found`);
5784
5804
  return t;
5785
5805
  }
5786
5806
  /** 3.4: espelha `markResolvedSeen` — idempotente (só seta se ainda null). */
@@ -5796,18 +5816,18 @@ var qe = Object.freeze({
5796
5816
  /** 3.4: espelha `submitSatisfaction` — terminal, seta `satisfiedAt`. */
5797
5817
  async submitSatisfaction(e) {
5798
5818
  if (!e || typeof e != "object")
5799
- throw new l("validation_failed", "input is required");
5819
+ throw new c("validation_failed", "input is required");
5800
5820
  if (e.rating !== null && e.rating !== void 0 && (!Number.isInteger(e.rating) || e.rating < 1 || e.rating > 5))
5801
- throw new l("validation_failed", "rating must be an integer 1-5 or null");
5821
+ throw new c("validation_failed", "rating must be an integer 1-5 or null");
5802
5822
  if (typeof e.comment == "string" && e.comment.length > 2e3)
5803
- throw new l("validation_failed", "comment max 2000 chars");
5823
+ throw new c("validation_failed", "comment max 2000 chars");
5804
5824
  let t = this._find(e.ticketId);
5805
5825
  t.satisfiedAt = (/* @__PURE__ */ new Date()).toISOString(), t.rating = e.rating ?? null, t.satisfactionComment = e.comment ?? null;
5806
5826
  }
5807
5827
  /** 3.4: espelha `contestTicket` — reabre e zera o ciclo de satisfação. */
5808
5828
  async contestTicket(e, t) {
5809
5829
  if (typeof t?.comment == "string" && t.comment.length > 2e3)
5810
- throw new l("validation_failed", "comment max 2000 chars");
5830
+ throw new c("validation_failed", "comment max 2000 chars");
5811
5831
  let r = this._find(e);
5812
5832
  r.status = "open", r.resolvedAt = null, r.resolvedNotifiedAt = null, r.satisfactionAttempts = 0, r.lastSatisfactionAttemptAt = null, r.satisfiedAt = null, r.rating = null, r.satisfactionComment = null;
5813
5833
  }
@@ -5846,40 +5866,40 @@ var qe = Object.freeze({
5846
5866
  collection(e) {
5847
5867
  let t = this._store, r = this._fixtures;
5848
5868
  if (!t.has(e)) {
5849
- let d = r.get(e);
5869
+ let l = r.get(e);
5850
5870
  t.set(
5851
5871
  e,
5852
- d ? new Map(Object.entries(d)) : /* @__PURE__ */ new Map()
5872
+ l ? new Map(Object.entries(l)) : /* @__PURE__ */ new Map()
5853
5873
  );
5854
5874
  }
5855
- let o = t.get(e), i = (d, p) => {
5856
- let f = d[p.field];
5857
- switch (p.op) {
5875
+ let o = t.get(e), i = (l, u) => {
5876
+ let f = l[u.field];
5877
+ switch (u.op) {
5858
5878
  case "==":
5859
- return f === p.value;
5879
+ return f === u.value;
5860
5880
  case "!=":
5861
- return f !== p.value;
5881
+ return f !== u.value;
5862
5882
  case "<":
5863
- return typeof f == "number" && typeof p.value == "number" && f < p.value;
5883
+ return typeof f == "number" && typeof u.value == "number" && f < u.value;
5864
5884
  case "<=":
5865
- return typeof f == "number" && typeof p.value == "number" && f <= p.value;
5885
+ return typeof f == "number" && typeof u.value == "number" && f <= u.value;
5866
5886
  case ">":
5867
- return typeof f == "number" && typeof p.value == "number" && f > p.value;
5887
+ return typeof f == "number" && typeof u.value == "number" && f > u.value;
5868
5888
  case ">=":
5869
- return typeof f == "number" && typeof p.value == "number" && f >= p.value;
5889
+ return typeof f == "number" && typeof u.value == "number" && f >= u.value;
5870
5890
  case "in":
5871
- return Array.isArray(p.value) && p.value.includes(f);
5891
+ return Array.isArray(u.value) && u.value.includes(f);
5872
5892
  case "array-contains":
5873
- return Array.isArray(f) && f.includes(p.value);
5893
+ return Array.isArray(f) && f.includes(u.value);
5874
5894
  case "not-in":
5875
- return Array.isArray(p.value) && !p.value.includes(f);
5895
+ return Array.isArray(u.value) && !u.value.includes(f);
5876
5896
  default:
5877
5897
  return true;
5878
5898
  }
5879
5899
  }, s = 0;
5880
- function a(d) {
5900
+ function a(l) {
5881
5901
  return {
5882
- docs: d.map((p, f) => ({ id: p.id ?? String(f), data: p })),
5902
+ docs: l.map((u, f) => ({ id: u.id ?? String(f), data: u })),
5883
5903
  nextCursor: null,
5884
5904
  fromCache: false,
5885
5905
  stale: false,
@@ -5887,111 +5907,111 @@ var qe = Object.freeze({
5887
5907
  changes: []
5888
5908
  };
5889
5909
  }
5890
- function c(d, p) {
5910
+ function d(l, u) {
5891
5911
  return {
5892
- docs: [{ id: p, data: d }],
5912
+ docs: [{ id: u, data: l }],
5893
5913
  fromCache: false,
5894
5914
  stale: false,
5895
5915
  hasPendingWrites: false,
5896
5916
  changes: []
5897
5917
  };
5898
5918
  }
5899
- let u = {
5900
- async list(d) {
5901
- let p = Array.from(o.values());
5902
- if (d?.where && d.where.length > 0 && (p = p.filter(
5903
- (m) => d.where.every((h) => i(m, h))
5904
- )), d?.orderBy) {
5905
- let { field: m, direction: h } = d.orderBy;
5906
- p = p.slice().sort((y, I) => {
5919
+ let p = {
5920
+ async list(l) {
5921
+ let u = Array.from(o.values());
5922
+ if (l?.where && l.where.length > 0 && (u = u.filter(
5923
+ (m) => l.where.every((h) => i(m, h))
5924
+ )), l?.orderBy) {
5925
+ let { field: m, direction: h } = l.orderBy;
5926
+ u = u.slice().sort((y, I) => {
5907
5927
  let w = y[m], k = I[m], N = w ?? "", g = k ?? "", _ = N < g ? -1 : N > g ? 1 : 0;
5908
5928
  return h === "desc" ? -_ : _;
5909
5929
  });
5910
5930
  }
5911
- let f = d?.limit ?? 20;
5912
- return p = p.slice(0, f), a(p);
5931
+ let f = l?.limit ?? 20;
5932
+ return u = u.slice(0, f), a(u);
5913
5933
  },
5914
- async get(d) {
5915
- let p = o.get(d);
5916
- return p ? c(p, d) : null;
5934
+ async get(l) {
5935
+ let u = o.get(l);
5936
+ return u ? d(u, l) : null;
5917
5937
  },
5918
- async add(d) {
5919
- let p = `mock-${++s}-${Math.random().toString(36).slice(2, 8)}`;
5920
- return o.set(p, { ...d, id: p }), { ok: true, id: p };
5938
+ async add(l) {
5939
+ let u = `mock-${++s}-${Math.random().toString(36).slice(2, 8)}`;
5940
+ return o.set(u, { ...l, id: u }), { ok: true, id: u };
5921
5941
  },
5922
- async set(d, p) {
5923
- return o.set(d, { ...p, id: d }), { ok: true };
5942
+ async set(l, u) {
5943
+ return o.set(l, { ...u, id: l }), { ok: true };
5924
5944
  },
5925
- async update(d, p) {
5926
- let f = o.get(d);
5927
- return f ? o.set(d, { ...f, ...p }) : o.set(d, { ...p, id: d }), { ok: true };
5945
+ async update(l, u) {
5946
+ let f = o.get(l);
5947
+ return f ? o.set(l, { ...f, ...u }) : o.set(l, { ...u, id: l }), { ok: true };
5928
5948
  },
5929
- async remove(d) {
5930
- return o.delete(d), { ok: true };
5949
+ async remove(l) {
5950
+ return o.delete(l), { ok: true };
5931
5951
  },
5932
- async batch(d) {
5933
- for (let p of d) {
5952
+ async batch(l) {
5953
+ for (let u of l) {
5934
5954
  let f = o;
5935
- if (p.kind === "add") {
5955
+ if (u.kind === "add") {
5936
5956
  let m = `mock-batch-${++s}`;
5937
- f.set(m, { ...p.data, id: m });
5938
- } else if (p.kind === "set")
5939
- f.set(p.id, { ...p.data, id: p.id });
5940
- else if (p.kind === "update") {
5941
- let m = f.get(p.id);
5942
- f.set(p.id, { ...m ?? {}, ...p.data, id: p.id });
5943
- } else p.kind === "remove" && f.delete(p.id);
5957
+ f.set(m, { ...u.data, id: m });
5958
+ } else if (u.kind === "set")
5959
+ f.set(u.id, { ...u.data, id: u.id });
5960
+ else if (u.kind === "update") {
5961
+ let m = f.get(u.id);
5962
+ f.set(u.id, { ...m ?? {}, ...u.data, id: u.id });
5963
+ } else u.kind === "remove" && f.delete(u.id);
5944
5964
  }
5945
5965
  return { ok: true };
5946
5966
  },
5947
- onDoc(d, p) {
5948
- let f = o.get(d);
5949
- return Promise.resolve().then(() => p(f || null)), () => {
5967
+ onDoc(l, u) {
5968
+ let f = o.get(l);
5969
+ return Promise.resolve().then(() => u(f || null)), () => {
5950
5970
  };
5951
5971
  },
5952
- onSnapshot(d, p) {
5972
+ onSnapshot(l, u) {
5953
5973
  return Promise.resolve().then(async () => {
5954
- let f = await u.list(d);
5955
- p(f);
5974
+ let f = await p.list(l);
5975
+ u(f);
5956
5976
  }), () => {
5957
5977
  };
5958
5978
  },
5959
- doc(d) {
5979
+ doc(l) {
5960
5980
  return {
5961
5981
  get id() {
5962
- return d;
5982
+ return l;
5963
5983
  },
5964
5984
  get path() {
5965
- return `${e}/${d}`;
5985
+ return `${e}/${l}`;
5966
5986
  },
5967
5987
  get collection() {
5968
5988
  return e;
5969
5989
  },
5970
5990
  async get() {
5971
- let p = o.get(d);
5972
- return p ? c(p, d) : null;
5991
+ let u = o.get(l);
5992
+ return u ? d(u, l) : null;
5973
5993
  },
5974
- async set(p) {
5975
- return o.set(d, { ...p, id: d }), { ok: true };
5994
+ async set(u) {
5995
+ return o.set(l, { ...u, id: l }), { ok: true };
5976
5996
  },
5977
- async update(p) {
5978
- let f = o.get(d);
5979
- return f ? o.set(d, { ...f, ...p }) : o.set(d, { ...p, id: d }), { ok: true };
5997
+ async update(u) {
5998
+ let f = o.get(l);
5999
+ return f ? o.set(l, { ...f, ...u }) : o.set(l, { ...u, id: l }), { ok: true };
5980
6000
  },
5981
6001
  async remove() {
5982
- return o.delete(d), { ok: true };
6002
+ return o.delete(l), { ok: true };
5983
6003
  },
5984
- onSnapshot(p) {
5985
- let f = o.get(d);
6004
+ onSnapshot(u) {
6005
+ let f = o.get(l);
5986
6006
  return Promise.resolve().then(
5987
- () => p(f ? c(f, d) : null)
6007
+ () => u(f ? d(f, l) : null)
5988
6008
  ), () => {
5989
6009
  };
5990
6010
  }
5991
6011
  };
5992
6012
  }
5993
6013
  };
5994
- return u;
6014
+ return p;
5995
6015
  }
5996
6016
  /**
5997
6017
  * Implementa SQL in-memory para testes — preferência: `@electric-sql/pglite`
@@ -6055,22 +6075,22 @@ var qe = Object.freeze({
6055
6075
  if (r.length > 0)
6056
6076
  for (let f of r)
6057
6077
  s.public.none(f);
6058
- let c = s.adapters.createPg().Pool, u = new c(), d = u.query.bind(u);
6059
- u.query = (f, ...m) => {
6078
+ let d = s.adapters.createPg().Pool, p = new d(), l = p.query.bind(p);
6079
+ p.query = (f, ...m) => {
6060
6080
  if (f !== null && typeof f == "object") {
6061
6081
  let y = f.types;
6062
6082
  y !== null && typeof y == "object" && "getTypeParser" in y && delete y.getTypeParser;
6063
6083
  }
6064
- return d(f, ...m);
6084
+ return l(f, ...m);
6065
6085
  };
6066
- let p = i.drizzle(u, { schema: e });
6086
+ let u = i.drizzle(p, { schema: e });
6067
6087
  return {
6068
- orm: p,
6088
+ orm: u,
6069
6089
  async transaction(f, m) {
6070
- return await p.transaction(f);
6090
+ return await u.transaction(f);
6071
6091
  },
6072
6092
  async close() {
6073
- let f = u;
6093
+ let f = p;
6074
6094
  f.end && await f.end();
6075
6095
  }
6076
6096
  };
@@ -6115,9 +6135,9 @@ var qe = Object.freeze({
6115
6135
  }
6116
6136
  async chat(e) {
6117
6137
  if (!e || typeof e.model != "string" || e.model.length === 0)
6118
- throw new l("validation_failed", "ai: model is required");
6138
+ throw new c("validation_failed", "ai: model is required");
6119
6139
  if (!Array.isArray(e.messages) || e.messages.length === 0)
6120
- throw new l("validation_failed", "ai: messages must be a non-empty array");
6140
+ throw new c("validation_failed", "ai: messages must be a non-empty array");
6121
6141
  this._calls.push({ model: e.model, messages: e.messages, stream: false });
6122
6142
  let t = this._reply(e), r = e.messages.reduce((i, s) => i + this._contentToText(s.content).length, 0), o = t.length;
6123
6143
  return {
@@ -6134,9 +6154,9 @@ var qe = Object.freeze({
6134
6154
  }
6135
6155
  stream(e) {
6136
6156
  if (!e || typeof e.model != "string" || e.model.length === 0)
6137
- throw new l("validation_failed", "ai: model is required");
6157
+ throw new c("validation_failed", "ai: model is required");
6138
6158
  if (!Array.isArray(e.messages) || e.messages.length === 0)
6139
- throw new l("validation_failed", "ai: messages must be a non-empty array");
6159
+ throw new c("validation_failed", "ai: messages must be a non-empty array");
6140
6160
  this._calls.push({ model: e.model, messages: e.messages, stream: true });
6141
6161
  let t = this._reply(e), r = t.match(/\S+\s*/g) ?? [t], o = Promise.resolve({ provider: "mock", usageWarning: false });
6142
6162
  async function* i() {
@@ -6152,41 +6172,41 @@ var qe = Object.freeze({
6152
6172
 
6153
6173
  // src/auth-pkce-shared.ts
6154
6174
  C();
6155
- function Vn() {
6175
+ function Bn() {
6156
6176
  let n = globalThis.crypto;
6157
6177
  if (!n || typeof n.getRandomValues != "function" || !n.subtle)
6158
- throw new l(
6178
+ throw new c(
6159
6179
  "runtime_unsupported",
6160
6180
  "auth.signIn requer WebCrypto (crypto.subtle) \u2014 indispon\xEDvel neste runtime. Use HTTPS (ou http://localhost) num browser moderno, ou instale um polyfill WebCrypto (ex: react-native-quick-crypto) em React Native."
6161
6181
  );
6162
6182
  return n;
6163
6183
  }
6164
- function Bn(n) {
6184
+ function Kn(n) {
6165
6185
  let e = "";
6166
6186
  for (let r of n) e += String.fromCharCode(r);
6167
6187
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
6168
6188
  }
6169
6189
  function Fe(n, e) {
6170
6190
  let t = new Uint8Array(e);
6171
- return n.getRandomValues(t), Bn(t);
6191
+ return n.getRandomValues(t), Kn(t);
6172
6192
  }
6173
- async function Kn(n, e) {
6193
+ async function zn(n, e) {
6174
6194
  let t = new TextEncoder().encode(e), r = await n.subtle.digest("SHA-256", t);
6175
- return Bn(new Uint8Array(r));
6195
+ return Kn(new Uint8Array(r));
6176
6196
  }
6177
6197
  function me(n) {
6178
6198
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.replace(/^https?:\/\/api\./, "https://auth.");
6179
6199
  }
6180
- function zn(n) {
6200
+ function Hn(n) {
6181
6201
  let e = n.oidcClientId;
6182
6202
  if (!e && n.apiKey && (e = gt(n.apiKey).keyId), !e)
6183
- throw new l(
6203
+ throw new c(
6184
6204
  "invalid_config",
6185
6205
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
6186
6206
  );
6187
6207
  return e;
6188
6208
  }
6189
- function Hn(n) {
6209
+ function Gn(n) {
6190
6210
  let e = new URL("/api/v1/oauth/authorize", n.idpOrigin);
6191
6211
  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;
6192
6212
  }
@@ -6214,27 +6234,27 @@ function he(n) {
6214
6234
  ...e
6215
6235
  };
6216
6236
  }
6217
- var Bo = "/api/v1/oauth/revoke";
6218
- async function Gn(n, e, t, r) {
6219
- let o = `${e}${Bo}`, i = true;
6237
+ var Ho = "/api/v1/oauth/revoke";
6238
+ async function Qn(n, e, t, r) {
6239
+ let o = `${e}${Ho}`, i = true;
6220
6240
  for (let s of r) {
6221
6241
  if (!s.token) continue;
6222
6242
  let a = new URLSearchParams({
6223
6243
  token: s.token,
6224
6244
  token_type_hint: s.hint,
6225
6245
  client_id: t
6226
- }).toString(), c = false;
6227
- for (let u = 0; u < 2 && !c; u++)
6246
+ }).toString(), d = false;
6247
+ for (let p = 0; p < 2 && !d; p++)
6228
6248
  try {
6229
- if (c = (await n(o, {
6249
+ if (d = (await n(o, {
6230
6250
  method: "POST",
6231
6251
  headers: { "content-type": "application/x-www-form-urlencoded" },
6232
6252
  body: a
6233
- })).ok, !c) break;
6253
+ })).ok, !d) break;
6234
6254
  } catch {
6235
- u === 0 && await new Promise((d) => setTimeout(d, 500));
6255
+ p === 0 && await new Promise((l) => setTimeout(l, 500));
6236
6256
  }
6237
- c || (i = false);
6257
+ d || (i = false);
6238
6258
  }
6239
6259
  return i;
6240
6260
  }
@@ -6243,14 +6263,14 @@ async function Gn(n, e, t, r) {
6243
6263
  be();
6244
6264
 
6245
6265
  // src/end-user-token.ts
6246
- var Ko = /* @__PURE__ */ new WeakMap();
6247
- function Qn(n, e) {
6248
- Ko.set(n, e);
6266
+ var Go = /* @__PURE__ */ new WeakMap();
6267
+ function Jn(n, e) {
6268
+ Go.set(n, e);
6249
6269
  }
6250
6270
 
6251
6271
  // src/unsupported-db.ts
6252
6272
  C();
6253
- var zo = "[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.)", Ho = /* @__PURE__ */ new Set([
6273
+ var Qo = "[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.)", Jo = /* @__PURE__ */ new Set([
6254
6274
  "then",
6255
6275
  "toJSON",
6256
6276
  "valueOf",
@@ -6259,13 +6279,13 @@ var zo = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O
6259
6279
  "asymmetricMatch",
6260
6280
  "nodeType"
6261
6281
  ]);
6262
- function Jn() {
6282
+ function Xn() {
6263
6283
  let n = () => {
6264
- throw new l("runtime_unsupported", zo, void 0, void 0, "react-native");
6284
+ throw new c("runtime_unsupported", Qo, void 0, void 0, "react-native");
6265
6285
  }, e = {};
6266
6286
  return new Proxy(e, {
6267
6287
  get(t, r) {
6268
- if (!(typeof r == "symbol" || Ho.has(r)))
6288
+ if (!(typeof r == "symbol" || Jo.has(r)))
6269
6289
  return r === "toString" ? () => "[NeetruDb indispon\xEDvel em React Native]" : n;
6270
6290
  },
6271
6291
  set() {
@@ -6275,7 +6295,7 @@ function Jn() {
6275
6295
  }
6276
6296
 
6277
6297
  // src/auth.ts
6278
- function Qo() {
6298
+ function Yo() {
6279
6299
  try {
6280
6300
  let e = globalThis.process?.env?.NEETRU_API_KEY;
6281
6301
  return typeof e == "string" && e.length > 0 ? e : void 0;
@@ -6283,7 +6303,7 @@ function Qo() {
6283
6303
  return;
6284
6304
  }
6285
6305
  }
6286
- function Jo(n) {
6306
+ function Zo(n) {
6287
6307
  if (n) return n;
6288
6308
  try {
6289
6309
  let t = globalThis.process?.env?.NEETRU_ENV;
@@ -6297,8 +6317,8 @@ function Jo(n) {
6297
6317
  }
6298
6318
  return "prod";
6299
6319
  }
6300
- var Xo = ye;
6301
- function Yo(n) {
6320
+ var ei = ye;
6321
+ function ti(n) {
6302
6322
  let e = n.sub ?? "", t = typeof n.email == "string" ? n.email : "";
6303
6323
  return {
6304
6324
  uid: e,
@@ -6325,7 +6345,7 @@ function ut(n) {
6325
6345
  } catch {
6326
6346
  }
6327
6347
  }
6328
- function Zo(n) {
6348
+ function ni(n) {
6329
6349
  let e = "neetru_id_token", t = "neetru_refresh_token", r = /* @__PURE__ */ new Set(), o = null, i = null, s = null;
6330
6350
  function a() {
6331
6351
  try {
@@ -6334,17 +6354,17 @@ function Zo(n) {
6334
6354
  return null;
6335
6355
  }
6336
6356
  }
6337
- function c() {
6357
+ function d() {
6338
6358
  try {
6339
6359
  return typeof globalThis.sessionStorage < "u" ? globalThis.sessionStorage : null;
6340
6360
  } catch {
6341
6361
  return null;
6342
6362
  }
6343
6363
  }
6344
- function u() {
6364
+ function p() {
6345
6365
  if (o) {
6346
6366
  let b = o.exp;
6347
- return typeof b == "number" && b * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), d(), y(), null) : o;
6367
+ return typeof b == "number" && b * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), l(), y(), null) : o;
6348
6368
  }
6349
6369
  let g = a();
6350
6370
  if (!g) return null;
@@ -6354,14 +6374,14 @@ function Zo(n) {
6354
6374
  let T = he(_);
6355
6375
  return T ? (o = T, I(T), o) : (g.removeItem(e), y(), null);
6356
6376
  }
6357
- function d() {
6377
+ function l() {
6358
6378
  for (let g of r)
6359
6379
  try {
6360
6380
  g(o);
6361
6381
  } catch {
6362
6382
  }
6363
6383
  }
6364
- function p() {
6384
+ function u() {
6365
6385
  i !== null && (clearTimeout(i), i = null);
6366
6386
  }
6367
6387
  function f() {
@@ -6370,7 +6390,7 @@ function Zo(n) {
6370
6390
  function m() {
6371
6391
  o = null;
6372
6392
  let g = a();
6373
- g?.removeItem(e), g?.removeItem(t), d();
6393
+ g?.removeItem(e), g?.removeItem(t), l();
6374
6394
  }
6375
6395
  function h() {
6376
6396
  return s || (s = (async () => {
@@ -6410,7 +6430,7 @@ function Zo(n) {
6410
6430
  let P = a();
6411
6431
  P?.setItem(e, A);
6412
6432
  let M = D?.refresh_token;
6413
- return typeof M == "string" && M.length > 0 && P?.setItem(t, M), o = L, I(L), d(), true;
6433
+ return typeof M == "string" && M.length > 0 && P?.setItem(t, M), o = L, I(L), l(), true;
6414
6434
  })().finally(() => {
6415
6435
  s = null;
6416
6436
  }), s);
@@ -6421,7 +6441,7 @@ function Zo(n) {
6421
6441
  });
6422
6442
  }
6423
6443
  function I(g) {
6424
- p();
6444
+ u();
6425
6445
  let _ = g.exp;
6426
6446
  if (typeof _ != "number") return;
6427
6447
  let T = _ * 1e3 - Date.now();
@@ -6436,12 +6456,12 @@ function Zo(n) {
6436
6456
  return;
6437
6457
  }
6438
6458
  i = setTimeout(() => {
6439
- i = null, u();
6459
+ i = null, p();
6440
6460
  }, T + 1);
6441
6461
  }
6442
6462
  }
6443
6463
  function w() {
6444
- return zn(n);
6464
+ return Hn(n);
6445
6465
  }
6446
6466
  async function k(g) {
6447
6467
  let _ = g ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
@@ -6455,11 +6475,11 @@ function Zo(n) {
6455
6475
  let b = T.searchParams, E = b.get("error");
6456
6476
  if (E) {
6457
6477
  let M = b.get("error_description") ?? E;
6458
- throw c()?.removeItem(ge), ut(T), new l(E, `OIDC authorize falhou: ${M}`);
6478
+ throw d()?.removeItem(ge), ut(T), new c(E, `OIDC authorize falhou: ${M}`);
6459
6479
  }
6460
6480
  let x = b.get("code");
6461
6481
  if (!x) return null;
6462
- let D = b.get("state"), A = c(), L = A?.getItem(ge) ?? null, P = null;
6482
+ let D = b.get("state"), A = d(), L = A?.getItem(ge) ?? null, P = null;
6463
6483
  if (L)
6464
6484
  try {
6465
6485
  P = JSON.parse(L);
@@ -6467,12 +6487,12 @@ function Zo(n) {
6467
6487
  P = null;
6468
6488
  }
6469
6489
  if (!P)
6470
- throw new l(
6490
+ throw new c(
6471
6491
  "oidc_state_mismatch",
6472
6492
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado nesta sess\xE3o (ou j\xE1 consumido)."
6473
6493
  );
6474
6494
  if (!D || D !== P.state)
6475
- throw A?.removeItem(ge), ut(T), new l(
6495
+ throw A?.removeItem(ge), ut(T), new c(
6476
6496
  "oidc_state_mismatch",
6477
6497
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
6478
6498
  );
@@ -6502,7 +6522,7 @@ function Zo(n) {
6502
6522
  body: x.toString()
6503
6523
  });
6504
6524
  } catch (U) {
6505
- throw new l(
6525
+ throw new c(
6506
6526
  "network_error",
6507
6527
  `POST ${E} falhou (network): ${U?.message ?? String(U)}`
6508
6528
  );
@@ -6515,7 +6535,7 @@ function Zo(n) {
6515
6535
  }
6516
6536
  if (!D.ok || typeof A?.error == "string") {
6517
6537
  let U = typeof A?.error_description == "string" && A.error_description || typeof A?.error == "string" && A.error || `HTTP ${D.status}`;
6518
- throw new l(
6538
+ throw new c(
6519
6539
  "token_exchange_failed",
6520
6540
  `Troca do authorization_code por tokens falhou no /token: ${U}`,
6521
6541
  D.status
@@ -6523,39 +6543,39 @@ function Zo(n) {
6523
6543
  }
6524
6544
  let L = A?.id_token;
6525
6545
  if (typeof L != "string" || L.length === 0)
6526
- throw new l(
6546
+ throw new c(
6527
6547
  "token_exchange_failed",
6528
6548
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado.",
6529
6549
  D.status
6530
6550
  );
6531
6551
  let P = dt(L);
6532
6552
  if (!P)
6533
- throw new l(
6553
+ throw new c(
6534
6554
  "token_exchange_failed",
6535
6555
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
6536
6556
  );
6537
6557
  if (P.nonce !== _.nonce)
6538
- throw new l(
6558
+ throw new c(
6539
6559
  "oidc_nonce_mismatch",
6540
6560
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
6541
6561
  );
6542
6562
  let M = he(L);
6543
6563
  if (!M)
6544
- throw new l(
6564
+ throw new c(
6545
6565
  "token_exchange_failed",
6546
6566
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
6547
6567
  );
6548
6568
  let F = a();
6549
6569
  F?.setItem(e, L);
6550
6570
  let j = A?.refresh_token;
6551
- return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = M, I(M), d(), { user: M, postLoginRedirect: _.postLoginRedirect };
6571
+ return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = M, I(M), l(), { user: M, postLoginRedirect: _.postLoginRedirect };
6552
6572
  }
6553
6573
  return {
6554
6574
  async signIn(g) {
6555
6575
  if (typeof globalThis.location < "u" && typeof globalThis.location.assign == "function") {
6556
- let _ = Vn(), T = g?.redirectUri ?? globalThis.location.origin, b = g?.scope ?? "openid profile email", E = w(), x = Fe(_, 16), D = Fe(_, 16), A = Fe(_, 32), L = await Kn(_, A), P = c();
6576
+ let _ = Bn(), T = g?.redirectUri ?? globalThis.location.origin, b = g?.scope ?? "openid profile email", E = w(), x = Fe(_, 16), D = Fe(_, 16), A = Fe(_, 32), L = await zn(_, A), P = d();
6557
6577
  if (!P)
6558
- throw new l(
6578
+ throw new c(
6559
6579
  "runtime_unsupported",
6560
6580
  "auth.signIn requer sessionStorage para guardar a transa\xE7\xE3o PKCE entre o redirect e o callback."
6561
6581
  );
@@ -6567,7 +6587,7 @@ function Zo(n) {
6567
6587
  postLoginRedirect: g?.postLoginRedirect
6568
6588
  };
6569
6589
  P.setItem(ge, JSON.stringify(M));
6570
- let F = me(n.baseUrl), j = Hn({
6590
+ let F = me(n.baseUrl), j = Gn({
6571
6591
  idpOrigin: F,
6572
6592
  clientId: E,
6573
6593
  redirectUri: T,
@@ -6579,7 +6599,7 @@ function Zo(n) {
6579
6599
  globalThis.location.assign(j.toString());
6580
6600
  return;
6581
6601
  }
6582
- throw new l(
6602
+ throw new c(
6583
6603
  "invalid_config",
6584
6604
  "auth.signIn requires a browser context or mocks. Use NEETRU_ENV=dev or pass mocks.auth."
6585
6605
  );
@@ -6595,28 +6615,28 @@ function Zo(n) {
6595
6615
  },
6596
6616
  async signOut() {
6597
6617
  let g = a(), _ = g?.getItem(t) ?? null;
6598
- if (g && (g.removeItem(e), g.removeItem(t)), p(), o = null, _) {
6618
+ if (g && (g.removeItem(e), g.removeItem(t)), u(), o = null, _) {
6599
6619
  let T = null;
6600
6620
  try {
6601
6621
  T = w();
6602
6622
  } catch {
6603
6623
  T = null;
6604
6624
  }
6605
- !(T && await Gn(n.fetch, me(n.baseUrl), T, [
6625
+ !(T && await Qn(n.fetch, me(n.baseUrl), T, [
6606
6626
  { token: _, hint: "refresh_token" }
6607
6627
  ])) && typeof console < "u" && console.warn(
6608
6628
  "[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."
6609
6629
  );
6610
6630
  }
6611
- d();
6631
+ l();
6612
6632
  },
6613
6633
  getUser() {
6614
- return u();
6634
+ return p();
6615
6635
  },
6616
6636
  onAuthStateChanged(g) {
6617
6637
  r.add(g);
6618
6638
  try {
6619
- g(u());
6639
+ g(p());
6620
6640
  } catch {
6621
6641
  }
6622
6642
  return () => {
@@ -6625,38 +6645,38 @@ function Zo(n) {
6625
6645
  },
6626
6646
  async verifyToken(g, _) {
6627
6647
  if (!g || typeof g != "string")
6628
- throw new l("token_invalid_signature", "token must be a non-empty string");
6648
+ throw new c("token_invalid_signature", "token must be a non-empty string");
6629
6649
  let b = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), E = b, x = `${b}/api/v1/oauth/.well-known/jwks`, D = _?.jwksCacheTtlMs ?? ee, A = _?.audience, L = yt(n.apiKey), P = A ?? n.oidcClientId ?? L?.keyId;
6630
6650
  if (!P)
6631
- throw new l(
6651
+ throw new c(
6632
6652
  "invalid_config",
6633
6653
  "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."
6634
6654
  );
6635
- let M = Xo(x, D);
6655
+ let M = ei(x, D);
6636
6656
  try {
6637
6657
  let { payload: F } = await jwtVerify(g, M, {
6638
6658
  issuer: E,
6639
6659
  audience: P,
6640
6660
  algorithms: ["RS256"]
6641
6661
  });
6642
- return Yo(F);
6662
+ return ti(F);
6643
6663
  } catch (F) {
6644
6664
  let j = F?.code ?? F?.name ?? "", U = F?.message ?? String(F);
6645
- throw j === "ERR_JWT_EXPIRED" ? new l("token_expired", `Token expired: ${U}`) : j === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new l("token_invalid_signature", `Token signature invalid: ${U}`) : j === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? U.includes('"aud"') || U.includes("audience") ? new l("token_invalid_audience", `Token audience mismatch: ${U}`) : U.includes('"iss"') || U.includes("issuer") ? new l("token_invalid_issuer", `Token issuer mismatch: ${U}`) : new l("token_invalid_signature", `Token claim validation failed: ${U}`) : new l("token_invalid_signature", `Token verification failed: ${U}`);
6665
+ throw j === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${U}`) : j === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${U}`) : j === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? U.includes('"aud"') || U.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${U}`) : U.includes('"iss"') || U.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${U}`) : new c("token_invalid_signature", `Token claim validation failed: ${U}`) : new c("token_invalid_signature", `Token verification failed: ${U}`);
6646
6666
  }
6647
6667
  }
6648
6668
  };
6649
6669
  }
6650
- function Xn(n = {}) {
6670
+ function Yn(n = {}) {
6651
6671
  let e = n.fetch ?? globalThis.fetch;
6652
6672
  if (typeof e != "function")
6653
- throw new l(
6673
+ throw new c(
6654
6674
  "invalid_config",
6655
6675
  "fetch is not available in this runtime. Pass `fetch` explicitly to createNeetruClient."
6656
6676
  );
6657
- let t = n.apiKey ?? Qo();
6677
+ let t = n.apiKey ?? Yo();
6658
6678
  At({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6659
- let r = Jo(n.env), o = n.baseUrl ?? (r === "dev-local" ? wt : je), i = vt(o, n.allowedHosts ?? []), s = Object.freeze({
6679
+ let r = Zo(n.env), o = n.baseUrl ?? (r === "dev-local" ? wt : je), i = vt(o, n.allowedHosts ?? []), s = Object.freeze({
6660
6680
  apiKey: t,
6661
6681
  oidcClientId: n.oidcClientId,
6662
6682
  baseUrl: i,
@@ -6664,33 +6684,33 @@ function Xn(n = {}) {
6664
6684
  env: r,
6665
6685
  productId: n.productId,
6666
6686
  tenantId: n.tenantId
6667
- }), a = r === "dev" && !Me(), c = n.mocks?.auth ?? (a ? new le({ ...qe }) : Zo(s)), u = n.mocks?.usage ?? (a ? new de() : Vt(s)), d = n.endUserAuth ?? c, p = n.mocks?.support ?? (a ? new ue() : Qt(s, {
6668
- getEndUserToken: () => d.getIdToken(),
6687
+ }), a = r === "dev" && !Me(), d = n.mocks?.auth ?? (a ? new le({ ...qe }) : ni(s)), p = n.mocks?.usage ?? (a ? new de() : Vt(s)), l = n.endUserAuth ?? d, u = n.mocks?.support ?? (a ? new ue() : Qt(s, {
6688
+ getEndUserToken: () => l.getIdToken(),
6669
6689
  // `refreshTokens` é opcional (MockAuth/mocks próprios omitem).
6670
6690
  refreshEndUserToken: (() => {
6671
- let k = d.refreshTokens;
6672
- return typeof k == "function" ? () => k.call(d) : void 0;
6691
+ let k = l.refreshTokens;
6692
+ return typeof k == "function" ? () => k.call(l) : void 0;
6673
6693
  })()
6674
- })), f = n.mocks?.entitlements ?? (a ? new pe() : qt()), m = n.mocks?.db ?? (Q() === "react-native" ? Jn() : nt(s, n.db)), h = n.mocks?.webhooks ?? (a ? new ae() : it(s)), y = n.mocks?.notifications ?? (a ? new ce() : at(s)), I = n.mocks?.ai ?? (a ? new fe() : ct(s)), w = Object.freeze({
6694
+ })), f = n.mocks?.entitlements ?? (a ? new pe() : qt()), m = n.mocks?.db ?? (Q() === "react-native" ? Xn() : nt(s, n.db)), h = n.mocks?.webhooks ?? (a ? new ae() : it(s)), y = n.mocks?.notifications ?? (a ? new ce() : at(s)), I = n.mocks?.ai ?? (a ? new fe() : ct(s)), w = Object.freeze({
6675
6695
  config: s,
6676
- auth: c,
6696
+ auth: d,
6677
6697
  catalog: Ut(s),
6678
6698
  entitlements: f,
6679
6699
  telemetry: Wt(s),
6680
- usage: u,
6681
- support: p,
6700
+ usage: p,
6701
+ support: u,
6682
6702
  db: m,
6683
6703
  checkout: ot(s),
6684
6704
  webhooks: h,
6685
6705
  notifications: y,
6686
6706
  ai: I
6687
6707
  });
6688
- return n.endUserAuth && Qn(w, n.endUserAuth), w;
6708
+ return n.endUserAuth && Jn(w, n.endUserAuth), w;
6689
6709
  }
6690
6710
  var pt = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6691
- function ei(n = {}) {
6711
+ function ri(n = {}) {
6692
6712
  let e = globalThis;
6693
- return e[pt] || (e[pt] = Xn(n)), e[pt];
6713
+ return e[pt] || (e[pt] = Yn(n)), e[pt];
6694
6714
  }
6695
6715
 
6696
6716
  // src/index.ts
@@ -6700,29 +6720,29 @@ q();
6700
6720
 
6701
6721
  // src/access-token.ts
6702
6722
  C();
6703
- var Zn = "https://auth.neetru.com", ni = "/api/v1/oauth/.well-known/jwks";
6704
- function er(n) {
6723
+ var er = "https://auth.neetru.com", ii = "/api/v1/oauth/.well-known/jwks";
6724
+ function tr(n) {
6705
6725
  let e = (Array.isArray(n) ? n : [n]).filter(
6706
6726
  (t) => typeof t == "string" && t.trim().length > 0
6707
6727
  );
6708
6728
  if (e.length === 0)
6709
- throw new l(
6729
+ throw new c(
6710
6730
  "invalid_config",
6711
6731
  "verifyAccessToken exige `audience` com ao menos um client_id OIDC do produto (web/iOS/Android). Sem audience, tokens emitidos para OUTROS produtos seriam aceitos."
6712
6732
  );
6713
6733
  return e;
6714
6734
  }
6715
- var Yn = "O token apresentado n\xE3o \xE9 um access_token (parece um id_token). Mande o access_token no Authorization.";
6735
+ var Zn = "O token apresentado n\xE3o \xE9 um access_token (parece um id_token). Mande o access_token no Authorization.";
6716
6736
  function K(n, e) {
6717
- return new l("token_invalid", n, 401, void 0, e);
6737
+ return new c("token_invalid", n, 401, void 0, e);
6718
6738
  }
6719
- async function tr(n, e) {
6720
- let t = er(e?.audience);
6739
+ async function nr(n, e) {
6740
+ let t = tr(e?.audience);
6721
6741
  if (typeof n != "string" || n.length === 0)
6722
6742
  throw K("access_token ausente.", "missing_token");
6723
6743
  if (n.split(".").length !== 3)
6724
6744
  throw K("O token n\xE3o \xE9 um JWT (access_token OIDC esperado).", "not_a_jwt");
6725
- let r = (e.issuer ?? Zn).replace(/\/+$/, ""), o = e.jwksUrl ?? `${r}${ni}`, i = Math.min(Math.max(e.clockToleranceSec ?? 5, 0), 60), s = ye(o, e.jwksCacheTtlMs ?? ee), a;
6745
+ let r = (e.issuer ?? er).replace(/\/+$/, ""), o = e.jwksUrl ?? `${r}${ii}`, i = Math.min(Math.max(e.clockToleranceSec ?? 5, 0), 60), s = ye(o, e.jwksCacheTtlMs ?? ee), a;
6726
6746
  try {
6727
6747
  ({ payload: a } = await jwtVerify(n, s, {
6728
6748
  issuer: r,
@@ -6734,30 +6754,30 @@ async function tr(n, e) {
6734
6754
  } catch (w) {
6735
6755
  let k = w?.code ?? "", N = w?.message ?? String(w);
6736
6756
  if (k === "ERR_JWT_EXPIRED")
6737
- throw new l("token_expired", "access_token expirado.", 401, void 0, "expired");
6757
+ throw new c("token_expired", "access_token expirado.", 401, void 0, "expired");
6738
6758
  if (k === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
6739
6759
  let _ = w?.claim;
6740
- throw _ === "aud" ? new l(
6760
+ throw _ === "aud" ? new c(
6741
6761
  "token_invalid_audience",
6742
6762
  "access_token emitido para um client OIDC que n\xE3o est\xE1 na lista desta API.",
6743
6763
  401,
6744
6764
  void 0,
6745
6765
  "audience"
6746
- ) : _ === "iss" ? new l("token_invalid_issuer", "access_token de outro emissor.", 401, void 0, "issuer") : _ === "jti" ? K(Yn, "not_access_token") : K(`Claim obrigat\xF3rio ausente ou inv\xE1lido no access_token (${_ ?? "desconhecido"}).`, "claims");
6766
+ ) : _ === "iss" ? new c("token_invalid_issuer", "access_token de outro emissor.", 401, void 0, "issuer") : _ === "jti" ? K(Zn, "not_access_token") : K(`Claim obrigat\xF3rio ausente ou inv\xE1lido no access_token (${_ ?? "desconhecido"}).`, "claims");
6747
6767
  }
6748
- throw k === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" || k === "ERR_JWKS_NO_MATCHING_KEY" || k === "ERR_JOSE_ALG_NOT_ALLOWED" || k === "ERR_JWKS_MULTIPLE_MATCHING_KEYS" ? new l(
6768
+ throw k === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" || k === "ERR_JWKS_NO_MATCHING_KEY" || k === "ERR_JOSE_ALG_NOT_ALLOWED" || k === "ERR_JWKS_MULTIPLE_MATCHING_KEYS" ? new c(
6749
6769
  "token_invalid_signature",
6750
6770
  "Assinatura do access_token inv\xE1lida.",
6751
6771
  401,
6752
6772
  void 0,
6753
6773
  "signature"
6754
- ) : k === "ERR_JWKS_TIMEOUT" || k === "ERR_JOSE_GENERIC" && /JSON Web Key Set/i.test(N) || k === "" && w instanceof TypeError ? new l("network_error", `Falha ao obter o JWKS do Core: ${N}`, void 0, void 0, "jwks") : K(`access_token inv\xE1lido: ${N}`, "malformed");
6774
+ ) : k === "ERR_JWKS_TIMEOUT" || k === "ERR_JOSE_GENERIC" && /JSON Web Key Set/i.test(N) || k === "" && w instanceof TypeError ? new c("network_error", `Falha ao obter o JWKS do Core: ${N}`, void 0, void 0, "jwks") : K(`access_token inv\xE1lido: ${N}`, "malformed");
6755
6775
  }
6756
- let c = a.jti, u = a.scope, d = a.client_id;
6757
- if (typeof c != "string" || c.length === 0 || typeof u != "string" || typeof d != "string")
6758
- throw K(Yn, "not_access_token");
6759
- let p = a.aud, f = typeof p == "string" ? p : Array.isArray(p) && p.length === 1 ? p[0] : void 0;
6760
- if (typeof f != "string" || f !== d)
6776
+ let d = a.jti, p = a.scope, l = a.client_id;
6777
+ if (typeof d != "string" || d.length === 0 || typeof p != "string" || typeof l != "string")
6778
+ throw K(Zn, "not_access_token");
6779
+ let u = a.aud, f = typeof u == "string" ? u : Array.isArray(u) && u.length === 1 ? u[0] : void 0;
6780
+ if (typeof f != "string" || f !== l)
6761
6781
  throw K("access_token inconsistente: client_id difere do aud.", "client_id_mismatch");
6762
6782
  let m = typeof a.sub == "string" ? a.sub : "", h = m.startsWith("client:");
6763
6783
  if (!m || h && e.allowClientCredentials !== true)
@@ -6765,9 +6785,9 @@ async function tr(n, e) {
6765
6785
  "access_token de m\xE1quina (client_credentials) n\xE3o representa um usu\xE1rio final.",
6766
6786
  "client_credentials"
6767
6787
  );
6768
- let y = u.split(" ").filter(Boolean), I = (e.requiredScopes ?? []).filter((w) => !y.includes(w));
6788
+ let y = p.split(" ").filter(Boolean), I = (e.requiredScopes ?? []).filter((w) => !y.includes(w));
6769
6789
  if (I.length > 0)
6770
- throw new l(
6790
+ throw new c(
6771
6791
  "insufficient_scope",
6772
6792
  `access_token sem os escopos exigidos: ${I.join(", ")}.`,
6773
6793
  403,
@@ -6776,17 +6796,17 @@ async function tr(n, e) {
6776
6796
  );
6777
6797
  return {
6778
6798
  sub: m,
6779
- clientId: d,
6799
+ clientId: l,
6780
6800
  audience: f,
6781
6801
  scopes: y,
6782
- jti: c,
6802
+ jti: d,
6783
6803
  issuedAt: a.iat,
6784
6804
  expiresAt: a.exp,
6785
6805
  isClientCredentials: h,
6786
6806
  claims: a
6787
6807
  };
6788
6808
  }
6789
- function nr(n, e) {
6809
+ function rr(n, e) {
6790
6810
  let t = e.toLowerCase(), r = n && typeof n == "object" && "headers" in n && n.headers ? n.headers : n;
6791
6811
  if (!r || typeof r != "object") return null;
6792
6812
  if (typeof r.get == "function")
@@ -6796,14 +6816,14 @@ function nr(n, e) {
6796
6816
  return Array.isArray(i) ? typeof i[0] == "string" ? i[0] : null : typeof i == "string" ? i : null;
6797
6817
  return null;
6798
6818
  }
6799
- function rr(n) {
6800
- let e = nr(n, "authorization");
6819
+ function or(n) {
6820
+ let e = rr(n, "authorization");
6801
6821
  if (!e) return null;
6802
6822
  let t = /^\s*Bearer\s+(\S+)\s*$/i.exec(e);
6803
6823
  return t ? t[1] : null;
6804
6824
  }
6805
- function or(n, e) {
6806
- let t = nr(n, "cookie");
6825
+ function ir(n, e) {
6826
+ let t = rr(n, "cookie");
6807
6827
  if (!t) return null;
6808
6828
  for (let r of t.split(";")) {
6809
6829
  let o = r.indexOf("=");
@@ -6817,13 +6837,13 @@ function or(n, e) {
6817
6837
  }
6818
6838
  return null;
6819
6839
  }
6820
- async function ri(n, e) {
6821
- er(e?.audience);
6822
- let t = rr(n);
6840
+ async function si(n, e) {
6841
+ tr(e?.audience);
6842
+ let t = or(n);
6823
6843
  if (t)
6824
- return { kind: "access_token", token: await tr(t, e) };
6844
+ return { kind: "access_token", token: await nr(t, e) };
6825
6845
  if (e.cookie) {
6826
- let r = or(n, e.cookie.name);
6846
+ let r = ir(n, e.cookie.name);
6827
6847
  if (r) {
6828
6848
  let o = await e.cookie.verify(r);
6829
6849
  if (o != null) return { kind: "cookie", session: o };
@@ -6831,8 +6851,8 @@ async function ri(n, e) {
6831
6851
  }
6832
6852
  return null;
6833
6853
  }
6834
- function oi(n) {
6835
- if (n instanceof l) {
6854
+ function ai(n) {
6855
+ if (n instanceof c) {
6836
6856
  if (n.code === "insufficient_scope")
6837
6857
  return {
6838
6858
  status: 403,
@@ -6864,6 +6884,6 @@ function oi(n) {
6864
6884
 
6865
6885
  // src/index.ts
6866
6886
  be();
6867
- var Aa = "3.8.0";
6887
+ var Da = "3.8.1";
6868
6888
 
6869
- export { je as DEFAULT_BASE_URL, qe as DEV_FIXTURE_USER, fe as MockAi, le as MockAuth, xe as MockCheckout, lt as MockDb, pe as MockEntitlements, ce as MockNotifications, ue as MockSupport, de as MockUsage, ae as MockWebhooks, Zn as NEETRU_OIDC_ISSUER, ze as NEETRU_SENTINEL_KEY, $ as NeetruAuthRequiredError, v as NeetruDbError, l as NeetruError, Aa as VERSION, oi as accessTokenErrorToHttp, ri as authenticateProductRequest, te as checkCoreVersionCompat, ct as createAiNamespace, ot as createCheckoutNamespace, Xn as createNeetruClient, nt as createNeetruDb, at as createNotificationsNamespace, it as createWebhooksNamespace, Q as detectNonServerRuntime, ei as getServerNeetruClient, Kr as increment, H as isFieldSentinel, Yt as isIncrementSentinel, Xt as isServerTimestampSentinel, rr as readBearerToken, or as readCookie, Br as serverTimestamp, tr as verifyAccessToken, Co as verifyWebhookRequest, _n as verifyWebhookSignature };
6889
+ export { je as DEFAULT_BASE_URL, qe as DEV_FIXTURE_USER, fe as MockAi, le as MockAuth, xe as MockCheckout, lt as MockDb, pe as MockEntitlements, ce as MockNotifications, ue as MockSupport, de as MockUsage, ae as MockWebhooks, er as NEETRU_OIDC_ISSUER, ze as NEETRU_SENTINEL_KEY, $ as NeetruAuthRequiredError, v as NeetruDbError, c as NeetruError, Da as VERSION, ai as accessTokenErrorToHttp, si as authenticateProductRequest, te as checkCoreVersionCompat, ct as createAiNamespace, ot as createCheckoutNamespace, Yn as createNeetruClient, nt as createNeetruDb, at as createNotificationsNamespace, it as createWebhooksNamespace, Q as detectNonServerRuntime, ri as getServerNeetruClient, zr as increment, H as isFieldSentinel, Yt as isIncrementSentinel, Xt as isServerTimestampSentinel, or as readBearerToken, ir as readCookie, Kr as serverTimestamp, nr as verifyAccessToken, Po as verifyWebhookRequest, bn as verifyWebhookSignature };