@neetru/sdk 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +4 -1
  3. package/dist/ai.cjs +1 -1
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +1 -1
  7. package/dist/auth.cjs +1171 -1110
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +1168 -1107
  11. package/dist/catalog.cjs +1 -1
  12. package/dist/catalog.d.cts +1 -1
  13. package/dist/catalog.d.ts +1 -1
  14. package/dist/catalog.mjs +1 -1
  15. package/dist/checkout.cjs +62 -49
  16. package/dist/checkout.d.cts +1 -1
  17. package/dist/checkout.d.ts +1 -1
  18. package/dist/checkout.mjs +62 -49
  19. package/dist/db-react.d.cts +1 -1
  20. package/dist/db-react.d.ts +1 -1
  21. package/dist/db.cjs +303 -270
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +322 -289
  25. package/dist/entitlements.d.cts +1 -1
  26. package/dist/entitlements.d.ts +1 -1
  27. package/dist/firestore-compat.d.cts +1 -1
  28. package/dist/firestore-compat.d.ts +1 -1
  29. package/dist/index.cjs +1275 -1214
  30. package/dist/index.d.cts +2 -2
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.mjs +1390 -1329
  33. package/dist/mobile.cjs +328 -276
  34. package/dist/mobile.d.cts +12 -2
  35. package/dist/mobile.d.ts +12 -2
  36. package/dist/mobile.mjs +328 -276
  37. package/dist/mocks.cjs +5 -5
  38. package/dist/mocks.d.cts +2 -2
  39. package/dist/mocks.d.ts +2 -2
  40. package/dist/mocks.mjs +4 -4
  41. package/dist/notifications.cjs +1 -1
  42. package/dist/notifications.d.cts +1 -1
  43. package/dist/notifications.d.ts +1 -1
  44. package/dist/notifications.mjs +1 -1
  45. package/dist/react.cjs +119 -119
  46. package/dist/react.d.cts +8 -2
  47. package/dist/react.d.ts +8 -2
  48. package/dist/react.mjs +119 -119
  49. package/dist/support.cjs +1 -1
  50. package/dist/support.d.cts +1 -1
  51. package/dist/support.d.ts +1 -1
  52. package/dist/support.mjs +1 -1
  53. package/dist/telemetry.cjs +62 -49
  54. package/dist/telemetry.d.cts +1 -1
  55. package/dist/telemetry.d.ts +1 -1
  56. package/dist/telemetry.mjs +62 -49
  57. package/dist/{types-D-9bjlM0.d.cts → types-Bl_4HROd.d.cts} +118 -19
  58. package/dist/{types-bVztFQTI.d.ts → types-Bqnsqvow.d.ts} +118 -19
  59. package/dist/usage.cjs +1 -1
  60. package/dist/usage.d.cts +1 -1
  61. package/dist/usage.d.ts +1 -1
  62. package/dist/usage.mjs +1 -1
  63. package/dist/webhooks.cjs +1 -1
  64. package/dist/webhooks.d.cts +1 -1
  65. package/dist/webhooks.d.ts +1 -1
  66. package/dist/webhooks.mjs +1 -1
  67. package/package.json +9 -1
package/dist/auth.mjs CHANGED
@@ -1,16 +1,16 @@
1
1
  import { jwtVerify, createRemoteJWKSet } from 'jose';
2
2
  import { openDB } from 'idb';
3
3
 
4
- var Hn = Object.defineProperty;
4
+ var Zn = Object.defineProperty;
5
5
  var $ = (n, e) => () => (n && (e = n(n = 0)), e);
