@neetru/sdk 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +4 -1
  3. package/dist/ai.cjs +1 -1
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +1 -1
  7. package/dist/auth.cjs +1171 -1110
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +1168 -1107
  11. package/dist/catalog.cjs +1 -1
  12. package/dist/catalog.d.cts +1 -1
  13. package/dist/catalog.d.ts +1 -1
  14. package/dist/catalog.mjs +1 -1
  15. package/dist/checkout.cjs +62 -49
  16. package/dist/checkout.d.cts +1 -1
  17. package/dist/checkout.d.ts +1 -1
  18. package/dist/checkout.mjs +62 -49
  19. package/dist/db-react.d.cts +1 -1
  20. package/dist/db-react.d.ts +1 -1
  21. package/dist/db.cjs +303 -270
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +322 -289
  25. package/dist/entitlements.d.cts +1 -1
  26. package/dist/entitlements.d.ts +1 -1
  27. package/dist/firestore-compat.d.cts +1 -1
  28. package/dist/firestore-compat.d.ts +1 -1
  29. package/dist/index.cjs +1275 -1214
  30. package/dist/index.d.cts +2 -2
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.mjs +1390 -1329
  33. package/dist/mobile.cjs +328 -276
  34. package/dist/mobile.d.cts +12 -2
  35. package/dist/mobile.d.ts +12 -2
  36. package/dist/mobile.mjs +328 -276
  37. package/dist/mocks.cjs +5 -5
  38. package/dist/mocks.d.cts +2 -2
  39. package/dist/mocks.d.ts +2 -2
  40. package/dist/mocks.mjs +4 -4
  41. package/dist/notifications.cjs +1 -1
  42. package/dist/notifications.d.cts +1 -1
  43. package/dist/notifications.d.ts +1 -1
  44. package/dist/notifications.mjs +1 -1
  45. package/dist/react.cjs +119 -119
  46. package/dist/react.d.cts +8 -2
  47. package/dist/react.d.ts +8 -2
  48. package/dist/react.mjs +119 -119
  49. package/dist/support.cjs +1 -1
  50. package/dist/support.d.cts +1 -1
  51. package/dist/support.d.ts +1 -1
  52. package/dist/support.mjs +1 -1
  53. package/dist/telemetry.cjs +62 -49
  54. package/dist/telemetry.d.cts +1 -1
  55. package/dist/telemetry.d.ts +1 -1
  56. package/dist/telemetry.mjs +62 -49
  57. package/dist/{types-D-9bjlM0.d.cts → types-Bl_4HROd.d.cts} +118 -19
  58. package/dist/{types-bVztFQTI.d.ts → types-Bqnsqvow.d.ts} +118 -19
  59. package/dist/usage.cjs +1 -1
  60. package/dist/usage.d.cts +1 -1
  61. package/dist/usage.d.ts +1 -1
  62. package/dist/usage.mjs +1 -1
  63. package/dist/webhooks.cjs +1 -1
  64. package/dist/webhooks.d.cts +1 -1
  65. package/dist/webhooks.d.ts +1 -1
  66. package/dist/webhooks.mjs +1 -1
  67. package/package.json +9 -1
package/dist/db.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  import { openDB } from 'idb';
2
2
 
3
- var Je = Object.defineProperty;
3
+ var Ze = Object.defineProperty;
4
4
  var S = (r, e) => () => (r && (e = r(r = 0)), e);
5
5
  var me = (r, e) => {
6
6
  for (var t in e)
7
- Je(r, t, { get: e[t], enumerable: true });
7
+ Ze(r, t, { get: e[t], enumerable: true });
8
8
  };
9
9
 
10
10
  // src/errors.ts
