@neetru/sdk 3.8.1 → 3.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +14 -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 +844 -803
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +841 -800
  11. package/dist/build-guard.cjs +186 -82
  12. package/dist/build-guard.d.cts +53 -1
  13. package/dist/build-guard.d.ts +53 -1
  14. package/dist/build-guard.mjs +175 -74
  15. package/dist/catalog.cjs +1 -1
  16. package/dist/catalog.d.cts +1 -1
  17. package/dist/catalog.d.ts +1 -1
  18. package/dist/catalog.mjs +1 -1
  19. package/dist/checkout.cjs +62 -49
  20. package/dist/checkout.d.cts +1 -1
  21. package/dist/checkout.d.ts +1 -1
  22. package/dist/checkout.mjs +62 -49
  23. package/dist/db-react.d.cts +1 -1
  24. package/dist/db-react.d.ts +1 -1
  25. package/dist/db.cjs +200 -187
  26. package/dist/db.d.cts +1 -1
  27. package/dist/db.d.ts +1 -1
  28. package/dist/db.mjs +193 -180
  29. package/dist/entitlements.d.cts +1 -1
  30. package/dist/entitlements.d.ts +1 -1
  31. package/dist/firestore-compat.d.cts +1 -1
  32. package/dist/firestore-compat.d.ts +1 -1
  33. package/dist/index.cjs +880 -839
  34. package/dist/index.d.cts +2 -2
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.mjs +847 -806
  37. package/dist/mobile.cjs +328 -276
  38. package/dist/mobile.d.cts +12 -2
  39. package/dist/mobile.d.ts +12 -2
  40. package/dist/mobile.mjs +328 -276
  41. package/dist/mocks.cjs +5 -5
  42. package/dist/mocks.d.cts +2 -2
  43. package/dist/mocks.d.ts +2 -2
  44. package/dist/mocks.mjs +4 -4
  45. package/dist/notifications.cjs +1 -1
  46. package/dist/notifications.d.cts +1 -1
  47. package/dist/notifications.d.ts +1 -1
  48. package/dist/notifications.mjs +1 -1
  49. package/dist/react.cjs +119 -119
  50. package/dist/react.d.cts +8 -2
  51. package/dist/react.d.ts +8 -2
  52. package/dist/react.mjs +119 -119
  53. package/dist/support.cjs +1 -1
  54. package/dist/support.d.cts +1 -1
  55. package/dist/support.d.ts +1 -1
  56. package/dist/support.mjs +1 -1
  57. package/dist/telemetry.cjs +62 -49
  58. package/dist/telemetry.d.cts +1 -1
  59. package/dist/telemetry.d.ts +1 -1
  60. package/dist/telemetry.mjs +62 -49
  61. package/dist/{types-yv3EDKg2.d.cts → types-Bl_4HROd.d.cts} +62 -3
  62. package/dist/{types-BYPk_3HR.d.ts → types-Bqnsqvow.d.ts} +62 -3
  63. package/dist/usage.cjs +1 -1
  64. package/dist/usage.d.cts +1 -1
  65. package/dist/usage.d.ts +1 -1
  66. package/dist/usage.mjs +1 -1
  67. package/dist/webhooks.cjs +1 -1
  68. package/dist/webhooks.d.cts +1 -1
  69. package/dist/webhooks.d.ts +1 -1
  70. package/dist/webhooks.mjs +1 -1
  71. package/package.json +9 -1
package/dist/auth.cjs CHANGED
@@ -3,15 +3,15 @@
3
3
  var jose = require('jose');
4
4
  var idb = require('idb');
5
5
 
6
- var Qn = Object.defineProperty;
6
+ var Zn = Object.defineProperty;
7
7
  var $ = (n, e) => () => (n && (e = n(n = 0)), e);