6
- var ot = (n, e) => {
6
+ var st = (n, e) => {
7
7
  for (var t in e)
8
- Hn(n, t, { get: e[t], enumerable: true });
8
+ Zn(n, t, { get: e[t], enumerable: true });
9
9
  };
10
10
 
11
11
  // src/errors.ts
12
- var l, V, I = $(() => {
13
- l = class n extends Error {
12
+ var c, K, C = $(() => {
13
+ c = class n extends Error {
14
14
  code;
15
15
  status;
16
16
  requestId;
@@ -33,7 +33,7 @@ var l, V, I = $(() => {
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
- }, V = class n extends l {
36
+ }, K = 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
  }
@@ -41,24 +41,24 @@ var l, V, I = $(() => {
41
41
  });
42
42
 
43
43
  // src/idempotency.ts
44
- function ht() {
44
+ function yt() {
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
  );
52
52
  }
53
- var gt = $(() => {
54
- I();
53
+ var _t = $(() => {
54
+ C();
55
55
  });
56
56
 
57
57
  // src/correlation.ts
58
- function _t(n) {
59
- return typeof n == "string" && n.length > 0 && n.length <= 128 && er.test(n);
58
+ function vt(n) {
59
+ return typeof n == "string" && n.length > 0 && n.length <= 128 && sr.test(n);
60
60
  }
61
- function tr() {
61
+ function ar() {
62
62
  let n = globalThis.crypto;
63
63
  try {
64
64
  if (n && typeof n.randomUUID == "function") return n.randomUUID();
@@ -76,24 +76,24 @@ function tr() {
76
76
  let r = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
77
77
  return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
78
78
  }
79
- function ae(n, e) {
79
+ function ce(n, e) {
80
80
  let t, r = {};
81
81
  for (let [i, s] of Object.entries(n)) {
82
- if (i.toLowerCase() === yt) {
83
- _t(s) && (t = s);
82
+ if (i.toLowerCase() === bt) {
83
+ vt(s) && (t = s);
84
84
  continue;
85
85
  }
86
86
  r[i] = s;
87
87
  }
88
- let o = t ?? (_t(e) ? e : void 0) ?? tr();
89
- return r[yt] = o, { headers: r, correlationId: o };
88
+ let o = t ?? (vt(e) ? e : void 0) ?? ar();
89
+ return r[bt] = o, { headers: r, correlationId: o };
90
90
  }
91
- var yt, er, Me = $(() => {
92
- yt = "x-correlation-id", er = /^[A-Za-z0-9._:\-]+$/;
91
+ var bt, sr, qe = $(() => {
92
+ bt = "x-correlation-id", sr = /^[A-Za-z0-9._:\-]+$/;
93
93
  });
94
94
 
95
95
  // src/server-only-key.ts
96
- function X() {
96
+ function Y() {
97
97
  try {
98
98
  let n = globalThis.navigator;
99
99
  if (n && n.product === "ReactNative") return "react-native";
@@ -106,108 +106,108 @@ function X() {
106
106
  }
107
107
  return null;
108
108
  }
109
- function bt(n, e) {
110
- let t = nr[n];
109
+ function wt(n, e) {
110
+ let t = cr[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
- function wt(n) {
113
+ function St(n) {
114
114
  if (!n.hasApiKey) return;
115
- let e = n.runtime === void 0 ? X() : n.runtime;
115
+ let e = n.runtime === void 0 ? Y() : n.runtime;
116
116
  if (e) {
117
117
  if (n.strict)
118
- throw new l("server_only_key", bt(e, true), void 0, void 0, e);
119
- if (!vt) {
120
- vt = true;
118
+ throw new c("server_only_key", wt(e, true), void 0, void 0, e);
119
+ if (!kt) {
120
+ kt = true;
121
121
  try {
122
- typeof console < "u" && typeof console.warn == "function" && console.warn(bt(e, !1));
122
+ typeof console < "u" && typeof console.warn == "function" && console.warn(wt(e, !1));
123
123
  } catch {
124
124
  }
125
125
  }
126
126
  }
127
127
  }
128
- var nr, vt, qe = $(() => {
129
- I();
130
- nr = {
128
+ var cr, kt, Fe = $(() => {
129
+ C();
130
+ cr = {
131
131
  browser: "no navegador",
132
132
  "react-native": "num app React Native"
133
133
  };
134
- vt = false;
134
+ kt = false;
135
135
  });
136
136
 
137
137
  // src/http.ts
138
- var Y = {};
139
- ot(Y, {
140
- checkCoreVersionCompat: () => ce,
138
+ var Z = {};
139
+ st(Z, {
140
+ checkCoreVersionCompat: () => le,
141
141
  httpRequest: () => v,
142
- statusToCode: () => le
142
+ statusToCode: () => de
143
143
  });
144
- function Fe(n) {
144
+ function je(n) {
145
145
  return n.split("+")[0] ?? n;
146
146
  }
147
- function or(n, e) {
148
- let t = Fe(n).split(".").map(Number), r = Fe(e).split(".").map(Number), o = Math.max(t.length, r.length);
147
+ function dr(n, e) {
148
+ let t = je(n).split(".").map(Number), r = je(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;
151
151
  if (s !== a) return s - a;
152
152
  }
153
153
  return 0;
154
154
  }
155
- function Ct() {
155
+ function Et() {
156
156
  try {
157
- return "3.8.0";
157
+ return "3.9.0";
158
158
  } catch {
159
159
  return;
160
160
  }
161
161
  }
162
- function ir() {
163
- let n = Ct();
162
+ function ur() {
163
+ let n = Et();
164
164
  return n ? parseInt(n.split(".")[0] ?? "3", 10) : 3;
165
165
  }
166
- function ce(n) {
166
+ function le(n) {
167
167
  if (!n) return;
168
- let e = ir(), t = rr[e];
168
+ let e = ur(), t = lr[e];
169
169
  if (!t) return;
170
- let r = Fe(n);
171
- if (or(r, t) < 0) {
170
+ let r = je(n);
171
+ if (dr(r, t) < 0) {
172
172
  let o = `${e}:${r}`;
173
- kt.has(o) || (kt.add(o), console.warn(
173
+ Tt.has(o) || (Tt.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 sr() {
178
+ function pr() {
179
179
  let n = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
180
- return X() ? "Esta opera\xE7\xE3o exige a credencial nrt_ do produto, que \xE9 S\xD3 DE SERVIDOR. No navegador/app, chame a API do seu produto (ex.: https://<produto>.neetru.com/api/v1) com o token do usu\xE1rio \u2014 o backend do produto faz esta chamada com o SDK e a chave. (" + n + ")" : n;
180
+ return Y() ? "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
  }
182
- function St(n) {
182
+ function Rt(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 ur(n) {
186
+ function yr(n) {
187
187
  if (!n) return null;
188
188
  let e = Number(n);
189
- if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), Tt);
189
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), It);
190
190
  let t = Date.parse(n);
191
191
  if (Number.isFinite(t)) {
192
192
  let r = t - Date.now();
193
- if (r > 0) return Math.min(r, Tt);
193
+ if (r > 0) return Math.min(r, It);
194
194
  }
195
195
  return null;
196
196
  }
197
- function Rt(n) {
197
+ function Ct(n) {
198
198
  return new Promise((e) => setTimeout(e, n));
199
199
  }
200
- function le(n) {
200
+ function de(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 pr(n, e, t) {
203
+ function _r(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))
207
207
  a !== void 0 && i.searchParams.set(s, String(a));
208
208
  return i.toString();
209
209
  }
210
- async function It(n) {
210
+ async function At(n) {
211
211
  let e = await n.text();
212
212
  if (e)
213
213
  try {
@@ -217,17 +217,17 @@ async function It(n) {
217
217
  }
218
218
  }
219
219
  async function v(n, e) {
220
- let t = e.method ?? "GET", r = pr(n.baseUrl, e.path, e.query), o = lr.has(t) ? ar : cr, i = e.retries ?? o, { headers: s, correlationId: a } = ae(
220
+ let t = e.method ?? "GET", r = _r(n.baseUrl, e.path, e.query), o = hr.has(t) ? fr : mr, i = e.retries ?? o, { headers: s, correlationId: a } = ce(
221
221
  { accept: "application/json", ...e.headers },
222
222
  e.correlationId
223
- ), c = Ct();
224
- if (c && (s["x-neetru-sdk-version"] = c), e.requireAuth) {
223
+ ), l = Et();
224
+ if (l && (s["x-neetru-sdk-version"] = l), e.requireAuth) {
225
225
  if (!n.apiKey)
226
- throw new l("missing_api_key", sr());
226
+ throw new c("missing_api_key", pr());
227
227
  s.authorization = `Bearer ${n.apiKey}`;
228
228
  }
229
229
  if (e.idempotencyKey) {
230
- let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : ht();
230
+ let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : yt();
231
231
  s["idempotency-key"] = f;
232
232
  }
233
233
  let d = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
@@ -235,7 +235,7 @@ async function v(n, e) {
235
235
  let u = null, p = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
236
236
  for (let f = 0; f <= i; f++) {
237
237
  if (p != null && Date.now() >= p)
238
- throw u ?? new l(
238
+ throw u ?? new c(
239
239
  "network_error",
240
240
  "Deadline excedido antes de completar a request",
241
241
  void 0,
@@ -243,77 +243,77 @@ async function v(n, e) {
243
243
  void 0,
244
244
  a
245
245
  );
246
- let _ = { method: t, headers: s };
247
- d !== void 0 && (_.body = d);
248
- let b = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
249
- _.signal = AbortSignal.timeout(b);
250
- let S;
246
+ let h = { method: t, headers: s };
247
+ d !== void 0 && (h.body = d);
248
+ let y = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
249
+ h.signal = AbortSignal.timeout(y);
250
+ let T;
251
251
  try {
252
- S = await n.fetch(r, _);
253
- } catch (h) {
254
- let C = h instanceof DOMException && h.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${h instanceof Error ? h.message : "fetch failed"}`;
255
- if (u = new l("network_error", C, void 0, void 0, void 0, a), f < i) {
256
- let D = St(f);
252
+ T = await n.fetch(r, h);
253
+ } catch (m) {
254
+ let S = m instanceof DOMException && m.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${m instanceof Error ? m.message : "fetch failed"}`;
255
+ if (u = new c("network_error", S, void 0, void 0, void 0, a), f < i) {
256
+ let D = Rt(f);
257
257
  if (p == null || Date.now() + D < p) {
258
- await Rt(D);
258
+ await Ct(D);
259
259
  continue;
260
260
  }
261
261
  }
262
262
  throw u;
263
263
  }
264
- let x = S.headers.get("x-request-id") ?? S.headers.get("x-correlation-id") ?? void 0;
265
- if (S.ok) {
266
- let h = S.headers.get("x-neetru-version");
267
- return h && ce(h), await It(S);
264
+ let x = T.headers.get("x-request-id") ?? T.headers.get("x-correlation-id") ?? void 0;
265
+ if (T.ok) {
266
+ let m = T.headers.get("x-neetru-version");
267
+ return m && le(m), await At(T);
268
268
  }
269
- let T = await It(S), P = le(S.status), q = `HTTP ${S.status}`, m;
270
- if (T && typeof T == "object") {
271
- let h = T.error;
272
- typeof h == "string" ? q = h : h && typeof h == "object" ? (typeof h.code == "string" && (P = h.code), typeof h.message == "string" && (q = h.message), typeof h.reason == "string" && (m = h.reason)) : (typeof T.code == "string" && (P = T.code), typeof T.message == "string" && (q = T.message)), typeof T.reason == "string" && (m = T.reason);
269
+ let R = await At(T), E = de(T.status), j = `HTTP ${T.status}`, g;
270
+ if (R && typeof R == "object") {
271
+ let m = R.error;
272
+ typeof m == "string" ? j = m : m && typeof m == "object" ? (typeof m.code == "string" && (E = m.code), typeof m.message == "string" && (j = m.message), typeof m.reason == "string" && (g = m.reason)) : (typeof R.code == "string" && (E = R.code), typeof R.message == "string" && (j = R.message)), typeof R.reason == "string" && (g = R.reason);
273
273
  }
274
- if (S.status === 410) {
275
- let h = S.headers.get("x-neetru-replacement");
276
- q === `HTTP ${S.status}` && (q = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), h && !q.includes(h) && (q += ` Substituto: ${h}.`);
274
+ if (T.status === 410) {
275
+ let m = T.headers.get("x-neetru-replacement");
276
+ j === `HTTP ${T.status}` && (j = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), m && !j.includes(m) && (j += ` Substituto: ${m}.`);
277
277
  }
278
- let g = new l(P, q, S.status, x, m, a);
279
- if (u = g, dr.has(P) && f < i) {
280
- let C = ur(S.headers.get("retry-after")) ?? St(f);
281
- if (p == null || Date.now() + C < p) {
282
- await Rt(C);
278
+ let b = new c(E, j, T.status, x, g, a);
279
+ if (u = b, gr.has(E) && f < i) {
280
+ let S = yr(T.headers.get("retry-after")) ?? Rt(f);
281
+ if (p == null || Date.now() + S < p) {
282
+ await Ct(S);
283
283
  continue;
284
284
  }
285
285
  }
286
- throw g;
286
+ throw b;
287
287
  }
288
- throw u ?? new l("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
288
+ throw u ?? new c("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
289
289
  }
290
- var rr, kt, ar, cr, lr, dr, Tt, M = $(() => {
291
- I();
292
- gt();
293
- Me();
290
+ var lr, Tt, fr, mr, hr, gr, It, F = $(() => {
291
+ C();
292
+ _t();
294
293
  qe();
295
- rr = {
294
+ Fe();
295
+ lr = {
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
- kt = /* @__PURE__ */ new Set();
301
- ar = 2, cr = 0, lr = /* @__PURE__ */ new Set(["GET", "HEAD"]), dr = /* @__PURE__ */ new Set([
300
+ Tt = /* @__PURE__ */ new Set();
301
+ fr = 2, mr = 0, hr = /* @__PURE__ */ new Set(["GET", "HEAD"]), gr = /* @__PURE__ */ new Set([
302
302
  "rate_limited",
303
303
  "server_error",
304
304
  "network_error"
305
305
  ]);
306
- Tt = 6e4;
306
+ It = 6e4;
307
307
  });
308
308
 
309
309
  // src/db-errors.ts
310
- var Rr, y, Z = $(() => {
311
- I();
312
- Rr = /* @__PURE__ */ new Set([
310
+ var Dr, _, ee = $(() => {
311
+ C();
312
+ Dr = /* @__PURE__ */ new Set([
313
313
  "db_unavailable",
314
314
  "db_conflict",
315
315
  "db_timeout"
316
- ]), y = class n extends l {
316
+ ]), _ = class n extends c {
317
317
  /** Código de erro fechado — específico de DB. */
318
318
  code;
319
319
  /**
@@ -327,16 +327,16 @@ var Rr, y, Z = $(() => {
327
327
  */
328
328
  dbId;
329
329
  constructor(e, t, r) {
330
- super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Rr.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
330
+ super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Dr.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
331
331
  }
332
332
  };
333
333
  });
334
334
 
335
335
  // src/db/sql/resilient-pool.ts
336
- function ve(n) {
337
- return typeof n == "object" && n !== null && n[He] === true;
336
+ function we(n) {
337
+ return typeof n == "object" && n !== null && n[Ge] === true;
338
338
  }
339
- function Hr(n) {
339
+ function Zr(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,67 +348,84 @@ function Hr(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 Qe(n) {
351
+ function Xt(n) {
352
+ let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
353
+ if (typeof e == "string" && eo.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 to(n) {
359
+ return Zr(n) || Xt(n);
360
+ }
361
+ function Je(n) {
352
362
  let e = { current: n }, t = null, r = {
353
- __neetruSwapInner(c) {
354
- let d = e.current;
355
- return e.current = c, d;
363
+ __neetruSwapInner(u) {
364
+ let p = e.current;
365
+ return e.current = u, p;
356
366
  },
357
367
  __neetruGetInner() {
358
368
  return e.current;
359
369
  },
360
- __neetruSetReLease(c) {
361
- t = c;
370
+ __neetruSetReLease(u) {
371
+ t = u;
362
372
  }
363
- }, o = (c, d) => c.query(...d), i = (...c) => c.length > 0 && typeof c[c.length - 1] == "function" ? o(e.current, c) : (async () => {
373
+ }, o = (u, p, f) => p[u](
374
+ ...f
375
+ ), i = (u, p) => (...f) => f.length > 0 && typeof f[f.length - 1] == "function" ? o(u, e.current, f) : (async () => {
364
376
  try {
365
- return await o(e.current, c);
366
- } catch (d) {
367
- let u = t;
368
- if (u === null || !Hr(d))
369
- throw d;
377
+ return await o(u, e.current, f);
378
+ } catch (h) {
379
+ let y = t;
380
+ if (y === null || !p(h))
381
+ throw h;
370
382
  try {
371
- await u();
383
+ await y();
372
384
  } catch {
373
- throw d;
385
+ throw h;
374
386
  }
375
- return await o(e.current, c);
387
+ return await o(u, e.current, f);
376
388
  }
377
- })(), s = Object.create(Object.getPrototypeOf(n));
378
- return new Proxy(s, {
379
- get(c, d) {
380
- if (d === He) return true;
381
- if (d === "__neetruSwapInner") return r.__neetruSwapInner;
382
- if (d === "__neetruGetInner") return r.__neetruGetInner;
383
- if (d === "__neetruSetReLease") return r.__neetruSetReLease;
384
- if (d === "query") return i;
385
- if (d === "constructor")
389
+ })(), s = i("query", to), a = i("connect", Xt), l = Object.create(Object.getPrototypeOf(n));
390
+ return new Proxy(l, {
391
+ get(u, p) {
392
+ if (p === Ge) return true;
393
+ if (p === "__neetruSwapInner") return r.__neetruSwapInner;
394
+ if (p === "__neetruGetInner") return r.__neetruGetInner;
395
+ if (p === "__neetruSetReLease") return r.__neetruSetReLease;
396
+ if (p === "query") return s;
397
+ if (p === "connect") {
398
+ let y = e.current;
399
+ return typeof y.connect == "function" ? a : y.connect;
400
+ }
401
+ if (p === "constructor")
386
402
  return e.current.constructor;
387
- let u = e.current, p = Reflect.get(u, d, u);
388
- return typeof p == "function" ? p.bind(u) : p;
403
+ let f = e.current, h = Reflect.get(f, p, f);
404
+ return typeof h == "function" ? h.bind(f) : h;
389
405
  }
390
406
  });
391
407
  }
392
- var He, Ge = $(() => {
393
- He = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
408
+ var Ge, eo, Xe = $(() => {
409
+ Ge = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
410
+ eo = /* @__PURE__ */ new Set(["28P01", "28000"]);
394
411
  });
395
412
 
396
413
  // src/db/sql/lease.ts
397
- function Gr(n, e) {
414
+ function ro(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 Jr(n) {
401
- if (n instanceof y) return n;
417
+ function oo(n) {
418
+ if (n instanceof _) return n;
402
419
  let e = n instanceof Error ? n.message : String(n), t = n instanceof Error ? n.code : void 0;
403
- return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new y(
420
+ return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new _(
404
421
  "db_unavailable",
405
422
  `Pool connection failed (${t}): ${e}`
406
- ) : e.includes("statement timeout") || e.includes("lock timeout") ? new y("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new y("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new y("db_permission_denied", `Permission denied: ${e}`) : new y("db_unavailable", `Database error: ${e}`);
423
+ ) : e.includes("statement timeout") || e.includes("lock timeout") ? new _("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new _("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new _("db_permission_denied", `Permission denied: ${e}`) : new _("db_unavailable", `Database error: ${e}`);
407
424
  }
408
- var Qr, J, re, Gt = $(() => {
409
- Z();
410
- Ge();
411
- Qr = 0.8, J = 3e4, re = class {
425
+ var no, X, oe, Yt = $(() => {
426
+ ee();
427
+ Xe();
428
+ no = 0.8, X = 3e4, oe = 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 Qr, J, re, Gt = $(() => {
448
465
  isolationLevel: t.isolationLevel
449
466
  }) : await this._orm.transaction(e);
450
467
  } catch (r) {
451
- throw Jr(r);
468
+ throw oo(r);
452
469
  }
453
470
  }
454
471
  async close() {
@@ -466,13 +483,13 @@ var Qr, J, re, Gt = $(() => {
466
483
  * usa `MIN_RENEWAL_DELAY_MS` como fallback seguro.
467
484
  */
468
485
  _calcRenewalDelayMs() {
469
- if (!this._lease) return J;
486
+ if (!this._lease) return X;
470
487
  let e = Date.parse(this._lease.expiresAt);
471
- if (!Number.isFinite(e)) return J;
488
+ if (!Number.isFinite(e)) return X;
472
489
  let t = this._deps.now(), r = e - t;
473
- if (r <= 0) return J;
474
- let o = r * (1 - Qr);
475
- return Math.max(J, Math.round(o));
490
+ if (r <= 0) return X;
491
+ let o = r * (1 - no);
492
+ return Math.max(X, Math.round(o));
476
493
  }
477
494
  _scheduleRenewal() {
478
495
  if (this._closed) return;
@@ -499,8 +516,8 @@ var Qr, J, re, Gt = $(() => {
499
516
  } catch (t) {
500
517
  this._renewalTimer = setTimeout(() => {
501
518
  this._doRenew();
502
- }, J), console.warn(
503
- `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${J}ms (cert TLS ef\xEAmero do servidor expira ~15min ap\xF3s o \xFAltimo swap):`,
519
+ }, X), console.warn(
520
+ `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${X}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 Qr, J, re, Gt = $(() => {
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
@@ -531,7 +551,7 @@ var Qr, J, re, Gt = $(() => {
531
551
  */
532
552
  async _reactiveReLease() {
533
553
  if (this._closed)
534
- throw new y(
554
+ throw new _(
535
555
  "db_unavailable",
536
556
  "SqlLeaseManager foi fechado \u2014 re-lease reativo abortado."
537
557
  );
@@ -568,30 +588,30 @@ var Qr, J, re, Gt = $(() => {
568
588
  */
569
589
  async _ensureInitialLease() {
570
590
  if (this._closed)
571
- throw new y(
591
+ throw new _(
572
592
  "db_unavailable",
573
593
  "SqlLeaseManager foi fechado \u2014 aquisi\xE7\xE3o de lease inicial abortada."
574
594
  );
575
595
  if (this._lease)
576
- return ve(this._pool) ? this._pool.__neetruGetInner() : this._pool;
596
+ return we(this._pool) ? this._pool.__neetruGetInner() : this._pool;
577
597
  if (this._initInFlight !== null) return this._initInFlight;
578
598
  let e = (async () => {
579
599
  let t;
580
600
  try {
581
601
  t = this._deps.database !== void 0 ? await this._deps.fetchLease({ database: this._deps.database }) : await this._deps.fetchLease();
582
602
  } catch (o) {
583
- if (o instanceof y) throw o;
603
+ if (o instanceof _) throw o;
584
604
  let i = o instanceof Error ? o.message : String(o);
585
- throw new y("db_unavailable", `Falha ao obter lease inicial: ${i}`);
605
+ throw new _("db_unavailable", `Falha ao obter lease inicial: ${i}`);
586
606
  }
587
607
  let r;
588
608
  try {
589
609
  r = this._deps.createPool(t);
590
610
  } catch (o) {
591
611
  let i = o instanceof Error ? o.message : String(o);
592
- throw new y("db_unavailable", `Falha ao abrir pool: ${i}`);
612
+ throw new _("db_unavailable", `Falha ao abrir pool: ${i}`);
593
613
  }
594
- return ve(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
614
+ return we(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
595
615
  }) : this._pool = r, this._lease = t, this._scheduleRenewal(), r;
596
616
  })();
597
617
  this._initInFlight = e;
@@ -607,12 +627,12 @@ var Qr, J, re, Gt = $(() => {
607
627
  * Exposto como método protegido para testes.
608
628
  */
609
629
  async _swapPool(e) {
610
- if (!Gr(this._lease, e)) {
630
+ if (!ro(this._lease, e)) {
611
631
  this._lease = e;
612
632
  return;
613
633
  }
614
634
  let t = this._deps.createPool(e);
615
- if (ve(this._pool)) {
635
+ if (we(this._pool)) {
616
636
  let i = this._pool.__neetruSwapInner(t);
617
637
  this._lease = e, i.end().catch(() => {
618
638
  });
@@ -625,7 +645,7 @@ var Qr, J, re, Gt = $(() => {
625
645
  // ─── Helpers ───────────────────────────────────────────────────────────────
626
646
  _assertOpen() {
627
647
  if (this._closed)
628
- throw new y(
648
+ throw new _(
629
649
  "db_unavailable",
630
650
  "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
631
651
  );
@@ -634,29 +654,29 @@ var Qr, J, re, Gt = $(() => {
634
654
  });
635
655
 
636
656
  // src/db/sql/sql-client.ts
637
- var rn = {};
638
- ot(rn, {
639
- DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => tn,
640
- DEFAULT_POOL_IDLE_MS: () => en,
641
- DEFAULT_POOL_MAX: () => Zt,
642
- LEASE_ENDPOINT: () => Jt,
643
- LEASE_RENEW_ENDPOINT: () => Xt,
644
- createDrizzleHandle: () => eo,
645
- createHttpLeaseFetcher: () => Yt,
646
- createPgPool: () => Zr,
647
- createSqlClientFromConfig: () => no,
648
- createSqlClientWithDeps: () => nn,
649
- resolvePoolTuning: () => Xe
657
+ var an = {};
658
+ st(an, {
659
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => on,
660
+ DEFAULT_POOL_IDLE_MS: () => rn,
661
+ DEFAULT_POOL_MAX: () => nn,
662
+ LEASE_ENDPOINT: () => Zt,
663
+ LEASE_RENEW_ENDPOINT: () => en,
664
+ createDrizzleHandle: () => co,
665
+ createHttpLeaseFetcher: () => tn,
666
+ createPgPool: () => ao,
667
+ createSqlClientFromConfig: () => uo,
668
+ createSqlClientWithDeps: () => sn,
669
+ resolvePoolTuning: () => Ze
650
670
  });
651
- function Xr(n) {
671
+ function io(n) {
652
672
  return n === "workspace" ? "staging" : n === "prod" ? "production" : "dev-local";
653
673
  }
654
- function Yt(n) {
674
+ function tn(n) {
655
675
  return async (e) => {
656
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = !!e?.leaseId, o = r ? Xt : Jt, i;
676
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = !!e?.leaseId, o = r ? en : Zt, i;
657
677
  r ? i = { leaseId: e.leaseId } : (i = {
658
678
  productId: n.productId ?? "",
659
- environment: Xr(n.env ?? "prod")
679
+ environment: io(n.env ?? "prod")
660
680
  }, e?.database !== void 0 && (i.database = e.database));
661
681
  let s;
662
682
  try {
@@ -669,35 +689,35 @@ function Yt(n) {
669
689
  retries: 2
670
690
  });
671
691
  } catch (a) {
672
- let c = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof l ? a.reason : void 0;
692
+ let l = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof c ? a.reason : void 0;
673
693
  if (u === "suspended" || u === "archived" || u === "revoked") {
674
694
  let p = u === "suspended" ? "ambiente suspenso \u2014 a m\xE1quina que o servia parou; ser\xE1 religado quando o ambiente voltar" : u === "archived" ? "ambiente arquivado \u2014 este banco foi arquivado e n\xE3o aceita mais conex\xF5es" : "lease revogado \u2014 as credenciais deste ambiente foram revogadas pelo Core";
675
- throw new y(
695
+ throw new _(
676
696
  "db_suspended",
677
- `Falha ao ${c} lease SQL: ${p} (reason=${u}).`
697
+ `Falha ao ${l} lease SQL: ${p} (reason=${u}).`
678
698
  );
679
699
  }
680
- throw new y(
700
+ throw new _(
681
701
  "db_unavailable",
682
- `Falha ao ${c} lease SQL: ${d}`
702
+ `Falha ao ${l} lease SQL: ${d}`
683
703
  );
684
704
  }
685
- return Yr(s);
705
+ return so(s);
686
706
  };
687
707
  }
688
- function Yr(n) {
708
+ function so(n) {
689
709
  if (!n || typeof n != "object")
690
- throw new y("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
710
+ throw new _("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
691
711
  let t = n.lease;
692
712
  if (!t || typeof t != "object")
693
- throw new y(
713
+ throw new _(
694
714
  "db_unavailable",
695
715
  'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
696
716
  );
697
717
  let r = t;
698
718
  function o(i, s) {
699
719
  if (typeof r[i] !== s)
700
- throw new y(
720
+ throw new _(
701
721
  "db_unavailable",
702
722
  `Campo obrigat\xF3rio "${i}" ausente ou tipo inv\xE1lido na resposta de lease.`
703
723
  );
@@ -717,22 +737,22 @@ function Yr(n) {
717
737
  expiresAt: o("expiresAt", "string")
718
738
  };
719
739
  }
720
- function Je(n, e, t, r) {
740
+ function Ye(n, e, t, r) {
721
741
  let o = typeof process < "u" ? process.env?.[n] : void 0;
722
742
  if (o === void 0 || o.trim() === "") return e;
723
743
  let i = Number.parseInt(o.trim(), 10);
724
744
  return !Number.isFinite(i) || i < t || i > r ? e : i;
725
745
  }
726
- function Xe() {
746
+ function Ze() {
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: Je("NEETRU_DB_POOL_MAX", Zt, 1, 100),
750
+ max: Ye("NEETRU_DB_POOL_MAX", nn, 1, 100),
731
751
  // Teto 15min = janela do cert; piso 1s.
732
- idleTimeoutMillis: Je("NEETRU_DB_POOL_IDLE_MS", en, 1e3, 9e5),
733
- connectionTimeoutMillis: Je(
752
+ idleTimeoutMillis: Ye("NEETRU_DB_POOL_IDLE_MS", rn, 1e3, 9e5),
753
+ connectionTimeoutMillis: Ye(
734
754
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
735
- tn,
755
+ on,
736
756
  1e3,
737
757
  12e4
738
758
  ),
@@ -740,7 +760,7 @@ function Xe() {
740
760
  keepAliveInitialDelayMillis: 1e4
741
761
  };
742
762
  }
743
- async function Zr(n) {
763
+ async function ao(n) {
744
764
  let { Pool: e } = await import(
745
765
  /* webpackIgnore: true */
746
766
  'pg'
@@ -757,17 +777,17 @@ async function Zr(n) {
757
777
  user: n.user,
758
778
  password: n.password,
759
779
  ssl: t,
760
- ...Xe()
780
+ ...Ze()
761
781
  });
762
782
  }
763
- async function eo(n, e) {
783
+ async function co(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 to(n, e) {
790
+ function lo(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 to(n, e) {
783
803
  };
784
804
  return n && Object.setPrototypeOf(i, n), i;
785
805
  }
786
- async function nn(n, e) {
806
+ async function sn(n, e) {
787
807
  let t = e?.database !== void 0 ? { ...n, database: e.database } : n;
788
808
  if (t.lazy) {
789
- let c = null, d = to(t.poolPrototype ?? null, () => {
790
- if (!c)
791
- throw new y("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
792
- return c._ensureInitialLease();
793
- }), u = Qe(d), p;
809
+ let l = null, d = lo(t.poolPrototype ?? null, () => {
810
+ if (!l)
811
+ throw new _("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
812
+ return l._ensureInitialLease();
813
+ }), u = Je(d), p;
794
814
  try {
795
815
  p = t.createDrizzle(u, t.schema);
796
- } catch (_) {
797
- let b = _ instanceof Error ? _.message : String(_);
798
- throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${b}`);
816
+ } catch (h) {
817
+ let y = h instanceof Error ? h.message : String(h);
818
+ throw new _("db_unavailable", `Falha ao criar handle Drizzle: ${y}`);
799
819
  }
800
- let f = new re(null, u, p, t);
801
- return c = f, u.__neetruSetReLease(() => f._reactiveReLease()), f;
820
+ let f = new oe(null, u, p, t);
821
+ return l = f, u.__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 y) throw c;
808
- let d = c instanceof Error ? c.message : String(c);
809
- throw new y("db_unavailable", `Falha ao obter lease inicial: ${d}`);
826
+ } catch (l) {
827
+ if (l instanceof _) throw l;
828
+ let d = l instanceof Error ? l.message : String(l);
829
+ throw new _("db_unavailable", `Falha ao obter lease inicial: ${d}`);
810
830
  }
811
831
  let o;
812
832
  try {
813
833
  o = t.createPool(r);
814
- } catch (c) {
815
- let d = c instanceof Error ? c.message : String(c);
816
- throw new y("db_unavailable", `Falha ao abrir pool: ${d}`);
834
+ } catch (l) {
835
+ let d = l instanceof Error ? l.message : String(l);
836
+ throw new _("db_unavailable", `Falha ao abrir pool: ${d}`);
817
837
  }
818
- let i = Qe(o), s;
838
+ let i = Je(o), s;
819
839
  try {
820
840
  s = t.createDrizzle(i, t.schema);
821
- } catch (c) {
841
+ } catch (l) {
822
842
  await o.end().catch(() => {
823
843
  });
824
- let d = c instanceof Error ? c.message : String(c);
825
- throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
844
+ let d = l instanceof Error ? l.message : String(l);
845
+ throw new _("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
826
846
  }
827
- let a = new re(r, i, s, t);
847
+ let a = new oe(r, i, s, t);
828
848
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
829
849
  }
830
- async function no(n, e, t) {
831
- let r = Yt(n), o, i;
850
+ async function uo(n, e, t) {
851
+ let r = tn(n), o, i;
832
852
  try {
833
853
  o = await import(
834
854
  /* webpackIgnore: true */
@@ -838,13 +858,13 @@ async function no(n, e, t) {
838
858
  'drizzle-orm/node-postgres'
839
859
  );
840
860
  } catch (d) {
841
- throw new y(
861
+ throw new _(
842
862
  "db_unavailable",
843
863
  `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${d.message})`
844
864
  );
845
865
  }
846
866
  let s = o.Pool ?? o.default?.Pool;
847
- return nn(
867
+ return sn(
848
868
  {
849
869
  fetchLease: r,
850
870
  createPool: (d) => {
@@ -863,7 +883,7 @@ async function no(n, e, t) {
863
883
  ssl: u,
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
- ...Xe()
886
+ ...Ze()
867
887
  });
868
888
  },
869
889
  createDrizzle: (d, u) => i.drizzle(d, { schema: u }),
@@ -879,100 +899,100 @@ async function no(n, e, t) {
879
899
  t
880
900
  );
881
901
  }
882
- var Jt, Xt, Zt, en, tn, on = $(() => {
883
- Z();
884
- I();
885
- Gt();
886
- Ge();
887
- Jt = "/api/sdk/v1/db/lease", Xt = "/api/sdk/v1/db/lease/renew";
888
- Zt = 10, en = 6e4, tn = 1e4;
902
+ var Zt, en, nn, rn, on, cn = $(() => {
903
+ ee();
904
+ C();
905
+ Yt();
906
+ Xe();
907
+ Zt = "/api/sdk/v1/db/lease", en = "/api/sdk/v1/db/lease/renew";
908
+ nn = 10, rn = 6e4, on = 1e4;
889
909
  });
890
- var Le = /* @__PURE__ */ new Map(), Ue = 3600 * 1e3;
891
- function it(n, e = Ue) {
892
- let t = Date.now(), r = Le.get(n);
910
+ var Ue = /* @__PURE__ */ new Map(), Me = 3600 * 1e3;
911
+ function at(n, e = Me) {
912
+ let t = Date.now(), r = Ue.get(n);
893
913
  if (r && t - r.createdAt < e)
894
914
  return r.jwks;
895
915
  let o = createRemoteJWKSet(new URL(n));
896
- return Le.set(n, { jwks: o, createdAt: t }), o;
916
+ return Ue.set(n, { jwks: o, createdAt: t }), o;
897
917
  }
898
- function st() {
899
- Le.clear();
918
+ function ct() {
919
+ Ue.clear();
900
920
  }
901
921
 
902
922
  // src/auth.ts
903
- I();
923
+ C();
904
924
 
905
925
  // src/api-key.ts
906
- I();
907
- var at = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
908
- function ct(n) {
926
+ C();
927
+ var lt = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
928
+ function dt(n) {
909
929
  if (typeof n != "string" || n.length === 0)
910
- throw new l(
930
+ throw new c(
911
931
  "invalid_config",
912
932
  "apiKey is required (formato nrt_<keyId>_<secret>)"
913
933
  );
914
- let e = at.exec(n);
934
+ let e = lt.exec(n);
915
935
  if (!e)
916
- throw new l(
936
+ throw new c(
917
937
  "invalid_config",
918
938
  "apiKey malformado - esperado formato nrt_<keyId>_<secret>"
919
939
  );
920
940
  return { keyId: e[1], secret: e[2] };
921
941
  }
922
- function lt(n) {
942
+ function ut(n) {
923
943
  if (typeof n != "string" || n.length === 0) return null;
924
- let e = at.exec(n);
944
+ let e = lt.exec(n);
925
945
  return e ? { keyId: e[1], secret: e[2] } : null;
926
946
  }
927
947
 
928
948
  // src/base-url-allowlist.ts
929
- I();
930
- var dt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), Gn = ".neetru.com", Jn = "neetru.com", Xn = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
931
- function ut(n) {
932
- return Xn.test(n);
949
+ C();
950
+ var pt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), tr = ".neetru.com", nr = "neetru.com", rr = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
951
+ function ft(n) {
952
+ return rr.test(n);
933
953
  }
934
- function Yn(n) {
954
+ function or(n) {
935
955
  return n.toLowerCase().replace(/\.+$/, "");
936
956
  }
937
- function pt(n, e = []) {
957
+ function mt(n, e = []) {
938
958
  if (typeof n != "string" || n.length === 0)
939
- throw new l("invalid_config", "baseUrl is required");
959
+ throw new c("invalid_config", "baseUrl is required");
940
960
  let t;
941
961
  try {
942
962
  t = new URL(n);
943
963
  } catch {
944
- throw new l("invalid_config", `baseUrl is not a valid URL: ${n}`);
964
+ throw new c("invalid_config", `baseUrl is not a valid URL: ${n}`);
945
965
  }
946
- let r = t.protocol, o = Yn(t.hostname);
947
- if (Zn())
966
+ let r = t.protocol, o = or(t.hostname);
967
+ if (ir())
948
968
  return typeof console < "u" && console.warn(
949
969
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${n} aceito sem valida\xE7\xE3o.`
950
970
  ), n.replace(/\/+$/, "");
951
971
  if (r !== "https:" && r !== "http:")
952
- throw new l(
972
+ throw new c(
953
973
  "invalid_config",
954
974
  `baseUrl protocol must be http: or https:, got ${r}`
955
975
  );
956
976
  if (r === "http:") {
957
- if (!(dt.has(o) || ut(o)))
958
- throw new l(
977
+ if (!(pt.has(o) || ft(o)))
978
+ throw new c(
959
979
  "invalid_config",
960
980
  `baseUrl with http: only allowed for localhost/127.0.0.1/*.test/*.localhost. Got: ${o}. Use https: or set NEETRU_ALLOW_INSECURE_BASEURL=1 to bypass.`
961
981
  );
962
982
  return n.replace(/\/+$/, "");
963
983
  }
964
- let i = o === Jn || o.endsWith(Gn), s = e.some((c) => {
965
- let d = c.toLowerCase();
984
+ let i = o === nr || o.endsWith(tr), s = e.some((l) => {
985
+ let d = l.toLowerCase();
966
986
  return o === d || o.endsWith(`.${d}`);
967
- }), a = dt.has(o) || ut(o);
987
+ }), a = pt.has(o) || ft(o);
968
988
  if (!i && !s && !a)
969
- throw new l(
989
+ throw new c(
970
990
  "invalid_config",
971
991
  `baseUrl ${o} is not in the allowlist. Allowed: *.neetru.com, localhost, or configure { allowedHosts: ['...'] }. Bypass: NEETRU_ALLOW_INSECURE_BASEURL=1.`
972
992
  );
973
993
  return n.replace(/\/+$/, "");
974
994
  }
975
- function Zn() {
995
+ function ir() {
976
996
  try {
977
997
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
978
998
  if (e === "1" || e === "true") return !0;
@@ -987,19 +1007,19 @@ function Zn() {
987
1007
  }
988
1008
 
989
1009
  // src/types.ts
990
- var ft = "https://api.neetru.com", mt = "http://localhost:9003";
1010
+ var ht = "https://api.neetru.com", gt = "http://localhost:9003";
991
1011
 
992
1012
  // src/catalog.ts
993
- I();
994
- M();
995
- function At(n) {
1013
+ C();
1014
+ F();
1015
+ function Pt(n) {
996
1016
  if (!n || typeof n != "object")
997
- throw new l("invalid_response", "Catalog response item is not an object");
1017
+ throw new c("invalid_response", "Catalog response item is not an object");
998
1018
  let e = n;
999
1019
  if (typeof e.slug != "string" || !e.slug)
1000
- throw new l("invalid_response", "Catalog product missing slug");
1020
+ throw new c("invalid_response", "Catalog product missing slug");
1001
1021
  if (typeof e.name != "string" || !e.name)
1002
- throw new l("invalid_response", "Catalog product missing name");
1022
+ throw new c("invalid_response", "Catalog product missing name");
1003
1023
  let t = {
1004
1024
  slug: e.slug,
1005
1025
  name: e.name
@@ -1011,7 +1031,7 @@ function At(n) {
1011
1031
  return typeof r.amountCents == "number" && (o.amountCents = r.amountCents), Array.isArray(r.features) && r.features.every((i) => typeof i == "string") && (o.features = r.features), o;
1012
1032
  })), t;
1013
1033
  }
1014
- function Et(n) {
1034
+ function Dt(n) {
1015
1035
  return {
1016
1036
  /**
1017
1037
  * Lista produtos publicados. Por default só `published=true`; staff
@@ -1023,12 +1043,12 @@ function Et(n) {
1023
1043
  path: "/api/sdk/v1/catalog"
1024
1044
  });
1025
1045
  if (!t || !Array.isArray(t.products))
1026
- throw new l(
1046
+ throw new c(
1027
1047
  "invalid_response",
1028
1048
  "Catalog list response missing products array"
1029
1049
  );
1030
1050
  return {
1031
- products: t.products.map(At),
1051
+ products: t.products.map(Pt),
1032
1052
  fetchedAt: typeof t.fetchedAt == "string" ? t.fetchedAt : (/* @__PURE__ */ new Date()).toISOString()
1033
1053
  };
1034
1054
  },
@@ -1039,42 +1059,42 @@ function Et(n) {
1039
1059
  */
1040
1060
  async get(e) {
1041
1061
  if (!e || typeof e != "string")
1042
- throw new l("validation_failed", "slug is required");
1062
+ throw new c("validation_failed", "slug is required");
1043
1063
  let t = await v(n, {
1044
1064
  method: "GET",
1045
1065
  path: `/api/sdk/v1/catalog/${encodeURIComponent(e)}`
1046
1066
  });
1047
1067
  if (!t || !t.product)
1048
- throw new l(
1068
+ throw new c(
1049
1069
  "invalid_response",
1050
1070
  "Catalog get response missing product"
1051
1071
  );
1052
- return At(t.product);
1072
+ return Pt(t.product);
1053
1073
  }
1054
1074
  };
1055
1075
  }
1056
1076
 
1057
1077
  // src/entitlements.ts
1058
- I();
1059
- var fr = "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.";
1060
- function Pt() {
1061
- throw new l("validation_failed", fr);
1078
+ C();
1079
+ var br = "client.entitlements.check()/checkDetailed() est\xE3o DEPRECADOS \u2014 apontavam para GET /api/v1/sdk/entitlements/check, um endpoint que o Core nunca escreve (sempre retornava not_subscribed). Use client.usage.check(resource, { productId, tenantId }) no lugar \u2014 mesmo resultado (allowed/reason/remaining/limit/behavior), endpoint real.";
1080
+ function Nt() {
1081
+ throw new c("validation_failed", br);
1062
1082
  }
1063
- function Dt(n) {
1083
+ function xt(n) {
1064
1084
  return {
1065
1085
  /**
1066
1086
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
1067
1087
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
1068
1088
  */
1069
1089
  async check(e, t, r) {
1070
- Pt();
1090
+ Nt();
1071
1091
  },
1072
1092
  /**
1073
1093
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
1074
1094
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
1075
1095
  */
1076
1096
  async checkDetailed(e, t, r) {
1077
- Pt();
1097
+ Nt();
1078
1098
  },
1079
1099
  /** Test helper legado — no-op (não há mais cache). Mantido por compat. */
1080
1100
  __resetCache() {
@@ -1083,16 +1103,31 @@ function Dt(n) {
1083
1103
  }
1084
1104
 
1085
1105
  // src/telemetry.ts
1086
- I();
1087
- M();
1088
- var Nt = ["debug", "info", "warn", "error", "fatal"];
1089
- function mr() {
1106
+ C();
1107
+ F();
1108
+
1109
+ // src/runtime-env.ts
1110
+ function $e() {
1111
+ try {
1112
+ if (typeof process < "u" && process.env)
1113
+ return process.env.NODE_ENV === "production";
1114
+ } catch {
1115
+ }
1116
+ return false;
1117
+ }
1118
+ function W(n) {
1119
+ return n === "dev" && !$e();
1120
+ }
1121
+
1122
+ // src/telemetry.ts
1123
+ var Ot = ["debug", "info", "warn", "error", "fatal"];
1124
+ function vr() {
1090
1125
  return typeof globalThis < "u" && typeof globalThis.window < "u";
1091
1126
  }
1092
- function xt() {
1093
- return mr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1127
+ function Lt() {
1128
+ return vr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1094
1129
  }
1095
- function hr(n) {
1130
+ function wr(n) {
1096
1131
  switch (n) {
1097
1132
  case "debug":
1098
1133
  return console.debug.bind(console);
@@ -1108,17 +1143,17 @@ function hr(n) {
1108
1143
  return console.log.bind(console);
1109
1144
  }
1110
1145
  }
1111
- var gr = 500, yr = 50;
1112
- function Ot(n) {
1146
+ var kr = 500, Sr = 50;
1147
+ function Ut(n) {
1113
1148
  let e = [], t = null, r = null;
1114
1149
  async function o() {
1115
1150
  if (e.length === 0) return;
1116
1151
  let s = e.splice(0, e.length), a = Promise.allSettled(
1117
- s.map(async (c) => {
1152
+ s.map(async (l) => {
1118
1153
  try {
1119
- let d = { name: c.name }, u = c.productSlug ?? n.productId;
1120
- u && (d.productSlug = u), c.properties && typeof c.properties == "object" && (d.properties = c.properties), c.timestamp && (d.timestamp = c.timestamp);
1121
- let p = xt();
1154
+ let d = { name: l.name }, u = l.productSlug ?? n.productId;
1155
+ u && (d.productSlug = u), l.properties && typeof l.properties == "object" && (d.properties = l.properties), l.timestamp && (d.timestamp = l.timestamp);
1156
+ let p = Lt();
1122
1157
  await v(n, {
1123
1158
  method: "POST",
1124
1159
  path: p.path,
@@ -1131,7 +1166,7 @@ function Ot(n) {
1131
1166
  idempotencyKey: !0
1132
1167
  });
1133
1168
  } catch (d) {
1134
- typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", c.name, d);
1169
+ typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", l.name, d);
1135
1170
  }
1136
1171
  })
1137
1172
  );
@@ -1142,7 +1177,7 @@ function Ot(n) {
1142
1177
  function i() {
1143
1178
  t || (t = setTimeout(() => {
1144
1179
  o();
1145
- }, gr));
1180
+ }, kr));
1146
1181
  }
1147
1182
  return {
1148
1183
  /**
@@ -1159,21 +1194,21 @@ function Ot(n) {
1159
1194
  */
1160
1195
  async event(s) {
1161
1196
  if (!s || typeof s != "object")
1162
- throw new l("validation_failed", "event input is required");
1197
+ throw new c("validation_failed", "event input is required");
1163
1198
  if (typeof s.name != "string" || s.name.length === 0)
1164
- throw new l("validation_failed", "event.name is required");
1199
+ throw new c("validation_failed", "event.name is required");
1165
1200
  if (s.name.length > 128)
1166
- throw new l("validation_failed", "event.name max 128 chars");
1167
- let a = { name: s.name }, c = s.productSlug ?? n.productId;
1168
- c && (a.productSlug = c), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1169
- let d = xt(), u = await v(n, {
1201
+ throw new c("validation_failed", "event.name max 128 chars");
1202
+ let a = { name: s.name }, l = s.productSlug ?? n.productId;
1203
+ l && (a.productSlug = l), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1204
+ let d = Lt(), u = await v(n, {
1170
1205
  method: "POST",
1171
1206
  path: d.path,
1172
1207
  body: a,
1173
1208
  requireAuth: d.requireAuth
1174
1209
  });
1175
1210
  if (!u || u.ok !== true || typeof u.eventId != "string")
1176
- throw new l("invalid_response", "Telemetry response missing eventId");
1211
+ throw new c("invalid_response", "Telemetry response missing eventId");
1177
1212
  return { ok: true, eventId: u.eventId };
1178
1213
  },
1179
1214
  /**
@@ -1187,7 +1222,7 @@ function Ot(n) {
1187
1222
  * ```
1188
1223
  */
1189
1224
  track(s) {
1190
- !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= yr ? (t && (clearTimeout(t), t = null), o()) : i());
1225
+ !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= Sr ? (t && (clearTimeout(t), t = null), o()) : i());
1191
1226
  },
1192
1227
  /**
1193
1228
  * Força flush imediato da queue de `track()`. Resolva antes de
@@ -1213,22 +1248,22 @@ function Ot(n) {
1213
1248
  */
1214
1249
  async log(s) {
1215
1250
  if (!s || typeof s != "object")
1216
- throw new l("validation_failed", "log input is required");
1217
- if (!Nt.includes(s.level))
1218
- throw new l("validation_failed", `level must be one of ${Nt.join(", ")}`);
1251
+ throw new c("validation_failed", "log input is required");
1252
+ if (!Ot.includes(s.level))
1253
+ throw new c("validation_failed", `level must be one of ${Ot.join(", ")}`);
1219
1254
  if (typeof s.message != "string" || s.message.length === 0)
1220
- throw new l("validation_failed", "message is required");
1255
+ throw new c("validation_failed", "message is required");
1221
1256
  if (s.message.length > 4e3)
1222
- throw new l("validation_failed", "message max 4000 chars");
1223
- if (n.env === "dev")
1224
- return hr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1257
+ throw new c("validation_failed", "message max 4000 chars");
1258
+ if (W(n.env))
1259
+ return wr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1225
1260
  let a = {
1226
1261
  level: s.level,
1227
1262
  message: s.message
1228
1263
  };
1229
1264
  s.metadata && (a.metadata = s.metadata);
1230
- let c = s.productSlug ?? n.productId;
1231
- c && (a.productSlug = c);
1265
+ let l = s.productSlug ?? n.productId;
1266
+ l && (a.productSlug = l);
1232
1267
  let d = s.correlationId;
1233
1268
  if (!d)
1234
1269
  try {
@@ -1246,7 +1281,7 @@ function Ot(n) {
1246
1281
  headers: u
1247
1282
  });
1248
1283
  if (!p || p.ok !== true)
1249
- throw new l("invalid_response", "Telemetry log response missing ok");
1284
+ throw new c("invalid_response", "Telemetry log response missing ok");
1250
1285
  return {
1251
1286
  ok: true,
1252
1287
  logId: typeof p.logId == "string" ? p.logId : void 0,
@@ -1257,22 +1292,22 @@ function Ot(n) {
1257
1292
  }
1258
1293
 
1259
1294
  // src/usage.ts
1260
- I();
1261
- M();
1295
+ C();
1296
+ F();
1262
1297
 
1263
1298
  // src/validators.ts
1264
- I();
1265
- var Lt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1299
+ C();
1300
+ var Mt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1266
1301
  function N(n, e) {
1267
- if (typeof e != "string" || !Lt.test(e))
1268
- throw new l(
1302
+ if (typeof e != "string" || !Mt.test(e))
1303
+ throw new c(
1269
1304
  "validation_failed",
1270
- `${n} must match ${Lt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1305
+ `${n} must match ${Mt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1271
1306
  );
1272
1307
  }
1273
1308
 
1274
1309
  // src/usage.ts
1275
- function Ut(n) {
1310
+ function qt(n) {
1276
1311
  return {
1277
1312
  /**
1278
1313
  * Reporta consumo metered de um resource. Hit no endpoint canônico
@@ -1288,17 +1323,17 @@ function Ut(n) {
1288
1323
  */
1289
1324
  async report(e, t = 1, r) {
1290
1325
  if (!e || typeof e != "string")
1291
- throw new l("validation_failed", "resource is required");
1326
+ throw new c("validation_failed", "resource is required");
1292
1327
  if (!Number.isFinite(t) || t <= 0 || !Number.isInteger(t))
1293
- throw new l("validation_failed", "qty must be a positive integer");
1328
+ throw new c("validation_failed", "qty must be a positive integer");
1294
1329
  let o = r?.productId ?? n.productId, i = r?.tenantId ?? n.tenantId;
1295
1330
  if (!o)
1296
- throw new l(
1331
+ throw new c(
1297
1332
  "validation_failed",
1298
1333
  "productId required (pass to options or set on createNeetruClient)"
1299
1334
  );
1300
1335
  if (!i)
1301
- throw new l(
1336
+ throw new c(
1302
1337
  "validation_failed",
1303
1338
  "tenantId required (pass to options or set on createNeetruClient)"
1304
1339
  );
@@ -1311,7 +1346,7 @@ function Ut(n) {
1311
1346
  idempotencyKey: true
1312
1347
  });
1313
1348
  if (!s || s.ok !== true)
1314
- throw new l("invalid_response", "usage.report response missing ok");
1349
+ throw new c("invalid_response", "usage.report response missing ok");
1315
1350
  return {
1316
1351
  ok: true,
1317
1352
  counterId: s.counterId,
@@ -1329,10 +1364,10 @@ function Ut(n) {
1329
1364
  */
1330
1365
  async check(e, t) {
1331
1366
  if (!e || typeof e != "string")
1332
- throw new l("validation_failed", "resource is required");
1367
+ throw new c("validation_failed", "resource is required");
1333
1368
  let r = t?.productId ?? n.productId, o = t?.tenantId ?? n.tenantId;
1334
1369
  if (!r || !o)
1335
- throw new l(
1370
+ throw new c(
1336
1371
  "validation_failed",
1337
1372
  "productId and tenantId required (pass to options or set on createNeetruClient)"
1338
1373
  );
@@ -1344,7 +1379,7 @@ function Ut(n) {
1344
1379
  requireAuth: true
1345
1380
  });
1346
1381
  if (!i || typeof i.allowed != "boolean")
1347
- throw new l("invalid_response", "usage.check response missing allowed");
1382
+ throw new c("invalid_response", "usage.check response missing allowed");
1348
1383
  let s = i.behavior ?? (i.reason === "limit_exceeded" ? "readonly" : null);
1349
1384
  return {
1350
1385
  allowed: i.allowed,
@@ -1360,22 +1395,22 @@ function Ut(n) {
1360
1395
  }
1361
1396
 
1362
1397
  // src/support.ts
1363
- I();
1364
- M();
1365
- var je = ["low", "normal", "high", "urgent"], _r = ["open", "pending", "resolved", "closed"], Mt = 50;
1366
- function qt(n) {
1398
+ C();
1399
+ F();
1400
+ var We = ["low", "normal", "high", "urgent"], Tr = ["open", "pending", "resolved", "closed"], Ft = 50;
1401
+ function jt(n) {
1367
1402
  if (!n || typeof n != "object")
1368
- throw new l("invalid_response", "Ticket response is not an object");
1403
+ throw new c("invalid_response", "Ticket response is not an object");
1369
1404
  let e = n;
1370
1405
  if (typeof e.id != "string")
1371
- throw new l("invalid_response", "Ticket missing id");
1406
+ throw new c("invalid_response", "Ticket missing id");
1372
1407
  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;
1373
1408
  return {
1374
1409
  id: e.id,
1375
1410
  subject: typeof e.subject == "string" ? e.subject : "",
1376
1411
  message: typeof e.message == "string" ? e.message : "",
1377
- severity: je.includes(e.severity) ? e.severity : "normal",
1378
- status: _r.includes(e.status) ? e.status : "open",
1412
+ severity: We.includes(e.severity) ? e.severity : "normal",
1413
+ status: Tr.includes(e.status) ? e.status : "open",
1379
1414
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
1380
1415
  updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : void 0,
1381
1416
  productSlug: typeof e.productId == "string" ? e.productId : typeof e.productSlug == "string" ? e.productSlug : void 0,
@@ -1393,48 +1428,48 @@ function qt(n) {
1393
1428
  satisfactionComment: typeof e.satisfactionComment == "string" ? e.satisfactionComment : null
1394
1429
  };
1395
1430
  }
1396
- function de(n) {
1431
+ function ue(n) {
1397
1432
  if (!n || typeof n != "string")
1398
- throw new l("validation_failed", "ticketId is required");
1433
+ throw new c("validation_failed", "ticketId is required");
1399
1434
  }
1400
- function Ft(n) {
1435
+ function $t(n) {
1401
1436
  if (typeof n == "string" && n.length > 2e3)
1402
- throw new l("validation_failed", "comment max 2000 chars");
1437
+ throw new c("validation_failed", "comment max 2000 chars");
1403
1438
  }
1404
- function jt(n, ...e) {
1439
+ function Wt(n, ...e) {
1405
1440
  for (let t of e)
1406
1441
  if (typeof t == "string" && t.length > 0)
1407
1442
  return N("productSlug", t), t;
1408
1443
  if (n.productId)
1409
1444
  return N("productId", n.productId), n.productId;
1410
- throw new l(
1445
+ throw new c(
1411
1446
  "validation_failed",
1412
1447
  "productId required (pass to input.productSlug or set on createNeetruClient)"
1413
1448
  );
1414
1449
  }
1415
- var br = "X-Neetru-End-User-Token", vr = "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.", wr = "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.", kr = "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.", Sr = "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.";
1416
- function $t(n) {
1417
- if (n instanceof l && !(n instanceof V)) {
1450
+ var Rr = "X-Neetru-End-User-Token", Ir = "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.", Cr = "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.", Ar = "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.", Er = "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.";
1451
+ function Bt(n) {
1452
+ if (n instanceof c && !(n instanceof K)) {
1418
1453
  if (n.code === "end_user_token_required")
1419
- throw new V(
1420
- wr,
1454
+ throw new K(
1455
+ Cr,
1421
1456
  "end_user_token_required",
1422
1457
  n.status,
1423
1458
  n.requestId,
1424
1459
  n.correlationId
1425
1460
  );
1426
1461
  if (n.code === "invalid_end_user_token")
1427
- throw new V(
1428
- kr,
1462
+ throw new K(
1463
+ Ar,
1429
1464
  "invalid_end_user_token",
1430
1465
  n.status,
1431
1466
  n.requestId,
1432
1467
  n.correlationId
1433
1468
  );
1434
1469
  if (n.code === "end_user_token_product_mismatch")
1435
- throw new l(
1470
+ throw new c(
1436
1471
  "forbidden",
1437
- Sr,
1472
+ Er,
1438
1473
  n.status,
1439
1474
  n.requestId,
1440
1475
  "end_user_token_product_mismatch",
@@ -1443,10 +1478,10 @@ function $t(n) {
1443
1478
  }
1444
1479
  throw n;
1445
1480
  }
1446
- function Tr(n) {
1447
- return n instanceof l && n.code === "invalid_end_user_token";
1481
+ function Pr(n) {
1482
+ return n instanceof c && n.code === "invalid_end_user_token";
1448
1483
  }
1449
- function Wt(n, e = {}) {
1484
+ function Vt(n, e = {}) {
1450
1485
  async function t() {
1451
1486
  try {
1452
1487
  let a = await e.getEndUserToken?.();
@@ -1464,28 +1499,28 @@ function Wt(n, e = {}) {
1464
1499
  }
1465
1500
  }
1466
1501
  function o(a) {
1467
- return a ? { [br]: a } : {};
1502
+ return a ? { [Rr]: a } : {};
1468
1503
  }
1469
- async function i(a, c) {
1504
+ async function i(a, l) {
1470
1505
  let d = await t();
1471
1506
  if (!d && a && await r() && (d = await t()), !d && a)
1472
- throw new V(vr, "no_signed_in_user");
1507
+ throw new K(Ir, "no_signed_in_user");
1473
1508
  try {
1474
- return await c(o(d));
1509
+ return await l(o(d));
1475
1510
  } catch (u) {
1476
- if (d && Tr(u) && await r()) {
1511
+ if (d && Pr(u) && await r()) {
1477
1512
  let p = await t();
1478
1513
  if (p)
1479
1514
  try {
1480
- return await c(o(p));
1515
+ return await l(o(p));
1481
1516
  } catch (f) {
1482
- $t(f);
1517
+ Bt(f);
1483
1518
  }
1484
1519
  }
1485
- $t(u);
1520
+ Bt(u);
1486
1521
  }
1487
1522
  }
1488
- async function s(a, c = {}) {
1523
+ async function s(a, l = {}) {
1489
1524
  await i(
1490
1525
  true,
1491
1526
  (d) => v(n, {
@@ -1493,7 +1528,7 @@ function Wt(n, e = {}) {
1493
1528
  path: a,
1494
1529
  requireAuth: !0,
1495
1530
  headers: d,
1496
- ...c
1531
+ ...l
1497
1532
  })
1498
1533
  );
1499
1534
  }
@@ -1506,22 +1541,22 @@ function Wt(n, e = {}) {
1506
1541
  */
1507
1542
  async createTicket(a) {
1508
1543
  if (!a || typeof a != "object")
1509
- throw new l("validation_failed", "input is required");
1544
+ throw new c("validation_failed", "input is required");
1510
1545
  if (!a.subject || typeof a.subject != "string")
1511
- throw new l("validation_failed", "subject is required");
1546
+ throw new c("validation_failed", "subject is required");
1512
1547
  if (a.subject.length > 200)
1513
- throw new l("validation_failed", "subject max 200 chars");
1548
+ throw new c("validation_failed", "subject max 200 chars");
1514
1549
  if (!a.message || typeof a.message != "string")
1515
- throw new l("validation_failed", "message is required");
1550
+ throw new c("validation_failed", "message is required");
1516
1551
  if (a.message.length > 1e4)
1517
- throw new l("validation_failed", "message max 10000 chars");
1518
- if (a.severity && !je.includes(a.severity))
1519
- throw new l(
1552
+ throw new c("validation_failed", "message max 10000 chars");
1553
+ if (a.severity && !We.includes(a.severity))
1554
+ throw new c(
1520
1555
  "validation_failed",
1521
- `severity must be one of ${je.join(", ")}`
1556
+ `severity must be one of ${We.join(", ")}`
1522
1557
  );
1523
1558
  let d = {
1524
- productId: jt(n, a.productSlug),
1559
+ productId: Wt(n, a.productSlug),
1525
1560
  subject: a.subject,
1526
1561
  message: a.message,
1527
1562
  severity: a.severity ?? "normal"
@@ -1538,7 +1573,7 @@ function Wt(n, e = {}) {
1538
1573
  headers: f
1539
1574
  })
1540
1575
  ), p = u && typeof u == "object" && "ticket" in u ? u.ticket : u;
1541
- return qt(p);
1576
+ return jt(p);
1542
1577
  },
1543
1578
  /**
1544
1579
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
@@ -1546,23 +1581,23 @@ function Wt(n, e = {}) {
1546
1581
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
1547
1582
  */
1548
1583
  async listMyTickets(a) {
1549
- let c = jt(n, a?.productSlug), d = a?.limit;
1550
- if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Mt))
1551
- throw new l(
1584
+ let l = Wt(n, a?.productSlug), d = a?.limit;
1585
+ if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Ft))
1586
+ throw new c(
1552
1587
  "validation_failed",
1553
- `limit must be an integer 1-${Mt} (Core default 20)`
1588
+ `limit must be an integer 1-${Ft} (Core default 20)`
1554
1589
  );
1555
1590
  let u = await i(
1556
1591
  true,
1557
1592
  (f) => v(n, {
1558
1593
  method: "GET",
1559
1594
  path: "/api/sdk/v1/support/tickets",
1560
- query: { productId: c, limit: d },
1595
+ query: { productId: l, limit: d },
1561
1596
  requireAuth: !0,
1562
1597
  headers: f
1563
1598
  })
1564
1599
  );
1565
- return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(qt);
1600
+ return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(jt);
1566
1601
  },
1567
1602
  /**
1568
1603
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
@@ -1570,7 +1605,7 @@ function Wt(n, e = {}) {
1570
1605
  * `POST /api/sdk/v1/support/tickets/{id}/resolved-seen`.
1571
1606
  */
1572
1607
  async markResolvedSeen(a) {
1573
- de(a), await s(
1608
+ ue(a), await s(
1574
1609
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/resolved-seen`
1575
1610
  );
1576
1611
  },
@@ -1581,7 +1616,7 @@ function Wt(n, e = {}) {
1581
1616
  * `POST /api/sdk/v1/support/tickets/{id}/satisfaction-attempt`.
1582
1617
  */
1583
1618
  async recordSatisfactionAttempt(a) {
1584
- de(a), await s(
1619
+ ue(a), await s(
1585
1620
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/satisfaction-attempt`,
1586
1621
  // Incrementa satisfactionAttempts += 1 no Core — sem idempotencyKey,
1587
1622
  // um retry de rede infla o contador (mesmo padrão de createTicket acima).
@@ -1594,10 +1629,10 @@ function Wt(n, e = {}) {
1594
1629
  */
1595
1630
  async submitSatisfaction(a) {
1596
1631
  if (!a || typeof a != "object")
1597
- throw new l("validation_failed", "input is required");
1598
- if (de(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1599
- throw new l("validation_failed", "rating must be an integer 1-5 or null");
1600
- Ft(a.comment), await s(
1632
+ throw new c("validation_failed", "input is required");
1633
+ if (ue(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1634
+ throw new c("validation_failed", "rating must be an integer 1-5 or null");
1635
+ $t(a.comment), await s(
1601
1636
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a.ticketId)}/satisfaction`,
1602
1637
  {
1603
1638
  body: {
@@ -1613,24 +1648,24 @@ function Wt(n, e = {}) {
1613
1648
  * satisfação/notificação. Endpoint canonical:
1614
1649
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
1615
1650
  */
1616
- async contestTicket(a, c) {
1617
- de(a), Ft(c?.comment), await s(
1651
+ async contestTicket(a, l) {
1652
+ ue(a), $t(l?.comment), await s(
1618
1653
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/contest`,
1619
- { body: { comment: c?.comment ?? void 0 } }
1654
+ { body: { comment: l?.comment ?? void 0 } }
1620
1655
  );
1621
1656
  }
1622
1657
  };
1623
1658
  }
1624
1659
 
1625
1660
  // src/db/client-db.ts
1626
- Z();
1661
+ ee();
1627
1662
 
1628
1663
  // src/db/offline/query-engine.ts
1629
- function Bt(n) {
1664
+ function Kt(n) {
1630
1665
  return n == null ? 0 : typeof n == "number" ? 1 : typeof n == "string" ? 2 : typeof n == "boolean" ? 3 : 4;
1631
1666
  }
1632
- function ee(n, e) {
1633
- let t = Bt(n), r = Bt(e);
1667
+ function te(n, e) {
1668
+ let t = Kt(n), r = Kt(e);
1634
1669
  if (t !== r) return t - r;
1635
1670
  if (n == null) return 0;
1636
1671
  if (typeof n == "number" && typeof e == "number") return n - e;
@@ -1639,7 +1674,7 @@ function ee(n, e) {
1639
1674
  let o = String(n), i = String(e);
1640
1675
  return o < i ? -1 : o > i ? 1 : 0;
1641
1676
  }
1642
- function $e(n, e) {
1677
+ function Be(n, e) {
1643
1678
  let t = e.split("."), r = n;
1644
1679
  for (let o of t) {
1645
1680
  if (r == null || typeof r != "object")
@@ -1648,8 +1683,8 @@ function $e(n, e) {
1648
1683
  }
1649
1684
  return r;
1650
1685
  }
1651
- function Ir(n, e) {
1652
- let t = $e(n, e.field);
1686
+ function Nr(n, e) {
1687
+ let t = Be(n, e.field);
1653
1688
  if (t === void 0) return false;
1654
1689
  let { op: r, value: o } = e;
1655
1690
  switch (r) {
@@ -1658,13 +1693,13 @@ function Ir(n, e) {
1658
1693
  case "!=":
1659
1694
  return t !== o;
1660
1695
  case "<":
1661
- return ee(t, o) < 0;
1696
+ return te(t, o) < 0;
1662
1697
  case "<=":
1663
- return ee(t, o) <= 0;
1698
+ return te(t, o) <= 0;
1664
1699
  case ">":
1665
- return ee(t, o) > 0;
1700
+ return te(t, o) > 0;
1666
1701
  case ">=":
1667
- return ee(t, o) >= 0;
1702
+ return te(t, o) >= 0;
1668
1703
  case "array-contains":
1669
1704
  return Array.isArray(t) && t.includes(o);
1670
1705
  case "in":
@@ -1679,24 +1714,24 @@ function Ir(n, e) {
1679
1714
  );
1680
1715
  }
1681
1716
  }
1682
- function Cr(n, e) {
1683
- return e.every((t) => Ir(n, t));
1717
+ function xr(n, e) {
1718
+ return e.every((t) => Nr(n, t));
1684
1719
  }
1685
- function Ar(n) {
1720
+ function Or(n) {
1686
1721
  return (e, t) => {
1687
1722
  if (n) {
1688
- let r = $e(e.data, n.field), o = $e(t.data, n.field), i = ee(r, o);
1723
+ let r = Be(e.data, n.field), o = Be(t.data, n.field), i = te(r, o);
1689
1724
  if (i !== 0)
1690
1725
  return n.direction === "desc" ? -i : i;
1691
1726
  }
1692
1727
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
1693
1728
  };
1694
1729
  }
1695
- function Er(n, e) {
1730
+ function Lr(n, e) {
1696
1731
  let t = n.findIndex((r) => r.id === e.docId);
1697
1732
  return t === -1 ? n : e.type === "startAfter" ? n.slice(t + 1) : n.slice(0, t);
1698
1733
  }
1699
- var z = class n {
1734
+ var H = class n {
1700
1735
  /**
1701
1736
  * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
1702
1737
  *
@@ -1710,11 +1745,11 @@ var z = class n {
1710
1745
  evaluate(e, t) {
1711
1746
  let r = e.filter((u) => !u.meta.deleted), o = t.where ?? [];
1712
1747
  o.length > 0 && (r = r.filter(
1713
- (u) => Cr(u.data, o)
1748
+ (u) => xr(u.data, o)
1714
1749
  ));
1715
- let i = Ar(t.orderBy), s = [...r].sort(i), a = t.cursor ? Er(s, t.cursor) : s, c = Math.min(t.limit ?? 20, 500);
1750
+ let i = Or(t.orderBy), s = [...r].sort(i), a = t.cursor ? Lr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1716
1751
  return {
1717
- docs: a.slice(0, c).map((u) => ({ id: u.id, data: u.data })),
1752
+ docs: a.slice(0, l).map((u) => ({ id: u.id, data: u.data })),
1718
1753
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
1719
1754
  // tem todos os docs da coleção. É responsabilidade do chamador (LocalStore)
1720
1755
  // injetar o flag de completude baseado nos metadados do query_cache.
@@ -1732,7 +1767,7 @@ var z = class n {
1732
1767
  };
1733
1768
 
1734
1769
  // src/db/offline/local-store.ts
1735
- var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_meta", H = "conflict_log", pe = class {
1770
+ var Mr = 1, B = "documents", V = "mutations", ne = "query_cache", pe = "sync_meta", Q = "conflict_log", fe = class {
1736
1771
  db = null;
1737
1772
  dbName;
1738
1773
  constructor(e) {
@@ -1744,22 +1779,22 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1744
1779
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
1745
1780
  */
1746
1781
  async open() {
1747
- this.db === null && (this.db = await openDB(this.dbName, Dr, {
1782
+ this.db === null && (this.db = await openDB(this.dbName, Mr, {
1748
1783
  upgrade(e) {
1749
- if (!e.objectStoreNames.contains(W)) {
1750
- let t = e.createObjectStore(W, {
1784
+ if (!e.objectStoreNames.contains(B)) {
1785
+ let t = e.createObjectStore(B, {
1751
1786
  keyPath: ["collection", "id"]
1752
1787
  });
1753
1788
  t.createIndex("by_collection", "collection"), t.createIndex("by_collection_state", ["collection", "meta.state"]), t.createIndex("by_updatedAtServer", "meta.updatedAtServer");
1754
1789
  }
1755
- if (!e.objectStoreNames.contains(B)) {
1756
- let t = e.createObjectStore(B, {
1790
+ if (!e.objectStoreNames.contains(V)) {
1791
+ let t = e.createObjectStore(V, {
1757
1792
  keyPath: "mutationId"
1758
1793
  });
1759
1794
  t.createIndex("by_seq", "seq"), t.createIndex("by_status", "status"), t.createIndex("by_doc", ["collection", "docId"]), t.createIndex("by_batch", "batchId");
1760
1795
  }
1761
- if (e.objectStoreNames.contains(te) || e.createObjectStore(te, { keyPath: "queryHash" }), e.objectStoreNames.contains(ue) || e.createObjectStore(ue, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1762
- let t = e.createObjectStore(H, {
1796
+ if (e.objectStoreNames.contains(ne) || e.createObjectStore(ne, { keyPath: "queryHash" }), e.objectStoreNames.contains(pe) || e.createObjectStore(pe, { keyPath: "key" }), !e.objectStoreNames.contains(Q)) {
1797
+ let t = e.createObjectStore(Q, {
1763
1798
  keyPath: "id",
1764
1799
  autoIncrement: true
1765
1800
  });
@@ -1801,14 +1836,14 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1801
1836
  * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
1802
1837
  */
1803
1838
  async getDoc(e, t) {
1804
- return await this.assertOpen().get(W, [e, t]) ?? null;
1839
+ return await this.assertOpen().get(B, [e, t]) ?? null;
1805
1840
  }
1806
1841
  /**
1807
1842
  * Insere ou atualiza um documento na store `documents`.
1808
1843
  * O documento é identificado pelo keyPath composto `[collection, id]`.
1809
1844
  */
1810
1845
  async putDoc(e) {
1811
- await this.assertOpen().put(W, e);
1846
+ await this.assertOpen().put(B, e);
1812
1847
  }
1813
1848
  /**
1814
1849
  * Marca um documento como tombstone (`deleted: true`).
@@ -1816,8 +1851,8 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1816
1851
  * No-op se o documento não existir.
1817
1852
  */
1818
1853
  async deleteDoc(e, t) {
1819
- let r = this.assertOpen(), o = await r.get(W, [e, t]);
1820
- o && await r.put(W, {
1854
+ let r = this.assertOpen(), o = await r.get(B, [e, t]);
1855
+ o && await r.put(B, {
1821
1856
  ...o,
1822
1857
  meta: {
1823
1858
  ...o.meta,
@@ -1833,8 +1868,8 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1833
1868
  * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
1834
1869
  */
1835
1870
  async listDocs(e, t) {
1836
- let o = await this.assertOpen().getAllFromIndex(W, "by_collection", e);
1837
- return z.evaluate(o, t);
1871
+ let o = await this.assertOpen().getAllFromIndex(B, "by_collection", e);
1872
+ return H.evaluate(o, t);
1838
1873
  }
1839
1874
  // ─── Sync meta (key-value) ──────────────────────────────────────────────────
1840
1875
  /**
@@ -1845,14 +1880,14 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1845
1880
  * 'lastFullResyncAt', 'leaderTabId'.
1846
1881
  */
1847
1882
  async getMeta(e) {
1848
- let r = await this.assertOpen().get(ue, e);
1883
+ let r = await this.assertOpen().get(pe, e);
1849
1884
  return r ? r.value : null;
1850
1885
  }
1851
1886
  /**
1852
1887
  * Armazena ou atualiza um valor na store `sync_meta`.
1853
1888
  */
1854
1889
  async setMeta(e, t) {
1855
- await this.assertOpen().put(ue, { key: e, value: t });
1890
+ await this.assertOpen().put(pe, { key: e, value: t });
1856
1891
  }
1857
1892
  // ─── Conflict log ───────────────────────────────────────────────────────────
1858
1893
  /**
@@ -1860,7 +1895,7 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1860
1895
  * O `id` é autoIncrement — não deve ser fornecido pelo chamador.
1861
1896
  */
1862
1897
  async appendConflict(e) {
1863
- let r = await this.assertOpen().add(H, e);
1898
+ let r = await this.assertOpen().add(Q, e);
1864
1899
  return { ...e, id: r };
1865
1900
  }
1866
1901
  /**
@@ -1868,15 +1903,15 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1868
1903
  * Filtra por `delivered` se a opção for fornecida.
1869
1904
  */
1870
1905
  async listConflicts(e) {
1871
- let r = await this.assertOpen().getAll(H);
1906
+ let r = await this.assertOpen().getAll(Q);
1872
1907
  return e?.delivered !== void 0 ? r.filter((o) => o.delivered === e.delivered) : r;
1873
1908
  }
1874
1909
  /**
1875
1910
  * Marca um registro do `conflict_log` como entregue ao produto.
1876
1911
  */
1877
1912
  async markConflictDelivered(e) {
1878
- let t = this.assertOpen(), r = await t.get(H, e);
1879
- r && await t.put(H, { ...r, delivered: true });
1913
+ let t = this.assertOpen(), r = await t.get(Q, e);
1914
+ r && await t.put(Q, { ...r, delivered: true });
1880
1915
  }
1881
1916
  // ─── Mutations (acessores usados pelo MutationQueue) ────────────────────────
1882
1917
  /**
@@ -1884,13 +1919,13 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1884
1919
  * Key: `mutationId`.
1885
1920
  */
1886
1921
  async putMutation(e) {
1887
- await this.assertOpen().put(B, e);
1922
+ await this.assertOpen().put(V, e);
1888
1923
  }
1889
1924
  /**
1890
1925
  * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
1891
1926
  */
1892
1927
  async getMutation(e) {
1893
- return await this.assertOpen().get(B, e) ?? null;
1928
+ return await this.assertOpen().get(V, e) ?? null;
1894
1929
  }
1895
1930
  /**
1896
1931
  * Lista mutações com filtros opcionais.
@@ -1898,14 +1933,14 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1898
1933
  */
1899
1934
  async listMutations(e) {
1900
1935
  let t = this.assertOpen(), r;
1901
- return e?.status !== void 0 ? r = await t.getAllFromIndex(B, "by_status", e.status) : e?.collection !== void 0 && e.docId !== void 0 ? r = await t.getAllFromIndex(B, "by_doc", [e.collection, e.docId]) : r = await t.getAllFromIndex(B, "by_seq"), r.sort((o, i) => o.seq - i.seq);
1936
+ return e?.status !== void 0 ? r = await t.getAllFromIndex(V, "by_status", e.status) : e?.collection !== void 0 && e.docId !== void 0 ? r = await t.getAllFromIndex(V, "by_doc", [e.collection, e.docId]) : r = await t.getAllFromIndex(V, "by_seq"), r.sort((o, i) => o.seq - i.seq);
1902
1937
  }
1903
1938
  /**
1904
1939
  * Remove uma mutação pelo `mutationId`.
1905
1940
  * No-op se não existir.
1906
1941
  */
1907
1942
  async deleteMutation(e) {
1908
- await this.assertOpen().delete(B, e);
1943
+ await this.assertOpen().delete(V, e);
1909
1944
  }
1910
1945
  // ─── Collection discovery ────────────────────────────────────────────────────
1911
1946
  /**
@@ -1918,7 +1953,7 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1918
1953
  * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
1919
1954
  */
1920
1955
  async listCollections() {
1921
- let t = await this.assertOpen().getAllFromIndex(W, "by_collection"), r = /* @__PURE__ */ new Set();
1956
+ let t = await this.assertOpen().getAllFromIndex(B, "by_collection"), r = /* @__PURE__ */ new Set();
1922
1957
  for (let o of t)
1923
1958
  r.add(o.collection);
1924
1959
  return Array.from(r);
@@ -1928,24 +1963,24 @@ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1928
1963
  * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
1929
1964
  */
1930
1965
  async getQueryCache(e) {
1931
- return await this.assertOpen().get(te, e) ?? null;
1966
+ return await this.assertOpen().get(ne, e) ?? null;
1932
1967
  }
1933
1968
  /**
1934
1969
  * Insere ou atualiza uma entrada de `query_cache`.
1935
1970
  */
1936
1971
  async putQueryCache(e) {
1937
- await this.assertOpen().put(te, e);
1972
+ await this.assertOpen().put(ne, e);
1938
1973
  }
1939
1974
  /**
1940
1975
  * Remove uma entrada de `query_cache` pelo queryHash.
1941
1976
  */
1942
1977
  async deleteQueryCache(e) {
1943
- await this.assertOpen().delete(te, e);
1978
+ await this.assertOpen().delete(ne, e);
1944
1979
  }
1945
1980
  };
1946
1981
 
1947
1982
  // src/db/offline/memory-store.ts
1948
- var fe = class {
1983
+ var me = class {
1949
1984
  // store `documents` — key: `${collection}\0${id}`
1950
1985
  _docs = /* @__PURE__ */ new Map();
1951
1986
  // store `mutations` — key: mutationId
@@ -1993,7 +2028,7 @@ var fe = class {
1993
2028
  let r = Array.from(this._docs.values()).filter(
1994
2029
  (o) => o.collection === e
1995
2030
  );
1996
- return z.evaluate(r, t);
2031
+ return H.evaluate(r, t);
1997
2032
  }
1998
2033
  // ─── Sync meta ──────────────────────────────────────────────────────────────
1999
2034
  async getMeta(e) {
@@ -2050,13 +2085,13 @@ var fe = class {
2050
2085
  };
2051
2086
 
2052
2087
  // src/db/offline/mutation-queue.ts
2053
- function We() {
2088
+ function Ve() {
2054
2089
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (n) => {
2055
2090
  let e = Math.random() * 16 | 0;
2056
2091
  return (n === "x" ? e : e & 3 | 8).toString(16);
2057
2092
  });
2058
2093
  }
2059
- var me = class {
2094
+ var he = class {
2060
2095
  store;
2061
2096
  /**
2062
2097
  * Ponteiro de sequência local.
@@ -2152,18 +2187,18 @@ var me = class {
2152
2187
  * Atômico: a persistência final é uma única operação putMutation.
2153
2188
  */
2154
2189
  async enqueue(e) {
2155
- let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, c = e.docId ?? (r === "add" ? We() : "");
2190
+ let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? Ve() : "");
2156
2191
  await this.syncSeq();
2157
- let u = (await this.store.listMutations({ collection: t, docId: c })).filter((_) => _.status === "queued").sort((_, b) => b.seq - _.seq)[0];
2192
+ let u = (await this.store.listMutations({ collection: t, docId: l })).filter((h) => h.status === "queued").sort((h, y) => y.seq - h.seq)[0];
2158
2193
  if (u !== void 0) {
2159
- let _ = this.tryCoalesce(u, r, o, s, a);
2160
- if (_ !== null) {
2161
- if ("removed" in _)
2194
+ let h = this.tryCoalesce(u, r, o, s, a);
2195
+ if (h !== null) {
2196
+ if ("removed" in h)
2162
2197
  return await this.store.deleteMutation(u.mutationId), {
2163
2198
  seq: u.seq,
2164
- mutationId: We(),
2199
+ mutationId: Ve(),
2165
2200
  collection: t,
2166
- docId: c,
2201
+ docId: l,
2167
2202
  op: "remove",
2168
2203
  payload: null,
2169
2204
  baseVersion: i,
@@ -2173,15 +2208,15 @@ var me = class {
2173
2208
  status: "queued",
2174
2209
  batchId: s
2175
2210
  };
2176
- let { coalesced: b } = _;
2177
- return await this.store.putMutation(b), b;
2211
+ let { coalesced: y } = h;
2212
+ return await this.store.putMutation(y), y;
2178
2213
  }
2179
2214
  }
2180
2215
  let f = {
2181
2216
  seq: this.nextSeq(),
2182
- mutationId: We(),
2217
+ mutationId: Ve(),
2183
2218
  collection: t,
2184
- docId: c,
2219
+ docId: l,
2185
2220
  op: r,
2186
2221
  payload: o,
2187
2222
  baseVersion: i,
@@ -2292,45 +2327,45 @@ var me = class {
2292
2327
  };
2293
2328
 
2294
2329
  // src/db/field-value.ts
2295
- var Vt = "__neetru__";
2296
- function Q(n) {
2297
- return typeof n == "object" && n !== null && Vt in n && typeof n[Vt] == "string";
2330
+ var zt = "__neetru__";
2331
+ function G(n) {
2332
+ return typeof n == "object" && n !== null && zt in n && typeof n[zt] == "string";
2298
2333
  }
2299
- function Nr(n) {
2300
- return Q(n) && n.__neetru__ === "serverTimestamp";
2334
+ function qr(n) {
2335
+ return G(n) && n.__neetru__ === "serverTimestamp";
2301
2336
  }
2302
- function xr(n) {
2303
- return Q(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2337
+ function Fr(n) {
2338
+ return G(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2304
2339
  }
2305
- function Or(n, e) {
2306
- return Nr(n) ? Date.now() : xr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2340
+ function jr(n, e) {
2341
+ return qr(n) ? Date.now() : Fr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2307
2342
  }
2308
- function K(n, e) {
2343
+ function z(n, e) {
2309
2344
  let t = false, r = {};
2310
2345
  for (let [o, i] of Object.entries(n))
2311
- Q(i) ? (t = true, r[o] = Or(i, e?.[o])) : r[o] = i;
2346
+ G(i) ? (t = true, r[o] = jr(i, e?.[o])) : r[o] = i;
2312
2347
  return t ? r : n;
2313
2348
  }
2314
- function Be(n) {
2349
+ function Ke(n) {
2315
2350
  for (let e of Object.values(n))
2316
- if (Q(e)) return true;
2351
+ if (G(e)) return true;
2317
2352
  return false;
2318
2353
  }
2319
2354
 
2320
2355
  // src/db/offline/sync-engine.ts
2321
- var Lr = 8, Ur = 1e3, Mr = 300 * 1e3, Ve = "truncatedCollections";
2322
- function qr(n) {
2323
- return n !== null && Be(n);
2356
+ var $r = 8, Wr = 1e3, Br = 300 * 1e3, ze = "truncatedCollections";
2357
+ function Vr(n) {
2358
+ return n !== null && Ke(n);
2324
2359
  }
2325
- function Fr(n) {
2360
+ function Kr(n) {
2326
2361
  if (n === null) return null;
2327
- if (!Be(n)) return n;
2362
+ if (!Ke(n)) return n;
2328
2363
  let e = {};
2329
2364
  for (let [t, r] of Object.entries(n))
2330
- Q(r) || (e[t] = r);
2365
+ G(r) || (e[t] = r);
2331
2366
  return e;
2332
2367
  }
2333
- var he = class {
2368
+ var ge = class {
2334
2369
  _store;
2335
2370
  _queue;
2336
2371
  _resolver;
@@ -2474,16 +2509,16 @@ var he = class {
2474
2509
  try {
2475
2510
  t = await this._transport.pushMutations(e);
2476
2511
  } catch (s) {
2477
- let a = s instanceof Error ? s.message : String(s), c = [], [d, ...u] = e;
2478
- await this._retryOrDeadLetter(d, a, c);
2512
+ let a = s instanceof Error ? s.message : String(s), l = [], [d, ...u] = e;
2513
+ await this._retryOrDeadLetter(d, a, l);
2479
2514
  for (let p of u)
2480
2515
  await this._queue.requeueInflight(p.mutationId);
2481
- return c.length > 0 && this._bus.emit(c), this._refreshPendingWrites().catch(() => {
2516
+ return l.length > 0 && this._bus.emit(l), this._refreshPendingWrites().catch(() => {
2482
2517
  }), false;
2483
2518
  }
2484
2519
  let r = [];
2485
2520
  for (let s of t.results) {
2486
- let a = e.find((c) => c.mutationId === s.mutationId);
2521
+ let a = e.find((l) => l.mutationId === s.mutationId);
2487
2522
  a && (s.outcome === "confirmed" ? (await this._queue.markApplied(a.mutationId), await this._applySyncedDoc(
2488
2523
  a.collection,
2489
2524
  a.docId,
@@ -2501,8 +2536,8 @@ var he = class {
2501
2536
  "partial_push: muta\xE7\xE3o n\xE3o processada no lote",
2502
2537
  r
2503
2538
  );
2504
- for (let c of a)
2505
- await this._queue.requeueInflight(c.mutationId);
2539
+ for (let l of a)
2540
+ await this._queue.requeueInflight(l.mutationId);
2506
2541
  }
2507
2542
  return r.length > 0 && this._bus.emit(r), i.length === 0;
2508
2543
  }
@@ -2524,13 +2559,13 @@ var he = class {
2524
2559
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
2525
2560
  return;
2526
2561
  }
2527
- let d = Fr(i.payload) ?? a?.data ?? {}, u = {
2562
+ let d = Kr(i.payload) ?? a?.data ?? {}, u = {
2528
2563
  collection: e,
2529
2564
  id: t,
2530
2565
  data: i.op === "update" ? { ...a?.data ?? {}, ...d } : (
2531
2566
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2532
2567
  // é a fonte de verdade até o pull; senão usa o payload literal.
2533
- qr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2568
+ Vr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2534
2569
  ),
2535
2570
  meta: {
2536
2571
  serverVersion: r,
@@ -2577,7 +2612,7 @@ var he = class {
2577
2612
  deleted: false,
2578
2613
  ownerId: null
2579
2614
  }
2580
- }, c = this._resolver.resolve(
2615
+ }, l = this._resolver.resolve(
2581
2616
  s,
2582
2617
  i,
2583
2618
  e
@@ -2591,7 +2626,7 @@ var he = class {
2591
2626
  detectedAt: Date.now(),
2592
2627
  delivered: false
2593
2628
  };
2594
- await this._store.appendConflict(c);
2629
+ await this._store.appendConflict(l);
2595
2630
  let d = {
2596
2631
  collection: e.collection,
2597
2632
  id: e.docId,
@@ -2634,7 +2669,7 @@ var he = class {
2634
2669
  ...i.meta,
2635
2670
  serverVersion: t.serverVersion ?? i.meta.serverVersion
2636
2671
  }
2637
- } : null, c = this._resolver.resolveRejected(
2672
+ } : null, l = this._resolver.resolveRejected(
2638
2673
  i,
2639
2674
  s,
2640
2675
  e,
@@ -2649,7 +2684,7 @@ var he = class {
2649
2684
  detectedAt: Date.now(),
2650
2685
  delivered: false
2651
2686
  };
2652
- await this._store.appendConflict(c), t.serverData ? (await this._store.putDoc({
2687
+ await this._store.appendConflict(l), t.serverData ? (await this._store.putDoc({
2653
2688
  ...i,
2654
2689
  data: t.serverData,
2655
2690
  meta: {
@@ -2683,7 +2718,7 @@ var he = class {
2683
2718
  * pending do doc no cache + registra `lastError`/dispara `onError`.
2684
2719
  */
2685
2720
  async _retryOrDeadLetter(e, t, r) {
2686
- if (e.attempts + 1 < Lr) {
2721
+ if (e.attempts + 1 < $r) {
2687
2722
  await this._queue.markRetry(e.mutationId, t);
2688
2723
  return;
2689
2724
  }
@@ -2724,7 +2759,7 @@ var he = class {
2724
2759
  }
2725
2760
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
2726
2761
  _backoffDelayMs(e) {
2727
- return Math.min(Ur * 2 ** (e - 1), Mr);
2762
+ return Math.min(Wr * 2 ** (e - 1), Br);
2728
2763
  }
2729
2764
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
2730
2765
  /**
@@ -2757,14 +2792,14 @@ var he = class {
2757
2792
  let r = [];
2758
2793
  await this._applyServerDocs(t.docs, r, true);
2759
2794
  let o = t.truncatedCollections ?? [], i = new Set(o);
2760
- await this._store.setMeta(Ve, o);
2795
+ await this._store.setMeta(ze, o);
2761
2796
  let s = new Set(
2762
2797
  t.docs.map((a) => `${a.collection}::${a.id}`)
2763
2798
  );
2764
2799
  for (let a of e) {
2765
2800
  if (i.has(a)) continue;
2766
- let c = await this._store.listDocs(a, {});
2767
- for (let { id: d } of c.docs) {
2801
+ let l = await this._store.listDocs(a, {});
2802
+ for (let { id: d } of l.docs) {
2768
2803
  let u = `${a}::${d}`;
2769
2804
  if (!s.has(u)) {
2770
2805
  let p = await this._store.getDoc(a, d);
@@ -2814,7 +2849,7 @@ var he = class {
2814
2849
  continue;
2815
2850
  }
2816
2851
  if (i && i.meta.state === "pending") {
2817
- let c = {
2852
+ let l = {
2818
2853
  collection: o.collection,
2819
2854
  id: o.id,
2820
2855
  data: o.data,
@@ -2831,7 +2866,7 @@ var he = class {
2831
2866
  (p) => p.collection === o.collection && p.docId === o.id
2832
2867
  );
2833
2868
  if (u) {
2834
- let p = this._resolver.resolve(i, c, u);
2869
+ let p = this._resolver.resolve(i, l, u);
2835
2870
  p.conflictRecord && await this._store.appendConflict(p.conflictRecord), await this._store.putDoc({
2836
2871
  ...i,
2837
2872
  meta: { ...i.meta, state: "conflict" }
@@ -2976,10 +3011,10 @@ var he = class {
2976
3011
  };
2977
3012
 
2978
3013
  // src/db/offline/conflict-resolver.ts
2979
- function Kt(n, e) {
3014
+ function Ht(n, e) {
2980
3015
  return e === null ? false : n === null ? true : e > n;
2981
3016
  }
2982
- var ge = class n {
3017
+ var ye = class n {
2983
3018
  /**
2984
3019
  * Resolve um conflito com base na operação da mutação (auto-dispatch).
2985
3020
  *
@@ -3013,7 +3048,7 @@ var ge = class n {
3013
3048
  resolvedData: t.data,
3014
3049
  conflictRecord: null
3015
3050
  };
3016
- if (!Kt(
3051
+ if (!Ht(
3017
3052
  e.meta.updatedAtServer,
3018
3053
  t.meta.updatedAtServer
3019
3054
  ))
@@ -3060,7 +3095,7 @@ var ge = class n {
3060
3095
  let i = t.data;
3061
3096
  if (e === null)
3062
3097
  return { outcome: "no_conflict", resolvedData: { ...i, ...r.payload ?? {} }, conflictRecord: null };
3063
- if (!Kt(
3098
+ if (!Ht(
3064
3099
  e.meta.updatedAtServer,
3065
3100
  t.meta.updatedAtServer
3066
3101
  ))
@@ -3068,7 +3103,7 @@ var ge = class n {
3068
3103
  let a = {};
3069
3104
  for (let d of o)
3070
3105
  a[d] = e.data[d];
3071
- let c = {
3106
+ let l = {
3072
3107
  collection: r.collection,
3073
3108
  docId: r.docId,
3074
3109
  mutationId: r.mutationId,
@@ -3081,7 +3116,7 @@ var ge = class n {
3081
3116
  return {
3082
3117
  outcome: "server_wins",
3083
3118
  resolvedData: i,
3084
- conflictRecord: c
3119
+ conflictRecord: l
3085
3120
  };
3086
3121
  }
3087
3122
  /**
@@ -3138,10 +3173,10 @@ var ge = class n {
3138
3173
  };
3139
3174
 
3140
3175
  // src/db/offline/change-bus.ts
3141
- function jr(n) {
3176
+ function zr(n) {
3142
3177
  return `${n.collection}::${n.doc.id}`;
3143
3178
  }
3144
- var ye = class {
3179
+ var _e = class {
3145
3180
  /** Listeners filtrados por coleção. */
3146
3181
  _collectionListeners = /* @__PURE__ */ new Map();
3147
3182
  /** Listeners globais (todas as coleções). */
@@ -3186,15 +3221,15 @@ var ye = class {
3186
3221
  if (e.length === 0) return;
3187
3222
  let t = /* @__PURE__ */ new Map();
3188
3223
  for (let i of e)
3189
- t.set(jr(i), i);
3224
+ t.set(zr(i), i);
3190
3225
  let r = Array.from(t.values()), o = /* @__PURE__ */ new Map();
3191
3226
  for (let i of r)
3192
3227
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
3193
3228
  for (let [i, s] of o) {
3194
3229
  let a = this._collectionListeners.get(i);
3195
3230
  if (a)
3196
- for (let c of a)
3197
- this._safeCall(c, s);
3231
+ for (let l of a)
3232
+ this._safeCall(l, s);
3198
3233
  }
3199
3234
  for (let i of this._globalListeners)
3200
3235
  this._safeCall(i, r);
@@ -3225,7 +3260,7 @@ var ye = class {
3225
3260
  };
3226
3261
 
3227
3262
  // src/db/offline/connectivity-monitor.ts
3228
- var _e = class {
3263
+ var be = class {
3229
3264
  _state;
3230
3265
  _listeners = /* @__PURE__ */ new Set();
3231
3266
  _nav;
@@ -3327,7 +3362,7 @@ var _e = class {
3327
3362
  };
3328
3363
 
3329
3364
  // src/db/offline/tab-coordinator.ts
3330
- var ne = class {
3365
+ var re = class {
3331
3366
  _lockName;
3332
3367
  _channelName;
3333
3368
  _lockManager;
@@ -3504,26 +3539,26 @@ var ne = class {
3504
3539
  };
3505
3540
 
3506
3541
  // src/db/collection-ref.ts
3507
- Z();
3508
- function $r() {
3542
+ ee();
3543
+ function Hr() {
3509
3544
  return typeof indexedDB > "u" || typeof window > "u";
3510
3545
  }
3511
- var zt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3512
- function Wr(n) {
3513
- if (!zt.test(n))
3514
- throw new y(
3546
+ var Qt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3547
+ function Qr(n) {
3548
+ if (!Qt.test(n))
3549
+ throw new _(
3515
3550
  "db_invalid_query",
3516
- `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${zt}.`
3551
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${Qt}.`
3517
3552
  );
3518
3553
  }
3519
- function G(n, e = "id") {
3554
+ function J(n, e = "id") {
3520
3555
  if (!n || typeof n != "string" || n.trim() === "")
3521
- throw new y(
3556
+ throw new _(
3522
3557
  "db_invalid_query",
3523
3558
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
3524
3559
  );
3525
3560
  }
3526
- function Br(n) {
3561
+ function Gr(n) {
3527
3562
  let e = {};
3528
3563
  if (n?.where && (e.where = n.where.map((t) => ({
3529
3564
  field: t.field,
@@ -3540,12 +3575,12 @@ function Br(n) {
3540
3575
  }
3541
3576
  return e;
3542
3577
  }
3543
- function Vr(n, e) {
3578
+ function Jr(n, e) {
3544
3579
  if (n.length < e) return null;
3545
3580
  let t = n[n.length - 1];
3546
3581
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
3547
3582
  }
3548
- var Ke = class {
3583
+ var He = class {
3549
3584
  constructor(e, t, r, o, i, s) {
3550
3585
  this._collection = e;
3551
3586
  this._store = t;
@@ -3587,10 +3622,10 @@ var Ke = class {
3587
3622
  }
3588
3623
  /** Constrói um DbListResult para a coleção com query opcional. */
3589
3624
  async _buildListResult(e) {
3590
- let t = Br(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 = Vr(o.docs, r), d = await this._store.getMeta(Ve), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3625
+ let t = Gr(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), l = Jr(o.docs, r), d = await this._store.getMeta(ze), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3591
3626
  return {
3592
- docs: o.docs.map((_) => ({ id: _.id, data: _.data })),
3593
- nextCursor: c,
3627
+ docs: o.docs.map((h) => ({ id: h.id, data: h.data })),
3628
+ nextCursor: l,
3594
3629
  fromCache: f,
3595
3630
  stale: p,
3596
3631
  hasPendingWrites: i,
@@ -3600,13 +3635,13 @@ var Ke = class {
3600
3635
  }
3601
3636
  // ── CRUD ────────────────────────────────────────────────────────────────────
3602
3637
  async get(e) {
3603
- return G(e), this._buildGetResult(e);
3638
+ return J(e), this._buildGetResult(e);
3604
3639
  }
3605
3640
  async list(e) {
3606
3641
  return this._buildListResult(e);
3607
3642
  }
3608
3643
  async add(e) {
3609
- let t = e, r = K(t, void 0), o = await this._queue.enqueue({
3644
+ let t = e, r = z(t, void 0), o = await this._queue.enqueue({
3610
3645
  collection: this._collection,
3611
3646
  op: "add",
3612
3647
  payload: t,
@@ -3633,8 +3668,8 @@ var Ke = class {
3633
3668
  }]), { ok: true, id: i };
3634
3669
  }
3635
3670
  async set(e, t) {
3636
- G(e);
3637
- let r = await this._store.getDoc(this._collection, e), o = t, i = K(o, void 0), s = await this._queue.enqueue({
3671
+ J(e);
3672
+ let r = await this._store.getDoc(this._collection, e), o = t, i = z(o, void 0), s = await this._queue.enqueue({
3638
3673
  collection: this._collection,
3639
3674
  docId: e,
3640
3675
  op: "set",
@@ -3662,8 +3697,8 @@ var Ke = class {
3662
3697
  }]), { ok: true };
3663
3698
  }
3664
3699
  async update(e, t, r) {
3665
- G(e);
3666
- let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = K(i, s), c = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3700
+ J(e);
3701
+ let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = z(i, s), l = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3667
3702
  collection: this._collection,
3668
3703
  docId: e,
3669
3704
  op: "update",
@@ -3676,7 +3711,7 @@ var Ke = class {
3676
3711
  return await this._store.putDoc({
3677
3712
  collection: this._collection,
3678
3713
  id: e,
3679
- data: c,
3714
+ data: l,
3680
3715
  meta: {
3681
3716
  serverVersion: o?.meta.serverVersion ?? null,
3682
3717
  updatedAtServer: o?.meta.updatedAtServer ?? null,
@@ -3692,11 +3727,11 @@ var Ke = class {
3692
3727
  }), this._bus.emit([{
3693
3728
  type: "modified",
3694
3729
  collection: this._collection,
3695
- doc: { id: e, data: c }
3730
+ doc: { id: e, data: l }
3696
3731
  }]), { ok: true };
3697
3732
  }
3698
3733
  async remove(e) {
3699
- G(e);
3734
+ J(e);
3700
3735
  let t = await this._store.getDoc(this._collection, e);
3701
3736
  return !t || t.meta.deleted, await this._queue.enqueue({
3702
3737
  collection: this._collection,
@@ -3716,13 +3751,13 @@ var Ke = class {
3716
3751
  for (let o of e) {
3717
3752
  let i = this._collection;
3718
3753
  if (o.kind === "add") {
3719
- let s = o.data, a = K(s, void 0), c = await this._queue.enqueue({
3754
+ let s = o.data, a = z(s, void 0), l = await this._queue.enqueue({
3720
3755
  collection: i,
3721
3756
  op: "add",
3722
3757
  payload: s,
3723
3758
  baseVersion: null,
3724
3759
  batchId: t
3725
- }), d = c.docId;
3760
+ }), d = l.docId;
3726
3761
  await this._store.putDoc({
3727
3762
  collection: i,
3728
3763
  id: d,
@@ -3732,18 +3767,18 @@ var Ke = class {
3732
3767
  updatedAtServer: null,
3733
3768
  updatedAtLocal: Date.now(),
3734
3769
  state: "pending",
3735
- pendingMutationIds: [c.mutationId],
3770
+ pendingMutationIds: [l.mutationId],
3736
3771
  deleted: false,
3737
3772
  ownerId: null
3738
3773
  }
3739
3774
  }), r.push({ type: "added", collection: i, doc: { id: d, data: a } });
3740
3775
  } else if (o.kind === "set") {
3741
- let s = o.id, a = o.data, c = await this._store.getDoc(i, s), d = K(a, void 0), u = await this._queue.enqueue({
3776
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = z(a, void 0), u = await this._queue.enqueue({
3742
3777
  collection: i,
3743
3778
  docId: s,
3744
3779
  op: "set",
3745
3780
  payload: a,
3746
- baseVersion: c?.meta.serverVersion ?? null,
3781
+ baseVersion: l?.meta.serverVersion ?? null,
3747
3782
  batchId: t
3748
3783
  });
3749
3784
  await this._store.putDoc({
@@ -3751,8 +3786,8 @@ var Ke = class {
3751
3786
  id: s,
3752
3787
  data: d,
3753
3788
  meta: {
3754
- serverVersion: c?.meta.serverVersion ?? null,
3755
- updatedAtServer: c?.meta.updatedAtServer ?? null,
3789
+ serverVersion: l?.meta.serverVersion ?? null,
3790
+ updatedAtServer: l?.meta.updatedAtServer ?? null,
3756
3791
  updatedAtLocal: Date.now(),
3757
3792
  state: "pending",
3758
3793
  pendingMutationIds: [u.mutationId],
@@ -3760,17 +3795,17 @@ var Ke = class {
3760
3795
  ownerId: null
3761
3796
  }
3762
3797
  }), r.push({
3763
- type: c && !c.meta.deleted ? "modified" : "added",
3798
+ type: l && !l.meta.deleted ? "modified" : "added",
3764
3799
  collection: i,
3765
3800
  doc: { id: s, data: d }
3766
3801
  });
3767
3802
  } else if (o.kind === "update") {
3768
- let s = o.id, a = o.data, c = await this._store.getDoc(i, s), d = c?.meta.deleted ? void 0 : c?.data, u = K(a, d), p = { ...c?.data ?? {}, ...u }, f = await this._queue.enqueue({
3803
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = l?.meta.deleted ? void 0 : l?.data, u = z(a, d), p = { ...l?.data ?? {}, ...u }, f = await this._queue.enqueue({
3769
3804
  collection: i,
3770
3805
  docId: s,
3771
3806
  op: "update",
3772
3807
  payload: a,
3773
- baseVersion: c?.meta.serverVersion ?? null,
3808
+ baseVersion: l?.meta.serverVersion ?? null,
3774
3809
  batchId: t,
3775
3810
  // bug_0273e4dd: propaga merge-upsert (writeBatch.set(merge) cria-se-ausente).
3776
3811
  upsert: o.upsert
@@ -3780,16 +3815,16 @@ var Ke = class {
3780
3815
  id: s,
3781
3816
  data: p,
3782
3817
  meta: {
3783
- serverVersion: c?.meta.serverVersion ?? null,
3784
- updatedAtServer: c?.meta.updatedAtServer ?? null,
3818
+ serverVersion: l?.meta.serverVersion ?? null,
3819
+ updatedAtServer: l?.meta.updatedAtServer ?? null,
3785
3820
  updatedAtLocal: Date.now(),
3786
3821
  state: "pending",
3787
3822
  pendingMutationIds: [
3788
- ...c?.meta.pendingMutationIds ?? [],
3823
+ ...l?.meta.pendingMutationIds ?? [],
3789
3824
  f.mutationId
3790
3825
  ],
3791
3826
  deleted: false,
3792
- ownerId: c?.meta.ownerId ?? null
3827
+ ownerId: l?.meta.ownerId ?? null
3793
3828
  }
3794
3829
  }), r.push({ type: "modified", collection: i, doc: { id: s, data: p } });
3795
3830
  } else if (o.kind === "remove") {
@@ -3808,7 +3843,7 @@ var Ke = class {
3808
3843
  }
3809
3844
  // ── Realtime ─────────────────────────────────────────────────────────────────
3810
3845
  onDoc(e, t) {
3811
- return G(e), this._buildGetResult(e).then((r) => {
3846
+ return J(e), this._buildGetResult(e).then((r) => {
3812
3847
  t(r ? r.docs[0]?.data ?? null : null);
3813
3848
  }).catch(() => t(null)), this._bus.subscribe(this._collection, (r) => {
3814
3849
  let o = r.find((i) => i.doc.id === e);
@@ -3820,11 +3855,11 @@ var Ke = class {
3820
3855
  });
3821
3856
  let r = this._bus.subscribe(this._collection, async (s) => {
3822
3857
  try {
3823
- let a = await this._buildListResult(e), c = s.map((d) => ({
3858
+ let a = await this._buildListResult(e), l = s.map((d) => ({
3824
3859
  type: d.type,
3825
3860
  doc: { id: d.doc.id, data: d.doc.data }
3826
3861
  }));
3827
- t({ ...a, changes: c });
3862
+ t({ ...a, changes: l });
3828
3863
  } catch {
3829
3864
  }
3830
3865
  }), o = this._engine.onSyncStateChange(async () => {
@@ -3838,15 +3873,15 @@ var Ke = class {
3838
3873
  this._collection,
3839
3874
  async (s, a) => {
3840
3875
  if (!a)
3841
- for (let c of s)
3842
- c.type === "removed" || c.data === null ? (await this._store.deleteDoc(this._collection, c.docId), this._bus.emit([{
3876
+ for (let l of s)
3877
+ l.type === "removed" || l.data === null ? (await this._store.deleteDoc(this._collection, l.docId), this._bus.emit([{
3843
3878
  type: "removed",
3844
3879
  collection: this._collection,
3845
- doc: { id: c.docId, data: {} }
3880
+ doc: { id: l.docId, data: {} }
3846
3881
  }])) : (await this._store.putDoc({
3847
3882
  collection: this._collection,
3848
- id: c.docId,
3849
- data: c.data,
3883
+ id: l.docId,
3884
+ data: l.data,
3850
3885
  meta: {
3851
3886
  serverVersion: `rt_${Date.now()}`,
3852
3887
  updatedAtServer: Date.now(),
@@ -3857,9 +3892,9 @@ var Ke = class {
3857
3892
  ownerId: null
3858
3893
  }
3859
3894
  }), this._bus.emit([{
3860
- type: c.type,
3895
+ type: l.type,
3861
3896
  collection: this._collection,
3862
- doc: { id: c.docId, data: c.data }
3897
+ doc: { id: l.docId, data: l.data }
3863
3898
  }]));
3864
3899
  }
3865
3900
  )), () => {
@@ -3867,7 +3902,7 @@ var Ke = class {
3867
3902
  };
3868
3903
  }
3869
3904
  doc(e) {
3870
- G(e);
3905
+ J(e);
3871
3906
  let t = this;
3872
3907
  return {
3873
3908
  get id() {
@@ -3894,14 +3929,14 @@ var Ke = class {
3894
3929
  onSnapshot(r) {
3895
3930
  t._buildGetResult(e).then((s) => r(s)).catch(() => r(null));
3896
3931
  let o = t._bus.subscribe(t._collection, async (s) => {
3897
- let a = s.find((c) => c.doc.id === e);
3932
+ let a = s.find((l) => l.doc.id === e);
3898
3933
  if (a)
3899
3934
  try {
3900
3935
  if (a.type === "removed")
3901
3936
  r(null);
3902
3937
  else {
3903
- let c = await t._buildGetResult(e);
3904
- r(c);
3938
+ let l = await t._buildGetResult(e);
3939
+ r(l);
3905
3940
  }
3906
3941
  } catch {
3907
3942
  r(null);
@@ -3920,7 +3955,7 @@ var Ke = class {
3920
3955
  }
3921
3956
  };
3922
3957
  }
3923
- }, ze = class {
3958
+ }, Qe = class {
3924
3959
  _store;
3925
3960
  _queue;
3926
3961
  _bus;
@@ -3930,7 +3965,7 @@ var Ke = class {
3930
3965
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3931
3966
  }
3932
3967
  collection(e) {
3933
- return Wr(e), new Ke(
3968
+ return Qr(e), new He(
3934
3969
  e,
3935
3970
  this._store,
3936
3971
  this._queue,
@@ -3959,23 +3994,23 @@ var Ke = class {
3959
3994
  return this._engine.onError(e);
3960
3995
  }
3961
3996
  };
3962
- async function Ht(n) {
3963
- let e = $r() ? new fe() : new pe(n.dbName);
3997
+ async function Gt(n) {
3998
+ let e = Hr() ? new me() : new fe(n.dbName);
3964
3999
  await e.open();
3965
- let t = new me(e), r = new ge(), o = new ye(), i = new _e({
4000
+ let t = new he(e), r = new ye(), o = new _e(), i = new be({
3966
4001
  // Se startOnline=false, injeta um navigator falso
3967
4002
  navigator: n.startOnline === false ? { onLine: false } : typeof navigator < "u" ? navigator : void 0
3968
4003
  }), s = n.singleTab ? (
3969
4004
  // Fake tab coordinator para single-tab mode (sempre líder)
3970
4005
  {
3971
4006
  isLeader: () => true,
3972
- onRoleChange: (c) => () => {
4007
+ onRoleChange: (l) => () => {
3973
4008
  }
3974
4009
  }
3975
- ) : new ne({
4010
+ ) : new re({
3976
4011
  lockName: `neetru-offline:${n.dbName}`,
3977
4012
  channelName: `neetru-offline:${n.dbName}`
3978
- }), a = new he({
4013
+ }), a = new ge({
3979
4014
  store: e,
3980
4015
  queue: t,
3981
4016
  resolver: r,
@@ -3985,7 +4020,7 @@ async function Ht(n) {
3985
4020
  connectivity: i,
3986
4021
  periodicSyncIntervalMs: n.periodicSyncIntervalMs ?? 300 * 1e3
3987
4022
  });
3988
- return i.start(), !n.singleTab && s instanceof ne && s.start(), new ze({
4023
+ return i.start(), !n.singleTab && s instanceof re && s.start(), new Qe({
3989
4024
  store: e,
3990
4025
  queue: t,
3991
4026
  bus: o,
@@ -3995,11 +4030,11 @@ async function Ht(n) {
3995
4030
  }
3996
4031
 
3997
4032
  // src/db/realtime/realtime-client.ts
3998
- var Kr = 0;
3999
- function Qt() {
4000
- return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++Kr}-${Math.random().toString(36).slice(2)}`;
4033
+ var Xr = 0;
4034
+ function Jt() {
4035
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++Xr}-${Math.random().toString(36).slice(2)}`;
4001
4036
  }
4002
- var be = class {
4037
+ var ve = class {
4003
4038
  // ── configuração ──────────────────────────────────────────────────────────
4004
4039
  _gatewayUrl;
4005
4040
  _wsFactory;
@@ -4037,7 +4072,7 @@ var be = class {
4037
4072
  _pendingFrames = [];
4038
4073
  // ── construtor ────────────────────────────────────────────────────────────
4039
4074
  constructor(e) {
4040
- this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? zr, 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();
4075
+ this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? Yr, 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();
4041
4076
  }
4042
4077
  // ── API pública ───────────────────────────────────────────────────────────
4043
4078
  /**
@@ -4051,8 +4086,8 @@ var be = class {
4051
4086
  */
4052
4087
  subscribe(e, t, r) {
4053
4088
  if (this._closed)
4054
- return Qt();
4055
- let o = Qt();
4089
+ return Jt();
4090
+ let o = Jt();
4056
4091
  this._subscriptions.set(o, {
4057
4092
  subscriptionId: o,
4058
4093
  collection: e,
@@ -4316,7 +4351,7 @@ var be = class {
4316
4351
  _detachHandlers(e) {
4317
4352
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
4318
4353
  }
4319
- }, zr = (n) => {
4354
+ }, Yr = (n) => {
4320
4355
  if (typeof WebSocket > "u")
4321
4356
  throw new Error(
4322
4357
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -4325,59 +4360,59 @@ var be = class {
4325
4360
  };
4326
4361
 
4327
4362
  // src/db/client-db.ts
4328
- var ro = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, we = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, sn = 200;
4329
- function oo(n, e, t) {
4330
- return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? io(e.realtimeGatewayUrl, t, e) : cn(t);
4363
+ var po = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, ke = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, ln = 200;
4364
+ function fo(n, e, t) {
4365
+ return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? mo(e.realtimeGatewayUrl, t, e) : un(t);
4331
4366
  }
4332
- function cn(n) {
4367
+ function un(n) {
4333
4368
  return {
4334
4369
  async pushMutations(e) {
4335
4370
  if (!n)
4336
- throw new y(
4371
+ throw new _(
4337
4372
  "db_unavailable",
4338
4373
  "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
4339
4374
  );
4340
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4375
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4341
4376
  for (let s of e)
4342
4377
  try {
4343
4378
  let a;
4344
4379
  s.op === "add" ? a = await t(n, {
4345
4380
  method: "PUT",
4346
- path: we(s.collection, s.docId),
4381
+ path: ke(s.collection, s.docId),
4347
4382
  body: { data: s.payload ?? {} },
4348
4383
  requireAuth: !0,
4349
4384
  retries: 2,
4350
4385
  headers: i
4351
4386
  }) : s.op === "set" ? a = await t(n, {
4352
4387
  method: "PUT",
4353
- path: we(s.collection, s.docId),
4388
+ path: ke(s.collection, s.docId),
4354
4389
  body: { data: s.payload ?? {} },
4355
4390
  requireAuth: !0,
4356
4391
  retries: 2,
4357
4392
  headers: i
4358
4393
  }) : s.op === "update" ? a = await t(n, {
4359
4394
  method: "PATCH",
4360
- path: we(s.collection, s.docId),
4395
+ path: ke(s.collection, s.docId),
4361
4396
  body: { data: s.payload ?? {}, ...s.upsert ? { upsert: !0 } : {} },
4362
4397
  requireAuth: !0,
4363
4398
  retries: 2,
4364
4399
  headers: i
4365
4400
  }) : a = await t(n, {
4366
4401
  method: "DELETE",
4367
- path: we(s.collection, s.docId),
4402
+ path: ke(s.collection, s.docId),
4368
4403
  requireAuth: !0,
4369
4404
  retries: 2,
4370
4405
  headers: i
4371
4406
  });
4372
- let c = a;
4407
+ let l = a;
4373
4408
  r.push({
4374
4409
  mutationId: s.mutationId,
4375
4410
  outcome: "confirmed",
4376
- serverVersion: c?.serverVersion ?? c?.id ?? `rest_${Date.now()}`,
4411
+ serverVersion: l?.serverVersion ?? l?.id ?? `rest_${Date.now()}`,
4377
4412
  serverTimestamp: Date.now()
4378
4413
  });
4379
4414
  } catch (a) {
4380
- let c = a instanceof Error ? a.message : String(a), d = a?.code, u = a?.status;
4415
+ let l = a instanceof Error ? a.message : String(a), d = a?.code, u = a?.status;
4381
4416
  if (d === "forbidden" || d === "unauthorized" || d === "not_found" || d === "conflict" || d === "validation_failed" || typeof u == "number" && u >= 400 && u < 500 && u !== 408 && u !== 429) {
4382
4417
  let f = d === "forbidden" || d === "unauthorized" ? "rejected_permission" : "rejected_validation";
4383
4418
  r.push({
@@ -4390,7 +4425,7 @@ function cn(n) {
4390
4425
  continue;
4391
4426
  }
4392
4427
  if (r.length === 0)
4393
- throw new y("db_unavailable", `pushMutations falhou: ${c}`);
4428
+ throw new _("db_unavailable", `pushMutations falhou: ${l}`);
4394
4429
  break;
4395
4430
  }
4396
4431
  return { results: r };
@@ -4401,13 +4436,13 @@ function cn(n) {
4401
4436
  async fullResync(e) {
4402
4437
  if (!n)
4403
4438
  return { docs: [], newWatermark: Date.now() };
4404
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4405
- for (let c of e) {
4439
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4440
+ for (let l of e) {
4406
4441
  let d;
4407
4442
  try {
4408
4443
  d = await t(n, {
4409
4444
  method: "GET",
4410
- path: ro(c),
4445
+ path: po(l),
4411
4446
  requireAuth: !0,
4412
4447
  retries: 2,
4413
4448
  headers: o,
@@ -4415,37 +4450,37 @@ function cn(n) {
4415
4450
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
4416
4451
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
4417
4452
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
4418
- query: { limit: sn }
4453
+ query: { limit: ln }
4419
4454
  });
4420
4455
  } catch (f) {
4421
- let _ = f instanceof Error ? f.message : String(f);
4422
- throw new y(
4456
+ let h = f instanceof Error ? f.message : String(f);
4457
+ throw new _(
4423
4458
  "db_unavailable",
4424
- `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${c}": ${_}`
4459
+ `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${h}`
4425
4460
  );
4426
4461
  }
4427
4462
  let u = d, p = Array.isArray(u?.items) ? u.items : [];
4428
- p.length >= sn && a.push(c);
4463
+ p.length >= ln && a.push(l);
4429
4464
  for (let f of p) {
4430
4465
  if (!f || typeof f != "object") continue;
4431
- let _ = f, b = typeof _.id == "string" ? _.id : null;
4432
- if (!b) continue;
4433
- let { id: S, ...x } = _, T = i, P = x._updatedAt;
4434
- if (typeof P == "number")
4435
- T = P;
4436
- else if (P !== null && typeof P == "object" && typeof P._seconds == "number")
4437
- T = P._seconds * 1e3;
4438
- else if (typeof P == "string") {
4439
- let m = Date.parse(P);
4440
- Number.isNaN(m) || (T = m);
4466
+ let h = f, y = typeof h.id == "string" ? h.id : null;
4467
+ if (!y) continue;
4468
+ let { id: T, ...x } = h, R = i, E = x._updatedAt;
4469
+ if (typeof E == "number")
4470
+ R = E;
4471
+ else if (E !== null && typeof E == "object" && typeof E._seconds == "number")
4472
+ R = E._seconds * 1e3;
4473
+ else if (typeof E == "string") {
4474
+ let g = Date.parse(E);
4475
+ Number.isNaN(g) || (R = g);
4441
4476
  }
4442
- let q = `rest_${b}_${T}`;
4477
+ let j = `rest_${y}_${R}`;
4443
4478
  s.push({
4444
- collection: c,
4445
- id: b,
4479
+ collection: l,
4480
+ id: y,
4446
4481
  data: x,
4447
- serverVersion: q,
4448
- serverTimestamp: T,
4482
+ serverVersion: j,
4483
+ serverTimestamp: R,
4449
4484
  deleted: false
4450
4485
  });
4451
4486
  }
@@ -4454,10 +4489,10 @@ function cn(n) {
4454
4489
  }
4455
4490
  };
4456
4491
  }
4457
- function io(n, e, t) {
4458
- let r = cn(e), o = new be({
4492
+ function mo(n, e, t) {
4493
+ let r = un(e), o = new ve({
4459
4494
  gatewayUrl: n,
4460
- ticketProvider: so(e, t),
4495
+ ticketProvider: ho(e, t),
4461
4496
  dbId: t.dbId,
4462
4497
  webSocketFactory: t._wsFactory
4463
4498
  });
@@ -4469,17 +4504,17 @@ function io(n, e, t) {
4469
4504
  // quando o engine é nosql-vm. Registra a subscription no NeetruRealtimeClient
4470
4505
  // e traduz os frames inbound para o contrato de `onChange`.
4471
4506
  subscribeCollection(i, s) {
4472
- let a = o.subscribe(i, {}, (c) => {
4473
- if (c.op === "resync") {
4507
+ let a = o.subscribe(i, {}, (l) => {
4508
+ if (l.op === "resync") {
4474
4509
  s([], true);
4475
4510
  return;
4476
4511
  }
4477
- if (c.op === "stale") {
4512
+ if (l.op === "stale") {
4478
4513
  s([], true);
4479
4514
  return;
4480
4515
  }
4481
- if (c.op === "delta" && c.changes) {
4482
- let d = c.changes.map((u) => ({
4516
+ if (l.op === "delta" && l.changes) {
4517
+ let d = l.changes.map((u) => ({
4483
4518
  type: u.type === "insert" ? "added" : u.type === "delete" ? "removed" : "modified",
4484
4519
  docId: u.documentId,
4485
4520
  data: u.data ?? null
@@ -4493,9 +4528,9 @@ function io(n, e, t) {
4493
4528
  }
4494
4529
  };
4495
4530
  }
4496
- function so(n, e) {
4531
+ function ho(n, e) {
4497
4532
  return async () => {
4498
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y));
4533
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z));
4499
4534
  return await t(n, {
4500
4535
  method: "POST",
4501
4536
  path: "/api/sdk/v1/db/realtime/ticket",
@@ -4508,21 +4543,21 @@ function so(n, e) {
4508
4543
  });
4509
4544
  };
4510
4545
  }
4511
- var an = false;
4512
- function ao(n, e) {
4513
- an || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (an = true, console.warn(
4546
+ var dn = false;
4547
+ function go(n, e) {
4548
+ dn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (dn = true, console.warn(
4514
4549
  '[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.'
4515
4550
  )));
4516
4551
  }
4517
- function ln(n, e = {}) {
4518
- ao(n, e);
4552
+ function pn(n, e = {}) {
4553
+ go(n, e);
4519
4554
  let t;
4520
4555
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
4521
4556
  '[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).'
4522
4557
  ), t = e.engine) : t = "rest";
4523
- let r = oo(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4524
- function c() {
4525
- return s || (s = Ht({
4558
+ let r = fo(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4559
+ function l() {
4560
+ return s || (s = Gt({
4526
4561
  dbName: i,
4527
4562
  transport: r,
4528
4563
  singleTab: e.singleTab ?? n.env !== "prod"
@@ -4530,15 +4565,15 @@ function ln(n, e = {}) {
4530
4565
  }
4531
4566
  return {
4532
4567
  collection(d) {
4533
- return a ? a.collection(d) : co(d, c);
4568
+ return a ? a.collection(d) : yo(d, l);
4534
4569
  },
4535
4570
  async sql(d, u) {
4536
- if (n.env === "dev")
4537
- throw new y(
4571
+ if (W(n.env))
4572
+ throw new _(
4538
4573
  "db_unavailable",
4539
4574
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4540
4575
  );
4541
- return (await Promise.resolve().then(() => (on(), rn))).createSqlClientFromConfig(n, d, u);
4576
+ return (await Promise.resolve().then(() => (cn(), an))).createSqlClientFromConfig(n, d, u);
4542
4577
  },
4543
4578
  get syncState() {
4544
4579
  return a?.syncState ?? {
@@ -4551,25 +4586,25 @@ function ln(n, e = {}) {
4551
4586
  onSyncStateChanged(d) {
4552
4587
  if (a) return a.onSyncStateChanged(d);
4553
4588
  let u = null, p = false;
4554
- return c().then((f) => {
4589
+ return l().then((f) => {
4555
4590
  p || (u = f.onSyncStateChanged(d));
4556
4591
  }), () => {
4557
4592
  p = true, u?.();
4558
4593
  };
4559
4594
  },
4560
4595
  async flush() {
4561
- return (await c()).flush();
4596
+ return (await l()).flush();
4562
4597
  },
4563
4598
  async clearCache() {
4564
- return (await c()).clearCache();
4599
+ return (await l()).clearCache();
4565
4600
  },
4566
4601
  async getConflicts() {
4567
- return (await c()).getConflicts();
4602
+ return (await l()).getConflicts();
4568
4603
  },
4569
4604
  onError(d) {
4570
4605
  if (a) return a.onError(d);
4571
4606
  let u = null, p = false;
4572
- return c().then((f) => {
4607
+ return l().then((f) => {
4573
4608
  p || (u = f.onError(d));
4574
4609
  }), () => {
4575
4610
  p = true, u?.();
@@ -4577,7 +4612,7 @@ function ln(n, e = {}) {
4577
4612
  }
4578
4613
  };
4579
4614
  }
4580
- function co(n, e) {
4615
+ function yo(n, e) {
4581
4616
  async function t() {
4582
4617
  return (await e()).collection(n);
4583
4618
  }
@@ -4656,25 +4691,25 @@ function co(n, e) {
4656
4691
  }
4657
4692
 
4658
4693
  // src/checkout.ts
4659
- I();
4660
- M();
4661
- function Ye(n, e) {
4694
+ C();
4695
+ F();
4696
+ function et(n, e) {
4662
4697
  let t = n?.accessToken || n?.idToken;
4663
4698
  if (!t || typeof t != "string")
4664
- throw new l(
4699
+ throw new c(
4665
4700
  "validation_failed",
4666
4701
  `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.`
4667
4702
  );
4668
4703
  return { requireAuth: false, headers: { authorization: `Bearer ${t}` } };
4669
4704
  }
4670
- function lo(n) {
4705
+ function _o(n) {
4671
4706
  if (!n || typeof n != "object")
4672
- throw new l("invalid_response", "checkout.start response is not an object");
4707
+ throw new c("invalid_response", "checkout.start response is not an object");
4673
4708
  let e = n;
4674
4709
  if (typeof e.intentId != "string" || !e.intentId)
4675
- throw new l("invalid_response", "checkout.start response missing intentId");
4710
+ throw new c("invalid_response", "checkout.start response missing intentId");
4676
4711
  if (typeof e.redirectUrl != "string" || !e.redirectUrl)
4677
- throw new l("invalid_response", "checkout.start response missing redirectUrl");
4712
+ throw new c("invalid_response", "checkout.start response missing redirectUrl");
4678
4713
  return {
4679
4714
  intentId: e.intentId,
4680
4715
  redirectUrl: e.redirectUrl,
@@ -4683,14 +4718,14 @@ function lo(n) {
4683
4718
  requiresKyc: e.requiresKyc === true
4684
4719
  };
4685
4720
  }
4686
- function uo(n) {
4721
+ function bo(n) {
4687
4722
  if (!n || typeof n != "object")
4688
- throw new l("invalid_response", "checkout.get response is not an object");
4723
+ throw new c("invalid_response", "checkout.get response is not an object");
4689
4724
  let e = n, t = e.intent;
4690
4725
  if (!t || typeof t != "object")
4691
- throw new l("invalid_response", "checkout.get response missing intent");
4726
+ throw new c("invalid_response", "checkout.get response missing intent");
4692
4727
  if (typeof t.intentId != "string")
4693
- throw new l("invalid_response", "checkout.get response missing intentId");
4728
+ throw new c("invalid_response", "checkout.get response missing intentId");
4694
4729
  return {
4695
4730
  intentId: t.intentId,
4696
4731
  uid: t.uid ?? "",
@@ -4705,35 +4740,35 @@ function uo(n) {
4705
4740
  isStale: e.isStale === true
4706
4741
  };
4707
4742
  }
4708
- function po() {
4743
+ function vo() {
4709
4744
  try {
4710
4745
  return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
4711
4746
  } catch {
4712
4747
  return false;
4713
4748
  }
4714
4749
  }
4715
- function fo(n) {
4750
+ function wo(n) {
4716
4751
  try {
4717
4752
  globalThis.location.assign(n);
4718
4753
  } catch {
4719
4754
  }
4720
4755
  }
4721
- function mo(n) {
4756
+ function ko(n) {
4722
4757
  return {
4723
4758
  async start(e) {
4724
4759
  if (!e?.productId)
4725
- throw new l("validation_failed", "checkout.start: productId is required");
4760
+ throw new c("validation_failed", "checkout.start: productId is required");
4726
4761
  if (!e?.planId)
4727
- throw new l("validation_failed", "checkout.start: planId is required");
4762
+ throw new c("validation_failed", "checkout.start: planId is required");
4728
4763
  if (!e?.callbackUrl)
4729
- throw new l("validation_failed", "checkout.start: callbackUrl is required");
4764
+ throw new c("validation_failed", "checkout.start: callbackUrl is required");
4730
4765
  let t = {
4731
4766
  productId: e.productId,
4732
4767
  planId: e.planId,
4733
4768
  callbackUrl: e.callbackUrl
4734
4769
  };
4735
4770
  e.tenantType && (t.targetTenantType = e.tenantType), e.tenantId && (t.targetTenantId = e.tenantId);
4736
- let { requireAuth: r, headers: o } = Ye(
4771
+ let { requireAuth: r, headers: o } = et(
4737
4772
  { accessToken: e.accessToken, idToken: e.idToken },
4738
4773
  "start"
4739
4774
  ), i = await v(n, {
@@ -4743,13 +4778,13 @@ function mo(n) {
4743
4778
  requireAuth: r,
4744
4779
  headers: o,
4745
4780
  idempotencyKey: true
4746
- }), s = lo(i);
4747
- return e.autoRedirect !== false && po() && fo(s.redirectUrl), s;
4781
+ }), s = _o(i);
4782
+ return e.autoRedirect !== false && vo() && wo(s.redirectUrl), s;
4748
4783
  },
4749
4784
  async get(e, t) {
4750
4785
  if (!e || typeof e != "string")
4751
- throw new l("validation_failed", "checkout.get: intentId is required");
4752
- let { requireAuth: r, headers: o } = Ye(
4786
+ throw new c("validation_failed", "checkout.get: intentId is required");
4787
+ let { requireAuth: r, headers: o } = et(
4753
4788
  { accessToken: t?.accessToken, idToken: t?.idToken },
4754
4789
  "get"
4755
4790
  ), i = await v(n, {
@@ -4758,12 +4793,12 @@ function mo(n) {
4758
4793
  requireAuth: r,
4759
4794
  headers: o
4760
4795
  });
4761
- return uo(i);
4796
+ return bo(i);
4762
4797
  },
4763
4798
  async cancel(e, t) {
4764
4799
  if (!e || typeof e != "string")
4765
- throw new l("validation_failed", "checkout.cancel: intentId is required");
4766
- let { requireAuth: r, headers: o } = Ye(
4800
+ throw new c("validation_failed", "checkout.cancel: intentId is required");
4801
+ let { requireAuth: r, headers: o } = et(
4767
4802
  { accessToken: t?.accessToken, idToken: t?.idToken },
4768
4803
  "cancel"
4769
4804
  );
@@ -4779,15 +4814,15 @@ function mo(n) {
4779
4814
  }
4780
4815
  };
4781
4816
  }
4782
- var Ze = class {
4817
+ var tt = class {
4783
4818
  intents = /* @__PURE__ */ new Map();
4784
4819
  async start(e) {
4785
4820
  if (!e?.productId)
4786
- throw new l("validation_failed", "checkout.start: productId is required");
4821
+ throw new c("validation_failed", "checkout.start: productId is required");
4787
4822
  if (!e?.planId)
4788
- throw new l("validation_failed", "checkout.start: planId is required");
4823
+ throw new c("validation_failed", "checkout.start: planId is required");
4789
4824
  if (!e?.callbackUrl)
4790
- throw new l("validation_failed", "checkout.start: callbackUrl is required");
4825
+ throw new c("validation_failed", "checkout.start: callbackUrl is required");
4791
4826
  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}`;
4792
4827
  return this.intents.set(t, {
4793
4828
  intentId: t,
@@ -4811,25 +4846,25 @@ var Ze = class {
4811
4846
  async get(e, t) {
4812
4847
  let r = this.intents.get(e);
4813
4848
  if (!r)
4814
- throw new l("not_found", `Mock intent ${e} not found`);
4849
+ throw new c("not_found", `Mock intent ${e} not found`);
4815
4850
  return { ...r };
4816
4851
  }
4817
4852
  async cancel(e, t) {
4818
4853
  let r = this.intents.get(e);
4819
4854
  if (!r)
4820
- throw new l("not_found", `Mock intent ${e} not found`);
4855
+ throw new c("not_found", `Mock intent ${e} not found`);
4821
4856
  let o = r.status === "cancelled";
4822
4857
  return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
4823
4858
  }
4824
4859
  };
4825
- function dn(n) {
4826
- return n.env === "dev" ? new Ze() : mo(n);
4860
+ function fn(n) {
4861
+ return W(n.env) ? new tt() : ko(n);
4827
4862
  }
4828
4863
 
4829
4864
  // src/webhooks.ts
4830
- I();
4831
- M();
4832
- var pn = [
4865
+ C();
4866
+ F();
4867
+ var hn = [
4833
4868
  "subscription.activated",
4834
4869
  "subscription.cancelled",
4835
4870
  "subscription.payment_failed",
@@ -4839,17 +4874,17 @@ var pn = [
4839
4874
  "account.reactivated",
4840
4875
  "support.ticket_replied"
4841
4876
  ];
4842
- function un(n) {
4877
+ function mn(n) {
4843
4878
  if (!n || typeof n != "object")
4844
- throw new l("invalid_response", "Webhook response is not an object");
4879
+ throw new c("invalid_response", "Webhook response is not an object");
4845
4880
  let e = n;
4846
4881
  if (typeof e.id != "string")
4847
- throw new l("invalid_response", "Webhook missing id");
4882
+ throw new c("invalid_response", "Webhook missing id");
4848
4883
  return {
4849
4884
  id: e.id,
4850
4885
  url: typeof e.url == "string" ? e.url : "",
4851
4886
  events: Array.isArray(e.events) ? e.events.filter(
4852
- (t) => pn.includes(t)
4887
+ (t) => hn.includes(t)
4853
4888
  ) : [],
4854
4889
  hasSecret: e.hasSecret === true,
4855
4890
  status: e.status === "active" || e.status === "degraded" || e.status === "disabled" ? e.status : "active",
@@ -4858,40 +4893,40 @@ function un(n) {
4858
4893
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString()
4859
4894
  };
4860
4895
  }
4861
- function fn(n) {
4896
+ function gn(n) {
4862
4897
  if (!n.url || typeof n.url != "string")
4863
- throw new l("validation_failed", "url \xE9 obrigat\xF3ria");
4898
+ throw new c("validation_failed", "url \xE9 obrigat\xF3ria");
4864
4899
  try {
4865
4900
  let e = new URL(n.url);
4866
4901
  if (e.protocol !== "https:" && e.protocol !== "http:")
4867
4902
  throw new Error("invalid protocol");
4868
4903
  } catch {
4869
- throw new l("validation_failed", `url inv\xE1lida: ${n.url}`);
4904
+ throw new c("validation_failed", `url inv\xE1lida: ${n.url}`);
4870
4905
  }
4871
4906
  if (!Array.isArray(n.events) || n.events.length === 0)
4872
- throw new l("validation_failed", "events deve ter pelo menos 1 evento");
4907
+ throw new c("validation_failed", "events deve ter pelo menos 1 evento");
4873
4908
  for (let e of n.events)
4874
- if (!pn.includes(e))
4875
- throw new l("validation_failed", `evento desconhecido: ${e}`);
4909
+ if (!hn.includes(e))
4910
+ throw new c("validation_failed", `evento desconhecido: ${e}`);
4876
4911
  if (n.secret !== void 0 && n.secret.length < 16)
4877
- throw new l("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4912
+ throw new c("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4878
4913
  }
4879
- function ke(n, ...e) {
4914
+ function Se(n, ...e) {
4880
4915
  for (let t of e)
4881
4916
  if (typeof t == "string" && t.length > 0)
4882
4917
  return N("productId", t), t;
4883
4918
  if (n.productId)
4884
4919
  return N("productId", n.productId), n.productId;
4885
- throw new l(
4920
+ throw new c(
4886
4921
  "validation_failed",
4887
4922
  "productId required (pass to options/input or set on createNeetruClient)"
4888
4923
  );
4889
4924
  }
4890
- function mn(n) {
4925
+ function yn(n) {
4891
4926
  return {
4892
4927
  async register(e) {
4893
- fn(e);
4894
- let t = ke(n, e.productId), r = await v(n, {
4928
+ gn(e);
4929
+ let t = Se(n, e.productId), r = await v(n, {
4895
4930
  method: "POST",
4896
4931
  path: "/api/sdk/v1/webhooks",
4897
4932
  body: {
@@ -4907,20 +4942,20 @@ function mn(n) {
4907
4942
  // dedup TTL 24h (mesmo padrão de usage.report/support.createTicket).
4908
4943
  idempotencyKey: true
4909
4944
  });
4910
- return un(r);
4945
+ return mn(r);
4911
4946
  },
4912
4947
  async list(e) {
4913
- let t = ke(n, e?.productId), r = await v(n, {
4948
+ let t = Se(n, e?.productId), r = await v(n, {
4914
4949
  method: "GET",
4915
4950
  path: "/api/sdk/v1/webhooks",
4916
4951
  query: { productId: t },
4917
4952
  requireAuth: true
4918
4953
  });
4919
- return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(un);
4954
+ return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(mn);
4920
4955
  },
4921
4956
  async unregister(e, t) {
4922
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
4923
- let r = ke(n, t?.productId);
4957
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4958
+ let r = Se(n, t?.productId);
4924
4959
  return await v(n, {
4925
4960
  method: "DELETE",
4926
4961
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}`,
@@ -4929,8 +4964,8 @@ function mn(n) {
4929
4964
  }), { ok: true };
4930
4965
  },
4931
4966
  async test(e, t) {
4932
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
4933
- let r = ke(n, t?.productId), o = await v(n, {
4967
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4968
+ let r = Se(n, t?.productId), o = await v(n, {
4934
4969
  method: "POST",
4935
4970
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}/test`,
4936
4971
  query: { productId: r },
@@ -4949,11 +4984,11 @@ function mn(n) {
4949
4984
  }
4950
4985
  };
4951
4986
  }
4952
- var Se = class {
4987
+ var Te = class {
4953
4988
  endpoints = /* @__PURE__ */ new Map();
4954
4989
  nextId = 1;
4955
4990
  async register(e) {
4956
- fn(e);
4991
+ gn(e);
4957
4992
  let t = `mock_wh_${this.nextId++}`, r = {
4958
4993
  id: t,
4959
4994
  url: e.url,
@@ -4969,32 +5004,32 @@ var Se = class {
4969
5004
  }
4970
5005
  async unregister(e, t) {
4971
5006
  if (!this.endpoints.has(e))
4972
- throw new l("not_found", `Webhook ${e} n\xE3o encontrado`);
5007
+ throw new c("not_found", `Webhook ${e} n\xE3o encontrado`);
4973
5008
  return this.endpoints.delete(e), { ok: true };
4974
5009
  }
4975
5010
  async test(e, t) {
4976
5011
  if (!this.endpoints.has(e))
4977
- throw new l("not_found", `Webhook ${e} n\xE3o encontrado`);
5012
+ throw new c("not_found", `Webhook ${e} n\xE3o encontrado`);
4978
5013
  return { ok: true, statusCode: 200, durationMs: 42 };
4979
5014
  }
4980
5015
  };
4981
5016
 
4982
5017
  // src/notifications.ts
4983
- I();
4984
- M();
4985
- var et = [
5018
+ C();
5019
+ F();
5020
+ var nt = [
4986
5021
  "info",
4987
5022
  "success",
4988
5023
  "warning",
4989
5024
  "error"
4990
5025
  ];
4991
- function hn(n) {
5026
+ function _n(n) {
4992
5027
  if (!n || typeof n != "object")
4993
- throw new l("invalid_response", "Notification response is not an object");
5028
+ throw new c("invalid_response", "Notification response is not an object");
4994
5029
  let e = n;
4995
5030
  if (typeof e.id != "string")
4996
- throw new l("invalid_response", "Notification missing id");
4997
- let t = et.includes(e.severity) ? e.severity : "info";
5031
+ throw new c("invalid_response", "Notification missing id");
5032
+ let t = nt.includes(e.severity) ? e.severity : "info";
4998
5033
  return {
4999
5034
  id: e.id,
5000
5035
  userId: typeof e.userId == "string" ? e.userId : "",
@@ -5009,37 +5044,37 @@ function hn(n) {
5009
5044
  dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
5010
5045
  };
5011
5046
  }
5012
- function gn(n) {
5013
- if (!n.userId) throw new l("validation_failed", "userId obrigat\xF3rio");
5014
- if (!n.kind) throw new l("validation_failed", "kind obrigat\xF3rio");
5015
- if (!n.title) throw new l("validation_failed", "title obrigat\xF3rio");
5016
- if (n.severity && !et.includes(n.severity))
5017
- throw new l(
5047
+ function bn(n) {
5048
+ if (!n.userId) throw new c("validation_failed", "userId obrigat\xF3rio");
5049
+ if (!n.kind) throw new c("validation_failed", "kind obrigat\xF3rio");
5050
+ if (!n.title) throw new c("validation_failed", "title obrigat\xF3rio");
5051
+ if (n.severity && !nt.includes(n.severity))
5052
+ throw new c(
5018
5053
  "validation_failed",
5019
- `severity inv\xE1lida: ${n.severity} (use ${et.join("|")})`
5054
+ `severity inv\xE1lida: ${n.severity} (use ${nt.join("|")})`
5020
5055
  );
5021
5056
  if (n.title.length > 200)
5022
- throw new l("validation_failed", "title m\xE1x 200 chars");
5057
+ throw new c("validation_failed", "title m\xE1x 200 chars");
5023
5058
  if (n.body && n.body.length > 2e3)
5024
- throw new l("validation_failed", "body m\xE1x 2000 chars");
5059
+ throw new c("validation_failed", "body m\xE1x 2000 chars");
5025
5060
  }
5026
- function Te(n, ...e) {
5061
+ function Re(n, ...e) {
5027
5062
  for (let t of e)
5028
5063
  if (typeof t == "string" && t.length > 0)
5029
5064
  return N("productId", t), t;
5030
5065
  if (n.productId)
5031
5066
  return N("productId", n.productId), n.productId;
5032
- throw new l(
5067
+ throw new c(
5033
5068
  "validation_failed",
5034
5069
  "productId required (pass to options/input or set on createNeetruClient)"
5035
5070
  );
5036
5071
  }
5037
- function yn(n) {
5072
+ function vn(n) {
5038
5073
  return {
5039
5074
  async send(e) {
5040
- gn(e);
5075
+ bn(e);
5041
5076
  let r = {
5042
- productId: Te(n, e.productId),
5077
+ productId: Re(n, e.productId),
5043
5078
  userId: e.userId,
5044
5079
  kind: e.kind,
5045
5080
  title: e.title,
@@ -5053,12 +5088,12 @@ function yn(n) {
5053
5088
  requireAuth: true,
5054
5089
  idempotencyKey: true
5055
5090
  });
5056
- return hn(o);
5091
+ return _n(o);
5057
5092
  },
5058
5093
  async list(e, t) {
5059
- if (!e) throw new l("validation_failed", "userId obrigat\xF3rio");
5094
+ if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5060
5095
  let o = {
5061
- productId: Te(n, t?.productId)
5096
+ productId: Re(n, t?.productId)
5062
5097
  };
5063
5098
  t?.includeDismissed && (o.includeDismissed = true), t?.onlyUnread && (o.onlyUnread = true), t?.limit && (o.limit = Math.min(Math.max(1, t.limit), 200));
5064
5099
  let i = await v(n, {
@@ -5067,11 +5102,11 @@ function yn(n) {
5067
5102
  query: o,
5068
5103
  requireAuth: true
5069
5104
  });
5070
- return (Array.isArray(i?.notifications) ? i.notifications : []).map(hn);
5105
+ return (Array.isArray(i?.notifications) ? i.notifications : []).map(_n);
5071
5106
  },
5072
5107
  async markRead(e, t) {
5073
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5074
- let r = Te(n, t?.productId);
5108
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5109
+ let r = Re(n, t?.productId);
5075
5110
  return await v(n, {
5076
5111
  method: "POST",
5077
5112
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/read`,
@@ -5080,8 +5115,8 @@ function yn(n) {
5080
5115
  }), { ok: true };
5081
5116
  },
5082
5117
  async dismiss(e, t) {
5083
- if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5084
- let r = Te(n, t?.productId);
5118
+ if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5119
+ let r = Re(n, t?.productId);
5085
5120
  return await v(n, {
5086
5121
  method: "POST",
5087
5122
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/dismiss`,
@@ -5091,11 +5126,11 @@ function yn(n) {
5091
5126
  }
5092
5127
  };
5093
5128
  }
5094
- var Re = class {
5129
+ var Ie = class {
5095
5130
  notifications = /* @__PURE__ */ new Map();
5096
5131
  nextId = 1;
5097
5132
  async send(e) {
5098
- if (gn(e), e.fingerprint) {
5133
+ if (bn(e), e.fingerprint) {
5099
5134
  let o = Date.now() - 864e5;
5100
5135
  for (let i of this.notifications.values())
5101
5136
  if ((i.metadata ?? {}).fingerprint === e.fingerprint && i.userId === e.userId && new Date(i.createdAt).getTime() > o)
@@ -5115,61 +5150,61 @@ var Re = class {
5115
5150
  return this.notifications.set(t, r), r;
5116
5151
  }
5117
5152
  async list(e, t) {
5118
- if (!e) throw new l("validation_failed", "userId obrigat\xF3rio");
5153
+ if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5119
5154
  let r = Math.min(Math.max(1, t?.limit ?? 50), 200);
5120
5155
  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);
5121
5156
  }
5122
5157
  async markRead(e, t) {
5123
5158
  let r = this.notifications.get(e);
5124
- if (!r) throw new l("not_found", `Notification ${e} n\xE3o encontrada`);
5159
+ if (!r) throw new c("not_found", `Notification ${e} n\xE3o encontrada`);
5125
5160
  return r.readAt || (r.readAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, r)), { ok: true };
5126
5161
  }
5127
5162
  async dismiss(e, t) {
5128
5163
  let r = this.notifications.get(e);
5129
- if (!r) throw new l("not_found", `Notification ${e} n\xE3o encontrada`);
5164
+ if (!r) throw new c("not_found", `Notification ${e} n\xE3o encontrada`);
5130
5165
  return r.dismissedAt || (r.dismissedAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, r)), { ok: true };
5131
5166
  }
5132
5167
  };
5133
5168
 
5134
5169
  // src/ai.ts
5135
- I();
5136
- M();
5137
- Me();
5138
- var ho = "/api/sdk/v1/ai/chat", _n = 12e4, Ie = 32768, bn = 32, vn = 4194304, wn = 2048, go = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, yo = /^https:\/\/[^\s]+$/, _o = /* @__PURE__ */ new Set(["low", "high", "auto"]), bo = /* @__PURE__ */ new Set(["system", "user", "assistant"]), kn = 100, Sn = 128, Tn = 32768, Rn = 0, In = 2, Cn = 200, An = 20, En = 12 * 1024 * 1024, Pn = 5e4, Dn = 16, Nn = 500, vo = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), wo = /^[a-zA-Z0-9_-]+$/;
5170
+ C();
5171
+ F();
5172
+ qe();
5173
+ var So = "/api/sdk/v1/ai/chat", wn = 12e4, Ce = 32768, kn = 32, Sn = 4194304, Tn = 2048, To = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, Ro = /^https:\/\/[^\s]+$/, Io = /* @__PURE__ */ new Set(["low", "high", "auto"]), Co = /* @__PURE__ */ new Set(["system", "user", "assistant"]), Rn = 100, In = 128, Cn = 32768, An = 0, En = 2, Pn = 200, Dn = 20, Nn = 12 * 1024 * 1024, xn = 5e4, On = 16, Ln = 500, Ao = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), Eo = /^[a-zA-Z0-9_-]+$/;
5139
5174
  function k(n) {
5140
- throw new l("validation_failed", n);
5175
+ throw new c("validation_failed", n);
5141
5176
  }
5142
- function ko(n) {
5177
+ function Po(n) {
5143
5178
  if (n.length === 0 || n.length % 4 !== 0) return false;
5144
5179
  let e = n.endsWith("==") ? 2 : n.endsWith("=") ? 1 : 0;
5145
5180
  return !(e > 0 ? n.slice(0, n.length - e) : n).includes("=");
5146
5181
  }
5147
- function So(n) {
5182
+ function Do(n) {
5148
5183
  let e = n.indexOf(",");
5149
5184
  if (e === -1) return 0;
5150
5185
  let t = n.slice(e + 1), r = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
5151
5186
  return Math.max(0, Math.floor(t.length * 3 / 4) - r);
5152
5187
  }
5153
- function To(n) {
5188
+ function No(n) {
5154
5189
  let e = 0, t = 0, r = 0;
5155
5190
  for (let o of n) {
5156
5191
  let i = o?.content;
5157
5192
  if (Array.isArray(i))
5158
5193
  for (let s of i) {
5159
- if (e++, e > Cn)
5160
- return `ai: total content parts exceeds ${Cn} per request`;
5194
+ if (e++, e > Pn)
5195
+ return `ai: total content parts exceeds ${Pn} per request`;
5161
5196
  if (s && typeof s == "object" && s.type === "image_url") {
5162
- if (t++, t > An)
5163
- return `ai: total images exceeds ${An} per request`;
5197
+ if (t++, t > Dn)
5198
+ return `ai: total images exceeds ${Dn} per request`;
5164
5199
  let a = s.image_url?.url;
5165
- if (typeof a == "string" && a.startsWith("data:") && (r += So(a), r > En))
5166
- return `ai: aggregate image bytes exceeds ${En} per request`;
5200
+ if (typeof a == "string" && a.startsWith("data:") && (r += Do(a), r > Nn))
5201
+ return `ai: aggregate image bytes exceeds ${Nn} per request`;
5167
5202
  }
5168
5203
  }
5169
5204
  }
5170
5205
  return null;
5171
5206
  }
5172
- function Ro(n) {
5207
+ function xo(n) {
5173
5208
  if (n === void 0) return null;
5174
5209
  if (n === null || typeof n != "object")
5175
5210
  return "ai: responseFormat json_schema.schema must be an object";
@@ -5180,11 +5215,11 @@ function Ro(n) {
5180
5215
  return "ai: responseFormat json_schema.schema is not serializable";
5181
5216
  }
5182
5217
  if (e === void 0) return "ai: responseFormat json_schema.schema is invalid";
5183
- if (e.length > Pn)
5184
- return `ai: responseFormat json_schema.schema exceeds ${Pn} serialized chars`;
5218
+ if (e.length > xn)
5219
+ return `ai: responseFormat json_schema.schema exceeds ${xn} serialized chars`;
5185
5220
  let t = 0, r = (o, i) => {
5186
- if (i > Dn)
5187
- return `ai: responseFormat json_schema.schema exceeds max depth ${Dn}`;
5221
+ if (i > On)
5222
+ return `ai: responseFormat json_schema.schema exceeds max depth ${On}`;
5188
5223
  if (Array.isArray(o)) {
5189
5224
  for (let s of o) {
5190
5225
  let a = r(s, i + 1);
@@ -5194,10 +5229,10 @@ function Ro(n) {
5194
5229
  }
5195
5230
  if (o && typeof o == "object")
5196
5231
  for (let s of Object.getOwnPropertyNames(o)) {
5197
- if (vo.has(s))
5232
+ if (Ao.has(s))
5198
5233
  return `ai: responseFormat json_schema.schema has forbidden key: ${s}`;
5199
- if (t++, t > Nn)
5200
- return `ai: responseFormat json_schema.schema exceeds ${Nn} keys`;
5234
+ if (t++, t > Ln)
5235
+ return `ai: responseFormat json_schema.schema exceeds ${Ln} keys`;
5201
5236
  let a = r(o[s], i + 1);
5202
5237
  if (a) return a;
5203
5238
  }
@@ -5205,44 +5240,44 @@ function Ro(n) {
5205
5240
  };
5206
5241
  return r(n, 0);
5207
5242
  }
5208
- function Io(n) {
5243
+ function Oo(n) {
5209
5244
  (typeof n != "string" || n.length === 0) && k("ai: image_url.url must be a non-empty string");
5210
5245
  let e = n;
5211
5246
  if (e.startsWith("data:")) {
5212
- e.length > vn && k(`ai: image_url.url (data:) exceeds ${vn} chars`), go.test(e) || k("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5247
+ e.length > Sn && k(`ai: image_url.url (data:) exceeds ${Sn} chars`), To.test(e) || k("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5213
5248
  let t = e.slice(e.indexOf(",") + 1);
5214
- ko(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5249
+ Po(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5215
5250
  return;
5216
5251
  }
5217
5252
  if (e.startsWith("https://")) {
5218
- e.length > wn && k(`ai: image_url.url (https:) exceeds ${wn} chars`), yo.test(e) || k("ai: image_url.url https: is invalid");
5253
+ e.length > Tn && k(`ai: image_url.url (https:) exceeds ${Tn} chars`), Ro.test(e) || k("ai: image_url.url https: is invalid");
5219
5254
  return;
5220
5255
  }
5221
5256
  k("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5222
5257
  }
5223
- function Co(n, e) {
5258
+ function Lo(n, e) {
5224
5259
  if (typeof n == "string") {
5225
- n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ie && k(`ai: message content exceeds ${Ie} chars`);
5260
+ n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ce && k(`ai: message content exceeds ${Ce} chars`);
5226
5261
  return;
5227
5262
  }
5228
- (!Array.isArray(n) || n.length === 0) && k("ai: message content must be a non-empty string or array of parts"), n.length > bn && k(`ai: message content has more than ${bn} parts`);
5263
+ (!Array.isArray(n) || n.length === 0) && k("ai: message content must be a non-empty string or array of parts"), n.length > kn && k(`ai: message content has more than ${kn} parts`);
5229
5264
  for (let t of n) {
5230
5265
  (!t || typeof t != "object") && k("ai: each content part must be an object");
5231
5266
  let r = t.type;
5232
5267
  if (r === "text") {
5233
5268
  let o = t.text;
5234
- (typeof o != "string" || o.length === 0) && k("ai: text part must have non-empty { text: string }"), o.length > Ie && k(`ai: text part exceeds ${Ie} chars`);
5269
+ (typeof o != "string" || o.length === 0) && k("ai: text part must have non-empty { text: string }"), o.length > Ce && k(`ai: text part exceeds ${Ce} chars`);
5235
5270
  } else if (r === "image_url") {
5236
5271
  e !== "user" && k(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5237
5272
  let o = t.image_url;
5238
- (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Io(o.url);
5273
+ (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Oo(o.url);
5239
5274
  let i = o.detail;
5240
- i !== void 0 && (typeof i != "string" || !_o.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5275
+ i !== void 0 && (typeof i != "string" || !Io.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5241
5276
  } else
5242
5277
  k("ai: content part type must be 'text' or 'image_url'");
5243
5278
  }
5244
5279
  }
5245
- function Ao(n) {
5280
+ function Uo(n) {
5246
5281
  (!n || typeof n != "object") && k("ai: responseFormat must be an object");
5247
5282
  let e = n.type;
5248
5283
  if (!(e === "text" || e === "json_object")) {
@@ -5250,8 +5285,8 @@ function Ao(n) {
5250
5285
  let t = n.json_schema;
5251
5286
  (!t || typeof t != "object") && k("ai: responseFormat json_schema requires { json_schema: { name } }");
5252
5287
  let r = t, o = r.name;
5253
- if ((typeof o != "string" || o.length === 0) && k("ai: responseFormat json_schema.name is required"), o.length > 64 && k("ai: responseFormat json_schema.name exceeds 64 chars"), wo.test(o) || k("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && k("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && k("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && k("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5254
- let i = Ro(r.schema);
5288
+ if ((typeof o != "string" || o.length === 0) && k("ai: responseFormat json_schema.name is required"), o.length > 64 && k("ai: responseFormat json_schema.name exceeds 64 chars"), Eo.test(o) || k("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && k("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && k("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && k("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5289
+ let i = xo(r.schema);
5255
5290
  i && k(i);
5256
5291
  }
5257
5292
  return;
@@ -5259,35 +5294,35 @@ function Ao(n) {
5259
5294
  k("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5260
5295
  }
5261
5296
  }
5262
- function xn(n, e, t) {
5297
+ function Un(n, e, t) {
5263
5298
  if (!e || typeof e != "object")
5264
- throw new l("validation_failed", "ai: options object is required");
5299
+ throw new c("validation_failed", "ai: options object is required");
5265
5300
  if (typeof e.model != "string" || e.model.length === 0)
5266
- throw new l("validation_failed", "ai: model is required");
5267
- if (e.model.length > Sn)
5268
- throw new l("validation_failed", `ai: model exceeds ${Sn} chars`);
5301
+ throw new c("validation_failed", "ai: model is required");
5302
+ if (e.model.length > In)
5303
+ throw new c("validation_failed", `ai: model exceeds ${In} chars`);
5269
5304
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5270
- throw new l("validation_failed", "ai: messages must be a non-empty array");
5271
- if (e.messages.length > kn)
5272
- throw new l("validation_failed", `ai: messages exceeds ${kn} per request`);
5305
+ throw new c("validation_failed", "ai: messages must be a non-empty array");
5306
+ if (e.messages.length > Rn)
5307
+ throw new c("validation_failed", `ai: messages exceeds ${Rn} per request`);
5273
5308
  for (let a of e.messages) {
5274
- if (!a || typeof a != "object" || typeof a.role != "string" || !bo.has(a.role))
5275
- throw new l(
5309
+ if (!a || typeof a != "object" || typeof a.role != "string" || !Co.has(a.role))
5310
+ throw new c(
5276
5311
  "validation_failed",
5277
5312
  "ai: each message role must be 'system' | 'user' | 'assistant'"
5278
5313
  );
5279
- Co(a.content, a.role);
5314
+ Lo(a.content, a.role);
5280
5315
  }
5281
- let r = To(e.messages);
5282
- if (r) throw new l("validation_failed", r);
5316
+ let r = No(e.messages);
5317
+ if (r) throw new c("validation_failed", r);
5283
5318
  let o = e.productId ?? n.productId, i = e.tenantId ?? n.tenantId;
5284
5319
  if (!o)
5285
- throw new l(
5320
+ throw new c(
5286
5321
  "validation_failed",
5287
5322
  "ai: productId required (pass to options or set on createNeetruClient)"
5288
5323
  );
5289
5324
  if (!i)
5290
- throw new l(
5325
+ throw new c(
5291
5326
  "validation_failed",
5292
5327
  "ai: tenantId required (pass to options or set on createNeetruClient)"
5293
5328
  );
@@ -5300,24 +5335,24 @@ function xn(n, e, t) {
5300
5335
  stream: t
5301
5336
  };
5302
5337
  if (e.maxTokens !== void 0) {
5303
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Tn)
5304
- throw new l(
5338
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Cn)
5339
+ throw new c(
5305
5340
  "validation_failed",
5306
- `ai: maxTokens must be a positive integer <= ${Tn}`
5341
+ `ai: maxTokens must be a positive integer <= ${Cn}`
5307
5342
  );
5308
5343
  s.maxTokens = e.maxTokens;
5309
5344
  }
5310
5345
  if (e.temperature !== void 0) {
5311
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < Rn || e.temperature > In)
5312
- throw new l(
5346
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < An || e.temperature > En)
5347
+ throw new c(
5313
5348
  "validation_failed",
5314
- `ai: temperature must be a finite number between ${Rn} and ${In}`
5349
+ `ai: temperature must be a finite number between ${An} and ${En}`
5315
5350
  );
5316
5351
  s.temperature = e.temperature;
5317
5352
  }
5318
- return e.responseFormat !== void 0 && (Ao(e.responseFormat), s.responseFormat = e.responseFormat), s;
5353
+ return e.responseFormat !== void 0 && (Uo(e.responseFormat), s.responseFormat = e.responseFormat), s;
5319
5354
  }
5320
- async function Mn(n) {
5355
+ async function jn(n) {
5321
5356
  try {
5322
5357
  let e = await n.text();
5323
5358
  return e ? JSON.parse(e) : void 0;
@@ -5325,48 +5360,48 @@ async function Mn(n) {
5325
5360
  return;
5326
5361
  }
5327
5362
  }
5328
- function Eo(n, e) {
5363
+ function Mo(n, e) {
5329
5364
  let t = n.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
5330
5365
  return `${t}${r}`;
5331
5366
  }
5332
- async function On(n, e, t, r) {
5367
+ async function Mn(n, e, t, r) {
5333
5368
  if (!n.apiKey)
5334
- throw new l(
5369
+ throw new c(
5335
5370
  "missing_api_key",
5336
5371
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
5337
5372
  );
5338
- let o = Eo(n.baseUrl, ho), { headers: i, correlationId: s } = ae({
5373
+ let o = Mo(n.baseUrl, So), { headers: i, correlationId: s } = ce({
5339
5374
  "content-type": "application/json",
5340
5375
  accept: r ? "text/event-stream" : "application/json",
5341
5376
  authorization: `Bearer ${n.apiKey}`
5342
5377
  }), a = { method: "POST", headers: i, body: JSON.stringify(e) };
5343
- r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(_n);
5344
- let c;
5378
+ r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(wn);
5379
+ let l;
5345
5380
  try {
5346
- c = await n.fetch(o, a);
5381
+ l = await n.fetch(o, a);
5347
5382
  } catch (p) {
5348
- let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${_n / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5349
- throw new l("network_error", f, void 0, void 0, void 0, s);
5383
+ let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${wn / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5384
+ throw new c("network_error", f, void 0, void 0, void 0, s);
5350
5385
  }
5351
- let d = c.headers.get("x-request-id") ?? c.headers.get("x-correlation-id") ?? void 0;
5352
- if (!c.ok) {
5353
- let p = await Mn(c), f = le(c.status), _ = `HTTP ${c.status}`;
5386
+ let d = l.headers.get("x-request-id") ?? l.headers.get("x-correlation-id") ?? void 0;
5387
+ if (!l.ok) {
5388
+ let p = await jn(l), f = de(l.status), h = `HTTP ${l.status}`;
5354
5389
  if (p && typeof p == "object" && "error" in p) {
5355
- let b = p.error;
5356
- typeof b == "string" ? _ = b : b && typeof b == "object" && (typeof b.code == "string" && (f = b.code), typeof b.message == "string" && (_ = b.message));
5390
+ let y = p.error;
5391
+ typeof y == "string" ? h = y : y && typeof y == "object" && (typeof y.code == "string" && (f = y.code), typeof y.message == "string" && (h = y.message));
5357
5392
  }
5358
- throw new l(f, _, c.status, d, void 0, s);
5393
+ throw new c(f, h, l.status, d, void 0, s);
5359
5394
  }
5360
- let u = c.headers.get("x-neetru-version");
5361
- return u && ce(u), c;
5395
+ let u = l.headers.get("x-neetru-version");
5396
+ return u && le(u), l;
5362
5397
  }
5363
- function Ln(n) {
5398
+ function qn(n) {
5364
5399
  return {
5365
5400
  provider: n.headers.get("x-neetru-provider") ?? "",
5366
5401
  usageWarning: n.headers.get("x-neetru-ai-usage-warning") === "1"
5367
5402
  };
5368
5403
  }
5369
- function Un(n) {
5404
+ function Fn(n) {
5370
5405
  let e = [];
5371
5406
  for (let r of n.split(`
5372
5407
  `)) {
@@ -5387,12 +5422,12 @@ function Un(n) {
5387
5422
  return null;
5388
5423
  }
5389
5424
  }
5390
- function qn(n) {
5425
+ function $n(n) {
5391
5426
  return {
5392
5427
  async chat(e) {
5393
- let t = xn(n, e, false), r = await On(n, t, e.signal, false), { provider: o, usageWarning: i } = Ln(r), s = await Mn(r);
5428
+ let t = Un(n, e, false), r = await Mn(n, t, e.signal, false), { provider: o, usageWarning: i } = qn(r), s = await jn(r);
5394
5429
  if (!s || s.ok !== true || !Array.isArray(s.choices))
5395
- throw new l("invalid_response", "ai.chat response missing ok/choices");
5430
+ throw new c("invalid_response", "ai.chat response missing ok/choices");
5396
5431
  return {
5397
5432
  choices: s.choices,
5398
5433
  usage: s.usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
@@ -5402,38 +5437,38 @@ function qn(n) {
5402
5437
  };
5403
5438
  },
5404
5439
  stream(e) {
5405
- let t = xn(n, e, true), r = On(n, t, e.signal, true), o = r.then(Ln);
5440
+ let t = Un(n, e, true), r = Mn(n, t, e.signal, true), o = r.then(qn);
5406
5441
  o.catch(() => {
5407
5442
  });
5408
5443
  async function* i() {
5409
5444
  let a = (await r).body;
5410
5445
  if (!a)
5411
- throw new l("invalid_response", "ai.stream: response has no body");
5412
- let c = a.getReader(), d = new TextDecoder(), u = "";
5446
+ throw new c("invalid_response", "ai.stream: response has no body");
5447
+ let l = a.getReader(), d = new TextDecoder(), u = "";
5413
5448
  try {
5414
5449
  for (; ; ) {
5415
- let { done: f, value: _ } = await c.read();
5450
+ let { done: f, value: h } = await l.read();
5416
5451
  if (f) break;
5417
- u += d.decode(_, { stream: !0 });
5418
- let b;
5419
- for (; (b = u.indexOf(`
5452
+ u += d.decode(h, { stream: !0 });
5453
+ let y;
5454
+ for (; (y = u.indexOf(`
5420
5455
 
5421
5456
  `)) !== -1; ) {
5422
- let S = u.slice(0, b);
5423
- u = u.slice(b + 2);
5424
- let x = Un(S);
5457
+ let T = u.slice(0, y);
5458
+ u = u.slice(y + 2);
5459
+ let x = Fn(T);
5425
5460
  if (x && "done" in x) return;
5426
5461
  x && "content" in x && (yield x.content);
5427
5462
  }
5428
5463
  }
5429
5464
  let p = u.trim();
5430
5465
  if (p) {
5431
- let f = Un(p);
5466
+ let f = Fn(p);
5432
5467
  f && "content" in f && (yield f.content);
5433
5468
  }
5434
5469
  } finally {
5435
5470
  try {
5436
- c.releaseLock();
5471
+ l.releaseLock();
5437
5472
  } catch {
5438
5473
  }
5439
5474
  try {
@@ -5451,20 +5486,8 @@ function qn(n) {
5451
5486
  }
5452
5487
 
5453
5488
  // src/mocks.ts
5454
- I();
5455
-
5456
- // src/runtime-env.ts
5457
- function Ce() {
5458
- try {
5459
- if (typeof process < "u" && process.env)
5460
- return process.env.NODE_ENV === "production";
5461
- } catch {
5462
- }
5463
- return false;
5464
- }
5465
-
5466
- // src/mocks.ts
5467
- var tt = Object.freeze({
5489
+ C();
5490
+ var rt = Object.freeze({
5468
5491
  uid: "dev-fixture-uid-0001",
5469
5492
  email: "dev@neetru.local",
5470
5493
  emailVerified: true,
@@ -5476,8 +5499,8 @@ var tt = Object.freeze({
5476
5499
  _listeners;
5477
5500
  _allowUnsignedDecode;
5478
5501
  constructor(e = null, t) {
5479
- if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Ce())
5480
- throw new l(
5502
+ if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && $e())
5503
+ throw new c(
5481
5504
  "invalid_config",
5482
5505
  "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."
5483
5506
  );
@@ -5486,10 +5509,10 @@ var tt = Object.freeze({
5486
5509
  );
5487
5510
  }
5488
5511
  async signIn(e) {
5489
- return this._user || (this._user = { ...tt }), this._notify(), this._user;
5512
+ return this._user || (this._user = { ...rt }), this._notify(), this._user;
5490
5513
  }
5491
5514
  async signOut() {
5492
- this._user = null, this._notify();
5515
+ return this._user = null, this._notify(), { localSessionCleared: true, remoteRevocation: "skipped" };
5493
5516
  }
5494
5517
  getUser() {
5495
5518
  return this._user;
@@ -5518,9 +5541,9 @@ var tt = Object.freeze({
5518
5541
  if (this._verifyTokenOverride)
5519
5542
  return this._verifyTokenOverride(e);
5520
5543
  if (!e)
5521
- throw new l("token_invalid_signature", "Token inv\xE1lido: string vazia");
5544
+ throw new c("token_invalid_signature", "Token inv\xE1lido: string vazia");
5522
5545
  if (!this._allowUnsignedDecode)
5523
- throw new l(
5546
+ throw new c(
5524
5547
  "unauthorized",
5525
5548
  "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."
5526
5549
  );
@@ -5546,7 +5569,7 @@ var tt = Object.freeze({
5546
5569
  } catch {
5547
5570
  }
5548
5571
  if (this._user) return this._user;
5549
- throw new l("token_invalid_signature", "Nenhum user mock dispon\xEDvel e JWT sem sub v\xE1lido");
5572
+ throw new c("token_invalid_signature", "Nenhum user mock dispon\xEDvel e JWT sem sub v\xE1lido");
5550
5573
  }
5551
5574
  /**
5552
5575
  * Mock de `handleRedirectCallback` (Bug 2 / 3.1.3) — não há redirect real no
@@ -5624,14 +5647,14 @@ var tt = Object.freeze({
5624
5647
  tenantId: r?.tenantId,
5625
5648
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
5626
5649
  });
5627
- let c = this._quotas.get(e)?.limit ?? -1;
5650
+ let l = this._quotas.get(e)?.limit ?? -1;
5628
5651
  return {
5629
5652
  ok: true,
5630
5653
  counterId: `mock_${e}`,
5631
5654
  value: s,
5632
- limit: c,
5633
- remaining: c < 0 ? -1 : Math.max(0, c - s),
5634
- status: c > 0 && s >= c ? "read_only_overlimit" : "ok"
5655
+ limit: l,
5656
+ remaining: l < 0 ? -1 : Math.max(0, l - s),
5657
+ status: l > 0 && s >= l ? "read_only_overlimit" : "ok"
5635
5658
  };
5636
5659
  }
5637
5660
  async check(e, t) {
@@ -5673,10 +5696,10 @@ var tt = Object.freeze({
5673
5696
  _tickets = [];
5674
5697
  _ticketSeq = 0;
5675
5698
  async createTicket(e) {
5676
- if (!e?.subject) throw new l("validation_failed", "subject required");
5677
- if (!e?.message) throw new l("validation_failed", "message required");
5699
+ if (!e?.subject) throw new c("validation_failed", "subject required");
5700
+ if (!e?.message) throw new c("validation_failed", "message required");
5678
5701
  if (!e?.productSlug)
5679
- throw new l(
5702
+ throw new c(
5680
5703
  "validation_failed",
5681
5704
  "productSlug required (3.0 breaking \u2014 pass to input or set on createNeetruClient)"
5682
5705
  );
@@ -5708,10 +5731,10 @@ var tt = Object.freeze({
5708
5731
  }
5709
5732
  _find(e) {
5710
5733
  if (!e || typeof e != "string")
5711
- throw new l("validation_failed", "ticketId is required");
5734
+ throw new c("validation_failed", "ticketId is required");
5712
5735
  let t = this._tickets.find((r) => r.id === e);
5713
5736
  if (!t)
5714
- throw new l("not_found", `ticket ${e} not found`);
5737
+ throw new c("not_found", `ticket ${e} not found`);
5715
5738
  return t;
5716
5739
  }
5717
5740
  /** 3.4: espelha `markResolvedSeen` — idempotente (só seta se ainda null). */
@@ -5727,18 +5750,18 @@ var tt = Object.freeze({
5727
5750
  /** 3.4: espelha `submitSatisfaction` — terminal, seta `satisfiedAt`. */
5728
5751
  async submitSatisfaction(e) {
5729
5752
  if (!e || typeof e != "object")
5730
- throw new l("validation_failed", "input is required");
5753
+ throw new c("validation_failed", "input is required");
5731
5754
  if (e.rating !== null && e.rating !== void 0 && (!Number.isInteger(e.rating) || e.rating < 1 || e.rating > 5))
5732
- throw new l("validation_failed", "rating must be an integer 1-5 or null");
5755
+ throw new c("validation_failed", "rating must be an integer 1-5 or null");
5733
5756
  if (typeof e.comment == "string" && e.comment.length > 2e3)
5734
- throw new l("validation_failed", "comment max 2000 chars");
5757
+ throw new c("validation_failed", "comment max 2000 chars");
5735
5758
  let t = this._find(e.ticketId);
5736
5759
  t.satisfiedAt = (/* @__PURE__ */ new Date()).toISOString(), t.rating = e.rating ?? null, t.satisfactionComment = e.comment ?? null;
5737
5760
  }
5738
5761
  /** 3.4: espelha `contestTicket` — reabre e zera o ciclo de satisfação. */
5739
5762
  async contestTicket(e, t) {
5740
5763
  if (typeof t?.comment == "string" && t.comment.length > 2e3)
5741
- throw new l("validation_failed", "comment max 2000 chars");
5764
+ throw new c("validation_failed", "comment max 2000 chars");
5742
5765
  let r = this._find(e);
5743
5766
  r.status = "open", r.resolvedAt = null, r.resolvedNotifiedAt = null, r.satisfactionAttempts = 0, r.lastSatisfactionAttemptAt = null, r.satisfiedAt = null, r.rating = null, r.satisfactionComment = null;
5744
5767
  }
@@ -5781,9 +5804,9 @@ var Ne = class {
5781
5804
  }
5782
5805
  async chat(e) {
5783
5806
  if (!e || typeof e.model != "string" || e.model.length === 0)
5784
- throw new l("validation_failed", "ai: model is required");
5807
+ throw new c("validation_failed", "ai: model is required");
5785
5808
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5786
- throw new l("validation_failed", "ai: messages must be a non-empty array");
5809
+ throw new c("validation_failed", "ai: messages must be a non-empty array");
5787
5810
  this._calls.push({ model: e.model, messages: e.messages, stream: false });
5788
5811
  let t = this._reply(e), r = e.messages.reduce((i, s) => i + this._contentToText(s.content).length, 0), o = t.length;
5789
5812
  return {
@@ -5800,9 +5823,9 @@ var Ne = class {
5800
5823
  }
5801
5824
  stream(e) {
5802
5825
  if (!e || typeof e.model != "string" || e.model.length === 0)
5803
- throw new l("validation_failed", "ai: model is required");
5826
+ throw new c("validation_failed", "ai: model is required");
5804
5827
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5805
- throw new l("validation_failed", "ai: messages must be a non-empty array");
5828
+ throw new c("validation_failed", "ai: messages must be a non-empty array");
5806
5829
  this._calls.push({ model: e.model, messages: e.messages, stream: true });
5807
5830
  let t = this._reply(e), r = t.match(/\S+\s*/g) ?? [t], o = Promise.resolve({ provider: "mock", usageWarning: false });
5808
5831
  async function* i() {
@@ -5816,47 +5839,68 @@ var Ne = class {
5816
5839
  }
5817
5840
  };
5818
5841
 
5842
+ // src/timeout.ts
5843
+ function Wn(n) {
5844
+ let e = globalThis.AbortSignal;
5845
+ if (typeof e?.timeout == "function")
5846
+ return { signal: e.timeout(n), clear: () => {
5847
+ } };
5848
+ if (typeof globalThis.AbortController != "function")
5849
+ return { signal: void 0, clear: () => {
5850
+ } };
5851
+ let t = new AbortController(), r = setTimeout(() => t.abort(), n);
5852
+ return r.unref?.(), { signal: t.signal, clear: () => clearTimeout(r) };
5853
+ }
5854
+ function Bn(n, e, t) {
5855
+ let r, o = new Promise((i) => {
5856
+ r = setTimeout(() => i(t()), e), r.unref?.();
5857
+ });
5858
+ return Promise.race([n, o]).finally(() => {
5859
+ r !== void 0 && clearTimeout(r);
5860
+ });
5861
+ }
5862
+
5819
5863
  // src/auth-pkce-shared.ts
5820
- I();
5821
- function Fn() {
5864
+ C();
5865
+ function Vn() {
5822
5866
  let n = globalThis.crypto;
5823
5867
  if (!n || typeof n.getRandomValues != "function" || !n.subtle)
5824
- throw new l(
5868
+ throw new c(
5825
5869
  "runtime_unsupported",
5826
5870
  "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."
5827
5871
  );
5828
5872
  return n;
5829
5873
  }
5830
- function jn(n) {
5874
+ function Kn(n) {
5831
5875
  let e = "";
5832
5876
  for (let r of n) e += String.fromCharCode(r);
5833
5877
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
5834
5878
  }
5835
5879
  function xe(n, e) {
5836
5880
  let t = new Uint8Array(e);
5837
- return n.getRandomValues(t), jn(t);
5881
+ return n.getRandomValues(t), Kn(t);
5838
5882
  }
5839
- async function $n(n, e) {
5883
+ async function zn(n, e) {
5840
5884
  let t = new TextEncoder().encode(e), r = await n.subtle.digest("SHA-256", t);
5841
- return jn(new Uint8Array(r));
5885
+ return Kn(new Uint8Array(r));
5842
5886
  }
5843
- function oe(n) {
5887
+ function ie(n) {
5844
5888
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.replace(/^https?:\/\/api\./, "https://auth.");
5845
5889
  }
5846
- function Wn(n) {
5890
+ function Hn(n) {
5847
5891
  let e = n.oidcClientId;
5848
- if (!e && n.apiKey && (e = ct(n.apiKey).keyId), !e)
5849
- throw new l(
5892
+ if (!e && n.apiKey && (e = dt(n.apiKey).keyId), !e)
5893
+ throw new c(
5850
5894
  "invalid_config",
5851
5895
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
5852
5896
  );
5853
5897
  return e;
5854
5898
  }
5855
- function Bn(n) {
5899
+ function Qn(n) {
5856
5900
  let e = new URL("/api/v1/oauth/authorize", n.idpOrigin);
5857
5901
  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;
5858
5902
  }
5859
- function nt(n) {
5903
+ function ot(n) {
5860
5904
  let e = n.split(".");
5861
5905
  if (e.length !== 3) return null;
5862
5906
  try {
@@ -5866,8 +5910,8 @@ function nt(n) {
5866
5910
  return null;
5867
5911
  }
5868
5912
  }
5869
- function ie(n) {
5870
- let e = nt(n);
5913
+ function se(n) {
5914
+ let e = ot(n);
5871
5915
  return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
5872
5916
  uid: e.sub,
5873
5917
  email: typeof e.email == "string" ? e.email : "",
@@ -5880,43 +5924,43 @@ function ie(n) {
5880
5924
  ...e
5881
5925
  };
5882
5926
  }
5883
- var Po = "/api/v1/oauth/revoke";
5884
- async function Vn(n, e, t, r) {
5885
- let o = `${e}${Po}`, i = true;
5927
+ var qo = "/api/v1/oauth/revoke";
5928
+ async function Gn(n, e, t, r) {
5929
+ let o = `${e}${qo}`, i = true;
5886
5930
  for (let s of r) {
5887
5931
  if (!s.token) continue;
5888
5932
  let a = new URLSearchParams({
5889
5933
  token: s.token,
5890
5934
  token_type_hint: s.hint,
5891
5935
  client_id: t
5892
- }).toString(), c = false;
5893
- for (let d = 0; d < 2 && !c; d++)
5936
+ }).toString(), l = false;
5937
+ for (let d = 0; d < 2 && !l; d++)
5894
5938
  try {
5895
- if (c = (await n(o, {
5939
+ if (l = (await n(o, {
5896
5940
  method: "POST",
5897
5941
  headers: { "content-type": "application/x-www-form-urlencoded" },
5898
5942
  body: a
5899
- })).ok, !c) break;
5943
+ })).ok, !l) break;
5900
5944
  } catch {
5901
5945
  d === 0 && await new Promise((u) => setTimeout(u, 500));
5902
5946
  }
5903
- c || (i = false);
5947
+ l || (i = false);
5904
5948
  }
5905
5949
  return i;
5906
5950
  }
5907
5951
 
5908
5952
  // src/auth.ts
5909
- qe();
5953
+ Fe();
5910
5954
 
5911
5955
  // src/end-user-token.ts
5912
- var Do = /* @__PURE__ */ new WeakMap();
5913
- function Kn(n, e) {
5914
- Do.set(n, e);
5956
+ var Fo = /* @__PURE__ */ new WeakMap();
5957
+ function Jn(n, e) {
5958
+ Fo.set(n, e);
5915
5959
  }
5916
5960
 
5917
5961
  // src/unsupported-db.ts
5918
- I();
5919
- var No = "[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.)", xo = /* @__PURE__ */ new Set([
5962
+ C();
5963
+ var jo = "[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.)", $o = /* @__PURE__ */ new Set([
5920
5964
  "then",
5921
5965
  "toJSON",
5922
5966
  "valueOf",
@@ -5925,13 +5969,13 @@ var No = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O
5925
5969
  "asymmetricMatch",
5926
5970
  "nodeType"
5927
5971
  ]);
5928
- function zn() {
5972
+ function Xn() {
5929
5973
  let n = () => {
5930
- throw new l("runtime_unsupported", No, void 0, void 0, "react-native");
5974
+ throw new c("runtime_unsupported", jo, void 0, void 0, "react-native");
5931
5975
  }, e = {};
5932
5976
  return new Proxy(e, {
5933
5977
  get(t, r) {
5934
- if (!(typeof r == "symbol" || xo.has(r)))
5978
+ if (!(typeof r == "symbol" || $o.has(r)))
5935
5979
  return r === "toString" ? () => "[NeetruDb indispon\xEDvel em React Native]" : n;
5936
5980
  },
5937
5981
  set() {
@@ -5941,7 +5985,7 @@ function zn() {
5941
5985
  }
5942
5986
 
5943
5987
  // src/auth.ts
5944
- function Lo() {
5988
+ function Bo() {
5945
5989
  try {
5946
5990
  let e = globalThis.process?.env?.NEETRU_API_KEY;
5947
5991
  return typeof e == "string" && e.length > 0 ? e : void 0;
@@ -5949,7 +5993,7 @@ function Lo() {
5949
5993
  return;
5950
5994
  }
5951
5995
  }
5952
- function Uo(n) {
5996
+ function Vo(n) {
5953
5997
  if (n) return n;
5954
5998
  try {
5955
5999
  let t = globalThis.process?.env?.NEETRU_ENV;
@@ -5963,11 +6007,11 @@ function Uo(n) {
5963
6007
  }
5964
6008
  return "prod";
5965
6009
  }
5966
- var Mo = it;
5967
- function ra() {
5968
- st();
6010
+ var Ko = at;
6011
+ function ga() {
6012
+ ct();
5969
6013
  }
5970
- function qo(n) {
6014
+ function zo(n) {
5971
6015
  let e = n.sub ?? "", t = typeof n.email == "string" ? n.email : "";
5972
6016
  return {
5973
6017
  uid: e,
@@ -5982,8 +6026,8 @@ function qo(n) {
5982
6026
  ...n
5983
6027
  };
5984
6028
  }
5985
- var se = "neetru_oauth_tx";
5986
- function rt(n) {
6029
+ var ae = "neetru_oauth_tx";
6030
+ function it(n) {
5987
6031
  try {
5988
6032
  let e = globalThis.history;
5989
6033
  if (!e || typeof e.replaceState != "function") return;
@@ -5994,7 +6038,7 @@ function rt(n) {
5994
6038
  } catch {
5995
6039
  }
5996
6040
  }
5997
- function Fo(n) {
6041
+ function Ho(n) {
5998
6042
  let e = "neetru_id_token", t = "neetru_refresh_token", r = /* @__PURE__ */ new Set(), o = null, i = null, s = null;
5999
6043
  function a() {
6000
6044
  try {
@@ -6003,7 +6047,7 @@ function Fo(n) {
6003
6047
  return null;
6004
6048
  }
6005
6049
  }
6006
- function c() {
6050
+ function l() {
6007
6051
  try {
6008
6052
  return typeof globalThis.sessionStorage < "u" ? globalThis.sessionStorage : null;
6009
6053
  } catch {
@@ -6012,21 +6056,21 @@ function Fo(n) {
6012
6056
  }
6013
6057
  function d() {
6014
6058
  if (o) {
6015
- let h = o.exp;
6016
- return typeof h == "number" && h * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), S(), null) : o;
6059
+ let m = o.exp;
6060
+ return typeof m == "number" && m * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), T(), null) : o;
6017
6061
  }
6018
- let m = a();
6019
- if (!m) return null;
6020
- let g = m.getItem(e);
6021
- if (!g)
6022
- return S(), null;
6023
- let w = ie(g);
6024
- return w ? (o = w, x(w), o) : (m.removeItem(e), S(), null);
6062
+ let g = a();
6063
+ if (!g) return null;
6064
+ let b = g.getItem(e);
6065
+ if (!b)
6066
+ return T(), null;
6067
+ let w = se(b);
6068
+ return w ? (o = w, x(w), o) : (g.removeItem(e), T(), null);
6025
6069
  }
6026
6070
  function u() {
6027
- for (let m of r)
6071
+ for (let g of r)
6028
6072
  try {
6029
- m(o);
6073
+ g(o);
6030
6074
  } catch {
6031
6075
  }
6032
6076
  }
@@ -6036,72 +6080,77 @@ function Fo(n) {
6036
6080
  function f() {
6037
6081
  return a()?.getItem(t) ?? null;
6038
6082
  }
6039
- function _() {
6083
+ function h() {
6040
6084
  o = null;
6041
- let m = a();
6042
- m?.removeItem(e), m?.removeItem(t), u();
6043
- }
6044
- function b() {
6045
- return s || (s = (async () => {
6046
- let m = f();
6047
- if (!m) return false;
6048
- let g;
6085
+ let g = a();
6086
+ g?.removeItem(e), g?.removeItem(t), u();
6087
+ }
6088
+ function y() {
6089
+ if (s) return s;
6090
+ let g = false, b = (async () => {
6091
+ let w = f();
6092
+ if (!w) return false;
6093
+ let m;
6049
6094
  try {
6050
- g = T();
6095
+ m = R();
6051
6096
  } catch {
6052
6097
  return false;
6053
6098
  }
6054
- let h = `${oe(n.baseUrl)}/api/v1/oauth/token`, C = new URLSearchParams({
6099
+ let D = `${ie(n.baseUrl)}/api/v1/oauth/token`, O = new URLSearchParams({
6055
6100
  grant_type: "refresh_token",
6056
- refresh_token: m,
6057
- client_id: g
6058
- }), D;
6101
+ refresh_token: w,
6102
+ client_id: m
6103
+ }), { signal: A, clear: M } = Wn(15e3), I;
6059
6104
  try {
6060
- D = await n.fetch(h, {
6105
+ I = await n.fetch(D, {
6061
6106
  method: "POST",
6062
6107
  headers: { "content-type": "application/x-www-form-urlencoded" },
6063
- body: C.toString()
6108
+ body: O.toString(),
6109
+ signal: A
6064
6110
  });
6065
6111
  } catch {
6066
6112
  return false;
6113
+ } finally {
6114
+ M();
6067
6115
  }
6068
- let E = null;
6116
+ let L = null;
6069
6117
  try {
6070
- E = await D.json();
6118
+ L = await I.json();
6071
6119
  } catch {
6072
- E = null;
6120
+ L = null;
6073
6121
  }
6074
- if (!D.ok || typeof E?.error == "string") return false;
6075
- let R = E?.id_token;
6076
- if (typeof R != "string" || R.length === 0) return false;
6077
- let O = ie(R);
6078
- if (!O) return false;
6079
- let A = a();
6080
- A?.setItem(e, R);
6081
- let U = E?.refresh_token;
6082
- return typeof U == "string" && U.length > 0 && A?.setItem(t, U), o = O, x(O), u(), true;
6083
- })().finally(() => {
6122
+ if (!I.ok || typeof L?.error == "string") return false;
6123
+ let U = L?.id_token;
6124
+ if (typeof U != "string" || U.length === 0) return false;
6125
+ let q = se(U);
6126
+ if (!q || g) return false;
6127
+ let P = a();
6128
+ P?.setItem(e, U);
6129
+ let Le = L?.refresh_token;
6130
+ return typeof Le == "string" && Le.length > 0 && P?.setItem(t, Le), o = q, x(q), u(), true;
6131
+ })();
6132
+ return s = Bn(b, 15e3, () => (g = true, false)).finally(() => {
6084
6133
  s = null;
6085
- }), s);
6134
+ }), s;
6086
6135
  }
6087
- function S() {
6088
- f() && b().then((m) => {
6089
- m || _();
6136
+ function T() {
6137
+ f() && y().then((g) => {
6138
+ g || h();
6090
6139
  });
6091
6140
  }
6092
- function x(m) {
6141
+ function x(g) {
6093
6142
  p();
6094
- let g = m.exp;
6095
- if (typeof g != "number") return;
6096
- let w = g * 1e3 - Date.now();
6143
+ let b = g.exp;
6144
+ if (typeof b != "number") return;
6145
+ let w = b * 1e3 - Date.now();
6097
6146
  if (!(w <= 0)) {
6098
6147
  if (f()) {
6099
- let h = Math.min(w, Math.max(3e4, w * 0.2)), C = Math.max(1, w - h);
6148
+ let m = Math.min(w, Math.max(3e4, w * 0.2)), S = Math.max(1, w - m);
6100
6149
  i = setTimeout(() => {
6101
- i = null, b().then((D) => {
6102
- D || _();
6150
+ i = null, y().then((D) => {
6151
+ D || h();
6103
6152
  });
6104
- }, C);
6153
+ }, S);
6105
6154
  return;
6106
6155
  }
6107
6156
  i = setTimeout(() => {
@@ -6109,223 +6158,235 @@ function Fo(n) {
6109
6158
  }, w + 1);
6110
6159
  }
6111
6160
  }
6112
- function T() {
6113
- return Wn(n);
6161
+ function R() {
6162
+ return Hn(n);
6114
6163
  }
6115
- async function P(m) {
6116
- let g = m ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6117
- if (!g) return null;
6164
+ async function E(g) {
6165
+ let b = g ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6166
+ if (!b) return null;
6118
6167
  let w;
6119
6168
  try {
6120
- w = new URL(g);
6169
+ w = new URL(b);
6121
6170
  } catch {
6122
6171
  return null;
6123
6172
  }
6124
- let h = w.searchParams, C = h.get("error");
6125
- if (C) {
6126
- let U = h.get("error_description") ?? C;
6127
- throw c()?.removeItem(se), rt(w), new l(C, `OIDC authorize falhou: ${U}`);
6173
+ let m = w.searchParams, S = m.get("error");
6174
+ if (S) {
6175
+ let L = m.get("error_description") ?? S;
6176
+ throw l()?.removeItem(ae), it(w), new c(S, `OIDC authorize falhou: ${L}`);
6128
6177
  }
6129
- let D = h.get("code");
6178
+ let D = m.get("code");
6130
6179
  if (!D) return null;
6131
- let E = h.get("state"), R = c(), O = R?.getItem(se) ?? null, A = null;
6132
- if (O)
6180
+ let O = m.get("state"), A = l(), M = A?.getItem(ae) ?? null, I = null;
6181
+ if (M)
6133
6182
  try {
6134
- A = JSON.parse(O);
6183
+ I = JSON.parse(M);
6135
6184
  } catch {
6136
- A = null;
6185
+ I = null;
6137
6186
  }
6138
- if (!A)
6139
- throw new l(
6187
+ if (!I)
6188
+ throw new c(
6140
6189
  "oidc_state_mismatch",
6141
6190
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado nesta sess\xE3o (ou j\xE1 consumido)."
6142
6191
  );
6143
- if (!E || E !== A.state)
6144
- throw R?.removeItem(se), rt(w), new l(
6192
+ if (!O || O !== I.state)
6193
+ throw A?.removeItem(ae), it(w), new c(
6145
6194
  "oidc_state_mismatch",
6146
6195
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
6147
6196
  );
6148
- return R?.removeItem(se), rt(w), {
6197
+ return A?.removeItem(ae), it(w), {
6149
6198
  code: D,
6150
- codeVerifier: A.codeVerifier,
6151
- redirectUri: A.redirectUri,
6152
- nonce: A.nonce,
6153
- state: A.state,
6154
- postLoginRedirect: A.postLoginRedirect
6199
+ codeVerifier: I.codeVerifier,
6200
+ redirectUri: I.redirectUri,
6201
+ nonce: I.nonce,
6202
+ state: I.state,
6203
+ postLoginRedirect: I.postLoginRedirect
6155
6204
  };
6156
6205
  }
6157
- async function q(m) {
6158
- let g = await P(m);
6159
- if (!g) return null;
6160
- let w = T(), C = `${oe(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
6206
+ async function j(g) {
6207
+ let b = await E(g);
6208
+ if (!b) return null;
6209
+ let w = R(), S = `${ie(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
6161
6210
  grant_type: "authorization_code",
6162
- code: g.code,
6163
- redirect_uri: g.redirectUri,
6211
+ code: b.code,
6212
+ redirect_uri: b.redirectUri,
6164
6213
  client_id: w,
6165
- code_verifier: g.codeVerifier
6166
- }), E;
6214
+ code_verifier: b.codeVerifier
6215
+ }), O;
6167
6216
  try {
6168
- E = await n.fetch(C, {
6217
+ O = await n.fetch(S, {
6169
6218
  method: "POST",
6170
6219
  headers: { "content-type": "application/x-www-form-urlencoded" },
6171
6220
  body: D.toString()
6172
6221
  });
6173
- } catch (L) {
6174
- throw new l(
6222
+ } catch (P) {
6223
+ throw new c(
6175
6224
  "network_error",
6176
- `POST ${C} falhou (network): ${L?.message ?? String(L)}`
6225
+ `POST ${S} falhou (network): ${P?.message ?? String(P)}`
6177
6226
  );
6178
6227
  }
6179
- let R = null;
6228
+ let A = null;
6180
6229
  try {
6181
- R = await E.json();
6230
+ A = await O.json();
6182
6231
  } catch {
6183
- R = null;
6232
+ A = null;
6184
6233
  }
6185
- if (!E.ok || typeof R?.error == "string") {
6186
- let L = typeof R?.error_description == "string" && R.error_description || typeof R?.error == "string" && R.error || `HTTP ${E.status}`;
6187
- throw new l(
6234
+ if (!O.ok || typeof A?.error == "string") {
6235
+ let P = typeof A?.error_description == "string" && A.error_description || typeof A?.error == "string" && A.error || `HTTP ${O.status}`;
6236
+ throw new c(
6188
6237
  "token_exchange_failed",
6189
- `Troca do authorization_code por tokens falhou no /token: ${L}`,
6190
- E.status
6238
+ `Troca do authorization_code por tokens falhou no /token: ${P}`,
6239
+ O.status
6191
6240
  );
6192
6241
  }
6193
- let O = R?.id_token;
6194
- if (typeof O != "string" || O.length === 0)
6195
- throw new l(
6242
+ let M = A?.id_token;
6243
+ if (typeof M != "string" || M.length === 0)
6244
+ throw new c(
6196
6245
  "token_exchange_failed",
6197
6246
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado.",
6198
- E.status
6247
+ O.status
6199
6248
  );
6200
- let A = nt(O);
6201
- if (!A)
6202
- throw new l(
6249
+ let I = ot(M);
6250
+ if (!I)
6251
+ throw new c(
6203
6252
  "token_exchange_failed",
6204
6253
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
6205
6254
  );
6206
- if (A.nonce !== g.nonce)
6207
- throw new l(
6255
+ if (I.nonce !== b.nonce)
6256
+ throw new c(
6208
6257
  "oidc_nonce_mismatch",
6209
6258
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
6210
6259
  );
6211
- let U = ie(O);
6212
- if (!U)
6213
- throw new l(
6260
+ let L = se(M);
6261
+ if (!L)
6262
+ throw new c(
6214
6263
  "token_exchange_failed",
6215
6264
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
6216
6265
  );
6217
- let F = a();
6218
- F?.setItem(e, O);
6219
- let j = R?.refresh_token;
6220
- return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = U, x(U), u(), { user: U, postLoginRedirect: g.postLoginRedirect };
6266
+ let U = a();
6267
+ U?.setItem(e, M);
6268
+ let q = A?.refresh_token;
6269
+ return typeof q == "string" && q.length > 0 && U?.setItem(t, q), o = L, x(L), u(), { user: L, postLoginRedirect: b.postLoginRedirect };
6221
6270
  }
6222
6271
  return {
6223
- async signIn(m) {
6272
+ async signIn(g) {
6224
6273
  if (typeof globalThis.location < "u" && typeof globalThis.location.assign == "function") {
6225
- let g = Fn(), w = m?.redirectUri ?? globalThis.location.origin, h = m?.scope ?? "openid profile email", C = T(), D = xe(g, 16), E = xe(g, 16), R = xe(g, 32), O = await $n(g, R), A = c();
6226
- if (!A)
6227
- throw new l(
6274
+ let b = Vn(), w = g?.redirectUri ?? globalThis.location.origin, m = g?.scope ?? "openid profile email", S = R(), D = xe(b, 16), O = xe(b, 16), A = xe(b, 32), M = await zn(b, A), I = l();
6275
+ if (!I)
6276
+ throw new c(
6228
6277
  "runtime_unsupported",
6229
6278
  "auth.signIn requer sessionStorage para guardar a transa\xE7\xE3o PKCE entre o redirect e o callback."
6230
6279
  );
6231
- let U = {
6280
+ let L = {
6232
6281
  state: D,
6233
- nonce: E,
6234
- codeVerifier: R,
6282
+ nonce: O,
6283
+ codeVerifier: A,
6235
6284
  redirectUri: w,
6236
- postLoginRedirect: m?.postLoginRedirect
6285
+ postLoginRedirect: g?.postLoginRedirect
6237
6286
  };
6238
- A.setItem(se, JSON.stringify(U));
6239
- let F = oe(n.baseUrl), j = Bn({
6240
- idpOrigin: F,
6241
- clientId: C,
6287
+ I.setItem(ae, JSON.stringify(L));
6288
+ let U = ie(n.baseUrl), q = Qn({
6289
+ idpOrigin: U,
6290
+ clientId: S,
6242
6291
  redirectUri: w,
6243
- scope: h,
6292
+ scope: m,
6244
6293
  state: D,
6245
- nonce: E,
6246
- codeChallenge: O
6294
+ nonce: O,
6295
+ codeChallenge: M
6247
6296
  });
6248
- globalThis.location.assign(j.toString());
6297
+ globalThis.location.assign(q.toString());
6249
6298
  return;
6250
6299
  }
6251
- throw new l(
6300
+ throw new c(
6252
6301
  "invalid_config",
6253
6302
  "auth.signIn requires a browser context or mocks. Use NEETRU_ENV=dev or pass mocks.auth."
6254
6303
  );
6255
6304
  },
6256
- handleRedirectCallback: P,
6257
- completeSignIn: q,
6305
+ handleRedirectCallback: E,
6306
+ completeSignIn: j,
6258
6307
  // 3.7.0: exposto pro client.support renovar a sessão 1x num 401
6259
6308
  // invalid_end_user_token (mesma função do refresh proativo, com dedup).
6260
- refreshTokens: b,
6309
+ refreshTokens: y,
6261
6310
  getIdToken() {
6262
- let g = a()?.getItem(e) ?? null;
6263
- return g && ie(g) ? g : null;
6311
+ let b = a()?.getItem(e) ?? null;
6312
+ return b && se(b) ? b : null;
6264
6313
  },
6265
6314
  async signOut() {
6266
- let m = a(), g = m?.getItem(t) ?? null;
6267
- if (m && (m.removeItem(e), m.removeItem(t)), p(), o = null, g) {
6268
- let w = null;
6315
+ let g = a(), b = g?.getItem(t) ?? null, w = true;
6316
+ if (g)
6317
+ for (let S of [e, t])
6318
+ try {
6319
+ g.removeItem(S);
6320
+ } catch {
6321
+ w = false;
6322
+ }
6323
+ p(), o = null;
6324
+ let m = "skipped";
6325
+ if (b) {
6326
+ let S = null;
6269
6327
  try {
6270
- w = T();
6328
+ S = R();
6271
6329
  } catch {
6272
- w = null;
6330
+ S = null;
6273
6331
  }
6274
- !(w && await Vn(n.fetch, oe(n.baseUrl), w, [
6275
- { token: g, hint: "refresh_token" }
6276
- ])) && typeof console < "u" && console.warn(
6277
- "[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."
6332
+ S ? m = await Gn(
6333
+ n.fetch,
6334
+ ie(n.baseUrl),
6335
+ S,
6336
+ [{ token: b, hint: "refresh_token" }]
6337
+ ) ? "accepted" : "failed" : m = "not_configured", m !== "accepted" && typeof console < "u" && console.warn(
6338
+ "[neetru-sdk] signOut: a revoga\xE7\xE3o do refresh_token no servidor n\xE3o foi confirmada (" + m + "). A sess\xE3o local foi encerrada, mas o refresh_token pode seguir v\xE1lido at\xE9 expirar. Trate o campo remoteRevocation do SignOutResult no produto."
6278
6339
  );
6279
6340
  }
6280
- u();
6341
+ return u(), { localSessionCleared: w, remoteRevocation: m };
6281
6342
  },
6282
6343
  getUser() {
6283
6344
  return d();
6284
6345
  },
6285
- onAuthStateChanged(m) {
6286
- r.add(m);
6346
+ onAuthStateChanged(g) {
6347
+ r.add(g);
6287
6348
  try {
6288
- m(d());
6349
+ g(d());
6289
6350
  } catch {
6290
6351
  }
6291
6352
  return () => {
6292
- r.delete(m);
6353
+ r.delete(g);
6293
6354
  };
6294
6355
  },
6295
- async verifyToken(m, g) {
6296
- if (!m || typeof m != "string")
6297
- throw new l("token_invalid_signature", "token must be a non-empty string");
6298
- let h = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), C = h, D = `${h}/api/v1/oauth/.well-known/jwks`, E = g?.jwksCacheTtlMs ?? Ue, R = g?.audience, O = lt(n.apiKey), A = R ?? n.oidcClientId ?? O?.keyId;
6299
- if (!A)
6300
- throw new l(
6356
+ async verifyToken(g, b) {
6357
+ if (!g || typeof g != "string")
6358
+ throw new c("token_invalid_signature", "token must be a non-empty string");
6359
+ let m = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), S = m, D = `${m}/api/v1/oauth/.well-known/jwks`, O = b?.jwksCacheTtlMs ?? Me, A = b?.audience, M = ut(n.apiKey), I = A ?? n.oidcClientId ?? M?.keyId;
6360
+ if (!I)
6361
+ throw new c(
6301
6362
  "invalid_config",
6302
6363
  "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."
6303
6364
  );
6304
- let U = Mo(D, E);
6365
+ let L = Ko(D, O);
6305
6366
  try {
6306
- let { payload: F } = await jwtVerify(m, U, {
6307
- issuer: C,
6308
- audience: A,
6367
+ let { payload: U } = await jwtVerify(g, L, {
6368
+ issuer: S,
6369
+ audience: I,
6309
6370
  algorithms: ["RS256"]
6310
6371
  });
6311
- return qo(F);
6312
- } catch (F) {
6313
- let j = F?.code ?? F?.name ?? "", L = F?.message ?? String(F);
6314
- throw j === "ERR_JWT_EXPIRED" ? new l("token_expired", `Token expired: ${L}`) : j === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new l("token_invalid_signature", `Token signature invalid: ${L}`) : j === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? L.includes('"aud"') || L.includes("audience") ? new l("token_invalid_audience", `Token audience mismatch: ${L}`) : L.includes('"iss"') || L.includes("issuer") ? new l("token_invalid_issuer", `Token issuer mismatch: ${L}`) : new l("token_invalid_signature", `Token claim validation failed: ${L}`) : new l("token_invalid_signature", `Token verification failed: ${L}`);
6372
+ return zo(U);
6373
+ } catch (U) {
6374
+ let q = U?.code ?? U?.name ?? "", P = U?.message ?? String(U);
6375
+ throw q === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${P}`) : q === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${P}`) : q === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? P.includes('"aud"') || P.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${P}`) : P.includes('"iss"') || P.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${P}`) : new c("token_invalid_signature", `Token claim validation failed: ${P}`) : new c("token_invalid_signature", `Token verification failed: ${P}`);
6315
6376
  }
6316
6377
  }
6317
6378
  };
6318
6379
  }
6319
- function jo(n = {}) {
6380
+ function Qo(n = {}) {
6320
6381
  let e = n.fetch ?? globalThis.fetch;
6321
6382
  if (typeof e != "function")
6322
- throw new l(
6383
+ throw new c(
6323
6384
  "invalid_config",
6324
6385
  "fetch is not available in this runtime. Pass `fetch` explicitly to createNeetruClient."
6325
6386
  );
6326
- let t = n.apiKey ?? Lo();
6327
- wt({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6328
- let r = Uo(n.env), o = n.baseUrl ?? (r === "dev-local" ? mt : ft), i = pt(o, n.allowedHosts ?? []), s = Object.freeze({
6387
+ let t = n.apiKey ?? Bo();
6388
+ St({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6389
+ let r = Vo(n.env), o = n.baseUrl ?? (r === "dev-local" ? gt : ht), i = mt(o, n.allowedHosts ?? []), s = Object.freeze({
6329
6390
  apiKey: t,
6330
6391
  oidcClientId: n.oidcClientId,
6331
6392
  baseUrl: i,
@@ -6333,36 +6394,36 @@ function jo(n = {}) {
6333
6394
  env: r,
6334
6395
  productId: n.productId,
6335
6396
  tenantId: n.tenantId
6336
- }), a = r === "dev" && !Ce(), c = n.mocks?.auth ?? (a ? new Ae({ ...tt }) : Fo(s)), d = n.mocks?.usage ?? (a ? new Ee() : Ut(s)), u = n.endUserAuth ?? c, p = n.mocks?.support ?? (a ? new Pe() : Wt(s, {
6397
+ }), a = W(r), l = n.mocks?.auth ?? (a ? new Ae({ ...rt }) : Ho(s)), d = n.mocks?.usage ?? (a ? new Ee() : qt(s)), u = n.endUserAuth ?? l, p = n.mocks?.support ?? (a ? new Pe() : Vt(s, {
6337
6398
  getEndUserToken: () => u.getIdToken(),
6338
6399
  // `refreshTokens` é opcional (MockAuth/mocks próprios omitem).
6339
6400
  refreshEndUserToken: (() => {
6340
- let P = u.refreshTokens;
6341
- return typeof P == "function" ? () => P.call(u) : void 0;
6401
+ let E = u.refreshTokens;
6402
+ return typeof E == "function" ? () => E.call(u) : void 0;
6342
6403
  })()
6343
- })), f = n.mocks?.entitlements ?? (a ? new De() : Dt()), _ = n.mocks?.db ?? (X() === "react-native" ? zn() : ln(s, n.db)), b = n.mocks?.webhooks ?? (a ? new Se() : mn(s)), S = n.mocks?.notifications ?? (a ? new Re() : yn(s)), x = n.mocks?.ai ?? (a ? new Ne() : qn(s)), T = Object.freeze({
6404
+ })), f = n.mocks?.entitlements ?? (a ? new De() : xt()), h = n.mocks?.db ?? (Y() === "react-native" ? Xn() : pn(s, n.db)), y = n.mocks?.webhooks ?? (a ? new Te() : yn(s)), T = n.mocks?.notifications ?? (a ? new Ie() : vn(s)), x = n.mocks?.ai ?? (a ? new Ne() : $n(s)), R = Object.freeze({
6344
6405
  config: s,
6345
- auth: c,
6346
- catalog: Et(s),
6406
+ auth: l,
6407
+ catalog: Dt(s),
6347
6408
  entitlements: f,
6348
- telemetry: Ot(s),
6409
+ telemetry: Ut(s),
6349
6410
  usage: d,
6350
6411
  support: p,
6351
- db: _,
6352
- checkout: dn(s),
6353
- webhooks: b,
6354
- notifications: S,
6412
+ db: h,
6413
+ checkout: fn(s),
6414
+ webhooks: y,
6415
+ notifications: T,
6355
6416
  ai: x
6356
6417
  });
6357
- return n.endUserAuth && Kn(T, n.endUserAuth), T;
6418
+ return n.endUserAuth && Jn(R, n.endUserAuth), R;
6358
6419
  }
6359
6420
  var Oe = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6360
- function oa(n = {}) {
6421
+ function ya(n = {}) {
6361
6422
  let e = globalThis;
6362
- return e[Oe] || (e[Oe] = jo(n)), e[Oe];
6423
+ return e[Oe] || (e[Oe] = Qo(n)), e[Oe];
6363
6424
  }
6364
- function ia() {
6425
+ function _a() {
6365
6426
  delete globalThis[Oe];
6366
6427
  }
6367
6428
 
6368
- export { ra as __resetJwksCacheForTests, ia as __resetServerNeetruClientForTests, jo as createNeetruClient, oa as getServerNeetruClient };
6429
+ export { ga as __resetJwksCacheForTests, _a as __resetServerNeetruClientForTests, Qo as createNeetruClient, ya as getServerNeetruClient };