11
- var g, x = S(() => {
12
- g = class r extends Error {
11
+ var b, x = S(() => {
12
+ b = class r extends Error {
13
13
  code;
14
14
  status;
15
15
  requestId;
@@ -36,13 +36,13 @@ var g, x = S(() => {
36
36
  });
37
37
 
38
38
  // src/db-errors.ts
39
- var Ye, p, I = S(() => {
39
+ var et, f, I = S(() => {
40
40
  x();
41
- Ye = /* @__PURE__ */ new Set([
41
+ et = /* @__PURE__ */ new Set([
42
42
  "db_unavailable",
43
43
  "db_conflict",
44
44
  "db_timeout"
45
- ]), p = class r extends g {
45
+ ]), f = class r extends b {
46
46
  /** Código de erro fechado — específico de DB. */
47
47
  code;
48
48
  /**
@@ -56,30 +56,30 @@ var Ye, p, I = S(() => {
56
56
  */
57
57
  dbId;
58
58
  constructor(e, t, n) {
59
- super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Ye.has(e), this.dbId = n, Object.setPrototypeOf(this, r.prototype);
59
+ super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = et.has(e), this.dbId = n, Object.setPrototypeOf(this, r.prototype);
60
60
  }
61
61
  };
62
62
  });
63
63
 
64
64
  // src/idempotency.ts
65
- function Te() {
65
+ function Re() {
66
66
  let r = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
67
67
  if (r && typeof r.randomUUID == "function")
68
68
  return r.randomUUID();
69
- throw new g(
69
+ throw new b(
70
70
  "runtime_unsupported",
71
71
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
72
72
  );
73
73
  }
74
- var Re = S(() => {
74
+ var De = S(() => {
75
75
  x();
76
76
  });
77
77
 
78
78
  // src/correlation.ts
79
- function ke(r) {
80
- return typeof r == "string" && r.length > 0 && r.length <= 128 && vt.test(r);
79
+ function Ce(r) {
80
+ return typeof r == "string" && r.length > 0 && r.length <= 128 && Tt.test(r);
81
81
  }
82
- function wt() {
82
+ function Rt() {
83
83
  let r = globalThis.crypto;
84
84
  try {
85
85
  if (r && typeof r.randomUUID == "function") return r.randomUUID();
@@ -97,24 +97,24 @@ function wt() {
97
97
  let n = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
98
98
  return `${n.slice(0, 8)}-${n.slice(8, 12)}-${n.slice(12, 16)}-${n.slice(16, 20)}-${n.slice(20)}`;
99
99
  }
100
- function Ce(r, e) {
100
+ function Ie(r, e) {
101
101
  let t, n = {};
102
102
  for (let [i, s] of Object.entries(r)) {
103
- if (i.toLowerCase() === De) {
104
- ke(s) && (t = s);
103
+ if (i.toLowerCase() === ke) {
104
+ Ce(s) && (t = s);
105
105
  continue;
106
106
  }
107
107
  n[i] = s;
108
108
  }
109
- let o = t ?? (ke(e) ? e : void 0) ?? wt();
110
- return n[De] = o, { headers: n, correlationId: o };
109
+ let o = t ?? (Ce(e) ? e : void 0) ?? Rt();
110
+ return n[ke] = o, { headers: n, correlationId: o };
111
111
  }
112
- var De, vt, Ie = S(() => {
113
- De = "x-correlation-id", vt = /^[A-Za-z0-9._:\-]+$/;
112
+ var ke, Tt, Pe = S(() => {
113
+ ke = "x-correlation-id", Tt = /^[A-Za-z0-9._:\-]+$/;
114
114
  });
115
115
 
116
116
  // src/server-only-key.ts
117
- function Pe() {
117
+ function Ee() {
118
118
  try {
119
119
  let r = globalThis.navigator;
120
120
  if (r && r.product === "ReactNative") return "react-native";
@@ -127,20 +127,20 @@ function Pe() {
127
127
  }
128
128
  return null;
129
129
  }
130
- var Ee = S(() => {
130
+ var Le = S(() => {
131
131
  });
132
132
 
133
133
  // src/http.ts
134
134
  var U = {};
135
135
  me(U, {
136
- checkCoreVersionCompat: () => qe,
137
- httpRequest: () => Mt,
138
- statusToCode: () => Fe
136
+ checkCoreVersionCompat: () => Fe,
137
+ httpRequest: () => At,
138
+ statusToCode: () => Ue
139
139
  });
140
140
  function se(r) {
141
141
  return r.split("+")[0] ?? r;
142
142
  }
143
- function Tt(r, e) {
143
+ function kt(r, e) {
144
144
  let t = se(r).split(".").map(Number), n = se(e).split(".").map(Number), o = Math.max(t.length, n.length);
145
145
  for (let i = 0; i < o; i++) {
146
146
  let s = t[i] ?? 0, a = n[i] ?? 0;
@@ -148,62 +148,62 @@ function Tt(r, e) {
148
148
  }
149
149
  return 0;
150
150
  }
151
- function Ne() {
151
+ function qe() {
152
152
  try {
153
- return "3.8.0";
153
+ return "3.9.0";
154
154
  } catch {
155
155
  return;
156
156
  }
157
157
  }
158
- function Rt() {
159
- let r = Ne();
158
+ function Ct() {
159
+ let r = qe();
160
160
  return r ? parseInt(r.split(".")[0] ?? "3", 10) : 3;
161
161
  }
162
- function qe(r) {
162
+ function Fe(r) {
163
163
  if (!r) return;
164
- let e = Rt(), t = St[e];
164
+ let e = Ct(), t = Dt[e];
165
165
  if (!t) return;
166
166
  let n = se(r);
167
- if (Tt(n, t) < 0) {
167
+ if (kt(n, t) < 0) {
168
168
  let o = `${e}:${n}`;
169
- Le.has(o) || (Le.add(o), console.warn(
169
+ Me.has(o) || (Me.add(o), console.warn(
170
170
  `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${r}" \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.`
171
171
  ));
172
172
  }
173
173
  }
174
- function Dt() {
174
+ function It() {
175
175
  let r = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
176
- return Pe() ? "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. (" + r + ")" : r;
176
+ return Ee() ? "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. (" + r + ")" : r;
177
177
  }
178
- function Me(r) {
178
+ function Oe(r) {
179
179
  let e = 200 * Math.pow(4, r), t = e * 0.2 * (Math.random() * 2 - 1);
180
180
  return Math.max(50, Math.round(e + t));
181
181
  }
182
- function Et(r) {
182
+ function Ot(r) {
183
183
  if (!r) return null;
184
184
  let e = Number(r);
185
- if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), Oe);
185
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), xe);
186
186
  let t = Date.parse(r);
187
187
  if (Number.isFinite(t)) {
188
188
  let n = t - Date.now();
189
- if (n > 0) return Math.min(n, Oe);
189
+ if (n > 0) return Math.min(n, xe);
190
190
  }
191
191
  return null;
192
192
  }
193
- function xe(r) {
193
+ function Ae(r) {
194
194
  return new Promise((e) => setTimeout(e, r));
195
195
  }
196
- function Fe(r) {
196
+ function Ue(r) {
197
197
  return r === 401 ? "unauthorized" : r === 403 ? "forbidden" : r === 404 ? "not_found" : r === 409 ? "conflict" : r === 410 ? "gone" : r === 422 || r === 400 ? "validation_failed" : r === 429 ? "rate_limited" : r >= 500 ? "server_error" : "unknown";
198
198
  }
199
- function Lt(r, e, t) {
199
+ function xt(r, e, t) {
200
200
  let n = r.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, i = new URL(`${n}${o}`);
201
201
  if (t)
202
202
  for (let [s, a] of Object.entries(t))
203
203
  a !== void 0 && i.searchParams.set(s, String(a));
204
204
  return i.toString();
205
205
  }
206
- async function Ae(r) {
206
+ async function Ne(r) {
207
207
  let e = await r.text();
208
208
  if (e)
209
209
  try {
@@ -212,26 +212,26 @@ async function Ae(r) {
212
212
  return;
213
213
  }
214
214
  }
215
- async function Mt(r, e) {
216
- let t = e.method ?? "GET", n = Lt(r.baseUrl, e.path, e.query), o = It.has(t) ? kt : Ct, i = e.retries ?? o, { headers: s, correlationId: a } = Ce(
215
+ async function At(r, e) {
216
+ let t = e.method ?? "GET", n = xt(r.baseUrl, e.path, e.query), o = Lt.has(t) ? Pt : Et, i = e.retries ?? o, { headers: s, correlationId: a } = Ie(
217
217
  { accept: "application/json", ...e.headers },
218
218
  e.correlationId
219
- ), c = Ne();
219
+ ), c = qe();
220
220
  if (c && (s["x-neetru-sdk-version"] = c), e.requireAuth) {
221
221
  if (!r.apiKey)
222
- throw new g("missing_api_key", Dt());
222
+ throw new b("missing_api_key", It());
223
223
  s.authorization = `Bearer ${r.apiKey}`;
224
224
  }
225
225
  if (e.idempotencyKey) {
226
- let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : Te();
227
- s["idempotency-key"] = f;
226
+ let p = typeof e.idempotencyKey == "string" ? e.idempotencyKey : Re();
227
+ s["idempotency-key"] = p;
228
228
  }
229
229
  let l = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
230
230
  l !== void 0 && (s["content-type"] = "application/json");
231
231
  let d = null, u = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
232
- for (let f = 0; f <= i; f++) {
232
+ for (let p = 0; p <= i; p++) {
233
233
  if (u != null && Date.now() >= u)
234
- throw d ?? new g(
234
+ throw d ?? new b(
235
235
  "network_error",
236
236
  "Deadline excedido antes de completar a request",
237
237
  void 0,
@@ -241,72 +241,72 @@ async function Mt(r, e) {
241
241
  );
242
242
  let h = { method: t, headers: s };
243
243
  l !== void 0 && (h.body = l);
244
- let v = u != null ? Math.max(1, Math.min(3e4, u - Date.now())) : 3e4;
245
- h.signal = AbortSignal.timeout(v);
246
- let _;
244
+ let _ = u != null ? Math.max(1, Math.min(3e4, u - Date.now())) : 3e4;
245
+ h.signal = AbortSignal.timeout(_);
246
+ let y;
247
247
  try {
248
- _ = await r.fetch(n, h);
248
+ y = await r.fetch(n, h);
249
249
  } catch (m) {
250
250
  let O = m instanceof DOMException && m.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${m instanceof Error ? m.message : "fetch failed"}`;
251
- if (d = new g("network_error", O, void 0, void 0, void 0, a), f < i) {
252
- let he = Me(f);
251
+ if (d = new b("network_error", O, void 0, void 0, void 0, a), p < i) {
252
+ let he = Oe(p);
253
253
  if (u == null || Date.now() + he < u) {
254
- await xe(he);
254
+ await Ae(he);
255
255
  continue;
256
256
  }
257
257
  }
258
258
  throw d;
259
259
  }
260
- let B = _.headers.get("x-request-id") ?? _.headers.get("x-correlation-id") ?? void 0;
261
- if (_.ok) {
262
- let m = _.headers.get("x-neetru-version");
263
- return m && qe(m), await Ae(_);
260
+ let B = y.headers.get("x-request-id") ?? y.headers.get("x-correlation-id") ?? void 0;
261
+ if (y.ok) {
262
+ let m = y.headers.get("x-neetru-version");
263
+ return m && Fe(m), await Ne(y);
264
264
  }
265
- let y = await Ae(_), b = Fe(_.status), w = `HTTP ${_.status}`, C;
266
- if (y && typeof y == "object") {
267
- let m = y.error;
268
- typeof m == "string" ? w = m : m && typeof m == "object" ? (typeof m.code == "string" && (b = m.code), typeof m.message == "string" && (w = m.message), typeof m.reason == "string" && (C = m.reason)) : (typeof y.code == "string" && (b = y.code), typeof y.message == "string" && (w = y.message)), typeof y.reason == "string" && (C = y.reason);
265
+ let g = await Ne(y), v = Ue(y.status), w = `HTTP ${y.status}`, C;
266
+ if (g && typeof g == "object") {
267
+ let m = g.error;
268
+ typeof m == "string" ? w = m : m && typeof m == "object" ? (typeof m.code == "string" && (v = m.code), typeof m.message == "string" && (w = m.message), typeof m.reason == "string" && (C = m.reason)) : (typeof g.code == "string" && (v = g.code), typeof g.message == "string" && (w = g.message)), typeof g.reason == "string" && (C = g.reason);
269
269
  }
270
- if (_.status === 410) {
271
- let m = _.headers.get("x-neetru-replacement");
272
- w === `HTTP ${_.status}` && (w = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), m && !w.includes(m) && (w += ` Substituto: ${m}.`);
270
+ if (y.status === 410) {
271
+ let m = y.headers.get("x-neetru-replacement");
272
+ w === `HTTP ${y.status}` && (w = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), m && !w.includes(m) && (w += ` Substituto: ${m}.`);
273
273
  }
274
- let fe = new g(b, w, _.status, B, C, a);
275
- if (d = fe, Pt.has(b) && f < i) {
276
- let O = Et(_.headers.get("retry-after")) ?? Me(f);
274
+ let fe = new b(v, w, y.status, B, C, a);
275
+ if (d = fe, Mt.has(v) && p < i) {
276
+ let O = Ot(y.headers.get("retry-after")) ?? Oe(p);
277
277
  if (u == null || Date.now() + O < u) {
278
- await xe(O);
278
+ await Ae(O);
279
279
  continue;
280
280
  }
281
281
  }
282
282
  throw fe;
283
283
  }
284
- throw d ?? new g("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
284
+ throw d ?? new b("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
285
285
  }
286
- var St, Le, kt, Ct, It, Pt, Oe, W = S(() => {
286
+ var Dt, Me, Pt, Et, Lt, Mt, xe, W = S(() => {
287
287
  x();
288
- Re();
289
- Ie();
290
- Ee();
291
- St = {
288
+ De();
289
+ Pe();
290
+ Le();
291
+ Dt = {
292
292
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
293
293
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
294
294
  3: "2026.05.1"
295
295
  };
296
- Le = /* @__PURE__ */ new Set();
297
- kt = 2, Ct = 0, It = /* @__PURE__ */ new Set(["GET", "HEAD"]), Pt = /* @__PURE__ */ new Set([
296
+ Me = /* @__PURE__ */ new Set();
297
+ Pt = 2, Et = 0, Lt = /* @__PURE__ */ new Set(["GET", "HEAD"]), Mt = /* @__PURE__ */ new Set([
298
298
  "rate_limited",
299
299
  "server_error",
300
300
  "network_error"
301
301
  ]);
302
- Oe = 6e4;
302
+ xe = 6e4;
303
303
  });
304
304
 
305
305
  // src/db/sql/resilient-pool.ts
306
306
  function J(r) {
307
307
  return typeof r == "object" && r !== null && r[ae] === true;
308
308
  }
309
- function Ot(r) {
309
+ function Nt(r) {
310
310
  let e = r && typeof r == "object" && "code" in r ? r.code : void 0;
311
311
  if (e === "ECONNREFUSED" || e === "ETIMEDOUT" || e === "ENOTFOUND" || e === "EHOSTUNREACH" || e === "EAI_AGAIN")
312
312
  return true;
@@ -318,67 +318,84 @@ function Ot(r) {
318
318
  let n = (r instanceof Error ? r.message : typeof r == "string" ? r : "").toLowerCase();
319
319
  return n.length === 0 ? false : !!(n.includes("certificate expired") || n.includes("certificate has expired") || n.includes("cert_has_expired") || n.includes("alert certificate expired") || n.includes("err_ssl") || n.includes("sslv3 alert") || n.includes("tlsv1 alert") || n.includes("econnrefused") || n.includes("etimedout") || n.includes("enotfound") || n.includes("ehostunreach") || n.includes("getaddrinfo"));
320
320
  }
321
+ function We(r) {
322
+ let e = r && typeof r == "object" && "code" in r ? r.code : void 0;
323
+ if (typeof e == "string" && qt.has(e.toUpperCase()))
324
+ return true;
325
+ let n = (r instanceof Error ? r.message : typeof r == "string" ? r : "").toLowerCase();
326
+ return n.length === 0 ? false : n.includes("password authentication failed") || n.includes("sasl authentication failed");
327
+ }
328
+ function Ft(r) {
329
+ return Nt(r) || We(r);
330
+ }
321
331
  function ce(r) {
322
332
  let e = { current: r }, t = null, n = {
323
- __neetruSwapInner(c) {
324
- let l = e.current;
325
- return e.current = c, l;
333
+ __neetruSwapInner(d) {
334
+ let u = e.current;
335
+ return e.current = d, u;
326
336
  },
327
337
  __neetruGetInner() {
328
338
  return e.current;
329
339
  },
330
- __neetruSetReLease(c) {
331
- t = c;
340
+ __neetruSetReLease(d) {
341
+ t = d;
332
342
  }
333
- }, o = (c, l) => c.query(...l), i = (...c) => c.length > 0 && typeof c[c.length - 1] == "function" ? o(e.current, c) : (async () => {
343
+ }, o = (d, u, p) => u[d](
344
+ ...p
345
+ ), i = (d, u) => (...p) => p.length > 0 && typeof p[p.length - 1] == "function" ? o(d, e.current, p) : (async () => {
334
346
  try {
335
- return await o(e.current, c);
336
- } catch (l) {
337
- let d = t;
338
- if (d === null || !Ot(l))
339
- throw l;
347
+ return await o(d, e.current, p);
348
+ } catch (h) {
349
+ let _ = t;
350
+ if (_ === null || !u(h))
351
+ throw h;
340
352
  try {
341
- await d();
353
+ await _();
342
354
  } catch {
343
- throw l;
355
+ throw h;
344
356
  }
345
- return await o(e.current, c);
357
+ return await o(d, e.current, p);
346
358
  }
347
- })(), s = Object.create(Object.getPrototypeOf(r));
348
- return new Proxy(s, {
349
- get(c, l) {
350
- if (l === ae) return true;
351
- if (l === "__neetruSwapInner") return n.__neetruSwapInner;
352
- if (l === "__neetruGetInner") return n.__neetruGetInner;
353
- if (l === "__neetruSetReLease") return n.__neetruSetReLease;
354
- if (l === "query") return i;
355
- if (l === "constructor")
359
+ })(), s = i("query", Ft), a = i("connect", We), c = Object.create(Object.getPrototypeOf(r));
360
+ return new Proxy(c, {
361
+ get(d, u) {
362
+ if (u === ae) return true;
363
+ if (u === "__neetruSwapInner") return n.__neetruSwapInner;
364
+ if (u === "__neetruGetInner") return n.__neetruGetInner;
365
+ if (u === "__neetruSetReLease") return n.__neetruSetReLease;
366
+ if (u === "query") return s;
367
+ if (u === "connect") {
368
+ let _ = e.current;
369
+ return typeof _.connect == "function" ? a : _.connect;
370
+ }
371
+ if (u === "constructor")
356
372
  return e.current.constructor;
357
- let d = e.current, u = Reflect.get(d, l, d);
358
- return typeof u == "function" ? u.bind(d) : u;
373
+ let p = e.current, h = Reflect.get(p, u, p);
374
+ return typeof h == "function" ? h.bind(p) : h;
359
375
  }
360
376
  });
361
377
  }
362
- var ae, le = S(() => {
378
+ var ae, qt, le = S(() => {
363
379
  ae = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
380
+ qt = /* @__PURE__ */ new Set(["28P01", "28000"]);
364
381
  });
365
382
 
366
383
  // src/db/sql/lease.ts
367
- function At(r, e) {
384
+ function Wt(r, e) {
368
385
  return r ? r.leaseId !== e.leaseId || r.credentialVersion !== e.credentialVersion || r.host !== e.host || r.port !== e.port || r.dbName !== e.dbName || r.user !== e.user || r.password !== e.password || r.sslca !== e.sslca || r.clientCert !== e.clientCert || r.clientKey !== e.clientKey : true;
369
386
  }
370
- function Nt(r) {
371
- if (r instanceof p) return r;
387
+ function $t(r) {
388
+ if (r instanceof f) return r;
372
389
  let e = r instanceof Error ? r.message : String(r), t = r instanceof Error ? r.code : void 0;
373
- return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new p(
390
+ return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new f(
374
391
  "db_unavailable",
375
392
  `Pool connection failed (${t}): ${e}`
376
- ) : e.includes("statement timeout") || e.includes("lock timeout") ? new p("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new p("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new p("db_permission_denied", `Permission denied: ${e}`) : new p("db_unavailable", `Database error: ${e}`);
393
+ ) : e.includes("statement timeout") || e.includes("lock timeout") ? new f("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new f("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new f("db_permission_denied", `Permission denied: ${e}`) : new f("db_unavailable", `Database error: ${e}`);
377
394
  }
378
- var xt, M, $, Ue = S(() => {
395
+ var Ut, M, $, $e = S(() => {
379
396
  I();
380
397
  le();
381
- xt = 0.8, M = 3e4, $ = class {
398
+ Ut = 0.8, M = 3e4, $ = class {
382
399
  /**
383
400
  * Lease atual. `null` no modo LAZY antes da 1ª query (o 1º lease é adiado —
384
401
  * ver `_ensureInitialLease`). Após a 1ª aquisição, sempre não-nulo.
@@ -418,7 +435,7 @@ var xt, M, $, Ue = S(() => {
418
435
  isolationLevel: t.isolationLevel
419
436
  }) : await this._orm.transaction(e);
420
437
  } catch (n) {
421
- throw Nt(n);
438
+ throw $t(n);
422
439
  }
423
440
  }
424
441
  async close() {
@@ -441,7 +458,7 @@ var xt, M, $, Ue = S(() => {
441
458
  if (!Number.isFinite(e)) return M;
442
459
  let t = this._deps.now(), n = e - t;
443
460
  if (n <= 0) return M;
444
- let o = n * (1 - xt);
461
+ let o = n * (1 - Ut);
445
462
  return Math.max(M, Math.round(o));
446
463
  }
447
464
  _scheduleRenewal() {
@@ -470,7 +487,7 @@ var xt, M, $, Ue = S(() => {
470
487
  this._renewalTimer = setTimeout(() => {
471
488
  this._doRenew();
472
489
  }, M), console.warn(
473
- `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${M}ms (cert TLS ef\xEAmero do servidor expira ~15min ap\xF3s o \xFAltimo swap):`,
490
+ `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${M}ms (o cert de cliente mTLS do lease expira ~15min ap\xF3s o \xFAltimo swap):`,
474
491
  t instanceof Error ? t.message : t
475
492
  );
476
493
  return;
@@ -482,10 +499,13 @@ var xt, M, $, Ue = S(() => {
482
499
  /**
483
500
  * Recuperação REATIVA: chamado pelo wrapper resiliente (`resilient-pool.ts`)
484
501
  * quando uma query plana falha num erro de ESTABELECIMENTO de conexão (cert
485
- * TLS efêmero do servidor expirado no meio de uma request, ou timer de
486
- * renovação que não disparou). Emite um lease NOVO e faz o swap do pool interno
487
- * do wrapper com
488
- * o certificado fresco; o wrapper então re-tenta a query 1x no pool novo.
502
+ * TLS de cliente mTLS do lease expirado no meio de uma request, ou timer de
503
+ * renovação que não disparou) ou de AUTENTICAÇÃO (senha rotacionada por
504
+ * `rotate-credentials` antes do próximo renew — SQLSTATE 28P01/28000, ou o
505
+ * 08P01+SASL do PgBouncer; também no `connect()` de uma transação). Emite um
506
+ * lease NOVO e faz o swap do pool interno do wrapper com a credencial e o
507
+ * certificado frescos (o pool velho é drenado com `end()`); o wrapper então
508
+ * re-tenta a operação 1x no pool novo.
489
509
  *
490
510
  * Vai DIRETO ao lease novo (sem `leaseId`) — a conexão falhou porque o
491
511
  * certificado do lease atual está ruim, então `renew` (que depende do lease
@@ -501,7 +521,7 @@ var xt, M, $, Ue = S(() => {
501
521
  */
502
522
  async _reactiveReLease() {
503
523
  if (this._closed)
504
- throw new p(
524
+ throw new f(
505
525
  "db_unavailable",
506
526
  "SqlLeaseManager foi fechado \u2014 re-lease reativo abortado."
507
527
  );
@@ -538,7 +558,7 @@ var xt, M, $, Ue = S(() => {
538
558
  */
539
559
  async _ensureInitialLease() {
540
560
  if (this._closed)
541
- throw new p(
561
+ throw new f(
542
562
  "db_unavailable",
543
563
  "SqlLeaseManager foi fechado \u2014 aquisi\xE7\xE3o de lease inicial abortada."
544
564
  );
@@ -550,16 +570,16 @@ var xt, M, $, Ue = S(() => {
550
570
  try {
551
571
  t = this._deps.database !== void 0 ? await this._deps.fetchLease({ database: this._deps.database }) : await this._deps.fetchLease();
552
572
  } catch (o) {
553
- if (o instanceof p) throw o;
573
+ if (o instanceof f) throw o;
554
574
  let i = o instanceof Error ? o.message : String(o);
555
- throw new p("db_unavailable", `Falha ao obter lease inicial: ${i}`);
575
+ throw new f("db_unavailable", `Falha ao obter lease inicial: ${i}`);
556
576
  }
557
577
  let n;
558
578
  try {
559
579
  n = this._deps.createPool(t);
560
580
  } catch (o) {
561
581
  let i = o instanceof Error ? o.message : String(o);
562
- throw new p("db_unavailable", `Falha ao abrir pool: ${i}`);
582
+ throw new f("db_unavailable", `Falha ao abrir pool: ${i}`);
563
583
  }
564
584
  return J(this._pool) ? this._pool.__neetruSwapInner(n).end().catch(() => {
565
585
  }) : this._pool = n, this._lease = t, this._scheduleRenewal(), n;
@@ -577,7 +597,7 @@ var xt, M, $, Ue = S(() => {
577
597
  * Exposto como método protegido para testes.
578
598
  */
579
599
  async _swapPool(e) {
580
- if (!At(this._lease, e)) {
600
+ if (!Wt(this._lease, e)) {
581
601
  this._lease = e;
582
602
  return;
583
603
  }
@@ -595,7 +615,7 @@ var xt, M, $, Ue = S(() => {
595
615
  // ─── Helpers ───────────────────────────────────────────────────────────────
596
616
  _assertOpen() {
597
617
  if (this._closed)
598
- throw new p(
618
+ throw new f(
599
619
  "db_unavailable",
600
620
  "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
601
621
  );
@@ -604,29 +624,29 @@ var xt, M, $, Ue = S(() => {
604
624
  });
605
625
 
606
626
  // src/db/sql/sql-client.ts
607
- var Ke = {};
608
- me(Ke, {
609
- DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => Qe,
610
- DEFAULT_POOL_IDLE_MS: () => je,
611
- DEFAULT_POOL_MAX: () => Ve,
612
- LEASE_ENDPOINT: () => We,
613
- LEASE_RENEW_ENDPOINT: () => $e,
614
- createDrizzleHandle: () => Wt,
615
- createHttpLeaseFetcher: () => Be,
616
- createPgPool: () => Ut,
617
- createSqlClientFromConfig: () => Bt,
618
- createSqlClientWithDeps: () => ze,
627
+ var Ge = {};
628
+ me(Ge, {
629
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => Ke,
630
+ DEFAULT_POOL_IDLE_MS: () => ze,
631
+ DEFAULT_POOL_MAX: () => Qe,
632
+ LEASE_ENDPOINT: () => Be,
633
+ LEASE_RENEW_ENDPOINT: () => Ve,
634
+ createDrizzleHandle: () => Qt,
635
+ createHttpLeaseFetcher: () => je,
636
+ createPgPool: () => jt,
637
+ createSqlClientFromConfig: () => Kt,
638
+ createSqlClientWithDeps: () => He,
619
639
  resolvePoolTuning: () => ue
620
640
  });
621
- function qt(r) {
641
+ function Bt(r) {
622
642
  return r === "workspace" ? "staging" : r === "prod" ? "production" : "dev-local";
623
643
  }
624
- function Be(r) {
644
+ function je(r) {
625
645
  return async (e) => {
626
- let { httpRequest: t } = await Promise.resolve().then(() => (W(), U)), n = !!e?.leaseId, o = n ? $e : We, i;
646
+ let { httpRequest: t } = await Promise.resolve().then(() => (W(), U)), n = !!e?.leaseId, o = n ? Ve : Be, i;
627
647
  n ? i = { leaseId: e.leaseId } : (i = {
628
648
  productId: r.productId ?? "",
629
- environment: qt(r.env ?? "prod")
649
+ environment: Bt(r.env ?? "prod")
630
650
  }, e?.database !== void 0 && (i.database = e.database));
631
651
  let s;
632
652
  try {
@@ -639,35 +659,35 @@ function Be(r) {
639
659
  retries: 2
640
660
  });
641
661
  } catch (a) {
642
- let c = n ? "renovar" : "obter", l = a instanceof Error ? a.message : String(a), d = a instanceof g ? a.reason : void 0;
662
+ let c = n ? "renovar" : "obter", l = a instanceof Error ? a.message : String(a), d = a instanceof b ? a.reason : void 0;
643
663
  if (d === "suspended" || d === "archived" || d === "revoked") {
644
664
  let u = d === "suspended" ? "ambiente suspenso \u2014 a m\xE1quina que o servia parou; ser\xE1 religado quando o ambiente voltar" : d === "archived" ? "ambiente arquivado \u2014 este banco foi arquivado e n\xE3o aceita mais conex\xF5es" : "lease revogado \u2014 as credenciais deste ambiente foram revogadas pelo Core";
645
- throw new p(
665
+ throw new f(
646
666
  "db_suspended",
647
667
  `Falha ao ${c} lease SQL: ${u} (reason=${d}).`
648
668
  );
649
669
  }
650
- throw new p(
670
+ throw new f(
651
671
  "db_unavailable",
652
672
  `Falha ao ${c} lease SQL: ${l}`
653
673
  );
654
674
  }
655
- return Ft(s);
675
+ return Vt(s);
656
676
  };
657
677
  }
658
- function Ft(r) {
678
+ function Vt(r) {
659
679
  if (!r || typeof r != "object")
660
- throw new p("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
680
+ throw new f("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
661
681
  let t = r.lease;
662
682
  if (!t || typeof t != "object")
663
- throw new p(
683
+ throw new f(
664
684
  "db_unavailable",
665
685
  'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
666
686
  );
667
687
  let n = t;
668
688
  function o(i, s) {
669
689
  if (typeof n[i] !== s)
670
- throw new p(
690
+ throw new f(
671
691
  "db_unavailable",
672
692
  `Campo obrigat\xF3rio "${i}" ausente ou tipo inv\xE1lido na resposta de lease.`
673
693
  );
@@ -697,12 +717,12 @@ function ue() {
697
717
  return {
698
718
  // Teto 100: bem abaixo do `max_client_conn = 500` do PgBouncer, com folga
699
719
  // para múltiplas instâncias do app dividirem o mesmo front-door.
700
- max: de("NEETRU_DB_POOL_MAX", Ve, 1, 100),
720
+ max: de("NEETRU_DB_POOL_MAX", Qe, 1, 100),
701
721
  // Teto 15min = janela do cert; piso 1s.
702
- idleTimeoutMillis: de("NEETRU_DB_POOL_IDLE_MS", je, 1e3, 9e5),
722
+ idleTimeoutMillis: de("NEETRU_DB_POOL_IDLE_MS", ze, 1e3, 9e5),
703
723
  connectionTimeoutMillis: de(
704
724
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
705
- Qe,
725
+ Ke,
706
726
  1e3,
707
727
  12e4
708
728
  ),
@@ -710,7 +730,7 @@ function ue() {
710
730
  keepAliveInitialDelayMillis: 1e4
711
731
  };
712
732
  }
713
- async function Ut(r) {
733
+ async function jt(r) {
714
734
  let { Pool: e } = await import(
715
735
  /* webpackIgnore: true */
716
736
  'pg'
@@ -730,14 +750,14 @@ async function Ut(r) {
730
750
  ...ue()
731
751
  });
732
752
  }
733
- async function Wt(r, e) {
753
+ async function Qt(r, e) {
734
754
  let { drizzle: t } = await import(
735
755
  /* webpackIgnore: true */
736
756
  'drizzle-orm/node-postgres'
737
757
  );
738
758
  return t(r, { schema: e });
739
759
  }
740
- function $t(r, e) {
760
+ function zt(r, e) {
741
761
  let t = null, n = null, o = () => t ? Promise.resolve(t) : (n || (n = e().then((s) => (t = s, n = null, s)).catch((s) => {
742
762
  throw n = null, s;
743
763
  })), n), i = {
@@ -753,37 +773,37 @@ function $t(r, e) {
753
773
  };
754
774
  return r && Object.setPrototypeOf(i, r), i;
755
775
  }
756
- async function ze(r, e) {
776
+ async function He(r, e) {
757
777
  let t = e?.database !== void 0 ? { ...r, database: e.database } : r;
758
778
  if (t.lazy) {
759
- let c = null, l = $t(t.poolPrototype ?? null, () => {
779
+ let c = null, l = zt(t.poolPrototype ?? null, () => {
760
780
  if (!c)
761
- throw new p("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
781
+ throw new f("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
762
782
  return c._ensureInitialLease();
763
783
  }), d = ce(l), u;
764
784
  try {
765
785
  u = t.createDrizzle(d, t.schema);
766
786
  } catch (h) {
767
- let v = h instanceof Error ? h.message : String(h);
768
- throw new p("db_unavailable", `Falha ao criar handle Drizzle: ${v}`);
787
+ let _ = h instanceof Error ? h.message : String(h);
788
+ throw new f("db_unavailable", `Falha ao criar handle Drizzle: ${_}`);
769
789
  }
770
- let f = new $(null, d, u, t);
771
- return c = f, d.__neetruSetReLease(() => f._reactiveReLease()), f;
790
+ let p = new $(null, d, u, t);
791
+ return c = p, d.__neetruSetReLease(() => p._reactiveReLease()), p;
772
792
  }
773
793
  let n;
774
794
  try {
775
795
  e?.database !== void 0 ? n = await t.fetchLease({ database: e.database }) : n = await t.fetchLease();
776
796
  } catch (c) {
777
- if (c instanceof p) throw c;
797
+ if (c instanceof f) throw c;
778
798
  let l = c instanceof Error ? c.message : String(c);
779
- throw new p("db_unavailable", `Falha ao obter lease inicial: ${l}`);
799
+ throw new f("db_unavailable", `Falha ao obter lease inicial: ${l}`);
780
800
  }
781
801
  let o;
782
802
  try {
783
803
  o = t.createPool(n);
784
804
  } catch (c) {
785
805
  let l = c instanceof Error ? c.message : String(c);
786
- throw new p("db_unavailable", `Falha ao abrir pool: ${l}`);
806
+ throw new f("db_unavailable", `Falha ao abrir pool: ${l}`);
787
807
  }
788
808
  let i = ce(o), s;
789
809
  try {
@@ -792,13 +812,13 @@ async function ze(r, e) {
792
812
  await o.end().catch(() => {
793
813
  });
794
814
  let l = c instanceof Error ? c.message : String(c);
795
- throw new p("db_unavailable", `Falha ao criar handle Drizzle: ${l}`);
815
+ throw new f("db_unavailable", `Falha ao criar handle Drizzle: ${l}`);
796
816
  }
797
817
  let a = new $(n, i, s, t);
798
818
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
799
819
  }
800
- async function Bt(r, e, t) {
801
- let n = Be(r), o, i;
820
+ async function Kt(r, e, t) {
821
+ let n = je(r), o, i;
802
822
  try {
803
823
  o = await import(
804
824
  /* webpackIgnore: true */
@@ -808,13 +828,13 @@ async function Bt(r, e, t) {
808
828
  'drizzle-orm/node-postgres'
809
829
  );
810
830
  } catch (l) {
811
- throw new p(
831
+ throw new f(
812
832
  "db_unavailable",
813
833
  `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${l.message})`
814
834
  );
815
835
  }
816
836
  let s = o.Pool ?? o.default?.Pool;
817
- return ze(
837
+ return He(
818
838
  {
819
839
  fetchLease: n,
820
840
  createPool: (l) => {
@@ -849,24 +869,37 @@ async function Bt(r, e, t) {
849
869
  t
850
870
  );
851
871
  }
852
- var We, $e, Ve, je, Qe, He = S(() => {
872
+ var Be, Ve, Qe, ze, Ke, Xe = S(() => {
853
873
  I();
854
874
  x();
855
- Ue();
875
+ $e();
856
876
  le();
857
- We = "/api/sdk/v1/db/lease", $e = "/api/sdk/v1/db/lease/renew";
858
- Ve = 10, je = 6e4, Qe = 1e4;
877
+ Be = "/api/sdk/v1/db/lease", Ve = "/api/sdk/v1/db/lease/renew";
878
+ Qe = 10, ze = 6e4, Ke = 1e4;
859
879
  });
860
880
 
861
881
  // src/db/client-db.ts
862
882
  I();
863
883
 
864
- // src/db/offline/query-engine.ts
884
+ // src/runtime-env.ts
885
+ function tt() {
886
+ try {
887
+ if (typeof process < "u" && process.env)
888
+ return process.env.NODE_ENV === "production";
889
+ } catch {
890
+ }
891
+ return false;
892
+ }
865
893
  function _e(r) {
894
+ return r === "dev" && !tt();
895
+ }
896
+
897
+ // src/db/offline/query-engine.ts
898
+ function ye(r) {
866
899
  return r == null ? 0 : typeof r == "number" ? 1 : typeof r == "string" ? 2 : typeof r == "boolean" ? 3 : 4;
867
900
  }
868
901
  function A(r, e) {
869
- let t = _e(r), n = _e(e);
902
+ let t = ye(r), n = ye(e);
870
903
  if (t !== n) return t - n;
871
904
  if (r == null) return 0;
872
905
  if (typeof r == "number" && typeof e == "number") return r - e;
@@ -884,7 +917,7 @@ function Z(r, e) {
884
917
  }
885
918
  return n;
886
919
  }
887
- function Ze(r, e) {
920
+ function nt(r, e) {
888
921
  let t = Z(r, e.field);
889
922
  if (t === void 0) return false;
890
923
  let { op: n, value: o } = e;
@@ -915,10 +948,10 @@ function Ze(r, e) {
915
948
  );
916
949
  }
917
950
  }
918
- function et(r, e) {
919
- return e.every((t) => Ze(r, t));
951
+ function rt(r, e) {
952
+ return e.every((t) => nt(r, t));
920
953
  }
921
- function tt(r) {
954
+ function ot(r) {
922
955
  return (e, t) => {
923
956
  if (r) {
924
957
  let n = Z(e.data, r.field), o = Z(t.data, r.field), i = A(n, o);
@@ -928,7 +961,7 @@ function tt(r) {
928
961
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
929
962
  };
930
963
  }
931
- function nt(r, e) {
964
+ function it(r, e) {
932
965
  let t = r.findIndex((n) => n.id === e.docId);
933
966
  return t === -1 ? r : e.type === "startAfter" ? r.slice(t + 1) : r.slice(0, t);
934
967
  }
@@ -946,9 +979,9 @@ var P = class r {
946
979
  evaluate(e, t) {
947
980
  let n = e.filter((d) => !d.meta.deleted), o = t.where ?? [];
948
981
  o.length > 0 && (n = n.filter(
949
- (d) => et(d.data, o)
982
+ (d) => rt(d.data, o)
950
983
  ));
951
- let i = tt(t.orderBy), s = [...n].sort(i), a = t.cursor ? nt(s, t.cursor) : s, c = Math.min(t.limit ?? 20, 500);
984
+ let i = ot(t.orderBy), s = [...n].sort(i), a = t.cursor ? it(s, t.cursor) : s, c = Math.min(t.limit ?? 20, 500);
952
985
  return {
953
986
  docs: a.slice(0, c).map((d) => ({ id: d.id, data: d.data })),
954
987
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
@@ -968,7 +1001,7 @@ var P = class r {
968
1001
  };
969
1002
 
970
1003
  // src/db/offline/local-store.ts
971
- var ot = 1, T = "documents", R = "mutations", N = "query_cache", V = "sync_meta", E = "conflict_log", j = class {
1004
+ var at = 1, T = "documents", R = "mutations", N = "query_cache", V = "sync_meta", E = "conflict_log", j = class {
972
1005
  db = null;
973
1006
  dbName;
974
1007
  constructor(e) {
@@ -980,7 +1013,7 @@ var ot = 1, T = "documents", R = "mutations", N = "query_cache", V = "sync_meta"
980
1013
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
981
1014
  */
982
1015
  async open() {
983
- this.db === null && (this.db = await openDB(this.dbName, ot, {
1016
+ this.db === null && (this.db = await openDB(this.dbName, at, {
984
1017
  upgrade(e) {
985
1018
  if (!e.objectStoreNames.contains(T)) {
986
1019
  let t = e.createObjectStore(T, {
@@ -1390,7 +1423,7 @@ var z = class {
1390
1423
  async enqueue(e) {
1391
1424
  let { collection: t, op: n, payload: o, baseVersion: i, batchId: s, upsert: a } = e, c = e.docId ?? (n === "add" ? ee() : "");
1392
1425
  await this.syncSeq();
1393
- let d = (await this.store.listMutations({ collection: t, docId: c })).filter((h) => h.status === "queued").sort((h, v) => v.seq - h.seq)[0];
1426
+ let d = (await this.store.listMutations({ collection: t, docId: c })).filter((h) => h.status === "queued").sort((h, _) => _.seq - h.seq)[0];
1394
1427
  if (d !== void 0) {
1395
1428
  let h = this.tryCoalesce(d, n, o, s, a);
1396
1429
  if (h !== null) {
@@ -1409,11 +1442,11 @@ var z = class {
1409
1442
  status: "queued",
1410
1443
  batchId: s
1411
1444
  };
1412
- let { coalesced: v } = h;
1413
- return await this.store.putMutation(v), v;
1445
+ let { coalesced: _ } = h;
1446
+ return await this.store.putMutation(_), _;
1414
1447
  }
1415
1448
  }
1416
- let f = {
1449
+ let p = {
1417
1450
  seq: this.nextSeq(),
1418
1451
  mutationId: ee(),
1419
1452
  collection: t,
@@ -1429,7 +1462,7 @@ var z = class {
1429
1462
  // bug_0273e4dd: só persiste o flag quando verdadeiro (mantém o doc limpo).
1430
1463
  ...a ? { upsert: true } : {}
1431
1464
  };
1432
- return await this.store.putMutation(f), f;
1465
+ return await this.store.putMutation(p), p;
1433
1466
  }
1434
1467
  // ─── Leitura da fila ─────────────────────────────────────────────────────────
1435
1468
  /**
@@ -1529,10 +1562,10 @@ var z = class {
1529
1562
 
1530
1563
  // src/db/field-value.ts
1531
1564
  var te = "__neetru__";
1532
- function it() {
1565
+ function ct() {
1533
1566
  return { __neetru__: "serverTimestamp" };
1534
1567
  }
1535
- function st(r) {
1568
+ function lt(r) {
1536
1569
  if (typeof r != "number" || !Number.isFinite(r))
1537
1570
  throw new TypeError(
1538
1571
  `increment(n): n deve ser um n\xFAmero finito (recebido: ${String(r)}).`
@@ -1542,19 +1575,19 @@ function st(r) {
1542
1575
  function D(r) {
1543
1576
  return typeof r == "object" && r !== null && te in r && typeof r[te] == "string";
1544
1577
  }
1545
- function ye(r) {
1578
+ function ge(r) {
1546
1579
  return D(r) && r.__neetru__ === "serverTimestamp";
1547
1580
  }
1548
- function ge(r) {
1581
+ function be(r) {
1549
1582
  return D(r) && r.__neetru__ === "increment" && typeof r.operand == "number" && Number.isFinite(r.operand);
1550
1583
  }
1551
- function at(r, e) {
1552
- return ye(r) ? Date.now() : ge(r) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + r.operand : r;
1584
+ function dt(r, e) {
1585
+ return ge(r) ? Date.now() : be(r) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + r.operand : r;
1553
1586
  }
1554
1587
  function k(r, e) {
1555
1588
  let t = false, n = {};
1556
1589
  for (let [o, i] of Object.entries(r))
1557
- D(i) ? (t = true, n[o] = at(i, e?.[o])) : n[o] = i;
1590
+ D(i) ? (t = true, n[o] = dt(i, e?.[o])) : n[o] = i;
1558
1591
  return t ? n : r;
1559
1592
  }
1560
1593
  function ne(r) {
@@ -1564,11 +1597,11 @@ function ne(r) {
1564
1597
  }
1565
1598
 
1566
1599
  // src/db/offline/sync-engine.ts
1567
- var ct = 8, lt = 1e3, dt = 300 * 1e3, re = "truncatedCollections";
1568
- function ut(r) {
1600
+ var ut = 8, pt = 1e3, ft = 300 * 1e3, re = "truncatedCollections";
1601
+ function ht(r) {
1569
1602
  return r !== null && ne(r);
1570
1603
  }
1571
- function pt(r) {
1604
+ function mt(r) {
1572
1605
  if (r === null) return null;
1573
1606
  if (!ne(r)) return r;
1574
1607
  let e = {};
@@ -1770,13 +1803,13 @@ var K = class {
1770
1803
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
1771
1804
  return;
1772
1805
  }
1773
- let l = pt(i.payload) ?? a?.data ?? {}, d = {
1806
+ let l = mt(i.payload) ?? a?.data ?? {}, d = {
1774
1807
  collection: e,
1775
1808
  id: t,
1776
1809
  data: i.op === "update" ? { ...a?.data ?? {}, ...l } : (
1777
1810
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
1778
1811
  // é a fonte de verdade até o pull; senão usa o payload literal.
1779
- ut(i.payload) ? { ...a?.data ?? {}, ...l } : l
1812
+ ht(i.payload) ? { ...a?.data ?? {}, ...l } : l
1780
1813
  ),
1781
1814
  meta: {
1782
1815
  serverVersion: n,
@@ -1929,7 +1962,7 @@ var K = class {
1929
1962
  * pending do doc no cache + registra `lastError`/dispara `onError`.
1930
1963
  */
1931
1964
  async _retryOrDeadLetter(e, t, n) {
1932
- if (e.attempts + 1 < ct) {
1965
+ if (e.attempts + 1 < ut) {
1933
1966
  await this._queue.markRetry(e.mutationId, t);
1934
1967
  return;
1935
1968
  }
@@ -1970,7 +2003,7 @@ var K = class {
1970
2003
  }
1971
2004
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
1972
2005
  _backoffDelayMs(e) {
1973
- return Math.min(lt * 2 ** (e - 1), dt);
2006
+ return Math.min(pt * 2 ** (e - 1), ft);
1974
2007
  }
1975
2008
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
1976
2009
  /**
@@ -2222,7 +2255,7 @@ var K = class {
2222
2255
  };
2223
2256
 
2224
2257
  // src/db/offline/conflict-resolver.ts
2225
- function be(r, e) {
2258
+ function ve(r, e) {
2226
2259
  return e === null ? false : r === null ? true : e > r;
2227
2260
  }
2228
2261
  var H = class r {
@@ -2259,7 +2292,7 @@ var H = class r {
2259
2292
  resolvedData: t.data,
2260
2293
  conflictRecord: null
2261
2294
  };
2262
- if (!be(
2295
+ if (!ve(
2263
2296
  e.meta.updatedAtServer,
2264
2297
  t.meta.updatedAtServer
2265
2298
  ))
@@ -2306,7 +2339,7 @@ var H = class r {
2306
2339
  let i = t.data;
2307
2340
  if (e === null)
2308
2341
  return { outcome: "no_conflict", resolvedData: { ...i, ...n.payload ?? {} }, conflictRecord: null };
2309
- if (!be(
2342
+ if (!ve(
2310
2343
  e.meta.updatedAtServer,
2311
2344
  t.meta.updatedAtServer
2312
2345
  ))
@@ -2384,7 +2417,7 @@ var H = class r {
2384
2417
  };
2385
2418
 
2386
2419
  // src/db/offline/change-bus.ts
2387
- function ft(r) {
2420
+ function _t(r) {
2388
2421
  return `${r.collection}::${r.doc.id}`;
2389
2422
  }
2390
2423
  var G = class {
@@ -2432,7 +2465,7 @@ var G = class {
2432
2465
  if (e.length === 0) return;
2433
2466
  let t = /* @__PURE__ */ new Map();
2434
2467
  for (let i of e)
2435
- t.set(ft(i), i);
2468
+ t.set(_t(i), i);
2436
2469
  let n = Array.from(t.values()), o = /* @__PURE__ */ new Map();
2437
2470
  for (let i of n)
2438
2471
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
@@ -2751,25 +2784,25 @@ var q = class {
2751
2784
 
2752
2785
  // src/db/collection-ref.ts
2753
2786
  I();
2754
- function ht() {
2787
+ function yt() {
2755
2788
  return typeof indexedDB > "u" || typeof window > "u";
2756
2789
  }
2757
- var ve = /^[a-z0-9][a-z0-9_-]{0,62}$/;
2758
- function mt(r) {
2759
- if (!ve.test(r))
2760
- throw new p(
2790
+ var we = /^[a-z0-9][a-z0-9_-]{0,62}$/;
2791
+ function gt(r) {
2792
+ if (!we.test(r))
2793
+ throw new f(
2761
2794
  "db_invalid_query",
2762
- `Nome de cole\xE7\xE3o inv\xE1lido: "${r}". Deve seguir o padr\xE3o ${ve}.`
2795
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${r}". Deve seguir o padr\xE3o ${we}.`
2763
2796
  );
2764
2797
  }
2765
2798
  function L(r, e = "id") {
2766
2799
  if (!r || typeof r != "string" || r.trim() === "")
2767
- throw new p(
2800
+ throw new f(
2768
2801
  "db_invalid_query",
2769
2802
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
2770
2803
  );
2771
2804
  }
2772
- function _t(r) {
2805
+ function bt(r) {
2773
2806
  let e = {};
2774
2807
  if (r?.where && (e.where = r.where.map((t) => ({
2775
2808
  field: t.field,
@@ -2786,7 +2819,7 @@ function _t(r) {
2786
2819
  }
2787
2820
  return e;
2788
2821
  }
2789
- function yt(r, e) {
2822
+ function vt(r, e) {
2790
2823
  if (r.length < e) return null;
2791
2824
  let t = r[r.length - 1];
2792
2825
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
@@ -2833,11 +2866,11 @@ var oe = class {
2833
2866
  }
2834
2867
  /** Constrói um DbListResult para a coleção com query opcional. */
2835
2868
  async _buildListResult(e) {
2836
- let t = _t(e), n = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), c = yt(o.docs, n), l = await this._store.getMeta(re), d = Array.isArray(l) && l.includes(this._collection), u = !s || a.status === "offline" || d, f = i || a.lastSyncedAt === null || u;
2869
+ let t = bt(e), n = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), c = vt(o.docs, n), l = await this._store.getMeta(re), d = Array.isArray(l) && l.includes(this._collection), u = !s || a.status === "offline" || d, p = i || a.lastSyncedAt === null || u;
2837
2870
  return {
2838
2871
  docs: o.docs.map((h) => ({ id: h.id, data: h.data })),
2839
2872
  nextCursor: c,
2840
- fromCache: f,
2873
+ fromCache: p,
2841
2874
  stale: u,
2842
2875
  hasPendingWrites: i,
2843
2876
  changes: [],
@@ -3011,7 +3044,7 @@ var oe = class {
3011
3044
  doc: { id: s, data: l }
3012
3045
  });
3013
3046
  } else if (o.kind === "update") {
3014
- let s = o.id, a = o.data, c = await this._store.getDoc(i, s), l = c?.meta.deleted ? void 0 : c?.data, d = k(a, l), u = { ...c?.data ?? {}, ...d }, f = await this._queue.enqueue({
3047
+ let s = o.id, a = o.data, c = await this._store.getDoc(i, s), l = c?.meta.deleted ? void 0 : c?.data, d = k(a, l), u = { ...c?.data ?? {}, ...d }, p = await this._queue.enqueue({
3015
3048
  collection: i,
3016
3049
  docId: s,
3017
3050
  op: "update",
@@ -3032,7 +3065,7 @@ var oe = class {
3032
3065
  state: "pending",
3033
3066
  pendingMutationIds: [
3034
3067
  ...c?.meta.pendingMutationIds ?? [],
3035
- f.mutationId
3068
+ p.mutationId
3036
3069
  ],
3037
3070
  deleted: false,
3038
3071
  ownerId: c?.meta.ownerId ?? null
@@ -3176,7 +3209,7 @@ var oe = class {
3176
3209
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3177
3210
  }
3178
3211
  collection(e) {
3179
- return mt(e), new oe(
3212
+ return gt(e), new oe(
3180
3213
  e,
3181
3214
  this._store,
3182
3215
  this._queue,
@@ -3205,8 +3238,8 @@ var oe = class {
3205
3238
  return this._engine.onError(e);
3206
3239
  }
3207
3240
  };
3208
- async function we(r) {
3209
- let e = ht() ? new Q() : new j(r.dbName);
3241
+ async function Se(r) {
3242
+ let e = yt() ? new Q() : new j(r.dbName);
3210
3243
  await e.open();
3211
3244
  let t = new z(e), n = new H(), o = new G(), i = new X({
3212
3245
  // Se startOnline=false, injeta um navigator falso
@@ -3241,9 +3274,9 @@ async function we(r) {
3241
3274
  }
3242
3275
 
3243
3276
  // src/db/realtime/realtime-client.ts
3244
- var gt = 0;
3245
- function Se() {
3246
- return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++gt}-${Math.random().toString(36).slice(2)}`;
3277
+ var wt = 0;
3278
+ function Te() {
3279
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++wt}-${Math.random().toString(36).slice(2)}`;
3247
3280
  }
3248
3281
  var F = class {
3249
3282
  // ── configuração ──────────────────────────────────────────────────────────
@@ -3283,7 +3316,7 @@ var F = class {
3283
3316
  _pendingFrames = [];
3284
3317
  // ── construtor ────────────────────────────────────────────────────────────
3285
3318
  constructor(e) {
3286
- this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? bt, 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();
3319
+ this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? St, 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();
3287
3320
  }
3288
3321
  // ── API pública ───────────────────────────────────────────────────────────
3289
3322
  /**
@@ -3297,8 +3330,8 @@ var F = class {
3297
3330
  */
3298
3331
  subscribe(e, t, n) {
3299
3332
  if (this._closed)
3300
- return Se();
3301
- let o = Se();
3333
+ return Te();
3334
+ let o = Te();
3302
3335
  this._subscriptions.set(o, {
3303
3336
  subscriptionId: o,
3304
3337
  collection: e,
@@ -3562,7 +3595,7 @@ var F = class {
3562
3595
  _detachHandlers(e) {
3563
3596
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
3564
3597
  }
3565
- }, bt = (r) => {
3598
+ }, St = (r) => {
3566
3599
  if (typeof WebSocket > "u")
3567
3600
  throw new Error(
3568
3601
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -3572,15 +3605,15 @@ var F = class {
3572
3605
 
3573
3606
  // src/db/client-db.ts
3574
3607
  I();
3575
- var Vt = (r) => `/api/sdk/v1/datastore/${encodeURIComponent(r)}`, Y = (r, e) => `/api/sdk/v1/datastore/${encodeURIComponent(r)}/${encodeURIComponent(e)}`, Ge = 200;
3576
- function jt(r, e, t) {
3577
- return e._transport ? e._transport : r === "firestore" && e.firestoreTransport ? e.firestoreTransport : r === "nosql-vm" && e.realtimeGatewayUrl ? Qt(e.realtimeGatewayUrl, t, e) : Xe(t);
3608
+ var Ht = (r) => `/api/sdk/v1/datastore/${encodeURIComponent(r)}`, Y = (r, e) => `/api/sdk/v1/datastore/${encodeURIComponent(r)}/${encodeURIComponent(e)}`, Je = 200;
3609
+ function Gt(r, e, t) {
3610
+ return e._transport ? e._transport : r === "firestore" && e.firestoreTransport ? e.firestoreTransport : r === "nosql-vm" && e.realtimeGatewayUrl ? Xt(e.realtimeGatewayUrl, t, e) : Ye(t);
3578
3611
  }
3579
- function Xe(r) {
3612
+ function Ye(r) {
3580
3613
  return {
3581
3614
  async pushMutations(e) {
3582
3615
  if (!r)
3583
- throw new p(
3616
+ throw new f(
3584
3617
  "db_unavailable",
3585
3618
  "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
3586
3619
  );
@@ -3626,18 +3659,18 @@ function Xe(r) {
3626
3659
  } catch (a) {
3627
3660
  let c = a instanceof Error ? a.message : String(a), l = a?.code, d = a?.status;
3628
3661
  if (l === "forbidden" || l === "unauthorized" || l === "not_found" || l === "conflict" || l === "validation_failed" || typeof d == "number" && d >= 400 && d < 500 && d !== 408 && d !== 429) {
3629
- let f = l === "forbidden" || l === "unauthorized" ? "rejected_permission" : "rejected_validation";
3662
+ let p = l === "forbidden" || l === "unauthorized" ? "rejected_permission" : "rejected_validation";
3630
3663
  n.push({
3631
3664
  mutationId: s.mutationId,
3632
3665
  outcome: "rejected",
3633
- reason: f,
3666
+ reason: p,
3634
3667
  serverVersion: null,
3635
3668
  serverData: null
3636
3669
  });
3637
3670
  continue;
3638
3671
  }
3639
3672
  if (n.length === 0)
3640
- throw new p("db_unavailable", `pushMutations falhou: ${c}`);
3673
+ throw new f("db_unavailable", `pushMutations falhou: ${c}`);
3641
3674
  break;
3642
3675
  }
3643
3676
  return { results: n };
@@ -3654,7 +3687,7 @@ function Xe(r) {
3654
3687
  try {
3655
3688
  l = await t(r, {
3656
3689
  method: "GET",
3657
- path: Vt(c),
3690
+ path: Ht(c),
3658
3691
  requireAuth: !0,
3659
3692
  retries: 2,
3660
3693
  headers: o,
@@ -3662,37 +3695,37 @@ function Xe(r) {
3662
3695
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
3663
3696
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
3664
3697
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
3665
- query: { limit: Ge }
3698
+ query: { limit: Je }
3666
3699
  });
3667
- } catch (f) {
3668
- let h = f instanceof Error ? f.message : String(f);
3669
- throw new p(
3700
+ } catch (p) {
3701
+ let h = p instanceof Error ? p.message : String(p);
3702
+ throw new f(
3670
3703
  "db_unavailable",
3671
3704
  `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${c}": ${h}`
3672
3705
  );
3673
3706
  }
3674
3707
  let d = l, u = Array.isArray(d?.items) ? d.items : [];
3675
- u.length >= Ge && a.push(c);
3676
- for (let f of u) {
3677
- if (!f || typeof f != "object") continue;
3678
- let h = f, v = typeof h.id == "string" ? h.id : null;
3679
- if (!v) continue;
3680
- let { id: _, ...B } = h, y = i, b = B._updatedAt;
3681
- if (typeof b == "number")
3682
- y = b;
3683
- else if (b !== null && typeof b == "object" && typeof b._seconds == "number")
3684
- y = b._seconds * 1e3;
3685
- else if (typeof b == "string") {
3686
- let C = Date.parse(b);
3687
- Number.isNaN(C) || (y = C);
3708
+ u.length >= Je && a.push(c);
3709
+ for (let p of u) {
3710
+ if (!p || typeof p != "object") continue;
3711
+ let h = p, _ = typeof h.id == "string" ? h.id : null;
3712
+ if (!_) continue;
3713
+ let { id: y, ...B } = h, g = i, v = B._updatedAt;
3714
+ if (typeof v == "number")
3715
+ g = v;
3716
+ else if (v !== null && typeof v == "object" && typeof v._seconds == "number")
3717
+ g = v._seconds * 1e3;
3718
+ else if (typeof v == "string") {
3719
+ let C = Date.parse(v);
3720
+ Number.isNaN(C) || (g = C);
3688
3721
  }
3689
- let w = `rest_${v}_${y}`;
3722
+ let w = `rest_${_}_${g}`;
3690
3723
  s.push({
3691
3724
  collection: c,
3692
- id: v,
3725
+ id: _,
3693
3726
  data: B,
3694
3727
  serverVersion: w,
3695
- serverTimestamp: y,
3728
+ serverTimestamp: g,
3696
3729
  deleted: false
3697
3730
  });
3698
3731
  }
@@ -3701,10 +3734,10 @@ function Xe(r) {
3701
3734
  }
3702
3735
  };
3703
3736
  }
3704
- function Qt(r, e, t) {
3705
- let n = Xe(e), o = new F({
3737
+ function Xt(r, e, t) {
3738
+ let n = Ye(e), o = new F({
3706
3739
  gatewayUrl: r,
3707
- ticketProvider: zt(e, t),
3740
+ ticketProvider: Jt(e, t),
3708
3741
  dbId: t.dbId,
3709
3742
  webSocketFactory: t._wsFactory
3710
3743
  });
@@ -3740,7 +3773,7 @@ function Qt(r, e, t) {
3740
3773
  }
3741
3774
  };
3742
3775
  }
3743
- function zt(r, e) {
3776
+ function Jt(r, e) {
3744
3777
  return async () => {
3745
3778
  let { httpRequest: t } = await Promise.resolve().then(() => (W(), U));
3746
3779
  return await t(r, {
@@ -3755,27 +3788,27 @@ function zt(r, e) {
3755
3788
  });
3756
3789
  };
3757
3790
  }
3758
- function zn(r, e, t, n) {
3791
+ function Zn(r, e, t, n) {
3759
3792
  return new F({ gatewayUrl: r, ticketProvider: e, dbId: t, webSocketFactory: n });
3760
3793
  }
3761
3794
  var pe = false;
3762
- function Kn() {
3795
+ function er() {
3763
3796
  pe = false;
3764
3797
  }
3765
- function Kt(r, e) {
3798
+ function Yt(r, e) {
3766
3799
  pe || e.dbId && r.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (pe = true, console.warn(
3767
3800
  '[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.'
3768
3801
  )));
3769
3802
  }
3770
- function Hn(r, e = {}) {
3771
- Kt(r, e);
3803
+ function tr(r, e = {}) {
3804
+ Yt(r, e);
3772
3805
  let t;
3773
3806
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
3774
3807
  '[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).'
3775
3808
  ), t = e.engine) : t = "rest";
3776
- let n = jt(t, e, r), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${r.productId ?? "sdk"}__${o}__${r.env}`, s = null, a = null;
3809
+ let n = Gt(t, e, r), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${r.productId ?? "sdk"}__${o}__${r.env}`, s = null, a = null;
3777
3810
  function c() {
3778
- return s || (s = we({
3811
+ return s || (s = Se({
3779
3812
  dbName: i,
3780
3813
  transport: n,
3781
3814
  singleTab: e.singleTab ?? r.env !== "prod"
@@ -3783,15 +3816,15 @@ function Hn(r, e = {}) {
3783
3816
  }
3784
3817
  return {
3785
3818
  collection(l) {
3786
- return a ? a.collection(l) : Ht(l, c);
3819
+ return a ? a.collection(l) : Zt(l, c);
3787
3820
  },
3788
3821
  async sql(l, d) {
3789
- if (r.env === "dev")
3790
- throw new p(
3822
+ if (_e(r.env))
3823
+ throw new f(
3791
3824
  "db_unavailable",
3792
3825
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
3793
3826
  );
3794
- return (await Promise.resolve().then(() => (He(), Ke))).createSqlClientFromConfig(r, l, d);
3827
+ return (await Promise.resolve().then(() => (Xe(), Ge))).createSqlClientFromConfig(r, l, d);
3795
3828
  },
3796
3829
  get syncState() {
3797
3830
  return a?.syncState ?? {
@@ -3804,8 +3837,8 @@ function Hn(r, e = {}) {
3804
3837
  onSyncStateChanged(l) {
3805
3838
  if (a) return a.onSyncStateChanged(l);
3806
3839
  let d = null, u = false;
3807
- return c().then((f) => {
3808
- u || (d = f.onSyncStateChanged(l));
3840
+ return c().then((p) => {
3841
+ u || (d = p.onSyncStateChanged(l));
3809
3842
  }), () => {
3810
3843
  u = true, d?.();
3811
3844
  };
@@ -3822,15 +3855,15 @@ function Hn(r, e = {}) {
3822
3855
  onError(l) {
3823
3856
  if (a) return a.onError(l);
3824
3857
  let d = null, u = false;
3825
- return c().then((f) => {
3826
- u || (d = f.onError(l));
3858
+ return c().then((p) => {
3859
+ u || (d = p.onError(l));
3827
3860
  }), () => {
3828
3861
  u = true, d?.();
3829
3862
  };
3830
3863
  }
3831
3864
  };
3832
3865
  }
3833
- function Ht(r, e) {
3866
+ function Zt(r, e) {
3834
3867
  async function t() {
3835
3868
  return (await e()).collection(r);
3836
3869
  }
@@ -3908,4 +3941,4 @@ function Ht(r, e) {
3908
3941
  };
3909
3942
  }
3910
3943
 
3911
- export { te as NEETRU_SENTINEL_KEY, p as NeetruDbError, Kn as __resetDbIdWarningForTests, Hn as createNeetruDb, Xe as createRestSyncTransport, zn as getWebSocketRealtimeClient, st as increment, D as isFieldSentinel, ge as isIncrementSentinel, ye as isServerTimestampSentinel, it as serverTimestamp };
3944
+ export { te as NEETRU_SENTINEL_KEY, f as NeetruDbError, er as __resetDbIdWarningForTests, tr as createNeetruDb, Ye as createRestSyncTransport, Zn as getWebSocketRealtimeClient, lt as increment, D as isFieldSentinel, be as isIncrementSentinel, ge as isServerTimestampSentinel, ct as serverTimestamp };