@neetru/sdk 3.6.0 → 3.7.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 (116) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/ai.cjs +254 -391
  3. package/dist/ai.d.cts +1 -1
  4. package/dist/ai.d.ts +1 -1
  5. package/dist/ai.mjs +254 -391
  6. package/dist/auth.cjs +3547 -4998
  7. package/dist/auth.d.cts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.mjs +3544 -4995
  10. package/dist/build-guard.cjs +101 -119
  11. package/dist/build-guard.mjs +91 -109
  12. package/dist/catalog.cjs +152 -224
  13. package/dist/catalog.d.cts +1 -1
  14. package/dist/catalog.d.ts +1 -1
  15. package/dist/catalog.mjs +152 -224
  16. package/dist/checkout.cjs +237 -320
  17. package/dist/checkout.d.cts +1 -1
  18. package/dist/checkout.d.ts +1 -1
  19. package/dist/checkout.mjs +236 -319
  20. package/dist/db-react.cjs +59 -87
  21. package/dist/db-react.d.cts +1 -1
  22. package/dist/db-react.d.ts +1 -1
  23. package/dist/db-react.mjs +56 -84
  24. package/dist/db.cjs +2055 -3013
  25. package/dist/db.d.cts +1 -1
  26. package/dist/db.d.ts +1 -1
  27. package/dist/db.mjs +2068 -3026
  28. package/dist/entitlements.cjs +12 -20
  29. package/dist/entitlements.d.cts +1 -1
  30. package/dist/entitlements.d.ts +1 -1
  31. package/dist/entitlements.mjs +12 -20
  32. package/dist/errors.cjs +9 -12
  33. package/dist/errors.d.cts +37 -2
  34. package/dist/errors.d.ts +37 -2
  35. package/dist/errors.mjs +8 -12
  36. package/dist/firestore-compat.cjs +241 -297
  37. package/dist/firestore-compat.d.cts +1 -1
  38. package/dist/firestore-compat.d.ts +1 -1
  39. package/dist/firestore-compat.mjs +215 -271
  40. package/dist/index.cjs +3605 -5131
  41. package/dist/index.d.cts +6 -4
  42. package/dist/index.d.ts +6 -4
  43. package/dist/index.mjs +3710 -5236
  44. package/dist/mobile.cjs +238 -342
  45. package/dist/mobile.d.cts +1 -1
  46. package/dist/mobile.d.ts +1 -1
  47. package/dist/mobile.mjs +238 -342
  48. package/dist/mocks.cjs +312 -447
  49. package/dist/mocks.d.cts +1 -1
  50. package/dist/mocks.d.ts +1 -1
  51. package/dist/mocks.mjs +306 -441
  52. package/dist/notifications.cjs +226 -314
  53. package/dist/notifications.d.cts +1 -1
  54. package/dist/notifications.d.ts +1 -1
  55. package/dist/notifications.mjs +225 -313
  56. package/dist/react.cjs +522 -693
  57. package/dist/react.d.cts +1 -1
  58. package/dist/react.d.ts +1 -1
  59. package/dist/react.mjs +512 -683
  60. package/dist/support.cjs +329 -325
  61. package/dist/support.d.cts +25 -3
  62. package/dist/support.d.ts +25 -3
  63. package/dist/support.mjs +328 -325
  64. package/dist/telemetry.cjs +197 -301
  65. package/dist/telemetry.d.cts +1 -1
  66. package/dist/telemetry.d.ts +1 -1
  67. package/dist/telemetry.mjs +197 -301
  68. package/dist/{types-Du_iioJ7.d.cts → types-Bx4kTLmk.d.cts} +26 -0
  69. package/dist/{types-BPATkXYu.d.ts → types-Dx0IrOSF.d.ts} +26 -0
  70. package/dist/usage.cjs +163 -227
  71. package/dist/usage.d.cts +1 -1
  72. package/dist/usage.d.ts +1 -1
  73. package/dist/usage.mjs +163 -227
  74. package/dist/webhooks.cjs +258 -359
  75. package/dist/webhooks.d.cts +1 -1
  76. package/dist/webhooks.d.ts +1 -1
  77. package/dist/webhooks.mjs +255 -356
  78. package/package.json +4 -3
  79. package/dist/ai.cjs.map +0 -1
  80. package/dist/ai.mjs.map +0 -1
  81. package/dist/auth.cjs.map +0 -1
  82. package/dist/auth.mjs.map +0 -1
  83. package/dist/build-guard.cjs.map +0 -1
  84. package/dist/build-guard.mjs.map +0 -1
  85. package/dist/catalog.cjs.map +0 -1
  86. package/dist/catalog.mjs.map +0 -1
  87. package/dist/checkout.cjs.map +0 -1
  88. package/dist/checkout.mjs.map +0 -1
  89. package/dist/db-react.cjs.map +0 -1
  90. package/dist/db-react.mjs.map +0 -1
  91. package/dist/db.cjs.map +0 -1
  92. package/dist/db.mjs.map +0 -1
  93. package/dist/entitlements.cjs.map +0 -1
  94. package/dist/entitlements.mjs.map +0 -1
  95. package/dist/errors.cjs.map +0 -1
  96. package/dist/errors.mjs.map +0 -1
  97. package/dist/firestore-compat.cjs.map +0 -1
  98. package/dist/firestore-compat.mjs.map +0 -1
  99. package/dist/index.cjs.map +0 -1
  100. package/dist/index.mjs.map +0 -1
  101. package/dist/mobile.cjs.map +0 -1
  102. package/dist/mobile.mjs.map +0 -1
  103. package/dist/mocks.cjs.map +0 -1
  104. package/dist/mocks.mjs.map +0 -1
  105. package/dist/notifications.cjs.map +0 -1
  106. package/dist/notifications.mjs.map +0 -1
  107. package/dist/react.cjs.map +0 -1
  108. package/dist/react.mjs.map +0 -1
  109. package/dist/support.cjs.map +0 -1
  110. package/dist/support.mjs.map +0 -1
  111. package/dist/telemetry.cjs.map +0 -1
  112. package/dist/telemetry.mjs.map +0 -1
  113. package/dist/usage.cjs.map +0 -1
  114. package/dist/usage.mjs.map +0 -1
  115. package/dist/webhooks.cjs.map +0 -1
  116. package/dist/webhooks.mjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/errors.ts