8
- var ot = (n, e) => {
8
+ var st = (n, e) => {
9
9
  for (var t in e)
10
- Qn(n, t, { get: e[t], enumerable: true });
10
+ Zn(n, t, { get: e[t], enumerable: true });
11
11
  };
12
12
 
13
13
  // src/errors.ts
14
- var c, V, I = $(() => {
14
+ var c, K, C = $(() => {
15
15
  c = class n extends Error {
16
16
  code;
17
17
  status;
@@ -35,7 +35,7 @@ var c, V, I = $(() => {
35
35
  constructor(e, t, r, o, i, s) {
36
36
  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);
37
37
  }
38
- }, V = class n extends c {
38
+ }, K = class n extends c {
39
39
  constructor(e, t, r, o, i) {
40
40
  super("auth_required", e, r, o, t, i), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, n.prototype);
41
41
  }
@@ -43,7 +43,7 @@ var c, V, I = $(() => {
43
43
  });
44
44
 
45
45
  // src/idempotency.ts
46
- function ht() {
46
+ function yt() {
47
47
  let n = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
48
48
  if (n && typeof n.randomUUID == "function")
49
49
  return n.randomUUID();
@@ -52,15 +52,15 @@ function ht() {
52
52
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
53
53
  );
54
54
  }
55
- var gt = $(() => {
56
- I();
55
+ var _t = $(() => {
56
+ C();
57
57
  });
58
58
 
59
59
  // src/correlation.ts
60
- function _t(n) {
61
- return typeof n == "string" && n.length > 0 && n.length <= 128 && tr.test(n);
60
+ function vt(n) {
61
+ return typeof n == "string" && n.length > 0 && n.length <= 128 && sr.test(n);
62
62
  }
63
- function nr() {
63
+ function ar() {
64
64
  let n = globalThis.crypto;
65
65
  try {
66
66
  if (n && typeof n.randomUUID == "function") return n.randomUUID();
@@ -78,24 +78,24 @@ function nr() {
78
78
  let r = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
79
79
  return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
80
80
  }
81
- function ae(n, e) {
81
+ function ce(n, e) {
82
82
  let t, r = {};
83
83
  for (let [i, s] of Object.entries(n)) {
84
- if (i.toLowerCase() === yt) {
85
- _t(s) && (t = s);
84
+ if (i.toLowerCase() === bt) {
85
+ vt(s) && (t = s);
86
86
  continue;
87
87
  }
88
88
  r[i] = s;
89
89
  }
90
- let o = t ?? (_t(e) ? e : void 0) ?? nr();
91
- return r[yt] = o, { headers: r, correlationId: o };
90
+ let o = t ?? (vt(e) ? e : void 0) ?? ar();
91
+ return r[bt] = o, { headers: r, correlationId: o };
92
92
  }
93
- var yt, tr, Me = $(() => {
94
- yt = "x-correlation-id", tr = /^[A-Za-z0-9._:\-]+$/;
93
+ var bt, sr, qe = $(() => {
94
+ bt = "x-correlation-id", sr = /^[A-Za-z0-9._:\-]+$/;
95
95
  });
96
96
 
97
97
  // src/server-only-key.ts
98
- function X() {
98
+ function Y() {
99
99
  try {
100
100
  let n = globalThis.navigator;
101
101
  if (n && n.product === "ReactNative") return "react-native";
@@ -108,108 +108,108 @@ function X() {
108
108
  }
109
109
  return null;
110
110
  }
111
- function bt(n, e) {
112
- let t = rr[n];
111
+ function wt(n, e) {
112
+ let t = cr[n];
113
113
  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();
114
114
  }
115
- function wt(n) {
115
+ function St(n) {
116
116
  if (!n.hasApiKey) return;
117
- let e = n.runtime === void 0 ? X() : n.runtime;
117
+ let e = n.runtime === void 0 ? Y() : n.runtime;
118
118
  if (e) {
119
119
  if (n.strict)
120
- throw new c("server_only_key", bt(e, true), void 0, void 0, e);
121
- if (!vt) {
122
- vt = true;
120
+ throw new c("server_only_key", wt(e, true), void 0, void 0, e);
121
+ if (!kt) {
122
+ kt = true;
123
123
  try {
124
- typeof console < "u" && typeof console.warn == "function" && console.warn(bt(e, !1));
124
+ typeof console < "u" && typeof console.warn == "function" && console.warn(wt(e, !1));
125
125
  } catch {
126
126
  }
127
127
  }
128
128
  }
129
129
  }
130
- var rr, vt, qe = $(() => {
131
- I();
132
- rr = {
130
+ var cr, kt, Fe = $(() => {
131
+ C();
132
+ cr = {
133
133
  browser: "no navegador",
134
134
  "react-native": "num app React Native"
135
135
  };
136
- vt = false;
136
+ kt = false;
137
137
  });
138
138
 
139
139
  // src/http.ts
140
- var Y = {};
141
- ot(Y, {
142
- checkCoreVersionCompat: () => ce,
140
+ var Z = {};
141
+ st(Z, {
142
+ checkCoreVersionCompat: () => le,
143
143
  httpRequest: () => v,
144
- statusToCode: () => le
144
+ statusToCode: () => de
145
145
  });
146
- function Fe(n) {
146
+ function je(n) {
147
147
  return n.split("+")[0] ?? n;
148
148
  }
149
- function ir(n, e) {
150
- let t = Fe(n).split(".").map(Number), r = Fe(e).split(".").map(Number), o = Math.max(t.length, r.length);
149
+ function dr(n, e) {
150
+ let t = je(n).split(".").map(Number), r = je(e).split(".").map(Number), o = Math.max(t.length, r.length);
151
151
  for (let i = 0; i < o; i++) {
152
152
  let s = t[i] ?? 0, a = r[i] ?? 0;
153
153
  if (s !== a) return s - a;
154
154
  }
155
155
  return 0;
156
156
  }
157
- function Ct() {
157
+ function Et() {
158
158
  try {
159
- return "3.8.1";
159
+ return "3.9.1";
160
160
  } catch {
161
161
  return;
162
162
  }
163
163
  }
164
- function sr() {
165
- let n = Ct();
164
+ function ur() {
165
+ let n = Et();
166
166
  return n ? parseInt(n.split(".")[0] ?? "3", 10) : 3;
167
167
  }
168
- function ce(n) {
168
+ function le(n) {
169
169
  if (!n) return;
170
- let e = sr(), t = or[e];
170
+ let e = ur(), t = lr[e];
171
171
  if (!t) return;
172
- let r = Fe(n);
173
- if (ir(r, t) < 0) {
172
+ let r = je(n);
173
+ if (dr(r, t) < 0) {
174
174
  let o = `${e}:${r}`;
175
- kt.has(o) || (kt.add(o), console.warn(
175
+ Tt.has(o) || (Tt.add(o), console.warn(
176
176
  `[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.`
177
177
  ));
178
178
  }
179
179
  }
180
- function ar() {
180
+ function pr() {
181
181
  let n = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
182
- 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;
182
+ 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;
183
183
  }
184
- function St(n) {
184
+ function Rt(n) {
185
185
  let e = 200 * Math.pow(4, n), t = e * 0.2 * (Math.random() * 2 - 1);
186
186
  return Math.max(50, Math.round(e + t));
187
187
  }
188
- function pr(n) {
188
+ function yr(n) {
189
189
  if (!n) return null;
190
190
  let e = Number(n);
191
- if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), Tt);
191
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), It);
192
192
  let t = Date.parse(n);
193
193
  if (Number.isFinite(t)) {
194
194
  let r = t - Date.now();
195
- if (r > 0) return Math.min(r, Tt);
195
+ if (r > 0) return Math.min(r, It);
196
196
  }
197
197
  return null;
198
198
  }
199
- function Rt(n) {
199
+ function Ct(n) {
200
200
  return new Promise((e) => setTimeout(e, n));
201
201
  }
202
- function le(n) {
202
+ function de(n) {
203
203
  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";
204
204
  }
205
- function fr(n, e, t) {
205
+ function _r(n, e, t) {
206
206
  let r = n.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, i = new URL(`${r}${o}`);
207
207
  if (t)
208
208
  for (let [s, a] of Object.entries(t))
209
209
  a !== void 0 && i.searchParams.set(s, String(a));
210
210
  return i.toString();
211
211
  }
212
- async function It(n) {
212
+ async function At(n) {
213
213
  let e = await n.text();
214
214
  if (e)
215
215
  try {
@@ -219,17 +219,17 @@ async function It(n) {
219
219
  }
220
220
  }
221
221
  async function v(n, e) {
222
- let t = e.method ?? "GET", r = fr(n.baseUrl, e.path, e.query), o = dr.has(t) ? cr : lr, i = e.retries ?? o, { headers: s, correlationId: a } = ae(
222
+ 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(
223
223
  { accept: "application/json", ...e.headers },
224
224
  e.correlationId
225
- ), l = Ct();
225
+ ), l = Et();
226
226
  if (l && (s["x-neetru-sdk-version"] = l), e.requireAuth) {
227
227
  if (!n.apiKey)
228
- throw new c("missing_api_key", ar());
228
+ throw new c("missing_api_key", pr());
229
229
  s.authorization = `Bearer ${n.apiKey}`;
230
230
  }
231
231
  if (e.idempotencyKey) {
232
- let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : ht();
232
+ let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : yt();
233
233
  s["idempotency-key"] = f;
234
234
  }
235
235
  let d = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
@@ -249,73 +249,73 @@ async function v(n, e) {
249
249
  d !== void 0 && (h.body = d);
250
250
  let y = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
251
251
  h.signal = AbortSignal.timeout(y);
252
- let S;
252
+ let T;
253
253
  try {
254
- S = await n.fetch(r, h);
255
- } catch (g) {
256
- let C = g instanceof DOMException && g.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${g instanceof Error ? g.message : "fetch failed"}`;
257
- if (u = new c("network_error", C, void 0, void 0, void 0, a), f < i) {
258
- let D = St(f);
254
+ T = await n.fetch(r, h);
255
+ } catch (m) {
256
+ let S = m instanceof DOMException && m.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${m instanceof Error ? m.message : "fetch failed"}`;
257
+ if (u = new c("network_error", S, void 0, void 0, void 0, a), f < i) {
258
+ let D = Rt(f);
259
259
  if (p == null || Date.now() + D < p) {
260
- await Rt(D);
260
+ await Ct(D);
261
261
  continue;
262
262
  }
263
263
  }
264
264
  throw u;
265
265
  }
266
- let x = S.headers.get("x-request-id") ?? S.headers.get("x-correlation-id") ?? void 0;
267
- if (S.ok) {
268
- let g = S.headers.get("x-neetru-version");
269
- return g && ce(g), await It(S);
266
+ let x = T.headers.get("x-request-id") ?? T.headers.get("x-correlation-id") ?? void 0;
267
+ if (T.ok) {
268
+ let m = T.headers.get("x-neetru-version");
269
+ return m && le(m), await At(T);
270
270
  }
271
- let T = await It(S), P = le(S.status), q = `HTTP ${S.status}`, m;
272
- if (T && typeof T == "object") {
273
- let g = T.error;
274
- typeof g == "string" ? q = g : g && typeof g == "object" ? (typeof g.code == "string" && (P = g.code), typeof g.message == "string" && (q = g.message), typeof g.reason == "string" && (m = g.reason)) : (typeof T.code == "string" && (P = T.code), typeof T.message == "string" && (q = T.message)), typeof T.reason == "string" && (m = T.reason);
271
+ let R = await At(T), E = de(T.status), j = `HTTP ${T.status}`, g;
272
+ if (R && typeof R == "object") {
273
+ let m = R.error;
274
+ 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);
275
275
  }
276
- if (S.status === 410) {
277
- let g = S.headers.get("x-neetru-replacement");
278
- q === `HTTP ${S.status}` && (q = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), g && !q.includes(g) && (q += ` Substituto: ${g}.`);
276
+ if (T.status === 410) {
277
+ let m = T.headers.get("x-neetru-replacement");
278
+ 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}.`);
279
279
  }
280
- let _ = new c(P, q, S.status, x, m, a);
281
- if (u = _, ur.has(P) && f < i) {
282
- let C = pr(S.headers.get("retry-after")) ?? St(f);
283
- if (p == null || Date.now() + C < p) {
284
- await Rt(C);
280
+ let b = new c(E, j, T.status, x, g, a);
281
+ if (u = b, gr.has(E) && f < i) {
282
+ let S = yr(T.headers.get("retry-after")) ?? Rt(f);
283
+ if (p == null || Date.now() + S < p) {
284
+ await Ct(S);
285
285
  continue;
286
286
  }
287
287
  }
288
- throw _;
288
+ throw b;
289
289
  }
290
290
  throw u ?? new c("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
291
291
  }
292
- var or, kt, cr, lr, dr, ur, Tt, M = $(() => {
293
- I();
294
- gt();
295
- Me();
292
+ var lr, Tt, fr, mr, hr, gr, It, F = $(() => {
293
+ C();
294
+ _t();
296
295
  qe();
297
- or = {
296
+ Fe();
297
+ lr = {
298
298
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
299
299
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
300
300
  3: "2026.05.1"
301
301
  };
302
- kt = /* @__PURE__ */ new Set();
303
- cr = 2, lr = 0, dr = /* @__PURE__ */ new Set(["GET", "HEAD"]), ur = /* @__PURE__ */ new Set([
302
+ Tt = /* @__PURE__ */ new Set();
303
+ fr = 2, mr = 0, hr = /* @__PURE__ */ new Set(["GET", "HEAD"]), gr = /* @__PURE__ */ new Set([
304
304
  "rate_limited",
305
305
  "server_error",
306
306
  "network_error"
307
307
  ]);
308
- Tt = 6e4;
308
+ It = 6e4;
309
309
  });
310
310
 
311
311
  // src/db-errors.ts
312
- var Ir, b, Z = $(() => {
313
- I();
314
- Ir = /* @__PURE__ */ new Set([
312
+ var Dr, _, ee = $(() => {
313
+ C();
314
+ Dr = /* @__PURE__ */ new Set([
315
315
  "db_unavailable",
316
316
  "db_conflict",
317
317
  "db_timeout"
318
- ]), b = class n extends c {
318
+ ]), _ = class n extends c {
319
319
  /** Código de erro fechado — específico de DB. */
320
320
  code;
321
321
  /**
@@ -329,16 +329,16 @@ var Ir, b, Z = $(() => {
329
329
  */
330
330
  dbId;
331
331
  constructor(e, t, r) {
332
- super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Ir.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
332
+ super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Dr.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
333
333
  }
334
334
  };
335
335
  });
336
336
 
337
337
  // src/db/sql/resilient-pool.ts
338
- function ve(n) {
339
- return typeof n == "object" && n !== null && n[He] === true;
338
+ function we(n) {
339
+ return typeof n == "object" && n !== null && n[Ge] === true;
340
340
  }
341
- function Qr(n) {
341
+ function Zr(n) {
342
342
  let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
343
343
  if (e === "ECONNREFUSED" || e === "ETIMEDOUT" || e === "ENOTFOUND" || e === "EHOSTUNREACH" || e === "EAI_AGAIN")
344
344
  return true;
@@ -350,17 +350,17 @@ function Qr(n) {
350
350
  let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
351
351
  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"));
352
352
  }
353
- function Gt(n) {
353
+ function Xt(n) {
354
354
  let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
355
- if (typeof e == "string" && Gr.has(e.toUpperCase()))
355
+ if (typeof e == "string" && eo.has(e.toUpperCase()))
356
356
  return true;
357
357
  let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
358
358
  return r.length === 0 ? false : r.includes("password authentication failed") || r.includes("sasl authentication failed");
359
359
  }
360
- function Jr(n) {
361
- return Qr(n) || Gt(n);
360
+ function to(n) {
361
+ return Zr(n) || Xt(n);
362
362
  }
363
- function Qe(n) {
363
+ function Je(n) {
364
364
  let e = { current: n }, t = null, r = {
365
365
  __neetruSwapInner(u) {
366
366
  let p = e.current;
@@ -388,10 +388,10 @@ function Qe(n) {
388
388
  }
389
389
  return await o(u, e.current, f);
390
390
  }
391
- })(), s = i("query", Jr), a = i("connect", Gt), l = Object.create(Object.getPrototypeOf(n));
391
+ })(), s = i("query", to), a = i("connect", Xt), l = Object.create(Object.getPrototypeOf(n));
392
392
  return new Proxy(l, {
393
393
  get(u, p) {
394
- if (p === He) return true;
394
+ if (p === Ge) return true;
395
395
  if (p === "__neetruSwapInner") return r.__neetruSwapInner;
396
396
  if (p === "__neetruGetInner") return r.__neetruGetInner;
397
397
  if (p === "__neetruSetReLease") return r.__neetruSetReLease;
@@ -407,27 +407,27 @@ function Qe(n) {
407
407
  }
408
408
  });
409
409
  }
410
- var He, Gr, Ge = $(() => {
411
- He = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
412
- Gr = /* @__PURE__ */ new Set(["28P01", "28000"]);
410
+ var Ge, eo, Xe = $(() => {
411
+ Ge = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
412
+ eo = /* @__PURE__ */ new Set(["28P01", "28000"]);
413
413
  });
414
414
 
415
415
  // src/db/sql/lease.ts
416
- function Yr(n, e) {
416
+ function ro(n, e) {
417
417
  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;
418
418
  }
419
- function Zr(n) {
420
- if (n instanceof b) return n;
419
+ function oo(n) {
420
+ if (n instanceof _) return n;
421
421
  let e = n instanceof Error ? n.message : String(n), t = n instanceof Error ? n.code : void 0;
422
- return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new b(
422
+ return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new _(
423
423
  "db_unavailable",
424
424
  `Pool connection failed (${t}): ${e}`
425
- ) : e.includes("statement timeout") || e.includes("lock timeout") ? new b("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new b("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new b("db_permission_denied", `Permission denied: ${e}`) : new b("db_unavailable", `Database error: ${e}`);
425
+ ) : 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}`);
426
426
  }
427
- var Xr, J, re, Jt = $(() => {
428
- Z();
429
- Ge();
430
- Xr = 0.8, J = 3e4, re = class {
427
+ var no, X, oe, Yt = $(() => {
428
+ ee();
429
+ Xe();
430
+ no = 0.8, X = 3e4, oe = class {
431
431
  /**
432
432
  * Lease atual. `null` no modo LAZY antes da 1ª query (o 1º lease é adiado —
433
433
  * ver `_ensureInitialLease`). Após a 1ª aquisição, sempre não-nulo.
@@ -467,7 +467,7 @@ var Xr, J, re, Jt = $(() => {
467
467
  isolationLevel: t.isolationLevel
468
468
  }) : await this._orm.transaction(e);
469
469
  } catch (r) {
470
- throw Zr(r);
470
+ throw oo(r);
471
471
  }
472
472
  }
473
473
  async close() {
@@ -485,13 +485,13 @@ var Xr, J, re, Jt = $(() => {
485
485
  * usa `MIN_RENEWAL_DELAY_MS` como fallback seguro.
486
486
  */
487
487
  _calcRenewalDelayMs() {
488
- if (!this._lease) return J;
488
+ if (!this._lease) return X;
489
489
  let e = Date.parse(this._lease.expiresAt);
490
- if (!Number.isFinite(e)) return J;
490
+ if (!Number.isFinite(e)) return X;
491
491
  let t = this._deps.now(), r = e - t;
492
- if (r <= 0) return J;
493
- let o = r * (1 - Xr);
494
- return Math.max(J, Math.round(o));
492
+ if (r <= 0) return X;
493
+ let o = r * (1 - no);
494
+ return Math.max(X, Math.round(o));
495
495
  }
496
496
  _scheduleRenewal() {
497
497
  if (this._closed) return;
@@ -518,8 +518,8 @@ var Xr, J, re, Jt = $(() => {
518
518
  } catch (t) {
519
519
  this._renewalTimer = setTimeout(() => {
520
520
  this._doRenew();
521
- }, J), console.warn(
522
- `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${J}ms (o cert de cliente mTLS do lease expira ~15min ap\xF3s o \xFAltimo swap):`,
521
+ }, X), console.warn(
522
+ `[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):`,
523
523
  t instanceof Error ? t.message : t
524
524
  );
525
525
  return;
@@ -553,7 +553,7 @@ var Xr, J, re, Jt = $(() => {
553
553
  */
554
554
  async _reactiveReLease() {
555
555
  if (this._closed)
556
- throw new b(
556
+ throw new _(
557
557
  "db_unavailable",
558
558
  "SqlLeaseManager foi fechado \u2014 re-lease reativo abortado."
559
559
  );
@@ -590,30 +590,30 @@ var Xr, J, re, Jt = $(() => {
590
590
  */
591
591
  async _ensureInitialLease() {
592
592
  if (this._closed)
593
- throw new b(
593
+ throw new _(
594
594
  "db_unavailable",
595
595
  "SqlLeaseManager foi fechado \u2014 aquisi\xE7\xE3o de lease inicial abortada."
596
596
  );
597
597
  if (this._lease)
598
- return ve(this._pool) ? this._pool.__neetruGetInner() : this._pool;
598
+ return we(this._pool) ? this._pool.__neetruGetInner() : this._pool;
599
599
  if (this._initInFlight !== null) return this._initInFlight;
600
600
  let e = (async () => {
601
601
  let t;
602
602
  try {
603
603
  t = this._deps.database !== void 0 ? await this._deps.fetchLease({ database: this._deps.database }) : await this._deps.fetchLease();
604
604
  } catch (o) {
605
- if (o instanceof b) throw o;
605
+ if (o instanceof _) throw o;
606
606
  let i = o instanceof Error ? o.message : String(o);
607
- throw new b("db_unavailable", `Falha ao obter lease inicial: ${i}`);
607
+ throw new _("db_unavailable", `Falha ao obter lease inicial: ${i}`);
608
608
  }
609
609
  let r;
610
610
  try {
611
611
  r = this._deps.createPool(t);
612
612
  } catch (o) {
613
613
  let i = o instanceof Error ? o.message : String(o);
614
- throw new b("db_unavailable", `Falha ao abrir pool: ${i}`);
614
+ throw new _("db_unavailable", `Falha ao abrir pool: ${i}`);
615
615
  }
616
- return ve(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
616
+ return we(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
617
617
  }) : this._pool = r, this._lease = t, this._scheduleRenewal(), r;
618
618
  })();
619
619
  this._initInFlight = e;
@@ -629,12 +629,12 @@ var Xr, J, re, Jt = $(() => {
629
629
  * Exposto como método protegido para testes.
630
630
  */
631
631
  async _swapPool(e) {
632
- if (!Yr(this._lease, e)) {
632
+ if (!ro(this._lease, e)) {
633
633
  this._lease = e;
634
634
  return;
635
635
  }
636
636
  let t = this._deps.createPool(e);
637
- if (ve(this._pool)) {
637
+ if (we(this._pool)) {
638
638
  let i = this._pool.__neetruSwapInner(t);
639
639
  this._lease = e, i.end().catch(() => {
640
640
  });
@@ -647,7 +647,7 @@ var Xr, J, re, Jt = $(() => {
647
647
  // ─── Helpers ───────────────────────────────────────────────────────────────
648
648
  _assertOpen() {
649
649
  if (this._closed)
650
- throw new b(
650
+ throw new _(
651
651
  "db_unavailable",
652
652
  "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
653
653
  );
@@ -656,29 +656,29 @@ var Xr, J, re, Jt = $(() => {
656
656
  });
657
657
 
658
658
  // src/db/sql/sql-client.ts
659
- var on = {};
660
- ot(on, {
661
- DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => nn,
662
- DEFAULT_POOL_IDLE_MS: () => tn,
663
- DEFAULT_POOL_MAX: () => en,
664
- LEASE_ENDPOINT: () => Xt,
665
- LEASE_RENEW_ENDPOINT: () => Yt,
666
- createDrizzleHandle: () => ro,
667
- createHttpLeaseFetcher: () => Zt,
668
- createPgPool: () => no,
669
- createSqlClientFromConfig: () => io,
670
- createSqlClientWithDeps: () => rn,
671
- resolvePoolTuning: () => Xe
659
+ var an = {};
660
+ st(an, {
661
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => on,
662
+ DEFAULT_POOL_IDLE_MS: () => rn,
663
+ DEFAULT_POOL_MAX: () => nn,
664
+ LEASE_ENDPOINT: () => Zt,
665
+ LEASE_RENEW_ENDPOINT: () => en,
666
+ createDrizzleHandle: () => co,
667
+ createHttpLeaseFetcher: () => tn,
668
+ createPgPool: () => ao,
669
+ createSqlClientFromConfig: () => uo,
670
+ createSqlClientWithDeps: () => sn,
671
+ resolvePoolTuning: () => Ze
672
672
  });
673
- function eo(n) {
673
+ function io(n) {
674
674
  return n === "workspace" ? "staging" : n === "prod" ? "production" : "dev-local";
675
675
  }
676
- function Zt(n) {
676
+ function tn(n) {
677
677
  return async (e) => {
678
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = !!e?.leaseId, o = r ? Yt : Xt, i;
678
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = !!e?.leaseId, o = r ? en : Zt, i;
679
679
  r ? i = { leaseId: e.leaseId } : (i = {
680
680
  productId: n.productId ?? "",
681
- environment: eo(n.env ?? "prod")
681
+ environment: io(n.env ?? "prod")
682
682
  }, e?.database !== void 0 && (i.database = e.database));
683
683
  let s;
684
684
  try {
@@ -694,32 +694,32 @@ function Zt(n) {
694
694
  let l = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof c ? a.reason : void 0;
695
695
  if (u === "suspended" || u === "archived" || u === "revoked") {
696
696
  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";
697
- throw new b(
697
+ throw new _(
698
698
  "db_suspended",
699
699
  `Falha ao ${l} lease SQL: ${p} (reason=${u}).`
700
700
  );
701
701
  }
702
- throw new b(
702
+ throw new _(
703
703
  "db_unavailable",
704
704
  `Falha ao ${l} lease SQL: ${d}`
705
705
  );
706
706
  }
707
- return to(s);
707
+ return so(s);
708
708
  };
709
709
  }
710
- function to(n) {
710
+ function so(n) {
711
711
  if (!n || typeof n != "object")
712
- throw new b("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
712
+ throw new _("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
713
713
  let t = n.lease;
714
714
  if (!t || typeof t != "object")
715
- throw new b(
715
+ throw new _(
716
716
  "db_unavailable",
717
717
  'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
718
718
  );
719
719
  let r = t;
720
720
  function o(i, s) {
721
721
  if (typeof r[i] !== s)
722
- throw new b(
722
+ throw new _(
723
723
  "db_unavailable",
724
724
  `Campo obrigat\xF3rio "${i}" ausente ou tipo inv\xE1lido na resposta de lease.`
725
725
  );
@@ -739,22 +739,22 @@ function to(n) {
739
739
  expiresAt: o("expiresAt", "string")
740
740
  };
741
741
  }
742
- function Je(n, e, t, r) {
742
+ function Ye(n, e, t, r) {
743
743
  let o = typeof process < "u" ? process.env?.[n] : void 0;
744
744
  if (o === void 0 || o.trim() === "") return e;
745
745
  let i = Number.parseInt(o.trim(), 10);
746
746
  return !Number.isFinite(i) || i < t || i > r ? e : i;
747
747
  }
748
- function Xe() {
748
+ function Ze() {
749
749
  return {
750
750
  // Teto 100: bem abaixo do `max_client_conn = 500` do PgBouncer, com folga
751
751
  // para múltiplas instâncias do app dividirem o mesmo front-door.
752
- max: Je("NEETRU_DB_POOL_MAX", en, 1, 100),
752
+ max: Ye("NEETRU_DB_POOL_MAX", nn, 1, 100),
753
753
  // Teto 15min = janela do cert; piso 1s.
754
- idleTimeoutMillis: Je("NEETRU_DB_POOL_IDLE_MS", tn, 1e3, 9e5),
755
- connectionTimeoutMillis: Je(
754
+ idleTimeoutMillis: Ye("NEETRU_DB_POOL_IDLE_MS", rn, 1e3, 9e5),
755
+ connectionTimeoutMillis: Ye(
756
756
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
757
- nn,
757
+ on,
758
758
  1e3,
759
759
  12e4
760
760
  ),
@@ -762,7 +762,7 @@ function Xe() {
762
762
  keepAliveInitialDelayMillis: 1e4
763
763
  };
764
764
  }
765
- async function no(n) {
765
+ async function ao(n) {
766
766
  let { Pool: e } = await import(
767
767
  /* webpackIgnore: true */
768
768
  'pg'
@@ -779,17 +779,17 @@ async function no(n) {
779
779
  user: n.user,
780
780
  password: n.password,
781
781
  ssl: t,
782
- ...Xe()
782
+ ...Ze()
783
783
  });
784
784
  }
785
- async function ro(n, e) {
785
+ async function co(n, e) {
786
786
  let { drizzle: t } = await import(
787
787
  /* webpackIgnore: true */
788
788
  'drizzle-orm/node-postgres'
789
789
  );
790
790
  return t(n, { schema: e });
791
791
  }
792
- function oo(n, e) {
792
+ function lo(n, e) {
793
793
  let t = null, r = null, o = () => t ? Promise.resolve(t) : (r || (r = e().then((s) => (t = s, r = null, s)).catch((s) => {
794
794
  throw r = null, s;
795
795
  })), r), i = {
@@ -805,52 +805,52 @@ function oo(n, e) {
805
805
  };
806
806
  return n && Object.setPrototypeOf(i, n), i;
807
807
  }
808
- async function rn(n, e) {
808
+ async function sn(n, e) {
809
809
  let t = e?.database !== void 0 ? { ...n, database: e.database } : n;
810
810
  if (t.lazy) {
811
- let l = null, d = oo(t.poolPrototype ?? null, () => {
811
+ let l = null, d = lo(t.poolPrototype ?? null, () => {
812
812
  if (!l)
813
- throw new b("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
813
+ throw new _("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
814
814
  return l._ensureInitialLease();
815
- }), u = Qe(d), p;
815
+ }), u = Je(d), p;
816
816
  try {
817
817
  p = t.createDrizzle(u, t.schema);
818
818
  } catch (h) {
819
819
  let y = h instanceof Error ? h.message : String(h);
820
- throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${y}`);
820
+ throw new _("db_unavailable", `Falha ao criar handle Drizzle: ${y}`);
821
821
  }
822
- let f = new re(null, u, p, t);
822
+ let f = new oe(null, u, p, t);
823
823
  return l = f, u.__neetruSetReLease(() => f._reactiveReLease()), f;
824
824
  }
825
825
  let r;
826
826
  try {
827
827
  e?.database !== void 0 ? r = await t.fetchLease({ database: e.database }) : r = await t.fetchLease();
828
828
  } catch (l) {
829
- if (l instanceof b) throw l;
829
+ if (l instanceof _) throw l;
830
830
  let d = l instanceof Error ? l.message : String(l);
831
- throw new b("db_unavailable", `Falha ao obter lease inicial: ${d}`);
831
+ throw new _("db_unavailable", `Falha ao obter lease inicial: ${d}`);
832
832
  }
833
833
  let o;
834
834
  try {
835
835
  o = t.createPool(r);
836
836
  } catch (l) {
837
837
  let d = l instanceof Error ? l.message : String(l);
838
- throw new b("db_unavailable", `Falha ao abrir pool: ${d}`);
838
+ throw new _("db_unavailable", `Falha ao abrir pool: ${d}`);
839
839
  }
840
- let i = Qe(o), s;
840
+ let i = Je(o), s;
841
841
  try {
842
842
  s = t.createDrizzle(i, t.schema);
843
843
  } catch (l) {
844
844
  await o.end().catch(() => {
845
845
  });
846
846
  let d = l instanceof Error ? l.message : String(l);
847
- throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
847
+ throw new _("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
848
848
  }
849
- let a = new re(r, i, s, t);
849
+ let a = new oe(r, i, s, t);
850
850
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
851
851
  }
852
- async function io(n, e, t) {
853
- let r = Zt(n), o, i;
852
+ async function uo(n, e, t) {
853
+ let r = tn(n), o, i;
854
854
  try {
855
855
  o = await import(
856
856
  /* webpackIgnore: true */
@@ -860,13 +860,13 @@ async function io(n, e, t) {
860
860
  'drizzle-orm/node-postgres'
861
861
  );
862
862
  } catch (d) {
863
- throw new b(
863
+ throw new _(
864
864
  "db_unavailable",
865
865
  `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${d.message})`
866
866
  );
867
867
  }
868
868
  let s = o.Pool ?? o.default?.Pool;
869
- return rn(
869
+ return sn(
870
870
  {
871
871
  fetchLease: r,
872
872
  createPool: (d) => {
@@ -885,7 +885,7 @@ async function io(n, e, t) {
885
885
  ssl: u,
886
886
  // Tuning centralizado (env-tunável) — ver resolvePoolTuning + auditoria
887
887
  // docs/_review/AUDITORIA_DB_CONN_PERF_2026-09-06.md no Core.
888
- ...Xe()
888
+ ...Ze()
889
889
  });
890
890
  },
891
891
  createDrizzle: (d, u) => i.drizzle(d, { schema: u }),
@@ -901,39 +901,39 @@ async function io(n, e, t) {
901
901
  t
902
902
  );
903
903
  }
904
- var Xt, Yt, en, tn, nn, sn = $(() => {
905
- Z();
906
- I();
907
- Jt();
908
- Ge();
909
- Xt = "/api/sdk/v1/db/lease", Yt = "/api/sdk/v1/db/lease/renew";
910
- en = 10, tn = 6e4, nn = 1e4;
904
+ var Zt, en, nn, rn, on, cn = $(() => {
905
+ ee();
906
+ C();
907
+ Yt();
908
+ Xe();
909
+ Zt = "/api/sdk/v1/db/lease", en = "/api/sdk/v1/db/lease/renew";
910
+ nn = 10, rn = 6e4, on = 1e4;
911
911
  });
912
- var Le = /* @__PURE__ */ new Map(), Ue = 3600 * 1e3;
913
- function it(n, e = Ue) {
914
- let t = Date.now(), r = Le.get(n);
912
+ var Ue = /* @__PURE__ */ new Map(), Me = 3600 * 1e3;
913
+ function at(n, e = Me) {
914
+ let t = Date.now(), r = Ue.get(n);
915
915
  if (r && t - r.createdAt < e)
916
916
  return r.jwks;
917
917
  let o = jose.createRemoteJWKSet(new URL(n));
918
- return Le.set(n, { jwks: o, createdAt: t }), o;
918
+ return Ue.set(n, { jwks: o, createdAt: t }), o;
919
919
  }
920
- function st() {
921
- Le.clear();
920
+ function ct() {
921
+ Ue.clear();
922
922
  }
923
923
 
924
924
  // src/auth.ts
925
- I();
925
+ C();
926
926
 
927
927
  // src/api-key.ts
928
- I();
929
- var at = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
930
- function ct(n) {
928
+ C();
929
+ var lt = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
930
+ function dt(n) {
931
931
  if (typeof n != "string" || n.length === 0)
932
932
  throw new c(
933
933
  "invalid_config",
934
934
  "apiKey is required (formato nrt_<keyId>_<secret>)"
935
935
  );
936
- let e = at.exec(n);
936
+ let e = lt.exec(n);
937
937
  if (!e)
938
938
  throw new c(
939
939
  "invalid_config",
@@ -941,22 +941,22 @@ function ct(n) {
941
941
  );
942
942
  return { keyId: e[1], secret: e[2] };
943
943
  }
944
- function lt(n) {
944
+ function ut(n) {
945
945
  if (typeof n != "string" || n.length === 0) return null;
946
- let e = at.exec(n);
946
+ let e = lt.exec(n);
947
947
  return e ? { keyId: e[1], secret: e[2] } : null;
948
948
  }
949
949
 
950
950
  // src/base-url-allowlist.ts
951
- I();
952
- var dt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), Jn = ".neetru.com", Xn = "neetru.com", Yn = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
953
- function ut(n) {
954
- return Yn.test(n);
951
+ C();
952
+ 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)$/;
953
+ function ft(n) {
954
+ return rr.test(n);
955
955
  }
956
- function Zn(n) {
956
+ function or(n) {
957
957
  return n.toLowerCase().replace(/\.+$/, "");
958
958
  }
959
- function pt(n, e = []) {
959
+ function mt(n, e = []) {
960
960
  if (typeof n != "string" || n.length === 0)
961
961
  throw new c("invalid_config", "baseUrl is required");
962
962
  let t;
@@ -965,8 +965,8 @@ function pt(n, e = []) {
965
965
  } catch {
966
966
  throw new c("invalid_config", `baseUrl is not a valid URL: ${n}`);
967
967
  }
968
- let r = t.protocol, o = Zn(t.hostname);
969
- if (er())
968
+ let r = t.protocol, o = or(t.hostname);
969
+ if (ir())
970
970
  return typeof console < "u" && console.warn(
971
971
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${n} aceito sem valida\xE7\xE3o.`
972
972
  ), n.replace(/\/+$/, "");
@@ -976,17 +976,17 @@ function pt(n, e = []) {
976
976
  `baseUrl protocol must be http: or https:, got ${r}`
977
977
  );
978
978
  if (r === "http:") {
979
- if (!(dt.has(o) || ut(o)))
979
+ if (!(pt.has(o) || ft(o)))
980
980
  throw new c(
981
981
  "invalid_config",
982
982
  `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.`
983
983
  );
984
984
  return n.replace(/\/+$/, "");
985
985
  }
986
- let i = o === Xn || o.endsWith(Jn), s = e.some((l) => {
986
+ let i = o === nr || o.endsWith(tr), s = e.some((l) => {
987
987
  let d = l.toLowerCase();
988
988
  return o === d || o.endsWith(`.${d}`);
989
- }), a = dt.has(o) || ut(o);
989
+ }), a = pt.has(o) || ft(o);
990
990
  if (!i && !s && !a)
991
991
  throw new c(
992
992
  "invalid_config",
@@ -994,7 +994,7 @@ function pt(n, e = []) {
994
994
  );
995
995
  return n.replace(/\/+$/, "");
996
996
  }
997
- function er() {
997
+ function ir() {
998
998
  try {
999
999
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
1000
1000
  if (e === "1" || e === "true") return !0;
@@ -1009,12 +1009,12 @@ function er() {
1009
1009
  }
1010
1010
 
1011
1011
  // src/types.ts
1012
- var ft = "https://api.neetru.com", mt = "http://localhost:9003";
1012
+ var ht = "https://api.neetru.com", gt = "http://localhost:9003";
1013
1013
 
1014
1014
  // src/catalog.ts
1015
- I();
1016
- M();
1017
- function At(n) {
1015
+ C();
1016
+ F();
1017
+ function Pt(n) {
1018
1018
  if (!n || typeof n != "object")
1019
1019
  throw new c("invalid_response", "Catalog response item is not an object");
1020
1020
  let e = n;
@@ -1033,7 +1033,7 @@ function At(n) {
1033
1033
  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;
1034
1034
  })), t;
1035
1035
  }
1036
- function Et(n) {
1036
+ function Dt(n) {
1037
1037
  return {
1038
1038
  /**
1039
1039
  * Lista produtos publicados. Por default só `published=true`; staff
@@ -1050,7 +1050,7 @@ function Et(n) {
1050
1050
  "Catalog list response missing products array"
1051
1051
  );
1052
1052
  return {
1053
- products: t.products.map(At),
1053
+ products: t.products.map(Pt),
1054
1054
  fetchedAt: typeof t.fetchedAt == "string" ? t.fetchedAt : (/* @__PURE__ */ new Date()).toISOString()
1055
1055
  };
1056
1056
  },
@@ -1071,32 +1071,32 @@ function Et(n) {
1071
1071
  "invalid_response",
1072
1072
  "Catalog get response missing product"
1073
1073
  );
1074
- return At(t.product);
1074
+ return Pt(t.product);
1075
1075
  }
1076
1076
  };
1077
1077
  }
1078
1078
 
1079
1079
  // src/entitlements.ts
1080
- I();
1081
- var mr = "client.entitlements.check()/checkDetailed() est\xE3o DEPRECADOS \u2014 apontavam para GET /api/v1/sdk/entitlements/check, um endpoint que o Core nunca escreve (sempre retornava not_subscribed). Use client.usage.check(resource, { productId, tenantId }) no lugar \u2014 mesmo resultado (allowed/reason/remaining/limit/behavior), endpoint real.";
1082
- function Pt() {
1083
- throw new c("validation_failed", mr);
1080
+ C();
1081
+ 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.";
1082
+ function Nt() {
1083
+ throw new c("validation_failed", br);
1084
1084
  }
1085
- function Dt(n) {
1085
+ function xt(n) {
1086
1086
  return {
1087
1087
  /**
1088
1088
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
1089
1089
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
1090
1090
  */
1091
1091
  async check(e, t, r) {
1092
- Pt();
1092
+ Nt();
1093
1093
  },
1094
1094
  /**
1095
1095
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
1096
1096
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
1097
1097
  */
1098
1098
  async checkDetailed(e, t, r) {
1099
- Pt();
1099
+ Nt();
1100
1100
  },
1101
1101
  /** Test helper legado — no-op (não há mais cache). Mantido por compat. */
1102
1102
  __resetCache() {
@@ -1105,16 +1105,31 @@ function Dt(n) {
1105
1105
  }
1106
1106
 
1107
1107
  // src/telemetry.ts
1108
- I();
1109
- M();
1110
- var Nt = ["debug", "info", "warn", "error", "fatal"];
1111
- function hr() {
1108
+ C();
1109
+ F();
1110
+
1111
+ // src/runtime-env.ts
1112
+ function $e() {
1113
+ try {
1114
+ if (typeof process < "u" && process.env)
1115
+ return process.env.NODE_ENV === "production";
1116
+ } catch {
1117
+ }
1118
+ return false;
1119
+ }
1120
+ function W(n) {
1121
+ return n === "dev" && !$e();
1122
+ }
1123
+
1124
+ // src/telemetry.ts
1125
+ var Ot = ["debug", "info", "warn", "error", "fatal"];
1126
+ function vr() {
1112
1127
  return typeof globalThis < "u" && typeof globalThis.window < "u";
1113
1128
  }
1114
- function xt() {
1115
- return hr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1129
+ function Lt() {
1130
+ return vr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1116
1131
  }
1117
- function gr(n) {
1132
+ function wr(n) {
1118
1133
  switch (n) {
1119
1134
  case "debug":
1120
1135
  return console.debug.bind(console);
@@ -1130,8 +1145,8 @@ function gr(n) {
1130
1145
  return console.log.bind(console);
1131
1146
  }
1132
1147
  }
1133
- var yr = 500, _r = 50;
1134
- function Ot(n) {
1148
+ var kr = 500, Sr = 50;
1149
+ function Ut(n) {
1135
1150
  let e = [], t = null, r = null;
1136
1151
  async function o() {
1137
1152
  if (e.length === 0) return;
@@ -1140,7 +1155,7 @@ function Ot(n) {
1140
1155
  try {
1141
1156
  let d = { name: l.name }, u = l.productSlug ?? n.productId;
1142
1157
  u && (d.productSlug = u), l.properties && typeof l.properties == "object" && (d.properties = l.properties), l.timestamp && (d.timestamp = l.timestamp);
1143
- let p = xt();
1158
+ let p = Lt();
1144
1159
  await v(n, {
1145
1160
  method: "POST",
1146
1161
  path: p.path,
@@ -1164,7 +1179,7 @@ function Ot(n) {
1164
1179
  function i() {
1165
1180
  t || (t = setTimeout(() => {
1166
1181
  o();
1167
- }, yr));
1182
+ }, kr));
1168
1183
  }
1169
1184
  return {
1170
1185
  /**
@@ -1188,7 +1203,7 @@ function Ot(n) {
1188
1203
  throw new c("validation_failed", "event.name max 128 chars");
1189
1204
  let a = { name: s.name }, l = s.productSlug ?? n.productId;
1190
1205
  l && (a.productSlug = l), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1191
- let d = xt(), u = await v(n, {
1206
+ let d = Lt(), u = await v(n, {
1192
1207
  method: "POST",
1193
1208
  path: d.path,
1194
1209
  body: a,
@@ -1209,7 +1224,7 @@ function Ot(n) {
1209
1224
  * ```
1210
1225
  */
1211
1226
  track(s) {
1212
- !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= _r ? (t && (clearTimeout(t), t = null), o()) : i());
1227
+ !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());
1213
1228
  },
1214
1229
  /**
1215
1230
  * Força flush imediato da queue de `track()`. Resolva antes de
@@ -1236,14 +1251,14 @@ function Ot(n) {
1236
1251
  async log(s) {
1237
1252
  if (!s || typeof s != "object")
1238
1253
  throw new c("validation_failed", "log input is required");
1239
- if (!Nt.includes(s.level))
1240
- throw new c("validation_failed", `level must be one of ${Nt.join(", ")}`);
1254
+ if (!Ot.includes(s.level))
1255
+ throw new c("validation_failed", `level must be one of ${Ot.join(", ")}`);
1241
1256
  if (typeof s.message != "string" || s.message.length === 0)
1242
1257
  throw new c("validation_failed", "message is required");
1243
1258
  if (s.message.length > 4e3)
1244
1259
  throw new c("validation_failed", "message max 4000 chars");
1245
- if (n.env === "dev")
1246
- return gr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1260
+ if (W(n.env))
1261
+ return wr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1247
1262
  let a = {
1248
1263
  level: s.level,
1249
1264
  message: s.message
@@ -1279,22 +1294,22 @@ function Ot(n) {
1279
1294
  }
1280
1295
 
1281
1296
  // src/usage.ts
1282
- I();
1283
- M();
1297
+ C();
1298
+ F();
1284
1299
 
1285
1300
  // src/validators.ts
1286
- I();
1287
- var Lt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1301
+ C();
1302
+ var Mt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1288
1303
  function N(n, e) {
1289
- if (typeof e != "string" || !Lt.test(e))
1304
+ if (typeof e != "string" || !Mt.test(e))
1290
1305
  throw new c(
1291
1306
  "validation_failed",
1292
- `${n} must match ${Lt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1307
+ `${n} must match ${Mt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1293
1308
  );
1294
1309
  }
1295
1310
 
1296
1311
  // src/usage.ts
1297
- function Ut(n) {
1312
+ function qt(n) {
1298
1313
  return {
1299
1314
  /**
1300
1315
  * Reporta consumo metered de um resource. Hit no endpoint canônico
@@ -1382,10 +1397,10 @@ function Ut(n) {
1382
1397
  }
1383
1398
 
1384
1399
  // src/support.ts
1385
- I();
1386
- M();
1387
- var je = ["low", "normal", "high", "urgent"], br = ["open", "pending", "resolved", "closed"], Mt = 50;
1388
- function qt(n) {
1400
+ C();
1401
+ F();
1402
+ var We = ["low", "normal", "high", "urgent"], Tr = ["open", "pending", "resolved", "closed"], Ft = 50;
1403
+ function jt(n) {
1389
1404
  if (!n || typeof n != "object")
1390
1405
  throw new c("invalid_response", "Ticket response is not an object");
1391
1406
  let e = n;
@@ -1396,8 +1411,8 @@ function qt(n) {
1396
1411
  id: e.id,
1397
1412
  subject: typeof e.subject == "string" ? e.subject : "",
1398
1413
  message: typeof e.message == "string" ? e.message : "",
1399
- severity: je.includes(e.severity) ? e.severity : "normal",
1400
- status: br.includes(e.status) ? e.status : "open",
1414
+ severity: We.includes(e.severity) ? e.severity : "normal",
1415
+ status: Tr.includes(e.status) ? e.status : "open",
1401
1416
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
1402
1417
  updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : void 0,
1403
1418
  productSlug: typeof e.productId == "string" ? e.productId : typeof e.productSlug == "string" ? e.productSlug : void 0,
@@ -1415,15 +1430,15 @@ function qt(n) {
1415
1430
  satisfactionComment: typeof e.satisfactionComment == "string" ? e.satisfactionComment : null
1416
1431
  };
1417
1432
  }
1418
- function de(n) {
1433
+ function ue(n) {
1419
1434
  if (!n || typeof n != "string")
1420
1435
  throw new c("validation_failed", "ticketId is required");
1421
1436
  }
1422
- function Ft(n) {
1437
+ function $t(n) {
1423
1438
  if (typeof n == "string" && n.length > 2e3)
1424
1439
  throw new c("validation_failed", "comment max 2000 chars");
1425
1440
  }
1426
- function jt(n, ...e) {
1441
+ function Wt(n, ...e) {
1427
1442
  for (let t of e)
1428
1443
  if (typeof t == "string" && t.length > 0)
1429
1444
  return N("productSlug", t), t;
@@ -1434,20 +1449,20 @@ function jt(n, ...e) {
1434
1449
  "productId required (pass to input.productSlug or set on createNeetruClient)"
1435
1450
  );
1436
1451
  }
1437
- var vr = "X-Neetru-End-User-Token", wr = "Esta opera\xE7\xE3o de suporte exige um usu\xE1rio final logado: o Core s\xF3 mostra/altera os tickets do pr\xF3prio usu\xE1rio (header X-Neetru-End-User-Token com o id_token OIDC). Fa\xE7a login com client.auth.signIn() e tente de novo.", kr = "O Core exige a identidade do usu\xE1rio final para esta opera\xE7\xE3o (403 end_user_token_required) e nenhum id_token foi aceito. Fa\xE7a login com client.auth.signIn() e tente de novo.", Sr = "O Core recusou o token do usu\xE1rio final (401 invalid_end_user_token \u2014 sess\xE3o expirada, usu\xE1rio inativo ou token que n\xE3o \xE9 id_token) e a renova\xE7\xE3o autom\xE1tica n\xE3o resolveu. Fa\xE7a login novamente com client.auth.signIn() e tente de novo.", Tr = "O id_token do usu\xE1rio final foi emitido para o client OIDC de OUTRO produto (403 end_user_token_product_mismatch). Confira se o login (client.auth / clientId OIDC) e a apiKey/productId do createNeetruClient s\xE3o do MESMO produto.";
1438
- function $t(n) {
1439
- if (n instanceof c && !(n instanceof V)) {
1452
+ 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.";
1453
+ function Bt(n) {
1454
+ if (n instanceof c && !(n instanceof K)) {
1440
1455
  if (n.code === "end_user_token_required")
1441
- throw new V(
1442
- kr,
1456
+ throw new K(
1457
+ Cr,
1443
1458
  "end_user_token_required",
1444
1459
  n.status,
1445
1460
  n.requestId,
1446
1461
  n.correlationId
1447
1462
  );
1448
1463
  if (n.code === "invalid_end_user_token")
1449
- throw new V(
1450
- Sr,
1464
+ throw new K(
1465
+ Ar,
1451
1466
  "invalid_end_user_token",
1452
1467
  n.status,
1453
1468
  n.requestId,
@@ -1456,7 +1471,7 @@ function $t(n) {
1456
1471
  if (n.code === "end_user_token_product_mismatch")
1457
1472
  throw new c(
1458
1473
  "forbidden",
1459
- Tr,
1474
+ Er,
1460
1475
  n.status,
1461
1476
  n.requestId,
1462
1477
  "end_user_token_product_mismatch",
@@ -1465,10 +1480,10 @@ function $t(n) {
1465
1480
  }
1466
1481
  throw n;
1467
1482
  }
1468
- function Rr(n) {
1483
+ function Pr(n) {
1469
1484
  return n instanceof c && n.code === "invalid_end_user_token";
1470
1485
  }
1471
- function Wt(n, e = {}) {
1486
+ function Vt(n, e = {}) {
1472
1487
  async function t() {
1473
1488
  try {
1474
1489
  let a = await e.getEndUserToken?.();
@@ -1486,25 +1501,25 @@ function Wt(n, e = {}) {
1486
1501
  }
1487
1502
  }
1488
1503
  function o(a) {
1489
- return a ? { [vr]: a } : {};
1504
+ return a ? { [Rr]: a } : {};
1490
1505
  }
1491
1506
  async function i(a, l) {
1492
1507
  let d = await t();
1493
1508
  if (!d && a && await r() && (d = await t()), !d && a)
1494
- throw new V(wr, "no_signed_in_user");
1509
+ throw new K(Ir, "no_signed_in_user");
1495
1510
  try {
1496
1511
  return await l(o(d));
1497
1512
  } catch (u) {
1498
- if (d && Rr(u) && await r()) {
1513
+ if (d && Pr(u) && await r()) {
1499
1514
  let p = await t();
1500
1515
  if (p)
1501
1516
  try {
1502
1517
  return await l(o(p));
1503
1518
  } catch (f) {
1504
- $t(f);
1519
+ Bt(f);
1505
1520
  }
1506
1521
  }
1507
- $t(u);
1522
+ Bt(u);
1508
1523
  }
1509
1524
  }
1510
1525
  async function s(a, l = {}) {
@@ -1537,13 +1552,13 @@ function Wt(n, e = {}) {
1537
1552
  throw new c("validation_failed", "message is required");
1538
1553
  if (a.message.length > 1e4)
1539
1554
  throw new c("validation_failed", "message max 10000 chars");
1540
- if (a.severity && !je.includes(a.severity))
1555
+ if (a.severity && !We.includes(a.severity))
1541
1556
  throw new c(
1542
1557
  "validation_failed",
1543
- `severity must be one of ${je.join(", ")}`
1558
+ `severity must be one of ${We.join(", ")}`
1544
1559
  );
1545
1560
  let d = {
1546
- productId: jt(n, a.productSlug),
1561
+ productId: Wt(n, a.productSlug),
1547
1562
  subject: a.subject,
1548
1563
  message: a.message,
1549
1564
  severity: a.severity ?? "normal"
@@ -1560,7 +1575,7 @@ function Wt(n, e = {}) {
1560
1575
  headers: f
1561
1576
  })
1562
1577
  ), p = u && typeof u == "object" && "ticket" in u ? u.ticket : u;
1563
- return qt(p);
1578
+ return jt(p);
1564
1579
  },
1565
1580
  /**
1566
1581
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
@@ -1568,11 +1583,11 @@ function Wt(n, e = {}) {
1568
1583
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
1569
1584
  */
1570
1585
  async listMyTickets(a) {
1571
- let l = jt(n, a?.productSlug), d = a?.limit;
1572
- if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Mt))
1586
+ let l = Wt(n, a?.productSlug), d = a?.limit;
1587
+ if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Ft))
1573
1588
  throw new c(
1574
1589
  "validation_failed",
1575
- `limit must be an integer 1-${Mt} (Core default 20)`
1590
+ `limit must be an integer 1-${Ft} (Core default 20)`
1576
1591
  );
1577
1592
  let u = await i(
1578
1593
  true,
@@ -1584,7 +1599,7 @@ function Wt(n, e = {}) {
1584
1599
  headers: f
1585
1600
  })
1586
1601
  );
1587
- return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(qt);
1602
+ return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(jt);
1588
1603
  },
1589
1604
  /**
1590
1605
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
@@ -1592,7 +1607,7 @@ function Wt(n, e = {}) {
1592
1607
  * `POST /api/sdk/v1/support/tickets/{id}/resolved-seen`.
1593
1608
  */
1594
1609
  async markResolvedSeen(a) {
1595
- de(a), await s(
1610
+ ue(a), await s(
1596
1611
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/resolved-seen`
1597
1612
  );
1598
1613
  },
@@ -1603,7 +1618,7 @@ function Wt(n, e = {}) {
1603
1618
  * `POST /api/sdk/v1/support/tickets/{id}/satisfaction-attempt`.
1604
1619
  */
1605
1620
  async recordSatisfactionAttempt(a) {
1606
- de(a), await s(
1621
+ ue(a), await s(
1607
1622
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/satisfaction-attempt`,
1608
1623
  // Incrementa satisfactionAttempts += 1 no Core — sem idempotencyKey,
1609
1624
  // um retry de rede infla o contador (mesmo padrão de createTicket acima).
@@ -1617,9 +1632,9 @@ function Wt(n, e = {}) {
1617
1632
  async submitSatisfaction(a) {
1618
1633
  if (!a || typeof a != "object")
1619
1634
  throw new c("validation_failed", "input is required");
1620
- if (de(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1635
+ if (ue(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1621
1636
  throw new c("validation_failed", "rating must be an integer 1-5 or null");
1622
- Ft(a.comment), await s(
1637
+ $t(a.comment), await s(
1623
1638
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a.ticketId)}/satisfaction`,
1624
1639
  {
1625
1640
  body: {
@@ -1636,7 +1651,7 @@ function Wt(n, e = {}) {
1636
1651
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
1637
1652
  */
1638
1653
  async contestTicket(a, l) {
1639
- de(a), Ft(l?.comment), await s(
1654
+ ue(a), $t(l?.comment), await s(
1640
1655
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/contest`,
1641
1656
  { body: { comment: l?.comment ?? void 0 } }
1642
1657
  );
@@ -1645,14 +1660,14 @@ function Wt(n, e = {}) {
1645
1660
  }
1646
1661
 
1647
1662
  // src/db/client-db.ts
1648
- Z();
1663
+ ee();
1649
1664
 
1650
1665
  // src/db/offline/query-engine.ts
1651
- function Bt(n) {
1666
+ function Kt(n) {
1652
1667
  return n == null ? 0 : typeof n == "number" ? 1 : typeof n == "string" ? 2 : typeof n == "boolean" ? 3 : 4;
1653
1668
  }
1654
- function ee(n, e) {
1655
- let t = Bt(n), r = Bt(e);
1669
+ function te(n, e) {
1670
+ let t = Kt(n), r = Kt(e);
1656
1671
  if (t !== r) return t - r;
1657
1672
  if (n == null) return 0;
1658
1673
  if (typeof n == "number" && typeof e == "number") return n - e;
@@ -1661,7 +1676,7 @@ function ee(n, e) {
1661
1676
  let o = String(n), i = String(e);
1662
1677
  return o < i ? -1 : o > i ? 1 : 0;
1663
1678
  }
1664
- function $e(n, e) {
1679
+ function Be(n, e) {
1665
1680
  let t = e.split("."), r = n;
1666
1681
  for (let o of t) {
1667
1682
  if (r == null || typeof r != "object")
@@ -1670,8 +1685,8 @@ function $e(n, e) {
1670
1685
  }
1671
1686
  return r;
1672
1687
  }
1673
- function Cr(n, e) {
1674
- let t = $e(n, e.field);
1688
+ function Nr(n, e) {
1689
+ let t = Be(n, e.field);
1675
1690
  if (t === void 0) return false;
1676
1691
  let { op: r, value: o } = e;
1677
1692
  switch (r) {
@@ -1680,13 +1695,13 @@ function Cr(n, e) {
1680
1695
  case "!=":
1681
1696
  return t !== o;
1682
1697
  case "<":
1683
- return ee(t, o) < 0;
1698
+ return te(t, o) < 0;
1684
1699
  case "<=":
1685
- return ee(t, o) <= 0;
1700
+ return te(t, o) <= 0;
1686
1701
  case ">":
1687
- return ee(t, o) > 0;
1702
+ return te(t, o) > 0;
1688
1703
  case ">=":
1689
- return ee(t, o) >= 0;
1704
+ return te(t, o) >= 0;
1690
1705
  case "array-contains":
1691
1706
  return Array.isArray(t) && t.includes(o);
1692
1707
  case "in":
@@ -1701,24 +1716,24 @@ function Cr(n, e) {
1701
1716
  );
1702
1717
  }
1703
1718
  }
1704
- function Ar(n, e) {
1705
- return e.every((t) => Cr(n, t));
1719
+ function xr(n, e) {
1720
+ return e.every((t) => Nr(n, t));
1706
1721
  }
1707
- function Er(n) {
1722
+ function Or(n) {
1708
1723
  return (e, t) => {
1709
1724
  if (n) {
1710
- let r = $e(e.data, n.field), o = $e(t.data, n.field), i = ee(r, o);
1725
+ let r = Be(e.data, n.field), o = Be(t.data, n.field), i = te(r, o);
1711
1726
  if (i !== 0)
1712
1727
  return n.direction === "desc" ? -i : i;
1713
1728
  }
1714
1729
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
1715
1730
  };
1716
1731
  }
1717
- function Pr(n, e) {
1732
+ function Lr(n, e) {
1718
1733
  let t = n.findIndex((r) => r.id === e.docId);
1719
1734
  return t === -1 ? n : e.type === "startAfter" ? n.slice(t + 1) : n.slice(0, t);
1720
1735
  }
1721
- var z = class n {
1736
+ var H = class n {
1722
1737
  /**
1723
1738
  * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
1724
1739
  *
@@ -1732,9 +1747,9 @@ var z = class n {
1732
1747
  evaluate(e, t) {
1733
1748
  let r = e.filter((u) => !u.meta.deleted), o = t.where ?? [];
1734
1749
  o.length > 0 && (r = r.filter(
1735
- (u) => Ar(u.data, o)
1750
+ (u) => xr(u.data, o)
1736
1751
  ));
1737
- let i = Er(t.orderBy), s = [...r].sort(i), a = t.cursor ? Pr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1752
+ let i = Or(t.orderBy), s = [...r].sort(i), a = t.cursor ? Lr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1738
1753
  return {
1739
1754
  docs: a.slice(0, l).map((u) => ({ id: u.id, data: u.data })),
1740
1755
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
@@ -1754,7 +1769,7 @@ var z = class n {
1754
1769
  };
1755
1770
 
1756
1771
  // src/db/offline/local-store.ts
1757
- var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_meta", H = "conflict_log", pe = class {
1772
+ var Mr = 1, B = "documents", V = "mutations", ne = "query_cache", pe = "sync_meta", Q = "conflict_log", fe = class {
1758
1773
  db = null;
1759
1774
  dbName;
1760
1775
  constructor(e) {
@@ -1766,22 +1781,22 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1766
1781
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
1767
1782
  */
1768
1783
  async open() {
1769
- this.db === null && (this.db = await idb.openDB(this.dbName, Nr, {
1784
+ this.db === null && (this.db = await idb.openDB(this.dbName, Mr, {
1770
1785
  upgrade(e) {
1771
- if (!e.objectStoreNames.contains(W)) {
1772
- let t = e.createObjectStore(W, {
1786
+ if (!e.objectStoreNames.contains(B)) {
1787
+ let t = e.createObjectStore(B, {
1773
1788
  keyPath: ["collection", "id"]
1774
1789
  });
1775
1790
  t.createIndex("by_collection", "collection"), t.createIndex("by_collection_state", ["collection", "meta.state"]), t.createIndex("by_updatedAtServer", "meta.updatedAtServer");
1776
1791
  }
1777
- if (!e.objectStoreNames.contains(B)) {
1778
- let t = e.createObjectStore(B, {
1792
+ if (!e.objectStoreNames.contains(V)) {
1793
+ let t = e.createObjectStore(V, {
1779
1794
  keyPath: "mutationId"
1780
1795
  });
1781
1796
  t.createIndex("by_seq", "seq"), t.createIndex("by_status", "status"), t.createIndex("by_doc", ["collection", "docId"]), t.createIndex("by_batch", "batchId");
1782
1797
  }
1783
- if (e.objectStoreNames.contains(te) || e.createObjectStore(te, { keyPath: "queryHash" }), e.objectStoreNames.contains(ue) || e.createObjectStore(ue, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1784
- let t = e.createObjectStore(H, {
1798
+ if (e.objectStoreNames.contains(ne) || e.createObjectStore(ne, { keyPath: "queryHash" }), e.objectStoreNames.contains(pe) || e.createObjectStore(pe, { keyPath: "key" }), !e.objectStoreNames.contains(Q)) {
1799
+ let t = e.createObjectStore(Q, {
1785
1800
  keyPath: "id",
1786
1801
  autoIncrement: true
1787
1802
  });
@@ -1823,14 +1838,14 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1823
1838
  * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
1824
1839
  */
1825
1840
  async getDoc(e, t) {
1826
- return await this.assertOpen().get(W, [e, t]) ?? null;
1841
+ return await this.assertOpen().get(B, [e, t]) ?? null;
1827
1842
  }
1828
1843
  /**
1829
1844
  * Insere ou atualiza um documento na store `documents`.
1830
1845
  * O documento é identificado pelo keyPath composto `[collection, id]`.
1831
1846
  */
1832
1847
  async putDoc(e) {
1833
- await this.assertOpen().put(W, e);
1848
+ await this.assertOpen().put(B, e);
1834
1849
  }
1835
1850
  /**
1836
1851
  * Marca um documento como tombstone (`deleted: true`).
@@ -1838,8 +1853,8 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1838
1853
  * No-op se o documento não existir.
1839
1854
  */
1840
1855
  async deleteDoc(e, t) {
1841
- let r = this.assertOpen(), o = await r.get(W, [e, t]);
1842
- o && await r.put(W, {
1856
+ let r = this.assertOpen(), o = await r.get(B, [e, t]);
1857
+ o && await r.put(B, {
1843
1858
  ...o,
1844
1859
  meta: {
1845
1860
  ...o.meta,
@@ -1855,8 +1870,8 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1855
1870
  * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
1856
1871
  */
1857
1872
  async listDocs(e, t) {
1858
- let o = await this.assertOpen().getAllFromIndex(W, "by_collection", e);
1859
- return z.evaluate(o, t);
1873
+ let o = await this.assertOpen().getAllFromIndex(B, "by_collection", e);
1874
+ return H.evaluate(o, t);
1860
1875
  }
1861
1876
  // ─── Sync meta (key-value) ──────────────────────────────────────────────────
1862
1877
  /**
@@ -1867,14 +1882,14 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1867
1882
  * 'lastFullResyncAt', 'leaderTabId'.
1868
1883
  */
1869
1884
  async getMeta(e) {
1870
- let r = await this.assertOpen().get(ue, e);
1885
+ let r = await this.assertOpen().get(pe, e);
1871
1886
  return r ? r.value : null;
1872
1887
  }
1873
1888
  /**
1874
1889
  * Armazena ou atualiza um valor na store `sync_meta`.
1875
1890
  */
1876
1891
  async setMeta(e, t) {
1877
- await this.assertOpen().put(ue, { key: e, value: t });
1892
+ await this.assertOpen().put(pe, { key: e, value: t });
1878
1893
  }
1879
1894
  // ─── Conflict log ───────────────────────────────────────────────────────────
1880
1895
  /**
@@ -1882,7 +1897,7 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1882
1897
  * O `id` é autoIncrement — não deve ser fornecido pelo chamador.
1883
1898
  */
1884
1899
  async appendConflict(e) {
1885
- let r = await this.assertOpen().add(H, e);
1900
+ let r = await this.assertOpen().add(Q, e);
1886
1901
  return { ...e, id: r };
1887
1902
  }
1888
1903
  /**
@@ -1890,15 +1905,15 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1890
1905
  * Filtra por `delivered` se a opção for fornecida.
1891
1906
  */
1892
1907
  async listConflicts(e) {
1893
- let r = await this.assertOpen().getAll(H);
1908
+ let r = await this.assertOpen().getAll(Q);
1894
1909
  return e?.delivered !== void 0 ? r.filter((o) => o.delivered === e.delivered) : r;
1895
1910
  }
1896
1911
  /**
1897
1912
  * Marca um registro do `conflict_log` como entregue ao produto.
1898
1913
  */
1899
1914
  async markConflictDelivered(e) {
1900
- let t = this.assertOpen(), r = await t.get(H, e);
1901
- r && await t.put(H, { ...r, delivered: true });
1915
+ let t = this.assertOpen(), r = await t.get(Q, e);
1916
+ r && await t.put(Q, { ...r, delivered: true });
1902
1917
  }
1903
1918
  // ─── Mutations (acessores usados pelo MutationQueue) ────────────────────────
1904
1919
  /**
@@ -1906,13 +1921,13 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1906
1921
  * Key: `mutationId`.
1907
1922
  */
1908
1923
  async putMutation(e) {
1909
- await this.assertOpen().put(B, e);
1924
+ await this.assertOpen().put(V, e);
1910
1925
  }
1911
1926
  /**
1912
1927
  * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
1913
1928
  */
1914
1929
  async getMutation(e) {
1915
- return await this.assertOpen().get(B, e) ?? null;
1930
+ return await this.assertOpen().get(V, e) ?? null;
1916
1931
  }
1917
1932
  /**
1918
1933
  * Lista mutações com filtros opcionais.
@@ -1920,14 +1935,14 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1920
1935
  */
1921
1936
  async listMutations(e) {
1922
1937
  let t = this.assertOpen(), r;
1923
- 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);
1938
+ 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);
1924
1939
  }
1925
1940
  /**
1926
1941
  * Remove uma mutação pelo `mutationId`.
1927
1942
  * No-op se não existir.
1928
1943
  */
1929
1944
  async deleteMutation(e) {
1930
- await this.assertOpen().delete(B, e);
1945
+ await this.assertOpen().delete(V, e);
1931
1946
  }
1932
1947
  // ─── Collection discovery ────────────────────────────────────────────────────
1933
1948
  /**
@@ -1940,7 +1955,7 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1940
1955
  * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
1941
1956
  */
1942
1957
  async listCollections() {
1943
- let t = await this.assertOpen().getAllFromIndex(W, "by_collection"), r = /* @__PURE__ */ new Set();
1958
+ let t = await this.assertOpen().getAllFromIndex(B, "by_collection"), r = /* @__PURE__ */ new Set();
1944
1959
  for (let o of t)
1945
1960
  r.add(o.collection);
1946
1961
  return Array.from(r);
@@ -1950,24 +1965,24 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1950
1965
  * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
1951
1966
  */
1952
1967
  async getQueryCache(e) {
1953
- return await this.assertOpen().get(te, e) ?? null;
1968
+ return await this.assertOpen().get(ne, e) ?? null;
1954
1969
  }
1955
1970
  /**
1956
1971
  * Insere ou atualiza uma entrada de `query_cache`.
1957
1972
  */
1958
1973
  async putQueryCache(e) {
1959
- await this.assertOpen().put(te, e);
1974
+ await this.assertOpen().put(ne, e);
1960
1975
  }
1961
1976
  /**
1962
1977
  * Remove uma entrada de `query_cache` pelo queryHash.
1963
1978
  */
1964
1979
  async deleteQueryCache(e) {
1965
- await this.assertOpen().delete(te, e);
1980
+ await this.assertOpen().delete(ne, e);
1966
1981
  }
1967
1982
  };
1968
1983
 
1969
1984
  // src/db/offline/memory-store.ts
1970
- var fe = class {
1985
+ var me = class {
1971
1986
  // store `documents` — key: `${collection}\0${id}`
1972
1987
  _docs = /* @__PURE__ */ new Map();
1973
1988
  // store `mutations` — key: mutationId
@@ -2015,7 +2030,7 @@ var fe = class {
2015
2030
  let r = Array.from(this._docs.values()).filter(
2016
2031
  (o) => o.collection === e
2017
2032
  );
2018
- return z.evaluate(r, t);
2033
+ return H.evaluate(r, t);
2019
2034
  }
2020
2035
  // ─── Sync meta ──────────────────────────────────────────────────────────────
2021
2036
  async getMeta(e) {
@@ -2072,13 +2087,13 @@ var fe = class {
2072
2087
  };
2073
2088
 
2074
2089
  // src/db/offline/mutation-queue.ts
2075
- function We() {
2090
+ function Ve() {
2076
2091
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (n) => {
2077
2092
  let e = Math.random() * 16 | 0;
2078
2093
  return (n === "x" ? e : e & 3 | 8).toString(16);
2079
2094
  });
2080
2095
  }
2081
- var me = class {
2096
+ var he = class {
2082
2097
  store;
2083
2098
  /**
2084
2099
  * Ponteiro de sequência local.
@@ -2174,7 +2189,7 @@ var me = class {
2174
2189
  * Atômico: a persistência final é uma única operação putMutation.
2175
2190
  */
2176
2191
  async enqueue(e) {
2177
- let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? We() : "");
2192
+ let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? Ve() : "");
2178
2193
  await this.syncSeq();
2179
2194
  let u = (await this.store.listMutations({ collection: t, docId: l })).filter((h) => h.status === "queued").sort((h, y) => y.seq - h.seq)[0];
2180
2195
  if (u !== void 0) {
@@ -2183,7 +2198,7 @@ var me = class {
2183
2198
  if ("removed" in h)
2184
2199
  return await this.store.deleteMutation(u.mutationId), {
2185
2200
  seq: u.seq,
2186
- mutationId: We(),
2201
+ mutationId: Ve(),
2187
2202
  collection: t,
2188
2203
  docId: l,
2189
2204
  op: "remove",
@@ -2201,7 +2216,7 @@ var me = class {
2201
2216
  }
2202
2217
  let f = {
2203
2218
  seq: this.nextSeq(),
2204
- mutationId: We(),
2219
+ mutationId: Ve(),
2205
2220
  collection: t,
2206
2221
  docId: l,
2207
2222
  op: r,
@@ -2314,45 +2329,45 @@ var me = class {
2314
2329
  };
2315
2330
 
2316
2331
  // src/db/field-value.ts
2317
- var Vt = "__neetru__";
2318
- function Q(n) {
2319
- return typeof n == "object" && n !== null && Vt in n && typeof n[Vt] == "string";
2332
+ var zt = "__neetru__";
2333
+ function G(n) {
2334
+ return typeof n == "object" && n !== null && zt in n && typeof n[zt] == "string";
2320
2335
  }
2321
- function xr(n) {
2322
- return Q(n) && n.__neetru__ === "serverTimestamp";
2336
+ function qr(n) {
2337
+ return G(n) && n.__neetru__ === "serverTimestamp";
2323
2338
  }
2324
- function Or(n) {
2325
- return Q(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2339
+ function Fr(n) {
2340
+ return G(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2326
2341
  }
2327
- function Lr(n, e) {
2328
- return xr(n) ? Date.now() : Or(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2342
+ function jr(n, e) {
2343
+ return qr(n) ? Date.now() : Fr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2329
2344
  }
2330
- function K(n, e) {
2345
+ function z(n, e) {
2331
2346
  let t = false, r = {};
2332
2347
  for (let [o, i] of Object.entries(n))
2333
- Q(i) ? (t = true, r[o] = Lr(i, e?.[o])) : r[o] = i;
2348
+ G(i) ? (t = true, r[o] = jr(i, e?.[o])) : r[o] = i;
2334
2349
  return t ? r : n;
2335
2350
  }
2336
- function Be(n) {
2351
+ function Ke(n) {
2337
2352
  for (let e of Object.values(n))
2338
- if (Q(e)) return true;
2353
+ if (G(e)) return true;
2339
2354
  return false;
2340
2355
  }
2341
2356
 
2342
2357
  // src/db/offline/sync-engine.ts
2343
- var Ur = 8, Mr = 1e3, qr = 300 * 1e3, Ve = "truncatedCollections";
2344
- function Fr(n) {
2345
- return n !== null && Be(n);
2358
+ var $r = 8, Wr = 1e3, Br = 300 * 1e3, ze = "truncatedCollections";
2359
+ function Vr(n) {
2360
+ return n !== null && Ke(n);
2346
2361
  }
2347
- function jr(n) {
2362
+ function Kr(n) {
2348
2363
  if (n === null) return null;
2349
- if (!Be(n)) return n;
2364
+ if (!Ke(n)) return n;
2350
2365
  let e = {};
2351
2366
  for (let [t, r] of Object.entries(n))
2352
- Q(r) || (e[t] = r);
2367
+ G(r) || (e[t] = r);
2353
2368
  return e;
2354
2369
  }
2355
- var he = class {
2370
+ var ge = class {
2356
2371
  _store;
2357
2372
  _queue;
2358
2373
  _resolver;
@@ -2546,13 +2561,13 @@ var he = class {
2546
2561
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
2547
2562
  return;
2548
2563
  }
2549
- let d = jr(i.payload) ?? a?.data ?? {}, u = {
2564
+ let d = Kr(i.payload) ?? a?.data ?? {}, u = {
2550
2565
  collection: e,
2551
2566
  id: t,
2552
2567
  data: i.op === "update" ? { ...a?.data ?? {}, ...d } : (
2553
2568
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2554
2569
  // é a fonte de verdade até o pull; senão usa o payload literal.
2555
- Fr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2570
+ Vr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2556
2571
  ),
2557
2572
  meta: {
2558
2573
  serverVersion: r,
@@ -2705,7 +2720,7 @@ var he = class {
2705
2720
  * pending do doc no cache + registra `lastError`/dispara `onError`.
2706
2721
  */
2707
2722
  async _retryOrDeadLetter(e, t, r) {
2708
- if (e.attempts + 1 < Ur) {
2723
+ if (e.attempts + 1 < $r) {
2709
2724
  await this._queue.markRetry(e.mutationId, t);
2710
2725
  return;
2711
2726
  }
@@ -2746,7 +2761,7 @@ var he = class {
2746
2761
  }
2747
2762
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
2748
2763
  _backoffDelayMs(e) {
2749
- return Math.min(Mr * 2 ** (e - 1), qr);
2764
+ return Math.min(Wr * 2 ** (e - 1), Br);
2750
2765
  }
2751
2766
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
2752
2767
  /**
@@ -2779,7 +2794,7 @@ var he = class {
2779
2794
  let r = [];
2780
2795
  await this._applyServerDocs(t.docs, r, true);
2781
2796
  let o = t.truncatedCollections ?? [], i = new Set(o);
2782
- await this._store.setMeta(Ve, o);
2797
+ await this._store.setMeta(ze, o);
2783
2798
  let s = new Set(
2784
2799
  t.docs.map((a) => `${a.collection}::${a.id}`)
2785
2800
  );
@@ -2998,10 +3013,10 @@ var he = class {
2998
3013
  };
2999
3014
 
3000
3015
  // src/db/offline/conflict-resolver.ts
3001
- function Kt(n, e) {
3016
+ function Ht(n, e) {
3002
3017
  return e === null ? false : n === null ? true : e > n;
3003
3018
  }
3004
- var ge = class n {
3019
+ var ye = class n {
3005
3020
  /**
3006
3021
  * Resolve um conflito com base na operação da mutação (auto-dispatch).
3007
3022
  *
@@ -3035,7 +3050,7 @@ var ge = class n {
3035
3050
  resolvedData: t.data,
3036
3051
  conflictRecord: null
3037
3052
  };
3038
- if (!Kt(
3053
+ if (!Ht(
3039
3054
  e.meta.updatedAtServer,
3040
3055
  t.meta.updatedAtServer
3041
3056
  ))
@@ -3082,7 +3097,7 @@ var ge = class n {
3082
3097
  let i = t.data;
3083
3098
  if (e === null)
3084
3099
  return { outcome: "no_conflict", resolvedData: { ...i, ...r.payload ?? {} }, conflictRecord: null };
3085
- if (!Kt(
3100
+ if (!Ht(
3086
3101
  e.meta.updatedAtServer,
3087
3102
  t.meta.updatedAtServer
3088
3103
  ))
@@ -3160,10 +3175,10 @@ var ge = class n {
3160
3175
  };
3161
3176
 
3162
3177
  // src/db/offline/change-bus.ts
3163
- function $r(n) {
3178
+ function zr(n) {
3164
3179
  return `${n.collection}::${n.doc.id}`;
3165
3180
  }
3166
- var ye = class {
3181
+ var _e = class {
3167
3182
  /** Listeners filtrados por coleção. */
3168
3183
  _collectionListeners = /* @__PURE__ */ new Map();
3169
3184
  /** Listeners globais (todas as coleções). */
@@ -3208,7 +3223,7 @@ var ye = class {
3208
3223
  if (e.length === 0) return;
3209
3224
  let t = /* @__PURE__ */ new Map();
3210
3225
  for (let i of e)
3211
- t.set($r(i), i);
3226
+ t.set(zr(i), i);
3212
3227
  let r = Array.from(t.values()), o = /* @__PURE__ */ new Map();
3213
3228
  for (let i of r)
3214
3229
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
@@ -3247,7 +3262,7 @@ var ye = class {
3247
3262
  };
3248
3263
 
3249
3264
  // src/db/offline/connectivity-monitor.ts
3250
- var _e = class {
3265
+ var be = class {
3251
3266
  _state;
3252
3267
  _listeners = /* @__PURE__ */ new Set();
3253
3268
  _nav;
@@ -3349,7 +3364,7 @@ var _e = class {
3349
3364
  };
3350
3365
 
3351
3366
  // src/db/offline/tab-coordinator.ts
3352
- var ne = class {
3367
+ var re = class {
3353
3368
  _lockName;
3354
3369
  _channelName;
3355
3370
  _lockManager;
@@ -3526,26 +3541,26 @@ var ne = class {
3526
3541
  };
3527
3542
 
3528
3543
  // src/db/collection-ref.ts
3529
- Z();
3530
- function Wr() {
3544
+ ee();
3545
+ function Hr() {
3531
3546
  return typeof indexedDB > "u" || typeof window > "u";
3532
3547
  }
3533
- var zt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3534
- function Br(n) {
3535
- if (!zt.test(n))
3536
- throw new b(
3548
+ var Qt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3549
+ function Qr(n) {
3550
+ if (!Qt.test(n))
3551
+ throw new _(
3537
3552
  "db_invalid_query",
3538
- `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${zt}.`
3553
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${Qt}.`
3539
3554
  );
3540
3555
  }
3541
- function G(n, e = "id") {
3556
+ function J(n, e = "id") {
3542
3557
  if (!n || typeof n != "string" || n.trim() === "")
3543
- throw new b(
3558
+ throw new _(
3544
3559
  "db_invalid_query",
3545
3560
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
3546
3561
  );
3547
3562
  }
3548
- function Vr(n) {
3563
+ function Gr(n) {
3549
3564
  let e = {};
3550
3565
  if (n?.where && (e.where = n.where.map((t) => ({
3551
3566
  field: t.field,
@@ -3562,12 +3577,12 @@ function Vr(n) {
3562
3577
  }
3563
3578
  return e;
3564
3579
  }
3565
- function Kr(n, e) {
3580
+ function Jr(n, e) {
3566
3581
  if (n.length < e) return null;
3567
3582
  let t = n[n.length - 1];
3568
3583
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
3569
3584
  }
3570
- var Ke = class {
3585
+ var He = class {
3571
3586
  constructor(e, t, r, o, i, s) {
3572
3587
  this._collection = e;
3573
3588
  this._store = t;
@@ -3609,7 +3624,7 @@ var Ke = class {
3609
3624
  }
3610
3625
  /** Constrói um DbListResult para a coleção com query opcional. */
3611
3626
  async _buildListResult(e) {
3612
- let t = Vr(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), l = Kr(o.docs, r), d = await this._store.getMeta(Ve), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3627
+ 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;
3613
3628
  return {
3614
3629
  docs: o.docs.map((h) => ({ id: h.id, data: h.data })),
3615
3630
  nextCursor: l,
@@ -3622,13 +3637,13 @@ var Ke = class {
3622
3637
  }
3623
3638
  // ── CRUD ────────────────────────────────────────────────────────────────────
3624
3639
  async get(e) {
3625
- return G(e), this._buildGetResult(e);
3640
+ return J(e), this._buildGetResult(e);
3626
3641
  }
3627
3642
  async list(e) {
3628
3643
  return this._buildListResult(e);
3629
3644
  }
3630
3645
  async add(e) {
3631
- let t = e, r = K(t, void 0), o = await this._queue.enqueue({
3646
+ let t = e, r = z(t, void 0), o = await this._queue.enqueue({
3632
3647
  collection: this._collection,
3633
3648
  op: "add",
3634
3649
  payload: t,
@@ -3655,8 +3670,8 @@ var Ke = class {
3655
3670
  }]), { ok: true, id: i };
3656
3671
  }
3657
3672
  async set(e, t) {
3658
- G(e);
3659
- let r = await this._store.getDoc(this._collection, e), o = t, i = K(o, void 0), s = await this._queue.enqueue({
3673
+ J(e);
3674
+ let r = await this._store.getDoc(this._collection, e), o = t, i = z(o, void 0), s = await this._queue.enqueue({
3660
3675
  collection: this._collection,
3661
3676
  docId: e,
3662
3677
  op: "set",
@@ -3684,8 +3699,8 @@ var Ke = class {
3684
3699
  }]), { ok: true };
3685
3700
  }
3686
3701
  async update(e, t, r) {
3687
- G(e);
3688
- let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = K(i, s), l = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3702
+ J(e);
3703
+ 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({
3689
3704
  collection: this._collection,
3690
3705
  docId: e,
3691
3706
  op: "update",
@@ -3718,7 +3733,7 @@ var Ke = class {
3718
3733
  }]), { ok: true };
3719
3734
  }
3720
3735
  async remove(e) {
3721
- G(e);
3736
+ J(e);
3722
3737
  let t = await this._store.getDoc(this._collection, e);
3723
3738
  return !t || t.meta.deleted, await this._queue.enqueue({
3724
3739
  collection: this._collection,
@@ -3738,7 +3753,7 @@ var Ke = class {
3738
3753
  for (let o of e) {
3739
3754
  let i = this._collection;
3740
3755
  if (o.kind === "add") {
3741
- let s = o.data, a = K(s, void 0), l = await this._queue.enqueue({
3756
+ let s = o.data, a = z(s, void 0), l = await this._queue.enqueue({
3742
3757
  collection: i,
3743
3758
  op: "add",
3744
3759
  payload: s,
@@ -3760,7 +3775,7 @@ var Ke = class {
3760
3775
  }
3761
3776
  }), r.push({ type: "added", collection: i, doc: { id: d, data: a } });
3762
3777
  } else if (o.kind === "set") {
3763
- let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = K(a, void 0), u = await this._queue.enqueue({
3778
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = z(a, void 0), u = await this._queue.enqueue({
3764
3779
  collection: i,
3765
3780
  docId: s,
3766
3781
  op: "set",
@@ -3787,7 +3802,7 @@ var Ke = class {
3787
3802
  doc: { id: s, data: d }
3788
3803
  });
3789
3804
  } else if (o.kind === "update") {
3790
- let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = l?.meta.deleted ? void 0 : l?.data, u = K(a, d), p = { ...l?.data ?? {}, ...u }, f = await this._queue.enqueue({
3805
+ 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({
3791
3806
  collection: i,
3792
3807
  docId: s,
3793
3808
  op: "update",
@@ -3830,7 +3845,7 @@ var Ke = class {
3830
3845
  }
3831
3846
  // ── Realtime ─────────────────────────────────────────────────────────────────
3832
3847
  onDoc(e, t) {
3833
- return G(e), this._buildGetResult(e).then((r) => {
3848
+ return J(e), this._buildGetResult(e).then((r) => {
3834
3849
  t(r ? r.docs[0]?.data ?? null : null);
3835
3850
  }).catch(() => t(null)), this._bus.subscribe(this._collection, (r) => {
3836
3851
  let o = r.find((i) => i.doc.id === e);
@@ -3889,7 +3904,7 @@ var Ke = class {
3889
3904
  };
3890
3905
  }
3891
3906
  doc(e) {
3892
- G(e);
3907
+ J(e);
3893
3908
  let t = this;
3894
3909
  return {
3895
3910
  get id() {
@@ -3942,7 +3957,7 @@ var Ke = class {
3942
3957
  }
3943
3958
  };
3944
3959
  }
3945
- }, ze = class {
3960
+ }, Qe = class {
3946
3961
  _store;
3947
3962
  _queue;
3948
3963
  _bus;
@@ -3952,7 +3967,7 @@ var Ke = class {
3952
3967
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3953
3968
  }
3954
3969
  collection(e) {
3955
- return Br(e), new Ke(
3970
+ return Qr(e), new He(
3956
3971
  e,
3957
3972
  this._store,
3958
3973
  this._queue,
@@ -3981,10 +3996,10 @@ var Ke = class {
3981
3996
  return this._engine.onError(e);
3982
3997
  }
3983
3998
  };
3984
- async function Ht(n) {
3985
- let e = Wr() ? new fe() : new pe(n.dbName);
3999
+ async function Gt(n) {
4000
+ let e = Hr() ? new me() : new fe(n.dbName);
3986
4001
  await e.open();
3987
- let t = new me(e), r = new ge(), o = new ye(), i = new _e({
4002
+ let t = new he(e), r = new ye(), o = new _e(), i = new be({
3988
4003
  // Se startOnline=false, injeta um navigator falso
3989
4004
  navigator: n.startOnline === false ? { onLine: false } : typeof navigator < "u" ? navigator : void 0
3990
4005
  }), s = n.singleTab ? (
@@ -3994,10 +4009,10 @@ async function Ht(n) {
3994
4009
  onRoleChange: (l) => () => {
3995
4010
  }
3996
4011
  }
3997
- ) : new ne({
4012
+ ) : new re({
3998
4013
  lockName: `neetru-offline:${n.dbName}`,
3999
4014
  channelName: `neetru-offline:${n.dbName}`
4000
- }), a = new he({
4015
+ }), a = new ge({
4001
4016
  store: e,
4002
4017
  queue: t,
4003
4018
  resolver: r,
@@ -4007,7 +4022,7 @@ async function Ht(n) {
4007
4022
  connectivity: i,
4008
4023
  periodicSyncIntervalMs: n.periodicSyncIntervalMs ?? 300 * 1e3
4009
4024
  });
4010
- return i.start(), !n.singleTab && s instanceof ne && s.start(), new ze({
4025
+ return i.start(), !n.singleTab && s instanceof re && s.start(), new Qe({
4011
4026
  store: e,
4012
4027
  queue: t,
4013
4028
  bus: o,
@@ -4017,11 +4032,11 @@ async function Ht(n) {
4017
4032
  }
4018
4033
 
4019
4034
  // src/db/realtime/realtime-client.ts
4020
- var zr = 0;
4021
- function Qt() {
4022
- return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++zr}-${Math.random().toString(36).slice(2)}`;
4035
+ var Xr = 0;
4036
+ function Jt() {
4037
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++Xr}-${Math.random().toString(36).slice(2)}`;
4023
4038
  }
4024
- var be = class {
4039
+ var ve = class {
4025
4040
  // ── configuração ──────────────────────────────────────────────────────────
4026
4041
  _gatewayUrl;
4027
4042
  _wsFactory;
@@ -4059,7 +4074,7 @@ var be = class {
4059
4074
  _pendingFrames = [];
4060
4075
  // ── construtor ────────────────────────────────────────────────────────────
4061
4076
  constructor(e) {
4062
- this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? Hr, this._setTimeout = e.setTimeoutFn ?? globalThis.setTimeout.bind(globalThis), this._clearTimeout = e.clearTimeoutFn ?? globalThis.clearTimeout.bind(globalThis), this._backoffBaseMs = e.backoffBaseMs ?? 1e3, this._backoffMaxMs = e.backoffMaxMs ?? 3e4, this._heartbeatIntervalMs = e.heartbeatIntervalMs ?? 25e3, this._ticketProvider = e.ticketProvider, this._dbId = e.dbId, this._connect();
4077
+ 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();
4063
4078
  }
4064
4079
  // ── API pública ───────────────────────────────────────────────────────────
4065
4080
  /**
@@ -4073,8 +4088,8 @@ var be = class {
4073
4088
  */
4074
4089
  subscribe(e, t, r) {
4075
4090
  if (this._closed)
4076
- return Qt();
4077
- let o = Qt();
4091
+ return Jt();
4092
+ let o = Jt();
4078
4093
  this._subscriptions.set(o, {
4079
4094
  subscriptionId: o,
4080
4095
  collection: e,
@@ -4338,7 +4353,7 @@ var be = class {
4338
4353
  _detachHandlers(e) {
4339
4354
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
4340
4355
  }
4341
- }, Hr = (n) => {
4356
+ }, Yr = (n) => {
4342
4357
  if (typeof WebSocket > "u")
4343
4358
  throw new Error(
4344
4359
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -4347,46 +4362,46 @@ var be = class {
4347
4362
  };
4348
4363
 
4349
4364
  // src/db/client-db.ts
4350
- var so = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, we = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, an = 200;
4351
- function ao(n, e, t) {
4352
- return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? co(e.realtimeGatewayUrl, t, e) : ln(t);
4365
+ var po = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, ke = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, ln = 200;
4366
+ function fo(n, e, t) {
4367
+ return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? mo(e.realtimeGatewayUrl, t, e) : un(t);
4353
4368
  }
4354
- function ln(n) {
4369
+ function un(n) {
4355
4370
  return {
4356
4371
  async pushMutations(e) {
4357
4372
  if (!n)
4358
- throw new b(
4373
+ throw new _(
4359
4374
  "db_unavailable",
4360
4375
  "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
4361
4376
  );
4362
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4377
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4363
4378
  for (let s of e)
4364
4379
  try {
4365
4380
  let a;
4366
4381
  s.op === "add" ? a = await t(n, {
4367
4382
  method: "PUT",
4368
- path: we(s.collection, s.docId),
4383
+ path: ke(s.collection, s.docId),
4369
4384
  body: { data: s.payload ?? {} },
4370
4385
  requireAuth: !0,
4371
4386
  retries: 2,
4372
4387
  headers: i
4373
4388
  }) : s.op === "set" ? a = await t(n, {
4374
4389
  method: "PUT",
4375
- path: we(s.collection, s.docId),
4390
+ path: ke(s.collection, s.docId),
4376
4391
  body: { data: s.payload ?? {} },
4377
4392
  requireAuth: !0,
4378
4393
  retries: 2,
4379
4394
  headers: i
4380
4395
  }) : s.op === "update" ? a = await t(n, {
4381
4396
  method: "PATCH",
4382
- path: we(s.collection, s.docId),
4397
+ path: ke(s.collection, s.docId),
4383
4398
  body: { data: s.payload ?? {}, ...s.upsert ? { upsert: !0 } : {} },
4384
4399
  requireAuth: !0,
4385
4400
  retries: 2,
4386
4401
  headers: i
4387
4402
  }) : a = await t(n, {
4388
4403
  method: "DELETE",
4389
- path: we(s.collection, s.docId),
4404
+ path: ke(s.collection, s.docId),
4390
4405
  requireAuth: !0,
4391
4406
  retries: 2,
4392
4407
  headers: i
@@ -4412,7 +4427,7 @@ function ln(n) {
4412
4427
  continue;
4413
4428
  }
4414
4429
  if (r.length === 0)
4415
- throw new b("db_unavailable", `pushMutations falhou: ${l}`);
4430
+ throw new _("db_unavailable", `pushMutations falhou: ${l}`);
4416
4431
  break;
4417
4432
  }
4418
4433
  return { results: r };
@@ -4423,13 +4438,13 @@ function ln(n) {
4423
4438
  async fullResync(e) {
4424
4439
  if (!n)
4425
4440
  return { docs: [], newWatermark: Date.now() };
4426
- 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 = [];
4441
+ 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 = [];
4427
4442
  for (let l of e) {
4428
4443
  let d;
4429
4444
  try {
4430
4445
  d = await t(n, {
4431
4446
  method: "GET",
4432
- path: so(l),
4447
+ path: po(l),
4433
4448
  requireAuth: !0,
4434
4449
  retries: 2,
4435
4450
  headers: o,
@@ -4437,37 +4452,37 @@ function ln(n) {
4437
4452
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
4438
4453
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
4439
4454
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
4440
- query: { limit: an }
4455
+ query: { limit: ln }
4441
4456
  });
4442
4457
  } catch (f) {
4443
4458
  let h = f instanceof Error ? f.message : String(f);
4444
- throw new b(
4459
+ throw new _(
4445
4460
  "db_unavailable",
4446
4461
  `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${h}`
4447
4462
  );
4448
4463
  }
4449
4464
  let u = d, p = Array.isArray(u?.items) ? u.items : [];
4450
- p.length >= an && a.push(l);
4465
+ p.length >= ln && a.push(l);
4451
4466
  for (let f of p) {
4452
4467
  if (!f || typeof f != "object") continue;
4453
4468
  let h = f, y = typeof h.id == "string" ? h.id : null;
4454
4469
  if (!y) continue;
4455
- let { id: S, ...x } = h, T = i, P = x._updatedAt;
4456
- if (typeof P == "number")
4457
- T = P;
4458
- else if (P !== null && typeof P == "object" && typeof P._seconds == "number")
4459
- T = P._seconds * 1e3;
4460
- else if (typeof P == "string") {
4461
- let m = Date.parse(P);
4462
- Number.isNaN(m) || (T = m);
4470
+ let { id: T, ...x } = h, R = i, E = x._updatedAt;
4471
+ if (typeof E == "number")
4472
+ R = E;
4473
+ else if (E !== null && typeof E == "object" && typeof E._seconds == "number")
4474
+ R = E._seconds * 1e3;
4475
+ else if (typeof E == "string") {
4476
+ let g = Date.parse(E);
4477
+ Number.isNaN(g) || (R = g);
4463
4478
  }
4464
- let q = `rest_${y}_${T}`;
4479
+ let j = `rest_${y}_${R}`;
4465
4480
  s.push({
4466
4481
  collection: l,
4467
4482
  id: y,
4468
4483
  data: x,
4469
- serverVersion: q,
4470
- serverTimestamp: T,
4484
+ serverVersion: j,
4485
+ serverTimestamp: R,
4471
4486
  deleted: false
4472
4487
  });
4473
4488
  }
@@ -4476,10 +4491,10 @@ function ln(n) {
4476
4491
  }
4477
4492
  };
4478
4493
  }
4479
- function co(n, e, t) {
4480
- let r = ln(e), o = new be({
4494
+ function mo(n, e, t) {
4495
+ let r = un(e), o = new ve({
4481
4496
  gatewayUrl: n,
4482
- ticketProvider: lo(e, t),
4497
+ ticketProvider: ho(e, t),
4483
4498
  dbId: t.dbId,
4484
4499
  webSocketFactory: t._wsFactory
4485
4500
  });
@@ -4515,9 +4530,9 @@ function co(n, e, t) {
4515
4530
  }
4516
4531
  };
4517
4532
  }
4518
- function lo(n, e) {
4533
+ function ho(n, e) {
4519
4534
  return async () => {
4520
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y));
4535
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z));
4521
4536
  return await t(n, {
4522
4537
  method: "POST",
4523
4538
  path: "/api/sdk/v1/db/realtime/ticket",
@@ -4530,21 +4545,21 @@ function lo(n, e) {
4530
4545
  });
4531
4546
  };
4532
4547
  }
4533
- var cn = false;
4534
- function uo(n, e) {
4535
- cn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (cn = true, console.warn(
4548
+ var dn = false;
4549
+ function go(n, e) {
4550
+ dn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (dn = true, console.warn(
4536
4551
  '[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.'
4537
4552
  )));
4538
4553
  }
4539
- function dn(n, e = {}) {
4540
- uo(n, e);
4554
+ function pn(n, e = {}) {
4555
+ go(n, e);
4541
4556
  let t;
4542
4557
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
4543
4558
  '[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).'
4544
4559
  ), t = e.engine) : t = "rest";
4545
- let r = ao(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4560
+ 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;
4546
4561
  function l() {
4547
- return s || (s = Ht({
4562
+ return s || (s = Gt({
4548
4563
  dbName: i,
4549
4564
  transport: r,
4550
4565
  singleTab: e.singleTab ?? n.env !== "prod"
@@ -4552,15 +4567,15 @@ function dn(n, e = {}) {
4552
4567
  }
4553
4568
  return {
4554
4569
  collection(d) {
4555
- return a ? a.collection(d) : po(d, l);
4570
+ return a ? a.collection(d) : yo(d, l);
4556
4571
  },
4557
4572
  async sql(d, u) {
4558
- if (n.env === "dev")
4559
- throw new b(
4573
+ if (W(n.env))
4574
+ throw new _(
4560
4575
  "db_unavailable",
4561
4576
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4562
4577
  );
4563
- return (await Promise.resolve().then(() => (sn(), on))).createSqlClientFromConfig(n, d, u);
4578
+ return (await Promise.resolve().then(() => (cn(), an))).createSqlClientFromConfig(n, d, u);
4564
4579
  },
4565
4580
  get syncState() {
4566
4581
  return a?.syncState ?? {
@@ -4599,7 +4614,7 @@ function dn(n, e = {}) {
4599
4614
  }
4600
4615
  };
4601
4616
  }
4602
- function po(n, e) {
4617
+ function yo(n, e) {
4603
4618
  async function t() {
4604
4619
  return (await e()).collection(n);
4605
4620
  }
@@ -4678,9 +4693,9 @@ function po(n, e) {
4678
4693
  }
4679
4694
 
4680
4695
  // src/checkout.ts
4681
- I();
4682
- M();
4683
- function Ye(n, e) {
4696
+ C();
4697
+ F();
4698
+ function et(n, e) {
4684
4699
  let t = n?.accessToken || n?.idToken;
4685
4700
  if (!t || typeof t != "string")
4686
4701
  throw new c(
@@ -4689,7 +4704,7 @@ function Ye(n, e) {
4689
4704
  );
4690
4705
  return { requireAuth: false, headers: { authorization: `Bearer ${t}` } };
4691
4706
  }
4692
- function fo(n) {
4707
+ function _o(n) {
4693
4708
  if (!n || typeof n != "object")
4694
4709
  throw new c("invalid_response", "checkout.start response is not an object");
4695
4710
  let e = n;
@@ -4705,7 +4720,7 @@ function fo(n) {
4705
4720
  requiresKyc: e.requiresKyc === true
4706
4721
  };
4707
4722
  }
4708
- function mo(n) {
4723
+ function bo(n) {
4709
4724
  if (!n || typeof n != "object")
4710
4725
  throw new c("invalid_response", "checkout.get response is not an object");
4711
4726
  let e = n, t = e.intent;
@@ -4727,20 +4742,20 @@ function mo(n) {
4727
4742
  isStale: e.isStale === true
4728
4743
  };
4729
4744
  }
4730
- function ho() {
4745
+ function vo() {
4731
4746
  try {
4732
4747
  return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
4733
4748
  } catch {
4734
4749
  return false;
4735
4750
  }
4736
4751
  }
4737
- function go(n) {
4752
+ function wo(n) {
4738
4753
  try {
4739
4754
  globalThis.location.assign(n);
4740
4755
  } catch {
4741
4756
  }
4742
4757
  }
4743
- function yo(n) {
4758
+ function ko(n) {
4744
4759
  return {
4745
4760
  async start(e) {
4746
4761
  if (!e?.productId)
@@ -4755,7 +4770,7 @@ function yo(n) {
4755
4770
  callbackUrl: e.callbackUrl
4756
4771
  };
4757
4772
  e.tenantType && (t.targetTenantType = e.tenantType), e.tenantId && (t.targetTenantId = e.tenantId);
4758
- let { requireAuth: r, headers: o } = Ye(
4773
+ let { requireAuth: r, headers: o } = et(
4759
4774
  { accessToken: e.accessToken, idToken: e.idToken },
4760
4775
  "start"
4761
4776
  ), i = await v(n, {
@@ -4765,13 +4780,13 @@ function yo(n) {
4765
4780
  requireAuth: r,
4766
4781
  headers: o,
4767
4782
  idempotencyKey: true
4768
- }), s = fo(i);
4769
- return e.autoRedirect !== false && ho() && go(s.redirectUrl), s;
4783
+ }), s = _o(i);
4784
+ return e.autoRedirect !== false && vo() && wo(s.redirectUrl), s;
4770
4785
  },
4771
4786
  async get(e, t) {
4772
4787
  if (!e || typeof e != "string")
4773
4788
  throw new c("validation_failed", "checkout.get: intentId is required");
4774
- let { requireAuth: r, headers: o } = Ye(
4789
+ let { requireAuth: r, headers: o } = et(
4775
4790
  { accessToken: t?.accessToken, idToken: t?.idToken },
4776
4791
  "get"
4777
4792
  ), i = await v(n, {
@@ -4780,12 +4795,12 @@ function yo(n) {
4780
4795
  requireAuth: r,
4781
4796
  headers: o
4782
4797
  });
4783
- return mo(i);
4798
+ return bo(i);
4784
4799
  },
4785
4800
  async cancel(e, t) {
4786
4801
  if (!e || typeof e != "string")
4787
4802
  throw new c("validation_failed", "checkout.cancel: intentId is required");
4788
- let { requireAuth: r, headers: o } = Ye(
4803
+ let { requireAuth: r, headers: o } = et(
4789
4804
  { accessToken: t?.accessToken, idToken: t?.idToken },
4790
4805
  "cancel"
4791
4806
  );
@@ -4801,7 +4816,7 @@ function yo(n) {
4801
4816
  }
4802
4817
  };
4803
4818
  }
4804
- var Ze = class {
4819
+ var tt = class {
4805
4820
  intents = /* @__PURE__ */ new Map();
4806
4821
  async start(e) {
4807
4822
  if (!e?.productId)
@@ -4844,14 +4859,14 @@ var Ze = class {
4844
4859
  return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
4845
4860
  }
4846
4861
  };
4847
- function un(n) {
4848
- return n.env === "dev" ? new Ze() : yo(n);
4862
+ function fn(n) {
4863
+ return W(n.env) ? new tt() : ko(n);
4849
4864
  }
4850
4865
 
4851
4866
  // src/webhooks.ts
4852
- I();
4853
- M();
4854
- var fn = [
4867
+ C();
4868
+ F();
4869
+ var hn = [
4855
4870
  "subscription.activated",
4856
4871
  "subscription.cancelled",
4857
4872
  "subscription.payment_failed",
@@ -4861,7 +4876,7 @@ var fn = [
4861
4876
  "account.reactivated",
4862
4877
  "support.ticket_replied"
4863
4878
  ];
4864
- function pn(n) {
4879
+ function mn(n) {
4865
4880
  if (!n || typeof n != "object")
4866
4881
  throw new c("invalid_response", "Webhook response is not an object");
4867
4882
  let e = n;
@@ -4871,7 +4886,7 @@ function pn(n) {
4871
4886
  id: e.id,
4872
4887
  url: typeof e.url == "string" ? e.url : "",
4873
4888
  events: Array.isArray(e.events) ? e.events.filter(
4874
- (t) => fn.includes(t)
4889
+ (t) => hn.includes(t)
4875
4890
  ) : [],
4876
4891
  hasSecret: e.hasSecret === true,
4877
4892
  status: e.status === "active" || e.status === "degraded" || e.status === "disabled" ? e.status : "active",
@@ -4880,7 +4895,7 @@ function pn(n) {
4880
4895
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString()
4881
4896
  };
4882
4897
  }
4883
- function mn(n) {
4898
+ function gn(n) {
4884
4899
  if (!n.url || typeof n.url != "string")
4885
4900
  throw new c("validation_failed", "url \xE9 obrigat\xF3ria");
4886
4901
  try {
@@ -4893,12 +4908,12 @@ function mn(n) {
4893
4908
  if (!Array.isArray(n.events) || n.events.length === 0)
4894
4909
  throw new c("validation_failed", "events deve ter pelo menos 1 evento");
4895
4910
  for (let e of n.events)
4896
- if (!fn.includes(e))
4911
+ if (!hn.includes(e))
4897
4912
  throw new c("validation_failed", `evento desconhecido: ${e}`);
4898
4913
  if (n.secret !== void 0 && n.secret.length < 16)
4899
4914
  throw new c("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4900
4915
  }
4901
- function ke(n, ...e) {
4916
+ function Se(n, ...e) {
4902
4917
  for (let t of e)
4903
4918
  if (typeof t == "string" && t.length > 0)
4904
4919
  return N("productId", t), t;
@@ -4909,11 +4924,11 @@ function ke(n, ...e) {
4909
4924
  "productId required (pass to options/input or set on createNeetruClient)"
4910
4925
  );
4911
4926
  }
4912
- function hn(n) {
4927
+ function yn(n) {
4913
4928
  return {
4914
4929
  async register(e) {
4915
- mn(e);
4916
- let t = ke(n, e.productId), r = await v(n, {
4930
+ gn(e);
4931
+ let t = Se(n, e.productId), r = await v(n, {
4917
4932
  method: "POST",
4918
4933
  path: "/api/sdk/v1/webhooks",
4919
4934
  body: {
@@ -4929,20 +4944,20 @@ function hn(n) {
4929
4944
  // dedup TTL 24h (mesmo padrão de usage.report/support.createTicket).
4930
4945
  idempotencyKey: true
4931
4946
  });
4932
- return pn(r);
4947
+ return mn(r);
4933
4948
  },
4934
4949
  async list(e) {
4935
- let t = ke(n, e?.productId), r = await v(n, {
4950
+ let t = Se(n, e?.productId), r = await v(n, {
4936
4951
  method: "GET",
4937
4952
  path: "/api/sdk/v1/webhooks",
4938
4953
  query: { productId: t },
4939
4954
  requireAuth: true
4940
4955
  });
4941
- return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(pn);
4956
+ return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(mn);
4942
4957
  },
4943
4958
  async unregister(e, t) {
4944
4959
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4945
- let r = ke(n, t?.productId);
4960
+ let r = Se(n, t?.productId);
4946
4961
  return await v(n, {
4947
4962
  method: "DELETE",
4948
4963
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}`,
@@ -4952,7 +4967,7 @@ function hn(n) {
4952
4967
  },
4953
4968
  async test(e, t) {
4954
4969
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4955
- let r = ke(n, t?.productId), o = await v(n, {
4970
+ let r = Se(n, t?.productId), o = await v(n, {
4956
4971
  method: "POST",
4957
4972
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}/test`,
4958
4973
  query: { productId: r },
@@ -4971,11 +4986,11 @@ function hn(n) {
4971
4986
  }
4972
4987
  };
4973
4988
  }
4974
- var Se = class {
4989
+ var Te = class {
4975
4990
  endpoints = /* @__PURE__ */ new Map();
4976
4991
  nextId = 1;
4977
4992
  async register(e) {
4978
- mn(e);
4993
+ gn(e);
4979
4994
  let t = `mock_wh_${this.nextId++}`, r = {
4980
4995
  id: t,
4981
4996
  url: e.url,
@@ -5002,21 +5017,21 @@ var Se = class {
5002
5017
  };
5003
5018
 
5004
5019
  // src/notifications.ts
5005
- I();
5006
- M();
5007
- var et = [
5020
+ C();
5021
+ F();
5022
+ var nt = [
5008
5023
  "info",
5009
5024
  "success",
5010
5025
  "warning",
5011
5026
  "error"
5012
5027
  ];
5013
- function gn(n) {
5028
+ function _n(n) {
5014
5029
  if (!n || typeof n != "object")
5015
5030
  throw new c("invalid_response", "Notification response is not an object");
5016
5031
  let e = n;
5017
5032
  if (typeof e.id != "string")
5018
5033
  throw new c("invalid_response", "Notification missing id");
5019
- let t = et.includes(e.severity) ? e.severity : "info";
5034
+ let t = nt.includes(e.severity) ? e.severity : "info";
5020
5035
  return {
5021
5036
  id: e.id,
5022
5037
  userId: typeof e.userId == "string" ? e.userId : "",
@@ -5031,21 +5046,21 @@ function gn(n) {
5031
5046
  dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
5032
5047
  };
5033
5048
  }
5034
- function yn(n) {
5049
+ function bn(n) {
5035
5050
  if (!n.userId) throw new c("validation_failed", "userId obrigat\xF3rio");
5036
5051
  if (!n.kind) throw new c("validation_failed", "kind obrigat\xF3rio");
5037
5052
  if (!n.title) throw new c("validation_failed", "title obrigat\xF3rio");
5038
- if (n.severity && !et.includes(n.severity))
5053
+ if (n.severity && !nt.includes(n.severity))
5039
5054
  throw new c(
5040
5055
  "validation_failed",
5041
- `severity inv\xE1lida: ${n.severity} (use ${et.join("|")})`
5056
+ `severity inv\xE1lida: ${n.severity} (use ${nt.join("|")})`
5042
5057
  );
5043
5058
  if (n.title.length > 200)
5044
5059
  throw new c("validation_failed", "title m\xE1x 200 chars");
5045
5060
  if (n.body && n.body.length > 2e3)
5046
5061
  throw new c("validation_failed", "body m\xE1x 2000 chars");
5047
5062
  }
5048
- function Te(n, ...e) {
5063
+ function Re(n, ...e) {
5049
5064
  for (let t of e)
5050
5065
  if (typeof t == "string" && t.length > 0)
5051
5066
  return N("productId", t), t;
@@ -5056,12 +5071,12 @@ function Te(n, ...e) {
5056
5071
  "productId required (pass to options/input or set on createNeetruClient)"
5057
5072
  );
5058
5073
  }
5059
- function _n(n) {
5074
+ function vn(n) {
5060
5075
  return {
5061
5076
  async send(e) {
5062
- yn(e);
5077
+ bn(e);
5063
5078
  let r = {
5064
- productId: Te(n, e.productId),
5079
+ productId: Re(n, e.productId),
5065
5080
  userId: e.userId,
5066
5081
  kind: e.kind,
5067
5082
  title: e.title,
@@ -5075,12 +5090,12 @@ function _n(n) {
5075
5090
  requireAuth: true,
5076
5091
  idempotencyKey: true
5077
5092
  });
5078
- return gn(o);
5093
+ return _n(o);
5079
5094
  },
5080
5095
  async list(e, t) {
5081
5096
  if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5082
5097
  let o = {
5083
- productId: Te(n, t?.productId)
5098
+ productId: Re(n, t?.productId)
5084
5099
  };
5085
5100
  t?.includeDismissed && (o.includeDismissed = true), t?.onlyUnread && (o.onlyUnread = true), t?.limit && (o.limit = Math.min(Math.max(1, t.limit), 200));
5086
5101
  let i = await v(n, {
@@ -5089,11 +5104,11 @@ function _n(n) {
5089
5104
  query: o,
5090
5105
  requireAuth: true
5091
5106
  });
5092
- return (Array.isArray(i?.notifications) ? i.notifications : []).map(gn);
5107
+ return (Array.isArray(i?.notifications) ? i.notifications : []).map(_n);
5093
5108
  },
5094
5109
  async markRead(e, t) {
5095
5110
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5096
- let r = Te(n, t?.productId);
5111
+ let r = Re(n, t?.productId);
5097
5112
  return await v(n, {
5098
5113
  method: "POST",
5099
5114
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/read`,
@@ -5103,7 +5118,7 @@ function _n(n) {
5103
5118
  },
5104
5119
  async dismiss(e, t) {
5105
5120
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5106
- let r = Te(n, t?.productId);
5121
+ let r = Re(n, t?.productId);
5107
5122
  return await v(n, {
5108
5123
  method: "POST",
5109
5124
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/dismiss`,
@@ -5113,11 +5128,11 @@ function _n(n) {
5113
5128
  }
5114
5129
  };
5115
5130
  }
5116
- var Re = class {
5131
+ var Ie = class {
5117
5132
  notifications = /* @__PURE__ */ new Map();
5118
5133
  nextId = 1;
5119
5134
  async send(e) {
5120
- if (yn(e), e.fingerprint) {
5135
+ if (bn(e), e.fingerprint) {
5121
5136
  let o = Date.now() - 864e5;
5122
5137
  for (let i of this.notifications.values())
5123
5138
  if ((i.metadata ?? {}).fingerprint === e.fingerprint && i.userId === e.userId && new Date(i.createdAt).getTime() > o)
@@ -5154,44 +5169,44 @@ var Re = class {
5154
5169
  };
5155
5170
 
5156
5171
  // src/ai.ts
5157
- I();
5158
- M();
5159
- Me();
5160
- var _o = "/api/sdk/v1/ai/chat", bn = 12e4, Ie = 32768, vn = 32, wn = 4194304, kn = 2048, bo = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, vo = /^https:\/\/[^\s]+$/, wo = /* @__PURE__ */ new Set(["low", "high", "auto"]), ko = /* @__PURE__ */ new Set(["system", "user", "assistant"]), Sn = 100, Tn = 128, Rn = 32768, In = 0, Cn = 2, An = 200, En = 20, Pn = 12 * 1024 * 1024, Dn = 5e4, Nn = 16, xn = 500, So = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), To = /^[a-zA-Z0-9_-]+$/;
5172
+ C();
5173
+ F();
5174
+ qe();
5175
+ 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_-]+$/;
5161
5176
  function k(n) {
5162
5177
  throw new c("validation_failed", n);
5163
5178
  }
5164
- function Ro(n) {
5179
+ function Po(n) {
5165
5180
  if (n.length === 0 || n.length % 4 !== 0) return false;
5166
5181
  let e = n.endsWith("==") ? 2 : n.endsWith("=") ? 1 : 0;
5167
5182
  return !(e > 0 ? n.slice(0, n.length - e) : n).includes("=");
5168
5183
  }
5169
- function Io(n) {
5184
+ function Do(n) {
5170
5185
  let e = n.indexOf(",");
5171
5186
  if (e === -1) return 0;
5172
5187
  let t = n.slice(e + 1), r = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
5173
5188
  return Math.max(0, Math.floor(t.length * 3 / 4) - r);
5174
5189
  }
5175
- function Co(n) {
5190
+ function No(n) {
5176
5191
  let e = 0, t = 0, r = 0;
5177
5192
  for (let o of n) {
5178
5193
  let i = o?.content;
5179
5194
  if (Array.isArray(i))
5180
5195
  for (let s of i) {
5181
- if (e++, e > An)
5182
- return `ai: total content parts exceeds ${An} per request`;
5196
+ if (e++, e > Pn)
5197
+ return `ai: total content parts exceeds ${Pn} per request`;
5183
5198
  if (s && typeof s == "object" && s.type === "image_url") {
5184
- if (t++, t > En)
5185
- return `ai: total images exceeds ${En} per request`;
5199
+ if (t++, t > Dn)
5200
+ return `ai: total images exceeds ${Dn} per request`;
5186
5201
  let a = s.image_url?.url;
5187
- if (typeof a == "string" && a.startsWith("data:") && (r += Io(a), r > Pn))
5188
- return `ai: aggregate image bytes exceeds ${Pn} per request`;
5202
+ if (typeof a == "string" && a.startsWith("data:") && (r += Do(a), r > Nn))
5203
+ return `ai: aggregate image bytes exceeds ${Nn} per request`;
5189
5204
  }
5190
5205
  }
5191
5206
  }
5192
5207
  return null;
5193
5208
  }
5194
- function Ao(n) {
5209
+ function xo(n) {
5195
5210
  if (n === void 0) return null;
5196
5211
  if (n === null || typeof n != "object")
5197
5212
  return "ai: responseFormat json_schema.schema must be an object";
@@ -5202,11 +5217,11 @@ function Ao(n) {
5202
5217
  return "ai: responseFormat json_schema.schema is not serializable";
5203
5218
  }
5204
5219
  if (e === void 0) return "ai: responseFormat json_schema.schema is invalid";
5205
- if (e.length > Dn)
5206
- return `ai: responseFormat json_schema.schema exceeds ${Dn} serialized chars`;
5220
+ if (e.length > xn)
5221
+ return `ai: responseFormat json_schema.schema exceeds ${xn} serialized chars`;
5207
5222
  let t = 0, r = (o, i) => {
5208
- if (i > Nn)
5209
- return `ai: responseFormat json_schema.schema exceeds max depth ${Nn}`;
5223
+ if (i > On)
5224
+ return `ai: responseFormat json_schema.schema exceeds max depth ${On}`;
5210
5225
  if (Array.isArray(o)) {
5211
5226
  for (let s of o) {
5212
5227
  let a = r(s, i + 1);
@@ -5216,10 +5231,10 @@ function Ao(n) {
5216
5231
  }
5217
5232
  if (o && typeof o == "object")
5218
5233
  for (let s of Object.getOwnPropertyNames(o)) {
5219
- if (So.has(s))
5234
+ if (Ao.has(s))
5220
5235
  return `ai: responseFormat json_schema.schema has forbidden key: ${s}`;
5221
- if (t++, t > xn)
5222
- return `ai: responseFormat json_schema.schema exceeds ${xn} keys`;
5236
+ if (t++, t > Ln)
5237
+ return `ai: responseFormat json_schema.schema exceeds ${Ln} keys`;
5223
5238
  let a = r(o[s], i + 1);
5224
5239
  if (a) return a;
5225
5240
  }
@@ -5227,44 +5242,44 @@ function Ao(n) {
5227
5242
  };
5228
5243
  return r(n, 0);
5229
5244
  }
5230
- function Eo(n) {
5245
+ function Oo(n) {
5231
5246
  (typeof n != "string" || n.length === 0) && k("ai: image_url.url must be a non-empty string");
5232
5247
  let e = n;
5233
5248
  if (e.startsWith("data:")) {
5234
- e.length > wn && k(`ai: image_url.url (data:) exceeds ${wn} chars`), bo.test(e) || k("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5249
+ 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,<...>");
5235
5250
  let t = e.slice(e.indexOf(",") + 1);
5236
- Ro(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5251
+ Po(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5237
5252
  return;
5238
5253
  }
5239
5254
  if (e.startsWith("https://")) {
5240
- e.length > kn && k(`ai: image_url.url (https:) exceeds ${kn} chars`), vo.test(e) || k("ai: image_url.url https: is invalid");
5255
+ e.length > Tn && k(`ai: image_url.url (https:) exceeds ${Tn} chars`), Ro.test(e) || k("ai: image_url.url https: is invalid");
5241
5256
  return;
5242
5257
  }
5243
5258
  k("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5244
5259
  }
5245
- function Po(n, e) {
5260
+ function Lo(n, e) {
5246
5261
  if (typeof n == "string") {
5247
- n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ie && k(`ai: message content exceeds ${Ie} chars`);
5262
+ n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ce && k(`ai: message content exceeds ${Ce} chars`);
5248
5263
  return;
5249
5264
  }
5250
- (!Array.isArray(n) || n.length === 0) && k("ai: message content must be a non-empty string or array of parts"), n.length > vn && k(`ai: message content has more than ${vn} parts`);
5265
+ (!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`);
5251
5266
  for (let t of n) {
5252
5267
  (!t || typeof t != "object") && k("ai: each content part must be an object");
5253
5268
  let r = t.type;
5254
5269
  if (r === "text") {
5255
5270
  let o = t.text;
5256
- (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`);
5271
+ (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`);
5257
5272
  } else if (r === "image_url") {
5258
5273
  e !== "user" && k(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5259
5274
  let o = t.image_url;
5260
- (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Eo(o.url);
5275
+ (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Oo(o.url);
5261
5276
  let i = o.detail;
5262
- i !== void 0 && (typeof i != "string" || !wo.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5277
+ i !== void 0 && (typeof i != "string" || !Io.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5263
5278
  } else
5264
5279
  k("ai: content part type must be 'text' or 'image_url'");
5265
5280
  }
5266
5281
  }
5267
- function Do(n) {
5282
+ function Uo(n) {
5268
5283
  (!n || typeof n != "object") && k("ai: responseFormat must be an object");
5269
5284
  let e = n.type;
5270
5285
  if (!(e === "text" || e === "json_object")) {
@@ -5272,8 +5287,8 @@ function Do(n) {
5272
5287
  let t = n.json_schema;
5273
5288
  (!t || typeof t != "object") && k("ai: responseFormat json_schema requires { json_schema: { name } }");
5274
5289
  let r = t, o = r.name;
5275
- if ((typeof o != "string" || o.length === 0) && k("ai: responseFormat json_schema.name is required"), o.length > 64 && k("ai: responseFormat json_schema.name exceeds 64 chars"), To.test(o) || k("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && k("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && k("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && k("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5276
- let i = Ao(r.schema);
5290
+ 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) {
5291
+ let i = xo(r.schema);
5277
5292
  i && k(i);
5278
5293
  }
5279
5294
  return;
@@ -5281,26 +5296,26 @@ function Do(n) {
5281
5296
  k("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5282
5297
  }
5283
5298
  }
5284
- function On(n, e, t) {
5299
+ function Un(n, e, t) {
5285
5300
  if (!e || typeof e != "object")
5286
5301
  throw new c("validation_failed", "ai: options object is required");
5287
5302
  if (typeof e.model != "string" || e.model.length === 0)
5288
5303
  throw new c("validation_failed", "ai: model is required");
5289
- if (e.model.length > Tn)
5290
- throw new c("validation_failed", `ai: model exceeds ${Tn} chars`);
5304
+ if (e.model.length > In)
5305
+ throw new c("validation_failed", `ai: model exceeds ${In} chars`);
5291
5306
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5292
5307
  throw new c("validation_failed", "ai: messages must be a non-empty array");
5293
- if (e.messages.length > Sn)
5294
- throw new c("validation_failed", `ai: messages exceeds ${Sn} per request`);
5308
+ if (e.messages.length > Rn)
5309
+ throw new c("validation_failed", `ai: messages exceeds ${Rn} per request`);
5295
5310
  for (let a of e.messages) {
5296
- if (!a || typeof a != "object" || typeof a.role != "string" || !ko.has(a.role))
5311
+ if (!a || typeof a != "object" || typeof a.role != "string" || !Co.has(a.role))
5297
5312
  throw new c(
5298
5313
  "validation_failed",
5299
5314
  "ai: each message role must be 'system' | 'user' | 'assistant'"
5300
5315
  );
5301
- Po(a.content, a.role);
5316
+ Lo(a.content, a.role);
5302
5317
  }
5303
- let r = Co(e.messages);
5318
+ let r = No(e.messages);
5304
5319
  if (r) throw new c("validation_failed", r);
5305
5320
  let o = e.productId ?? n.productId, i = e.tenantId ?? n.tenantId;
5306
5321
  if (!o)
@@ -5322,24 +5337,24 @@ function On(n, e, t) {
5322
5337
  stream: t
5323
5338
  };
5324
5339
  if (e.maxTokens !== void 0) {
5325
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Rn)
5340
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Cn)
5326
5341
  throw new c(
5327
5342
  "validation_failed",
5328
- `ai: maxTokens must be a positive integer <= ${Rn}`
5343
+ `ai: maxTokens must be a positive integer <= ${Cn}`
5329
5344
  );
5330
5345
  s.maxTokens = e.maxTokens;
5331
5346
  }
5332
5347
  if (e.temperature !== void 0) {
5333
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < In || e.temperature > Cn)
5348
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < An || e.temperature > En)
5334
5349
  throw new c(
5335
5350
  "validation_failed",
5336
- `ai: temperature must be a finite number between ${In} and ${Cn}`
5351
+ `ai: temperature must be a finite number between ${An} and ${En}`
5337
5352
  );
5338
5353
  s.temperature = e.temperature;
5339
5354
  }
5340
- return e.responseFormat !== void 0 && (Do(e.responseFormat), s.responseFormat = e.responseFormat), s;
5355
+ return e.responseFormat !== void 0 && (Uo(e.responseFormat), s.responseFormat = e.responseFormat), s;
5341
5356
  }
5342
- async function qn(n) {
5357
+ async function jn(n) {
5343
5358
  try {
5344
5359
  let e = await n.text();
5345
5360
  return e ? JSON.parse(e) : void 0;
@@ -5347,32 +5362,32 @@ async function qn(n) {
5347
5362
  return;
5348
5363
  }
5349
5364
  }
5350
- function No(n, e) {
5365
+ function Mo(n, e) {
5351
5366
  let t = n.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
5352
5367
  return `${t}${r}`;
5353
5368
  }
5354
- async function Ln(n, e, t, r) {
5369
+ async function Mn(n, e, t, r) {
5355
5370
  if (!n.apiKey)
5356
5371
  throw new c(
5357
5372
  "missing_api_key",
5358
5373
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
5359
5374
  );
5360
- let o = No(n.baseUrl, _o), { headers: i, correlationId: s } = ae({
5375
+ let o = Mo(n.baseUrl, So), { headers: i, correlationId: s } = ce({
5361
5376
  "content-type": "application/json",
5362
5377
  accept: r ? "text/event-stream" : "application/json",
5363
5378
  authorization: `Bearer ${n.apiKey}`
5364
5379
  }), a = { method: "POST", headers: i, body: JSON.stringify(e) };
5365
- r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(bn);
5380
+ r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(wn);
5366
5381
  let l;
5367
5382
  try {
5368
5383
  l = await n.fetch(o, a);
5369
5384
  } catch (p) {
5370
- let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${bn / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5385
+ 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"}`;
5371
5386
  throw new c("network_error", f, void 0, void 0, void 0, s);
5372
5387
  }
5373
5388
  let d = l.headers.get("x-request-id") ?? l.headers.get("x-correlation-id") ?? void 0;
5374
5389
  if (!l.ok) {
5375
- let p = await qn(l), f = le(l.status), h = `HTTP ${l.status}`;
5390
+ let p = await jn(l), f = de(l.status), h = `HTTP ${l.status}`;
5376
5391
  if (p && typeof p == "object" && "error" in p) {
5377
5392
  let y = p.error;
5378
5393
  typeof y == "string" ? h = y : y && typeof y == "object" && (typeof y.code == "string" && (f = y.code), typeof y.message == "string" && (h = y.message));
@@ -5380,15 +5395,15 @@ async function Ln(n, e, t, r) {
5380
5395
  throw new c(f, h, l.status, d, void 0, s);
5381
5396
  }
5382
5397
  let u = l.headers.get("x-neetru-version");
5383
- return u && ce(u), l;
5398
+ return u && le(u), l;
5384
5399
  }
5385
- function Un(n) {
5400
+ function qn(n) {
5386
5401
  return {
5387
5402
  provider: n.headers.get("x-neetru-provider") ?? "",
5388
5403
  usageWarning: n.headers.get("x-neetru-ai-usage-warning") === "1"
5389
5404
  };
5390
5405
  }
5391
- function Mn(n) {
5406
+ function Fn(n) {
5392
5407
  let e = [];
5393
5408
  for (let r of n.split(`
5394
5409
  `)) {
@@ -5409,10 +5424,10 @@ function Mn(n) {
5409
5424
  return null;
5410
5425
  }
5411
5426
  }
5412
- function Fn(n) {
5427
+ function $n(n) {
5413
5428
  return {
5414
5429
  async chat(e) {
5415
- let t = On(n, e, false), r = await Ln(n, t, e.signal, false), { provider: o, usageWarning: i } = Un(r), s = await qn(r);
5430
+ let t = Un(n, e, false), r = await Mn(n, t, e.signal, false), { provider: o, usageWarning: i } = qn(r), s = await jn(r);
5416
5431
  if (!s || s.ok !== true || !Array.isArray(s.choices))
5417
5432
  throw new c("invalid_response", "ai.chat response missing ok/choices");
5418
5433
  return {
@@ -5424,7 +5439,7 @@ function Fn(n) {
5424
5439
  };
5425
5440
  },
5426
5441
  stream(e) {
5427
- let t = On(n, e, true), r = Ln(n, t, e.signal, true), o = r.then(Un);
5442
+ let t = Un(n, e, true), r = Mn(n, t, e.signal, true), o = r.then(qn);
5428
5443
  o.catch(() => {
5429
5444
  });
5430
5445
  async function* i() {
@@ -5441,16 +5456,16 @@ function Fn(n) {
5441
5456
  for (; (y = u.indexOf(`
5442
5457
 
5443
5458
  `)) !== -1; ) {
5444
- let S = u.slice(0, y);
5459
+ let T = u.slice(0, y);
5445
5460
  u = u.slice(y + 2);
5446
- let x = Mn(S);
5461
+ let x = Fn(T);
5447
5462
  if (x && "done" in x) return;
5448
5463
  x && "content" in x && (yield x.content);
5449
5464
  }
5450
5465
  }
5451
5466
  let p = u.trim();
5452
5467
  if (p) {
5453
- let f = Mn(p);
5468
+ let f = Fn(p);
5454
5469
  f && "content" in f && (yield f.content);
5455
5470
  }
5456
5471
  } finally {
@@ -5473,20 +5488,8 @@ function Fn(n) {
5473
5488
  }
5474
5489
 
5475
5490
  // src/mocks.ts
5476
- I();
5477
-
5478
- // src/runtime-env.ts
5479
- function Ce() {
5480
- try {
5481
- if (typeof process < "u" && process.env)
5482
- return process.env.NODE_ENV === "production";
5483
- } catch {
5484
- }
5485
- return false;
5486
- }
5487
-
5488
- // src/mocks.ts
5489
- var tt = Object.freeze({
5491
+ C();
5492
+ var rt = Object.freeze({
5490
5493
  uid: "dev-fixture-uid-0001",
5491
5494
  email: "dev@neetru.local",
5492
5495
  emailVerified: true,
@@ -5498,7 +5501,7 @@ var tt = Object.freeze({
5498
5501
  _listeners;
5499
5502
  _allowUnsignedDecode;
5500
5503
  constructor(e = null, t) {
5501
- if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Ce())
5504
+ if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && $e())
5502
5505
  throw new c(
5503
5506
  "invalid_config",
5504
5507
  "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."
@@ -5508,10 +5511,10 @@ var tt = Object.freeze({
5508
5511
  );
5509
5512
  }
5510
5513
  async signIn(e) {
5511
- return this._user || (this._user = { ...tt }), this._notify(), this._user;
5514
+ return this._user || (this._user = { ...rt }), this._notify(), this._user;
5512
5515
  }
5513
5516
  async signOut() {
5514
- this._user = null, this._notify();
5517
+ return this._user = null, this._notify(), { localSessionCleared: true, remoteRevocation: "skipped" };
5515
5518
  }
5516
5519
  getUser() {
5517
5520
  return this._user;
@@ -5838,9 +5841,30 @@ var Ne = class {
5838
5841
  }
5839
5842
  };
5840
5843
 
5844
+ // src/timeout.ts
5845
+ function Wn(n) {
5846
+ let e = globalThis.AbortSignal;
5847
+ if (typeof e?.timeout == "function")
5848
+ return { signal: e.timeout(n), clear: () => {
5849
+ } };
5850
+ if (typeof globalThis.AbortController != "function")
5851
+ return { signal: void 0, clear: () => {
5852
+ } };
5853
+ let t = new AbortController(), r = setTimeout(() => t.abort(), n);
5854
+ return r.unref?.(), { signal: t.signal, clear: () => clearTimeout(r) };
5855
+ }
5856
+ function Bn(n, e, t) {
5857
+ let r, o = new Promise((i) => {
5858
+ r = setTimeout(() => i(t()), e), r.unref?.();
5859
+ });
5860
+ return Promise.race([n, o]).finally(() => {
5861
+ r !== void 0 && clearTimeout(r);
5862
+ });
5863
+ }
5864
+
5841
5865
  // src/auth-pkce-shared.ts
5842
- I();
5843
- function jn() {
5866
+ C();
5867
+ function Vn() {
5844
5868
  let n = globalThis.crypto;
5845
5869
  if (!n || typeof n.getRandomValues != "function" || !n.subtle)
5846
5870
  throw new c(
@@ -5849,36 +5873,36 @@ function jn() {
5849
5873
  );
5850
5874
  return n;
5851
5875
  }
5852
- function $n(n) {
5876
+ function Kn(n) {
5853
5877
  let e = "";
5854
5878
  for (let r of n) e += String.fromCharCode(r);
5855
5879
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
5856
5880
  }
5857
5881
  function xe(n, e) {
5858
5882
  let t = new Uint8Array(e);
5859
- return n.getRandomValues(t), $n(t);
5883
+ return n.getRandomValues(t), Kn(t);
5860
5884
  }
5861
- async function Wn(n, e) {
5885
+ async function zn(n, e) {
5862
5886
  let t = new TextEncoder().encode(e), r = await n.subtle.digest("SHA-256", t);
5863
- return $n(new Uint8Array(r));
5887
+ return Kn(new Uint8Array(r));
5864
5888
  }
5865
- function oe(n) {
5889
+ function ie(n) {
5866
5890
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.replace(/^https?:\/\/api\./, "https://auth.");
5867
5891
  }
5868
- function Bn(n) {
5892
+ function Hn(n) {
5869
5893
  let e = n.oidcClientId;
5870
- if (!e && n.apiKey && (e = ct(n.apiKey).keyId), !e)
5894
+ if (!e && n.apiKey && (e = dt(n.apiKey).keyId), !e)
5871
5895
  throw new c(
5872
5896
  "invalid_config",
5873
5897
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
5874
5898
  );
5875
5899
  return e;
5876
5900
  }
5877
- function Vn(n) {
5901
+ function Qn(n) {
5878
5902
  let e = new URL("/api/v1/oauth/authorize", n.idpOrigin);
5879
5903
  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;
5880
5904
  }
5881
- function nt(n) {
5905
+ function ot(n) {
5882
5906
  let e = n.split(".");
5883
5907
  if (e.length !== 3) return null;
5884
5908
  try {
@@ -5888,8 +5912,8 @@ function nt(n) {
5888
5912
  return null;
5889
5913
  }
5890
5914
  }
5891
- function ie(n) {
5892
- let e = nt(n);
5915
+ function se(n) {
5916
+ let e = ot(n);
5893
5917
  return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
5894
5918
  uid: e.sub,
5895
5919
  email: typeof e.email == "string" ? e.email : "",
@@ -5902,9 +5926,9 @@ function ie(n) {
5902
5926
  ...e
5903
5927
  };
5904
5928
  }
5905
- var xo = "/api/v1/oauth/revoke";
5906
- async function Kn(n, e, t, r) {
5907
- let o = `${e}${xo}`, i = true;
5929
+ var qo = "/api/v1/oauth/revoke";
5930
+ async function Gn(n, e, t, r) {
5931
+ let o = `${e}${qo}`, i = true;
5908
5932
  for (let s of r) {
5909
5933
  if (!s.token) continue;
5910
5934
  let a = new URLSearchParams({
@@ -5928,17 +5952,17 @@ async function Kn(n, e, t, r) {
5928
5952
  }
5929
5953
 
5930
5954
  // src/auth.ts
5931
- qe();
5955
+ Fe();
5932
5956
 
5933
5957
  // src/end-user-token.ts
5934
- var Oo = /* @__PURE__ */ new WeakMap();
5935
- function zn(n, e) {
5936
- Oo.set(n, e);
5958
+ var Fo = /* @__PURE__ */ new WeakMap();
5959
+ function Jn(n, e) {
5960
+ Fo.set(n, e);
5937
5961
  }
5938
5962
 
5939
5963
  // src/unsupported-db.ts
5940
- I();
5941
- var Lo = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O app n\xE3o acessa o banco do produto diretamente: chame a API do SEU produto (ex.: https://<produto>.neetru.com/api/v1) com o access_token do usu\xE1rio (Authorization: Bearer) \u2014 o backend do produto usa client.db no servidor. (At\xE9 a 3.7.x o db ca\xEDa em mem\xF3ria em sil\xEAncio e os dados sumiam ao fechar o app.)", Uo = /* @__PURE__ */ new Set([
5964
+ C();
5965
+ 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([
5942
5966
  "then",
5943
5967
  "toJSON",
5944
5968
  "valueOf",
@@ -5947,13 +5971,13 @@ var Lo = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O
5947
5971
  "asymmetricMatch",
5948
5972
  "nodeType"
5949
5973
  ]);
5950
- function Hn() {
5974
+ function Xn() {
5951
5975
  let n = () => {
5952
- throw new c("runtime_unsupported", Lo, void 0, void 0, "react-native");
5976
+ throw new c("runtime_unsupported", jo, void 0, void 0, "react-native");
5953
5977
  }, e = {};
5954
5978
  return new Proxy(e, {
5955
5979
  get(t, r) {
5956
- if (!(typeof r == "symbol" || Uo.has(r)))
5980
+ if (!(typeof r == "symbol" || $o.has(r)))
5957
5981
  return r === "toString" ? () => "[NeetruDb indispon\xEDvel em React Native]" : n;
5958
5982
  },
5959
5983
  set() {
@@ -5963,7 +5987,7 @@ function Hn() {
5963
5987
  }
5964
5988
 
5965
5989
  // src/auth.ts
5966
- function qo() {
5990
+ function Bo() {
5967
5991
  try {
5968
5992
  let e = globalThis.process?.env?.NEETRU_API_KEY;
5969
5993
  return typeof e == "string" && e.length > 0 ? e : void 0;
@@ -5971,7 +5995,7 @@ function qo() {
5971
5995
  return;
5972
5996
  }
5973
5997
  }
5974
- function Fo(n) {
5998
+ function Vo(n) {
5975
5999
  if (n) return n;
5976
6000
  try {
5977
6001
  let t = globalThis.process?.env?.NEETRU_ENV;
@@ -5985,11 +6009,11 @@ function Fo(n) {
5985
6009
  }
5986
6010
  return "prod";
5987
6011
  }
5988
- var jo = it;
5989
- function sa() {
5990
- st();
6012
+ var Ko = at;
6013
+ function ga() {
6014
+ ct();
5991
6015
  }
5992
- function $o(n) {
6016
+ function zo(n) {
5993
6017
  let e = n.sub ?? "", t = typeof n.email == "string" ? n.email : "";
5994
6018
  return {
5995
6019
  uid: e,
@@ -6004,8 +6028,8 @@ function $o(n) {
6004
6028
  ...n
6005
6029
  };
6006
6030
  }
6007
- var se = "neetru_oauth_tx";
6008
- function rt(n) {
6031
+ var ae = "neetru_oauth_tx";
6032
+ function it(n) {
6009
6033
  try {
6010
6034
  let e = globalThis.history;
6011
6035
  if (!e || typeof e.replaceState != "function") return;
@@ -6016,7 +6040,7 @@ function rt(n) {
6016
6040
  } catch {
6017
6041
  }
6018
6042
  }
6019
- function Wo(n) {
6043
+ function Ho(n) {
6020
6044
  let e = "neetru_id_token", t = "neetru_refresh_token", r = /* @__PURE__ */ new Set(), o = null, i = null, s = null;
6021
6045
  function a() {
6022
6046
  try {
@@ -6034,21 +6058,21 @@ function Wo(n) {
6034
6058
  }
6035
6059
  function d() {
6036
6060
  if (o) {
6037
- let g = o.exp;
6038
- return typeof g == "number" && g * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), S(), null) : o;
6061
+ let m = o.exp;
6062
+ return typeof m == "number" && m * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), T(), null) : o;
6039
6063
  }
6040
- let m = a();
6041
- if (!m) return null;
6042
- let _ = m.getItem(e);
6043
- if (!_)
6044
- return S(), null;
6045
- let w = ie(_);
6046
- return w ? (o = w, x(w), o) : (m.removeItem(e), S(), null);
6064
+ let g = a();
6065
+ if (!g) return null;
6066
+ let b = g.getItem(e);
6067
+ if (!b)
6068
+ return T(), null;
6069
+ let w = se(b);
6070
+ return w ? (o = w, x(w), o) : (g.removeItem(e), T(), null);
6047
6071
  }
6048
6072
  function u() {
6049
- for (let m of r)
6073
+ for (let g of r)
6050
6074
  try {
6051
- m(o);
6075
+ g(o);
6052
6076
  } catch {
6053
6077
  }
6054
6078
  }
@@ -6060,70 +6084,75 @@ function Wo(n) {
6060
6084
  }
6061
6085
  function h() {
6062
6086
  o = null;
6063
- let m = a();
6064
- m?.removeItem(e), m?.removeItem(t), u();
6087
+ let g = a();
6088
+ g?.removeItem(e), g?.removeItem(t), u();
6065
6089
  }
6066
6090
  function y() {
6067
- return s || (s = (async () => {
6068
- let m = f();
6069
- if (!m) return false;
6070
- let _;
6091
+ if (s) return s;
6092
+ let g = false, b = (async () => {
6093
+ let w = f();
6094
+ if (!w) return false;
6095
+ let m;
6071
6096
  try {
6072
- _ = T();
6097
+ m = R();
6073
6098
  } catch {
6074
6099
  return false;
6075
6100
  }
6076
- let g = `${oe(n.baseUrl)}/api/v1/oauth/token`, C = new URLSearchParams({
6101
+ let D = `${ie(n.baseUrl)}/api/v1/oauth/token`, O = new URLSearchParams({
6077
6102
  grant_type: "refresh_token",
6078
- refresh_token: m,
6079
- client_id: _
6080
- }), D;
6103
+ refresh_token: w,
6104
+ client_id: m
6105
+ }), { signal: A, clear: M } = Wn(15e3), I;
6081
6106
  try {
6082
- D = await n.fetch(g, {
6107
+ I = await n.fetch(D, {
6083
6108
  method: "POST",
6084
6109
  headers: { "content-type": "application/x-www-form-urlencoded" },
6085
- body: C.toString()
6110
+ body: O.toString(),
6111
+ signal: A
6086
6112
  });
6087
6113
  } catch {
6088
6114
  return false;
6115
+ } finally {
6116
+ M();
6089
6117
  }
6090
- let E = null;
6118
+ let L = null;
6091
6119
  try {
6092
- E = await D.json();
6120
+ L = await I.json();
6093
6121
  } catch {
6094
- E = null;
6122
+ L = null;
6095
6123
  }
6096
- if (!D.ok || typeof E?.error == "string") return false;
6097
- let R = E?.id_token;
6098
- if (typeof R != "string" || R.length === 0) return false;
6099
- let O = ie(R);
6100
- if (!O) return false;
6101
- let A = a();
6102
- A?.setItem(e, R);
6103
- let U = E?.refresh_token;
6104
- return typeof U == "string" && U.length > 0 && A?.setItem(t, U), o = O, x(O), u(), true;
6105
- })().finally(() => {
6124
+ if (!I.ok || typeof L?.error == "string") return false;
6125
+ let U = L?.id_token;
6126
+ if (typeof U != "string" || U.length === 0) return false;
6127
+ let q = se(U);
6128
+ if (!q || g) return false;
6129
+ let P = a();
6130
+ P?.setItem(e, U);
6131
+ let Le = L?.refresh_token;
6132
+ return typeof Le == "string" && Le.length > 0 && P?.setItem(t, Le), o = q, x(q), u(), true;
6133
+ })();
6134
+ return s = Bn(b, 15e3, () => (g = true, false)).finally(() => {
6106
6135
  s = null;
6107
- }), s);
6136
+ }), s;
6108
6137
  }
6109
- function S() {
6110
- f() && y().then((m) => {
6111
- m || h();
6138
+ function T() {
6139
+ f() && y().then((g) => {
6140
+ g || h();
6112
6141
  });
6113
6142
  }
6114
- function x(m) {
6143
+ function x(g) {
6115
6144
  p();
6116
- let _ = m.exp;
6117
- if (typeof _ != "number") return;
6118
- let w = _ * 1e3 - Date.now();
6145
+ let b = g.exp;
6146
+ if (typeof b != "number") return;
6147
+ let w = b * 1e3 - Date.now();
6119
6148
  if (!(w <= 0)) {
6120
6149
  if (f()) {
6121
- let g = Math.min(w, Math.max(3e4, w * 0.2)), C = Math.max(1, w - g);
6150
+ let m = Math.min(w, Math.max(3e4, w * 0.2)), S = Math.max(1, w - m);
6122
6151
  i = setTimeout(() => {
6123
6152
  i = null, y().then((D) => {
6124
6153
  D || h();
6125
6154
  });
6126
- }, C);
6155
+ }, S);
6127
6156
  return;
6128
6157
  }
6129
6158
  i = setTimeout(() => {
@@ -6131,143 +6160,143 @@ function Wo(n) {
6131
6160
  }, w + 1);
6132
6161
  }
6133
6162
  }
6134
- function T() {
6135
- return Bn(n);
6163
+ function R() {
6164
+ return Hn(n);
6136
6165
  }
6137
- async function P(m) {
6138
- let _ = m ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6139
- if (!_) return null;
6166
+ async function E(g) {
6167
+ let b = g ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6168
+ if (!b) return null;
6140
6169
  let w;
6141
6170
  try {
6142
- w = new URL(_);
6171
+ w = new URL(b);
6143
6172
  } catch {
6144
6173
  return null;
6145
6174
  }
6146
- let g = w.searchParams, C = g.get("error");
6147
- if (C) {
6148
- let U = g.get("error_description") ?? C;
6149
- throw l()?.removeItem(se), rt(w), new c(C, `OIDC authorize falhou: ${U}`);
6175
+ let m = w.searchParams, S = m.get("error");
6176
+ if (S) {
6177
+ let L = m.get("error_description") ?? S;
6178
+ throw l()?.removeItem(ae), it(w), new c(S, `OIDC authorize falhou: ${L}`);
6150
6179
  }
6151
- let D = g.get("code");
6180
+ let D = m.get("code");
6152
6181
  if (!D) return null;
6153
- let E = g.get("state"), R = l(), O = R?.getItem(se) ?? null, A = null;
6154
- if (O)
6182
+ let O = m.get("state"), A = l(), M = A?.getItem(ae) ?? null, I = null;
6183
+ if (M)
6155
6184
  try {
6156
- A = JSON.parse(O);
6185
+ I = JSON.parse(M);
6157
6186
  } catch {
6158
- A = null;
6187
+ I = null;
6159
6188
  }
6160
- if (!A)
6189
+ if (!I)
6161
6190
  throw new c(
6162
6191
  "oidc_state_mismatch",
6163
6192
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado nesta sess\xE3o (ou j\xE1 consumido)."
6164
6193
  );
6165
- if (!E || E !== A.state)
6166
- throw R?.removeItem(se), rt(w), new c(
6194
+ if (!O || O !== I.state)
6195
+ throw A?.removeItem(ae), it(w), new c(
6167
6196
  "oidc_state_mismatch",
6168
6197
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
6169
6198
  );
6170
- return R?.removeItem(se), rt(w), {
6199
+ return A?.removeItem(ae), it(w), {
6171
6200
  code: D,
6172
- codeVerifier: A.codeVerifier,
6173
- redirectUri: A.redirectUri,
6174
- nonce: A.nonce,
6175
- state: A.state,
6176
- postLoginRedirect: A.postLoginRedirect
6201
+ codeVerifier: I.codeVerifier,
6202
+ redirectUri: I.redirectUri,
6203
+ nonce: I.nonce,
6204
+ state: I.state,
6205
+ postLoginRedirect: I.postLoginRedirect
6177
6206
  };
6178
6207
  }
6179
- async function q(m) {
6180
- let _ = await P(m);
6181
- if (!_) return null;
6182
- let w = T(), C = `${oe(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
6208
+ async function j(g) {
6209
+ let b = await E(g);
6210
+ if (!b) return null;
6211
+ let w = R(), S = `${ie(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
6183
6212
  grant_type: "authorization_code",
6184
- code: _.code,
6185
- redirect_uri: _.redirectUri,
6213
+ code: b.code,
6214
+ redirect_uri: b.redirectUri,
6186
6215
  client_id: w,
6187
- code_verifier: _.codeVerifier
6188
- }), E;
6216
+ code_verifier: b.codeVerifier
6217
+ }), O;
6189
6218
  try {
6190
- E = await n.fetch(C, {
6219
+ O = await n.fetch(S, {
6191
6220
  method: "POST",
6192
6221
  headers: { "content-type": "application/x-www-form-urlencoded" },
6193
6222
  body: D.toString()
6194
6223
  });
6195
- } catch (L) {
6224
+ } catch (P) {
6196
6225
  throw new c(
6197
6226
  "network_error",
6198
- `POST ${C} falhou (network): ${L?.message ?? String(L)}`
6227
+ `POST ${S} falhou (network): ${P?.message ?? String(P)}`
6199
6228
  );
6200
6229
  }
6201
- let R = null;
6230
+ let A = null;
6202
6231
  try {
6203
- R = await E.json();
6232
+ A = await O.json();
6204
6233
  } catch {
6205
- R = null;
6234
+ A = null;
6206
6235
  }
6207
- if (!E.ok || typeof R?.error == "string") {
6208
- let L = typeof R?.error_description == "string" && R.error_description || typeof R?.error == "string" && R.error || `HTTP ${E.status}`;
6236
+ if (!O.ok || typeof A?.error == "string") {
6237
+ let P = typeof A?.error_description == "string" && A.error_description || typeof A?.error == "string" && A.error || `HTTP ${O.status}`;
6209
6238
  throw new c(
6210
6239
  "token_exchange_failed",
6211
- `Troca do authorization_code por tokens falhou no /token: ${L}`,
6212
- E.status
6240
+ `Troca do authorization_code por tokens falhou no /token: ${P}`,
6241
+ O.status
6213
6242
  );
6214
6243
  }
6215
- let O = R?.id_token;
6216
- if (typeof O != "string" || O.length === 0)
6244
+ let M = A?.id_token;
6245
+ if (typeof M != "string" || M.length === 0)
6217
6246
  throw new c(
6218
6247
  "token_exchange_failed",
6219
6248
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado.",
6220
- E.status
6249
+ O.status
6221
6250
  );
6222
- let A = nt(O);
6223
- if (!A)
6251
+ let I = ot(M);
6252
+ if (!I)
6224
6253
  throw new c(
6225
6254
  "token_exchange_failed",
6226
6255
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
6227
6256
  );
6228
- if (A.nonce !== _.nonce)
6257
+ if (I.nonce !== b.nonce)
6229
6258
  throw new c(
6230
6259
  "oidc_nonce_mismatch",
6231
6260
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
6232
6261
  );
6233
- let U = ie(O);
6234
- if (!U)
6262
+ let L = se(M);
6263
+ if (!L)
6235
6264
  throw new c(
6236
6265
  "token_exchange_failed",
6237
6266
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
6238
6267
  );
6239
- let F = a();
6240
- F?.setItem(e, O);
6241
- let j = R?.refresh_token;
6242
- return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = U, x(U), u(), { user: U, postLoginRedirect: _.postLoginRedirect };
6268
+ let U = a();
6269
+ U?.setItem(e, M);
6270
+ let q = A?.refresh_token;
6271
+ return typeof q == "string" && q.length > 0 && U?.setItem(t, q), o = L, x(L), u(), { user: L, postLoginRedirect: b.postLoginRedirect };
6243
6272
  }
6244
6273
  return {
6245
- async signIn(m) {
6274
+ async signIn(g) {
6246
6275
  if (typeof globalThis.location < "u" && typeof globalThis.location.assign == "function") {
6247
- let _ = jn(), w = m?.redirectUri ?? globalThis.location.origin, g = m?.scope ?? "openid profile email", C = T(), D = xe(_, 16), E = xe(_, 16), R = xe(_, 32), O = await Wn(_, R), A = l();
6248
- if (!A)
6276
+ 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();
6277
+ if (!I)
6249
6278
  throw new c(
6250
6279
  "runtime_unsupported",
6251
6280
  "auth.signIn requer sessionStorage para guardar a transa\xE7\xE3o PKCE entre o redirect e o callback."
6252
6281
  );
6253
- let U = {
6282
+ let L = {
6254
6283
  state: D,
6255
- nonce: E,
6256
- codeVerifier: R,
6284
+ nonce: O,
6285
+ codeVerifier: A,
6257
6286
  redirectUri: w,
6258
- postLoginRedirect: m?.postLoginRedirect
6287
+ postLoginRedirect: g?.postLoginRedirect
6259
6288
  };
6260
- A.setItem(se, JSON.stringify(U));
6261
- let F = oe(n.baseUrl), j = Vn({
6262
- idpOrigin: F,
6263
- clientId: C,
6289
+ I.setItem(ae, JSON.stringify(L));
6290
+ let U = ie(n.baseUrl), q = Qn({
6291
+ idpOrigin: U,
6292
+ clientId: S,
6264
6293
  redirectUri: w,
6265
- scope: g,
6294
+ scope: m,
6266
6295
  state: D,
6267
- nonce: E,
6268
- codeChallenge: O
6296
+ nonce: O,
6297
+ codeChallenge: M
6269
6298
  });
6270
- globalThis.location.assign(j.toString());
6299
+ globalThis.location.assign(q.toString());
6271
6300
  return;
6272
6301
  }
6273
6302
  throw new c(
@@ -6275,79 +6304,91 @@ function Wo(n) {
6275
6304
  "auth.signIn requires a browser context or mocks. Use NEETRU_ENV=dev or pass mocks.auth."
6276
6305
  );
6277
6306
  },
6278
- handleRedirectCallback: P,
6279
- completeSignIn: q,
6307
+ handleRedirectCallback: E,
6308
+ completeSignIn: j,
6280
6309
  // 3.7.0: exposto pro client.support renovar a sessão 1x num 401
6281
6310
  // invalid_end_user_token (mesma função do refresh proativo, com dedup).
6282
6311
  refreshTokens: y,
6283
6312
  getIdToken() {
6284
- let _ = a()?.getItem(e) ?? null;
6285
- return _ && ie(_) ? _ : null;
6313
+ let b = a()?.getItem(e) ?? null;
6314
+ return b && se(b) ? b : null;
6286
6315
  },
6287
6316
  async signOut() {
6288
- let m = a(), _ = m?.getItem(t) ?? null;
6289
- if (m && (m.removeItem(e), m.removeItem(t)), p(), o = null, _) {
6290
- let w = null;
6317
+ let g = a(), b = g?.getItem(t) ?? null, w = true;
6318
+ if (g)
6319
+ for (let S of [e, t])
6320
+ try {
6321
+ g.removeItem(S);
6322
+ } catch {
6323
+ w = false;
6324
+ }
6325
+ p(), o = null;
6326
+ let m = "skipped";
6327
+ if (b) {
6328
+ let S = null;
6291
6329
  try {
6292
- w = T();
6330
+ S = R();
6293
6331
  } catch {
6294
- w = null;
6332
+ S = null;
6295
6333
  }
6296
- !(w && await Kn(n.fetch, oe(n.baseUrl), w, [
6297
- { token: _, hint: "refresh_token" }
6298
- ])) && typeof console < "u" && console.warn(
6299
- "[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."
6334
+ S ? m = await Gn(
6335
+ n.fetch,
6336
+ ie(n.baseUrl),
6337
+ S,
6338
+ [{ token: b, hint: "refresh_token" }]
6339
+ ) ? "accepted" : "failed" : m = "not_configured", m !== "accepted" && typeof console < "u" && console.warn(
6340
+ "[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."
6300
6341
  );
6301
6342
  }
6302
- u();
6343
+ return u(), { localSessionCleared: w, remoteRevocation: m };
6303
6344
  },
6304
6345
  getUser() {
6305
6346
  return d();
6306
6347
  },
6307
- onAuthStateChanged(m) {
6308
- r.add(m);
6348
+ onAuthStateChanged(g) {
6349
+ r.add(g);
6309
6350
  try {
6310
- m(d());
6351
+ g(d());
6311
6352
  } catch {
6312
6353
  }
6313
6354
  return () => {
6314
- r.delete(m);
6355
+ r.delete(g);
6315
6356
  };
6316
6357
  },
6317
- async verifyToken(m, _) {
6318
- if (!m || typeof m != "string")
6358
+ async verifyToken(g, b) {
6359
+ if (!g || typeof g != "string")
6319
6360
  throw new c("token_invalid_signature", "token must be a non-empty string");
6320
- let g = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), C = g, D = `${g}/api/v1/oauth/.well-known/jwks`, E = _?.jwksCacheTtlMs ?? Ue, R = _?.audience, O = lt(n.apiKey), A = R ?? n.oidcClientId ?? O?.keyId;
6321
- if (!A)
6361
+ 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;
6362
+ if (!I)
6322
6363
  throw new c(
6323
6364
  "invalid_config",
6324
6365
  "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."
6325
6366
  );
6326
- let U = jo(D, E);
6367
+ let L = Ko(D, O);
6327
6368
  try {
6328
- let { payload: F } = await jose.jwtVerify(m, U, {
6329
- issuer: C,
6330
- audience: A,
6369
+ let { payload: U } = await jose.jwtVerify(g, L, {
6370
+ issuer: S,
6371
+ audience: I,
6331
6372
  algorithms: ["RS256"]
6332
6373
  });
6333
- return $o(F);
6334
- } catch (F) {
6335
- let j = F?.code ?? F?.name ?? "", L = F?.message ?? String(F);
6336
- throw j === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${L}`) : j === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${L}`) : j === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? L.includes('"aud"') || L.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${L}`) : L.includes('"iss"') || L.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${L}`) : new c("token_invalid_signature", `Token claim validation failed: ${L}`) : new c("token_invalid_signature", `Token verification failed: ${L}`);
6374
+ return zo(U);
6375
+ } catch (U) {
6376
+ let q = U?.code ?? U?.name ?? "", P = U?.message ?? String(U);
6377
+ 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}`);
6337
6378
  }
6338
6379
  }
6339
6380
  };
6340
6381
  }
6341
- function Bo(n = {}) {
6382
+ function Qo(n = {}) {
6342
6383
  let e = n.fetch ?? globalThis.fetch;
6343
6384
  if (typeof e != "function")
6344
6385
  throw new c(
6345
6386
  "invalid_config",
6346
6387
  "fetch is not available in this runtime. Pass `fetch` explicitly to createNeetruClient."
6347
6388
  );
6348
- let t = n.apiKey ?? qo();
6349
- wt({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6350
- let r = Fo(n.env), o = n.baseUrl ?? (r === "dev-local" ? mt : ft), i = pt(o, n.allowedHosts ?? []), s = Object.freeze({
6389
+ let t = n.apiKey ?? Bo();
6390
+ St({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6391
+ let r = Vo(n.env), o = n.baseUrl ?? (r === "dev-local" ? gt : ht), i = mt(o, n.allowedHosts ?? []), s = Object.freeze({
6351
6392
  apiKey: t,
6352
6393
  oidcClientId: n.oidcClientId,
6353
6394
  baseUrl: i,
@@ -6355,39 +6396,39 @@ function Bo(n = {}) {
6355
6396
  env: r,
6356
6397
  productId: n.productId,
6357
6398
  tenantId: n.tenantId
6358
- }), a = r === "dev" && !Ce(), l = n.mocks?.auth ?? (a ? new Ae({ ...tt }) : Wo(s)), d = n.mocks?.usage ?? (a ? new Ee() : Ut(s)), u = n.endUserAuth ?? l, p = n.mocks?.support ?? (a ? new Pe() : Wt(s, {
6399
+ }), 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, {
6359
6400
  getEndUserToken: () => u.getIdToken(),
6360
6401
  // `refreshTokens` é opcional (MockAuth/mocks próprios omitem).
6361
6402
  refreshEndUserToken: (() => {
6362
- let P = u.refreshTokens;
6363
- return typeof P == "function" ? () => P.call(u) : void 0;
6403
+ let E = u.refreshTokens;
6404
+ return typeof E == "function" ? () => E.call(u) : void 0;
6364
6405
  })()
6365
- })), f = n.mocks?.entitlements ?? (a ? new De() : Dt()), h = n.mocks?.db ?? (X() === "react-native" ? Hn() : dn(s, n.db)), y = n.mocks?.webhooks ?? (a ? new Se() : hn(s)), S = n.mocks?.notifications ?? (a ? new Re() : _n(s)), x = n.mocks?.ai ?? (a ? new Ne() : Fn(s)), T = Object.freeze({
6406
+ })), 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({
6366
6407
  config: s,
6367
6408
  auth: l,
6368
- catalog: Et(s),
6409
+ catalog: Dt(s),
6369
6410
  entitlements: f,
6370
- telemetry: Ot(s),
6411
+ telemetry: Ut(s),
6371
6412
  usage: d,
6372
6413
  support: p,
6373
6414
  db: h,
6374
- checkout: un(s),
6415
+ checkout: fn(s),
6375
6416
  webhooks: y,
6376
- notifications: S,
6417
+ notifications: T,
6377
6418
  ai: x
6378
6419
  });
6379
- return n.endUserAuth && zn(T, n.endUserAuth), T;
6420
+ return n.endUserAuth && Jn(R, n.endUserAuth), R;
6380
6421
  }
6381
6422
  var Oe = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6382
- function aa(n = {}) {
6423
+ function ya(n = {}) {
6383
6424
  let e = globalThis;
6384
- return e[Oe] || (e[Oe] = Bo(n)), e[Oe];
6425
+ return e[Oe] || (e[Oe] = Qo(n)), e[Oe];
6385
6426
  }
6386
- function ca() {
6427
+ function _a() {
6387
6428
  delete globalThis[Oe];
6388
6429
  }
6389
6430
 
6390
- exports.__resetJwksCacheForTests = sa;
6391
- exports.__resetServerNeetruClientForTests = ca;
6392
- exports.createNeetruClient = Bo;
6393
- exports.getServerNeetruClient = aa;
6431
+ exports.__resetJwksCacheForTests = ga;
6432
+ exports.__resetServerNeetruClientForTests = _a;
6433
+ exports.createNeetruClient = Qo;
6434
+ exports.getServerNeetruClient = ya;