4
- var NeetruError = class _NeetruError extends Error {
4
+ var a = class e extends Error {
5
5
  code;
6
6
  status;
7
7
  requestId;
@@ -14,233 +14,184 @@ var NeetruError = class _NeetruError extends Error {
14
14
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
15
15
  */
16
16
  reason;
17
- constructor(code, message, status, requestId, reason) {
18
- super(message);
19
- this.name = "NeetruError";
20
- this.code = code;
21
- this.status = status;
22
- this.requestId = requestId;
23
- this.reason = reason;
24
- Object.setPrototypeOf(this, _NeetruError.prototype);
17
+ constructor(r, n, d, m, c) {
18
+ super(n), this.name = "NeetruError", this.code = r, this.status = d, this.requestId = m, this.reason = c, Object.setPrototypeOf(this, e.prototype);
25
19
  }
26
20
  };
27
21
 
28
22
  // src/idempotency.ts
29
- function generateIdempotencyKey() {
30
- const cryptoObj = typeof globalThis !== "undefined" && "crypto" in globalThis ? globalThis.crypto : void 0;
31
- if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
32
- return cryptoObj.randomUUID();
33
- }
34
- throw new NeetruError(
23
+ function R() {
24
+ let e = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
25
+ if (e && typeof e.randomUUID == "function")
26
+ return e.randomUUID();
27
+ throw new a(
35
28
  "runtime_unsupported",
36
29
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
37
30
  );
38
31
  }
39
32
 
40
33
  // src/http.ts
41
- var COMPAT_MATRIX = {
34
+ var L = {
42
35
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
43
36
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
44
37
  3: "2026.05.1"
45
38
  };
46
- function stripRevision(v) {
47
- return v.split("+")[0] ?? v;
39
+ function v(e) {
40
+ return e.split("+")[0] ?? e;
48
41
  }
49
- function compareCalVer(a, b) {
50
- const partsA = stripRevision(a).split(".").map(Number);
51
- const partsB = stripRevision(b).split(".").map(Number);
52
- const len = Math.max(partsA.length, partsB.length);
53
- for (let i = 0; i < len; i++) {
54
- const pa = partsA[i] ?? 0;
55
- const pb = partsB[i] ?? 0;
56
- if (pa !== pb) return pa - pb;
42
+ function O(e, r) {
43
+ let n = v(e).split(".").map(Number), d = v(r).split(".").map(Number), m = Math.max(n.length, d.length);
44
+ for (let c = 0; c < m; c++) {
45
+ let t = n[c] ?? 0, i = d[c] ?? 0;
46
+ if (t !== i) return t - i;
57
47
  }
58
48
  return 0;
59
49
  }
60
- function readInjectedSdkVersion() {
50
+ function D() {
61
51
  try {
62
- return "3.6.0";
52
+ return "3.7.0";
63
53
  } catch {
64
- return void 0;
54
+ return;
65
55
  }
66
56
  }
67
- function getSdkMajor() {
68
- const ver = readInjectedSdkVersion();
69
- if (ver) return parseInt(ver.split(".")[0] ?? "3", 10);
70
- return 3;
57
+ function U() {
58
+ let e = D();
59
+ return e ? parseInt(e.split(".")[0] ?? "3", 10) : 3;
71
60
  }
72
- var _warnedCoreTooOld = /* @__PURE__ */ new Set();
73
- function checkCoreVersionCompat(coreVersion) {
74
- if (!coreVersion) return;
75
- const sdkMajor = getSdkMajor();
76
- const minCore = COMPAT_MATRIX[sdkMajor];
77
- if (!minCore) return;
78
- const stripped = stripRevision(coreVersion);
79
- if (compareCalVer(stripped, minCore) < 0) {
80
- const key = `${sdkMajor}:${stripped}`;
81
- if (!_warnedCoreTooOld.has(key)) {
82
- _warnedCoreTooOld.add(key);
83
- console.warn(
84
- `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${coreVersion}" \xE9 anterior ao m\xEDnimo recomendado "${minCore}" para SDK major ${sdkMajor}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
85
- );
86
- }
61
+ var A = /* @__PURE__ */ new Set();
62
+ function j(e) {
63
+ if (!e) return;
64
+ let r = U(), n = L[r];
65
+ if (!n) return;
66
+ let d = v(e);
67
+ if (O(d, n) < 0) {
68
+ let m = `${r}:${d}`;
69
+ A.has(m) || (A.add(m), console.warn(
70
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${e}" \xE9 anterior ao m\xEDnimo recomendado "${n}" para SDK major ${r}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
71
+ ));
87
72
  }
88
73
  }
89
- var DEFAULT_RETRIES_READ = 2;
90
- var DEFAULT_RETRIES_WRITE = 0;
91
- var READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
92
- var RETRYABLE_CODES = /* @__PURE__ */ new Set([
74
+ var $ = 2, K = 0, H = /* @__PURE__ */ new Set(["GET", "HEAD"]), F = /* @__PURE__ */ new Set([
93
75
  "rate_limited",
94
76
  "server_error",
95
77
  "network_error"
96
78
  ]);
97
- function backoffMs(attempt) {
98
- const base = 200 * Math.pow(4, attempt);
99
- const jitter = base * 0.2 * (Math.random() * 2 - 1);
100
- return Math.max(50, Math.round(base + jitter));
79
+ function I(e) {
80
+ let r = 200 * Math.pow(4, e), n = r * 0.2 * (Math.random() * 2 - 1);
81
+ return Math.max(50, Math.round(r + n));
101
82
  }
102
- var MAX_RETRY_AFTER_MS = 6e4;
103
- function parseRetryAfter(value) {
104
- if (!value) return null;
105
- const secs = Number(value);
106
- if (Number.isFinite(secs) && secs >= 0) return Math.min(Math.round(secs * 1e3), MAX_RETRY_AFTER_MS);
107
- const dateMs = Date.parse(value);
108
- if (Number.isFinite(dateMs)) {
109
- const delta = dateMs - Date.now();
110
- if (delta > 0) return Math.min(delta, MAX_RETRY_AFTER_MS);
83
+ var S = 6e4;
84
+ function V(e) {
85
+ if (!e) return null;
86
+ let r = Number(e);
87
+ if (Number.isFinite(r) && r >= 0) return Math.min(Math.round(r * 1e3), S);
88
+ let n = Date.parse(e);
89
+ if (Number.isFinite(n)) {
90
+ let d = n - Date.now();
91
+ if (d > 0) return Math.min(d, S);
111
92
  }
112
93
  return null;
113
94
  }
114
- function sleep(ms) {
115
- return new Promise((resolve) => setTimeout(resolve, ms));
95
+ function q(e) {
96
+ return new Promise((r) => setTimeout(r, e));
116
97
  }
117
- function statusToCode(status) {
118
- if (status === 401) return "unauthorized";
119
- if (status === 403) return "forbidden";
120
- if (status === 404) return "not_found";
121
- if (status === 409) return "conflict";
122
- if (status === 422 || status === 400) return "validation_failed";
123
- if (status === 429) return "rate_limited";
124
- if (status >= 500) return "server_error";
125
- return "unknown";
98
+ function G(e) {
99
+ return e === 401 ? "unauthorized" : e === 403 ? "forbidden" : e === 404 ? "not_found" : e === 409 ? "conflict" : e === 410 ? "gone" : e === 422 || e === 400 ? "validation_failed" : e === 429 ? "rate_limited" : e >= 500 ? "server_error" : "unknown";
126
100
  }
127
- function buildUrl(baseUrl, path, query) {
128
- const base = baseUrl.replace(/\/+$/, "");
129
- const p = path.startsWith("/") ? path : `/${path}`;
130
- const url = new URL(`${base}${p}`);
131
- if (query) {
132
- for (const [k, v] of Object.entries(query)) {
133
- if (v === void 0) continue;
134
- url.searchParams.set(k, String(v));
135
- }
136
- }
137
- return url.toString();
101
+ function z(e, r, n) {
102
+ let d = e.replace(/\/+$/, ""), m = r.startsWith("/") ? r : `/${r}`, c = new URL(`${d}${m}`);
103
+ if (n)
104
+ for (let [t, i] of Object.entries(n))
105
+ i !== void 0 && c.searchParams.set(t, String(i));
106
+ return c.toString();
138
107
  }
139
- async function safeJson(res) {
140
- const text = await res.text();
141
- if (!text) return void 0;
142
- try {
143
- return JSON.parse(text);
144
- } catch {
145
- return void 0;
146
- }
108
+ async function x(e) {
109
+ let r = await e.text();
110
+ if (r)
111
+ try {
112
+ return JSON.parse(r);
113
+ } catch {
114
+ return;
115
+ }
147
116
  }
148
- async function httpRequest(config, opts) {
149
- const method = opts.method ?? "GET";
150
- const url = buildUrl(config.baseUrl, opts.path, opts.query);
151
- const defaultRetries = READ_METHODS.has(method) ? DEFAULT_RETRIES_READ : DEFAULT_RETRIES_WRITE;
152
- const maxRetries = opts.retries ?? defaultRetries;
153
- const headers = {
117
+ async function _(e, r) {
118
+ let n = r.method ?? "GET", d = z(e.baseUrl, r.path, r.query), m = H.has(n) ? $ : K, c = r.retries ?? m, t = {
154
119
  accept: "application/json",
155
- ...opts.headers
156
- };
157
- const sdkVersion = readInjectedSdkVersion();
158
- if (sdkVersion) {
159
- headers["x-neetru-sdk-version"] = sdkVersion;
160
- }
161
- if (opts.requireAuth) {
162
- if (!config.apiKey) {
163
- throw new NeetruError(
120
+ ...r.headers
121
+ }, i = D();
122
+ if (i && (t["x-neetru-sdk-version"] = i), r.requireAuth) {
123
+ if (!e.apiKey)
124
+ throw new a(
164
125
  "missing_api_key",
165
126
  "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
166
127
  );
167
- }
168
- headers.authorization = `Bearer ${config.apiKey}`;
169
- }
170
- if (opts.idempotencyKey) {
171
- const key = typeof opts.idempotencyKey === "string" ? opts.idempotencyKey : generateIdempotencyKey();
172
- headers["idempotency-key"] = key;
128
+ t.authorization = `Bearer ${e.apiKey}`;
173
129
  }
174
- const bodyString = opts.body !== void 0 && method !== "GET" && method !== "DELETE" ? JSON.stringify(opts.body) : void 0;
175
- if (bodyString !== void 0) {
176
- headers["content-type"] = "application/json";
130
+ if (r.idempotencyKey) {
131
+ let f = typeof r.idempotencyKey == "string" ? r.idempotencyKey : R();
132
+ t["idempotency-key"] = f;
177
133
  }
178
- let lastError = null;
179
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
180
- const init = { method, headers };
181
- if (bodyString !== void 0) init.body = bodyString;
182
- init.signal = AbortSignal.timeout(3e4);
183
- let res;
134
+ let l = r.body !== void 0 && n !== "GET" && n !== "DELETE" ? JSON.stringify(r.body) : void 0;
135
+ l !== void 0 && (t["content-type"] = "application/json");
136
+ let s = null, u = r.deadlineMs != null ? Date.now() + r.deadlineMs : null;
137
+ for (let f = 0; f <= c; f++) {
138
+ if (u != null && Date.now() >= u)
139
+ throw s ?? new a("network_error", "Deadline excedido antes de completar a request");
140
+ let y = { method: n, headers: t };
141
+ l !== void 0 && (y.body = l);
142
+ let M = u != null ? Math.max(1, Math.min(3e4, u - Date.now())) : 3e4;
143
+ y.signal = AbortSignal.timeout(M);
144
+ let p;
184
145
  try {
185
- res = await config.fetch(url, init);
186
- } catch (err2) {
187
- const message2 = err2 instanceof DOMException && err2.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${err2 instanceof Error ? err2.message : "fetch failed"}`;
188
- lastError = new NeetruError("network_error", message2);
189
- if (attempt < maxRetries) {
190
- await sleep(backoffMs(attempt));
191
- continue;
146
+ p = await e.fetch(d, y);
147
+ } catch (o) {
148
+ let w = o instanceof DOMException && o.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${o instanceof Error ? o.message : "fetch failed"}`;
149
+ if (s = new a("network_error", w), f < c) {
150
+ let k = I(f);
151
+ if (u == null || Date.now() + k < u) {
152
+ await q(k);
153
+ continue;
154
+ }
192
155
  }
193
- throw lastError;
156
+ throw s;
194
157
  }
195
- const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-correlation-id") ?? void 0;
196
- if (res.ok) {
197
- const coreVersion = res.headers.get("x-neetru-version");
198
- if (coreVersion) checkCoreVersionCompat(coreVersion);
199
- const parsed = await safeJson(res);
200
- return parsed;
158
+ let P = p.headers.get("x-request-id") ?? p.headers.get("x-correlation-id") ?? void 0;
159
+ if (p.ok) {
160
+ let o = p.headers.get("x-neetru-version");
161
+ return o && j(o), await x(p);
201
162
  }
202
- const body = await safeJson(res);
203
- let code = statusToCode(res.status);
204
- let message = `HTTP ${res.status}`;
205
- let reason;
206
- if (body && typeof body === "object") {
207
- const errField = body.error;
208
- if (typeof errField === "string") {
209
- message = errField;
210
- } else if (errField && typeof errField === "object") {
211
- if (typeof errField.code === "string") code = errField.code;
212
- if (typeof errField.message === "string") message = errField.message;
213
- if (typeof errField.reason === "string") reason = errField.reason;
214
- } else {
215
- if (typeof body.code === "string") code = body.code;
216
- if (typeof body.message === "string") message = body.message;
217
- }
218
- if (typeof body.reason === "string") reason = body.reason;
163
+ let g = await x(p), b = G(p.status), h = `HTTP ${p.status}`, T;
164
+ if (g && typeof g == "object") {
165
+ let o = g.error;
166
+ typeof o == "string" ? h = o : o && typeof o == "object" ? (typeof o.code == "string" && (b = o.code), typeof o.message == "string" && (h = o.message), typeof o.reason == "string" && (T = o.reason)) : (typeof g.code == "string" && (b = g.code), typeof g.message == "string" && (h = g.message)), typeof g.reason == "string" && (T = g.reason);
167
+ }
168
+ if (p.status === 410) {
169
+ let o = p.headers.get("x-neetru-replacement");
170
+ h === `HTTP ${p.status}` && (h = `Endpoint ${r.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), o && !h.includes(o) && (h += ` Substituto: ${o}.`);
219
171
  }
220
- const err = new NeetruError(code, message, res.status, requestId, reason);
221
- lastError = err;
222
- const isRetryable = RETRYABLE_CODES.has(code);
223
- if (isRetryable && attempt < maxRetries) {
224
- const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
225
- const delay = retryAfter ?? backoffMs(attempt);
226
- await sleep(delay);
227
- continue;
172
+ let E = new a(b, h, p.status, P, T);
173
+ if (s = E, F.has(b) && f < c) {
174
+ let w = V(p.headers.get("retry-after")) ?? I(f);
175
+ if (u == null || Date.now() + w < u) {
176
+ await q(w);
177
+ continue;
178
+ }
228
179
  }
229
- throw err;
180
+ throw E;
230
181
  }
231
- throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
182
+ throw s ?? new a("unknown", "unexpected httpRequest exit");
232
183
  }
233
184
 
234
185
  // src/telemetry.ts
235
- var VALID_LOG_LEVELS = ["debug", "info", "warn", "error", "fatal"];
236
- function isBrowserContext() {
237
- return typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
186
+ var N = ["debug", "info", "warn", "error", "fatal"];
187
+ function B() {
188
+ return typeof globalThis < "u" && typeof globalThis.window < "u";
238
189
  }
239
- function resolveEventTransport() {
240
- return isBrowserContext() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
190
+ function C() {
191
+ return B() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
241
192
  }
242
- function consoleFor(level) {
243
- switch (level) {
193
+ function J(e) {
194
+ switch (e) {
244
195
  case "debug":
245
196
  return console.debug.bind(console);
246
197
  case "info":
@@ -255,58 +206,41 @@ function consoleFor(level) {
255
206
  return console.log.bind(console);
256
207
  }
257
208
  }
258
- var TRACK_FLUSH_MS = 500;
259
- var TRACK_MAX_QUEUE = 50;
260
- function createTelemetryNamespace(config) {
261
- const queue = [];
262
- let flushTimer = null;
263
- let _inflightDrain = null;
264
- async function drainQueue() {
265
- if (queue.length === 0) return;
266
- const batch = queue.splice(0, queue.length);
267
- const work = Promise.allSettled(
268
- batch.map(async (ev) => {
209
+ var X = 500, Y = 50;
210
+ function se(e) {
211
+ let r = [], n = null, d = null;
212
+ async function m() {
213
+ if (r.length === 0) return;
214
+ let t = r.splice(0, r.length), i = Promise.allSettled(
215
+ t.map(async (l) => {
269
216
  try {
270
- const body = { name: ev.name };
271
- const productSlug = ev.productSlug ?? config.productId;
272
- if (productSlug) body.productSlug = productSlug;
273
- if (ev.properties && typeof ev.properties === "object") {
274
- body.properties = ev.properties;
275
- }
276
- if (ev.timestamp) body.timestamp = ev.timestamp;
277
- const transport = resolveEventTransport();
278
- await httpRequest(config, {
217
+ let s = { name: l.name }, u = l.productSlug ?? e.productId;
218
+ u && (s.productSlug = u), l.properties && typeof l.properties == "object" && (s.properties = l.properties), l.timestamp && (s.timestamp = l.timestamp);
219
+ let f = C();
220
+ await _(e, {
279
221
  method: "POST",
280
- path: transport.path,
281
- body,
282
- requireAuth: transport.requireAuth,
222
+ path: f.path,
223
+ body: s,
224
+ requireAuth: f.requireAuth,
283
225
  retries: 1,
284
226
  // caça-bruxas: retry sem Idempotency-Key duplicava o evento se o
285
227
  // servidor já tinha persistido antes da falha transiente. Mesmo
286
228
  // padrão do usage.report (key estável por chamada, reusada no retry).
287
- idempotencyKey: true
229
+ idempotencyKey: !0
288
230
  });
289
- } catch (err) {
290
- if (typeof console !== "undefined") {
291
- console.warn("[neetru-sdk] telemetry.track flush failed for event", ev.name, err);
292
- }
231
+ } catch (s) {
232
+ typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", l.name, s);
293
233
  }
294
234
  })
295
235
  );
296
- _inflightDrain = work.then(() => {
297
- _inflightDrain = null;
298
- });
299
- await work;
300
- flushTimer = null;
301
- if (queue.length > 0) {
302
- scheduleFlush();
303
- }
236
+ d = i.then(() => {
237
+ d = null;
238
+ }), await i, n = null, r.length > 0 && c();
304
239
  }
305
- function scheduleFlush() {
306
- if (flushTimer) return;
307
- flushTimer = setTimeout(() => {
308
- void drainQueue();
309
- }, TRACK_FLUSH_MS);
240
+ function c() {
241
+ n || (n = setTimeout(() => {
242
+ m();
243
+ }, X));
310
244
  }
311
245
  return {
312
246
  /**
@@ -321,34 +255,24 @@ function createTelemetryNamespace(config) {
321
255
  * });
322
256
  * ```
323
257
  */
324
- async event(input) {
325
- if (!input || typeof input !== "object") {
326
- throw new NeetruError("validation_failed", "event input is required");
327
- }
328
- if (typeof input.name !== "string" || input.name.length === 0) {
329
- throw new NeetruError("validation_failed", "event.name is required");
330
- }
331
- if (input.name.length > 128) {
332
- throw new NeetruError("validation_failed", "event.name max 128 chars");
333
- }
334
- const body = { name: input.name };
335
- const productSlug = input.productSlug ?? config.productId;
336
- if (productSlug) body.productSlug = productSlug;
337
- if (input.properties && typeof input.properties === "object") {
338
- body.properties = input.properties;
339
- }
340
- if (input.timestamp) body.timestamp = input.timestamp;
341
- const transport = resolveEventTransport();
342
- const raw = await httpRequest(config, {
258
+ async event(t) {
259
+ if (!t || typeof t != "object")
260
+ throw new a("validation_failed", "event input is required");
261
+ if (typeof t.name != "string" || t.name.length === 0)
262
+ throw new a("validation_failed", "event.name is required");
263
+ if (t.name.length > 128)
264
+ throw new a("validation_failed", "event.name max 128 chars");
265
+ let i = { name: t.name }, l = t.productSlug ?? e.productId;
266
+ l && (i.productSlug = l), t.properties && typeof t.properties == "object" && (i.properties = t.properties), t.timestamp && (i.timestamp = t.timestamp);
267
+ let s = C(), u = await _(e, {
343
268
  method: "POST",
344
- path: transport.path,
345
- body,
346
- requireAuth: transport.requireAuth
269
+ path: s.path,
270
+ body: i,
271
+ requireAuth: s.requireAuth
347
272
  });
348
- if (!raw || raw.ok !== true || typeof raw.eventId !== "string") {
349
- throw new NeetruError("invalid_response", "Telemetry response missing eventId");
350
- }
351
- return { ok: true, eventId: raw.eventId };
273
+ if (!u || u.ok !== true || typeof u.eventId != "string")
274
+ throw new a("invalid_response", "Telemetry response missing eventId");
275
+ return { ok: true, eventId: u.eventId };
352
276
  },
353
277
  /**
354
278
  * Fire-and-forget: enqueue + flush 500ms debounce. Não retorna `eventId`
@@ -360,32 +284,15 @@ function createTelemetryNamespace(config) {
360
284
  * // segue execução; flush async em background
361
285
  * ```
362
286
  */
363
- track(input) {
364
- if (!input || typeof input !== "object") return;
365
- if (typeof input.name !== "string" || input.name.length === 0) return;
366
- if (input.name.length > 128) return;
367
- queue.push(input);
368
- if (queue.length >= TRACK_MAX_QUEUE) {
369
- if (flushTimer) {
370
- clearTimeout(flushTimer);
371
- flushTimer = null;
372
- }
373
- void drainQueue();
374
- } else {
375
- scheduleFlush();
376
- }
287
+ track(t) {
288
+ !t || typeof t != "object" || typeof t.name != "string" || t.name.length === 0 || t.name.length > 128 || (r.push(t), r.length >= Y ? (n && (clearTimeout(n), n = null), m()) : c());
377
289
  },
378
290
  /**
379
291
  * Força flush imediato da queue de `track()`. Resolva antes de
380
292
  * page unload / SSR boundary pra não perder eventos.
381
293
  */
382
294
  async flush() {
383
- if (flushTimer) {
384
- clearTimeout(flushTimer);
385
- flushTimer = null;
386
- }
387
- if (_inflightDrain) await _inflightDrain;
388
- await drainQueue();
295
+ n && (clearTimeout(n), n = null), d && await d, await m();
389
296
  },
390
297
  /**
391
298
  * Registra um log estruturado per-product (Sprint 6).
@@ -402,60 +309,49 @@ function createTelemetryNamespace(config) {
402
309
  * });
403
310
  * ```
404
311
  */
405
- async log(input) {
406
- if (!input || typeof input !== "object") {
407
- throw new NeetruError("validation_failed", "log input is required");
408
- }
409
- if (!VALID_LOG_LEVELS.includes(input.level)) {
410
- throw new NeetruError("validation_failed", `level must be one of ${VALID_LOG_LEVELS.join(", ")}`);
411
- }
412
- if (typeof input.message !== "string" || input.message.length === 0) {
413
- throw new NeetruError("validation_failed", "message is required");
414
- }
415
- if (input.message.length > 4e3) {
416
- throw new NeetruError("validation_failed", "message max 4000 chars");
417
- }
418
- if (config.env === "dev") {
419
- const fn = consoleFor(input.level);
420
- fn(`[neetru-sdk] ${input.level}: ${input.message}`, input.metadata ?? {});
421
- return { ok: true, mode: "mock" };
422
- }
423
- const body = {
424
- level: input.level,
425
- message: input.message
312
+ async log(t) {
313
+ if (!t || typeof t != "object")
314
+ throw new a("validation_failed", "log input is required");
315
+ if (!N.includes(t.level))
316
+ throw new a("validation_failed", `level must be one of ${N.join(", ")}`);
317
+ if (typeof t.message != "string" || t.message.length === 0)
318
+ throw new a("validation_failed", "message is required");
319
+ if (t.message.length > 4e3)
320
+ throw new a("validation_failed", "message max 4000 chars");
321
+ if (e.env === "dev")
322
+ return J(t.level)(`[neetru-sdk] ${t.level}: ${t.message}`, t.metadata ?? {}), { ok: true, mode: "mock" };
323
+ let i = {
324
+ level: t.level,
325
+ message: t.message
426
326
  };
427
- if (input.metadata) body.metadata = input.metadata;
428
- const productSlug = input.productSlug ?? config.productId;
429
- if (productSlug) body.productSlug = productSlug;
430
- let cid = input.correlationId;
431
- if (!cid) {
327
+ t.metadata && (i.metadata = t.metadata);
328
+ let l = t.productSlug ?? e.productId;
329
+ l && (i.productSlug = l);
330
+ let s = t.correlationId;
331
+ if (!s)
432
332
  try {
433
- const g = globalThis.NEETRU_CORRELATION_ID;
434
- if (typeof g === "string" && g.length > 0) cid = g;
333
+ let y = globalThis.NEETRU_CORRELATION_ID;
334
+ typeof y == "string" && y.length > 0 && (s = y);
435
335
  } catch {
436
336
  }
437
- }
438
- const headers = {};
439
- if (cid) headers["x-correlation-id"] = cid;
440
- const raw = await httpRequest(config, {
337
+ let u = {};
338
+ s && (u["x-correlation-id"] = s);
339
+ let f = await _(e, {
441
340
  method: "POST",
442
341
  path: "/api/sdk/v1/telemetry/log",
443
- body,
342
+ body: i,
444
343
  requireAuth: true,
445
- headers
344
+ headers: u
446
345
  });
447
- if (!raw || raw.ok !== true) {
448
- throw new NeetruError("invalid_response", "Telemetry log response missing ok");
449
- }
346
+ if (!f || f.ok !== true)
347
+ throw new a("invalid_response", "Telemetry log response missing ok");
450
348
  return {
451
349
  ok: true,
452
- logId: typeof raw.logId === "string" ? raw.logId : void 0,
350
+ logId: typeof f.logId == "string" ? f.logId : void 0,
453
351
  mode: "http"
454
352
  };
455
353
  }
456
354
  };
457
355
  }
458
356
 
459
- exports.createTelemetryNamespace = createTelemetryNamespace;
460
- //# sourceMappingURL=telemetry.cjs.map
461
- //# sourceMappingURL=telemetry.cjs.map
357
+ exports.createTelemetryNamespace = se;
@@ -1,4 +1,4 @@
1
- import { ag as ResolvedConfig, as as TelemetryEventInput, ar as TelemetryEventAck, au as TelemetryLogInput, at as TelemetryLogAck } from './types-Du_iioJ7.cjs';
1
+ import { ag as ResolvedConfig, as as TelemetryEventInput, ar as TelemetryEventAck, au as TelemetryLogInput, at as TelemetryLogAck } from './types-Bx4kTLmk.cjs';
2
2
  import 'drizzle-orm/node-postgres';
3
3
  import './errors.cjs';
4
4
 
@@ -1,4 +1,4 @@
1
- import { ag as ResolvedConfig, as as TelemetryEventInput, ar as TelemetryEventAck, au as TelemetryLogInput, at as TelemetryLogAck } from './types-BPATkXYu.js';
1
+ import { ag as ResolvedConfig, as as TelemetryEventInput, ar as TelemetryEventAck, au as TelemetryLogInput, at as TelemetryLogAck } from './types-Dx0IrOSF.js';
2
2
  import 'drizzle-orm/node-postgres';
3
3
  import './errors.js';
4
4